app.js 641 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217
  1. // DebTik - Debian Linux Router 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. dhcpServerTab: 'servers',
  49. dhcpServers: [],
  50. dhcpNetworks: [],
  51. dhcpLeases: [],
  52. dhcpOptions: [],
  53. dhcpServerSummary: null
  54. };
  55. const API_BASE = '/api';
  56. function escapeHtml(str) {
  57. if (str === null || str === undefined) return '';
  58. return String(str)
  59. .replace(/&/g, '&')
  60. .replace(/</g, '&lt;')
  61. .replace(/>/g, '&gt;')
  62. .replace(/"/g, '&quot;')
  63. .replace(/'/g, '&#039;');
  64. }
  65. function formatBytes(bytes) {
  66. if (bytes === undefined || bytes === null || isNaN(bytes) || bytes === 0) return '0 B';
  67. const k = 1024;
  68. const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
  69. const i = Math.floor(Math.log(bytes) / Math.log(k));
  70. if (i < 0 || i >= sizes.length) return `${bytes} B`;
  71. return `${parseFloat((bytes / Math.pow(k, i)).toFixed(2))} ${sizes[i]}`;
  72. }
  73. // Initialize on page load
  74. document.addEventListener('DOMContentLoaded', () => {
  75. const hash = window.location.hash.replace('#', '') || 'dashboard';
  76. navigate(hash);
  77. initTableSorting();
  78. fetchData();
  79. // Live polling every 2.5 seconds
  80. setInterval(() => {
  81. if (state.isPolling) {
  82. fetchData(false);
  83. }
  84. }, 2500);
  85. });
  86. // Navigation Handler
  87. function navigate(tabName) {
  88. if (tabName === 'dynamic-routing' || tabName === 'routing') {
  89. navigate('bgp');
  90. return;
  91. }
  92. if (tabName === 'vlans') {
  93. navigate('interfaces');
  94. return;
  95. }
  96. state.activeTab = tabName;
  97. window.location.hash = tabName;
  98. // Update nav links styling
  99. document.querySelectorAll('.nav-link').forEach(link => {
  100. 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';
  101. });
  102. const activeNav = document.getElementById(`nav-${tabName}`);
  103. if (activeNav) {
  104. 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';
  105. }
  106. // Update page headers
  107. const titles = {
  108. dashboard: { title: 'Dashboard Overview', sub: 'Live router performance and network telemetry' },
  109. interfaces: { title: 'Network Interfaces', sub: 'Interface Table View' },
  110. 'dhcp-client': { title: 'DHCP Client', sub: 'DHCP Client List' },
  111. 'dhcp-server': { title: 'DHCP Server & Subnets', sub: 'DHCP Server instances, subnet networks (NTP, TFTP, DNS), dynamic leases & static reservations' },
  112. bridge: { title: 'Bridge Interfaces', sub: 'IEEE 802.1D / 802.1Q VLAN-aware Layer 2 switching, RSTP & hardware forwarding (FDB)' },
  113. vlans: { title: 'VLAN Virtual Networks', sub: 'IEEE 802.1Q sub-interface segmentation and routing' },
  114. firewall: { title: 'Network Firewall', sub: 'Stateful packet inspection, NAT, traffic mangle, address lists & connection tracking' },
  115. routes: { title: 'Routing & Policy', sub: 'Routing tables, static routes (DAS/DAC), and policy routing rules' },
  116. bgp: { title: 'BGP Dynamic Routing', sub: 'BGP multi-instance peering sessions, advertised networks, and routing table (RIB)' },
  117. ospf: { title: 'OSPF Dynamic Routing', sub: 'OSPFv2 link-state routing, dynamic neighbor adjacencies, and multi-area topology' },
  118. 'routing-filters': { title: 'Routing Policy Filters', sub: 'Route filter chains, prefix matching, BGP community maps & policy-based path control' },
  119. 'dynamic-routing': { title: 'BGP Dynamic Routing', sub: 'Dynamic routing engine and peering sessions' },
  120. ppp: { title: 'PPP Servers & Secrets', sub: 'Subscriber authentication, dynamic IP pools and VPN access concentrators' },
  121. eoip: { title: 'EoIP Tunnels', sub: 'Ethernet over IP (EoIP / GRETAP) Layer 2 encapsulation & transparent network bridging' },
  122. aerotun: { title: 'AeroTUN High-Speed VPN', sub: 'Ultra-fast Layer 3 encrypted tunnel with ChaCha20-Poly1305 and live Adaptive LZ4 compression' },
  123. pppoe: { title: 'PPPoE Client WAN', sub: 'Point-to-Point Protocol over Ethernet WAN access' },
  124. wireguard: { title: 'WireGuard VPN', sub: 'High-performance cryptographic Layer 3 tunnels with ChaCha20-Poly1305 key exchange' },
  125. ipsec: { title: 'IPSec (IKEv2) strongSwan', sub: 'Enterprise Site-to-Site & Roadwarrior IPSec controller' },
  126. l2tp: { title: 'L2TP VPN Client', sub: 'Layer 2 Tunneling Protocol via xl2tpd' },
  127. pptp: { title: 'PPTP VPN Client', sub: 'Point-to-Point Tunneling Protocol with MPPE-128 encryption' },
  128. vrrp: { title: 'VRRP High Availability', sub: 'Virtual Router Redundancy Protocol, active-backup gateway failover & Virtual IP (VIP) routing' },
  129. bwtest: { title: 'Bandwidth Test Benchmark', sub: 'High-speed line-rate throughput benchmark, token-bucket rate limiting, loss & jitter telemetry' },
  130. tools: { title: 'Diagnostic & Troubleshooting Tools', sub: 'Network latency analysis, ICMP/MTR telemetry, path tracing, DNS resolution and TCP probing' },
  131. persistence: { title: 'Debian Configuration', sub: 'Native /etc/network/interfaces.d/ persistence manager' },
  132. settings: { title: 'Router Settings & DNS', sub: 'System DNS forwarder, upstream resolvers, static host mappings, and appliance identity' }
  133. };
  134. const header = titles[tabName] || titles.dashboard;
  135. const pTitle = document.getElementById('page-title');
  136. if (pTitle) pTitle.innerText = header.title;
  137. const pSub = document.getElementById('page-subtitle');
  138. if (pSub) pSub.innerText = header.sub;
  139. // Toggle sections dynamically for all section elements
  140. document.querySelectorAll('main section[id^="section-"]').forEach(el => {
  141. if (el.id === `section-${tabName}`) {
  142. el.classList.remove('hidden');
  143. } else {
  144. el.classList.add('hidden');
  145. }
  146. });
  147. if (tabName === 'bridge') loadBridge();
  148. if (tabName === 'firewall') loadFirewall();
  149. if (tabName === 'routes') loadRoutes();
  150. if (tabName === 'bgp') {
  151. loadDynamicRouting();
  152. switchBgpSubTab(state.activeBgpSubTab || 'bgp-peers');
  153. }
  154. if (tabName === 'ospf') {
  155. loadDynamicRouting();
  156. switchOspfTab(state.activeOspfTab || 'instances');
  157. }
  158. if (tabName === 'routing-filters') loadDynamicRouting();
  159. if (tabName === 'dynamic-routing') loadDynamicRouting();
  160. if (tabName === 'ppp') loadPPP();
  161. if (tabName === 'eoip') loadEoIP();
  162. if (tabName === 'aerotun') loadAeroTUN();
  163. if (tabName === 'persistence') loadDebianConfig();
  164. if (tabName === 'pppoe') loadPPPoE();
  165. if (tabName === 'wireguard') loadWireGuard();
  166. if (tabName === 'ipsec') loadIPSec();
  167. if (tabName === 'l2tp') loadL2TP();
  168. if (tabName === 'pptp') loadPPTP();
  169. if (tabName === 'tools') loadToolsView();
  170. if (tabName === 'dhcp-client') loadDHCPClients();
  171. if (tabName === 'dhcp-server') loadDHCPServer();
  172. if (tabName === 'vrrp') loadVRRP();
  173. if (tabName === 'bwtest') loadBwTestView();
  174. if (tabName === 'settings') loadSettingsData();
  175. setTimeout(initTableSorting, 50);
  176. }
  177. // Fetch all core system, network and VPN telemetry
  178. async function fetchData(isManual = false) {
  179. const spinner = document.getElementById('refresh-spinner');
  180. if (isManual && spinner) spinner.classList.add('animate-spin');
  181. try {
  182. const [statusRes, ifacesRes, vlansRes, vpnRes, fwRes, dynRes, brSummaryRes, dhcpSumRes, dhcpClientsRes, vrrpSumRes] = await Promise.all([
  183. fetch(`${API_BASE}/system/status`),
  184. fetch(`${API_BASE}/interfaces`),
  185. fetch(`${API_BASE}/vlans`),
  186. fetch(`${API_BASE}/vpn/status`),
  187. fetch(`${API_BASE}/firewall/summary`),
  188. fetch(`${API_BASE}/routing/dynamic/summary`),
  189. fetch(`${API_BASE}/bridge/summary`),
  190. fetch(`${API_BASE}/dhcp/clients/summary`),
  191. fetch(`${API_BASE}/dhcp/clients`),
  192. fetch(`${API_BASE}/vrrp/summary`).catch(() => null)
  193. ]);
  194. if (vrrpSumRes && vrrpSumRes.ok) {
  195. state.vrrpSummary = await vrrpSumRes.json();
  196. renderVRRPSummary();
  197. }
  198. if (dhcpSumRes && dhcpSumRes.ok) {
  199. state.dhcpSummary = await dhcpSumRes.json();
  200. const bDhcp = document.getElementById('badge-dhcp-client-count');
  201. if (bDhcp) bDhcp.innerText = state.dhcpSummary?.total_clients || 0;
  202. }
  203. if (dhcpClientsRes && dhcpClientsRes.ok) {
  204. state.dhcpClients = await dhcpClientsRes.json();
  205. }
  206. if (brSummaryRes.ok) {
  207. state.bridgeSummary = await brSummaryRes.json();
  208. const bBridge = document.getElementById('badge-bridge-count');
  209. if (bBridge) bBridge.innerText = state.bridgeSummary?.bridges_count || 0;
  210. const sBr = document.getElementById('bridge-stat-bridges');
  211. if (sBr) sBr.innerText = state.bridgeSummary?.bridges_count || 0;
  212. const sPorts = document.getElementById('bridge-stat-ports');
  213. if (sPorts) sPorts.innerText = state.bridgeSummary?.ports_count || 0;
  214. const sHosts = document.getElementById('bridge-stat-hosts');
  215. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  216. }
  217. if (statusRes.ok) state.systemStatus = await statusRes.json();
  218. if (ifacesRes.ok) {
  219. const ifacesData = await ifacesRes.json();
  220. const rawIfaces = Array.isArray(ifacesData) ? ifacesData : [];
  221. state.interfaces = rawIfaces.filter(i => {
  222. if (!i.name) return false;
  223. if (i.name.startsWith('ep_')) return false;
  224. return !['gre0', 'gretap0', 'erspan0', 'sit0', 'tunl0', 'ip6tnl0', 'ip6gre0', 'ip6erspan0'].includes(i.name);
  225. });
  226. try { populateToolsInterfaces(); } catch (e) {}
  227. }
  228. if (vlansRes.ok) {
  229. const vlansData = await vlansRes.json();
  230. state.vlans = Array.isArray(vlansData) ? vlansData : [];
  231. }
  232. if (vpnRes.ok) state.vpnStatus = await vpnRes.json();
  233. if (fwRes && fwRes.ok) state.fwSummary = await fwRes.json();
  234. if (dynRes && dynRes.ok) state.dynSummary = await dynRes.json();
  235. updateSystemMetrics();
  236. updateBadges();
  237. if (state.activeTab === 'dashboard') renderDashboard();
  238. if (state.activeTab === 'interfaces') renderInterfacesList();
  239. if (state.activeTab === 'vlans') renderVlansList();
  240. if (state.activeTab === 'firewall') loadFirewall(false);
  241. if (state.activeTab === 'routes') loadRoutes(false);
  242. if (state.activeTab === 'dynamic-routing' || state.activeTab === 'bgp' || state.activeTab === 'ospf') loadDynamicRouting(false);
  243. if (state.activeTab === 'ppp') loadPPP(false);
  244. if (state.activeTab === 'eoip') loadEoIP(false);
  245. if (state.activeTab === 'aerotun') loadAeroTUN(false);
  246. if (state.activeTab === 'pppoe') loadPPPoE(false);
  247. if (state.activeTab === 'wireguard') loadWireGuard(false);
  248. if (state.activeTab === 'ipsec') loadIPSec(false);
  249. if (state.activeTab === 'l2tp') loadL2TP(false);
  250. if (state.activeTab === 'pptp') loadPPTP(false);
  251. if (state.activeTab === 'dhcp-client') loadDHCPClients(false);
  252. if (state.activeTab === 'dhcp-server') loadDHCPServer(false);
  253. if (state.activeTab === 'vrrp') loadVRRP(false);
  254. if (state.activeTab === 'settings') loadSettingsData(false);
  255. fetchBwTestServerStatus();
  256. } catch (err) {
  257. console.error('Failed to fetch router state:', err);
  258. } finally {
  259. if (isManual && spinner) {
  260. setTimeout(() => spinner.classList.remove('animate-spin'), 300);
  261. }
  262. }
  263. }
  264. // Update Top KPI and Sidebar Telemetry
  265. function updateSystemMetrics() {
  266. const s = state.systemStatus;
  267. const v = state.vpnStatus;
  268. if (!s) return;
  269. // Sidebar Host & Uptime
  270. const sideHost = document.getElementById('side-hostname');
  271. if (sideHost) sideHost.innerText = s.hostname || 'debian-lxc';
  272. const sideUp = document.getElementById('side-uptime');
  273. if (sideUp) sideUp.innerText = s.uptime_human || '0m';
  274. const sideGw = document.getElementById('side-gateway-ip');
  275. if (sideGw) sideGw.innerText = s.default_gateway ? `GW: ${s.default_gateway}` : 'GW: Isolated';
  276. // Compute CPU Metrics
  277. let cpuPct = 0;
  278. if (s.cpu_pct !== undefined) {
  279. cpuPct = s.cpu_pct;
  280. } else if (s.cpu_load && s.cpu_load.length > 0) {
  281. const cores = s.cpu_cores || 1;
  282. cpuPct = Math.min(100, Math.round((parseFloat(s.cpu_load[0]) / cores) * 100));
  283. }
  284. const cpuPctStr = `${cpuPct.toFixed(1)}%`;
  285. const cpuWidth = `${Math.max(3, Math.min(100, cpuPct))}%`;
  286. const loadStr = s.cpu_load ? s.cpu_load.join(', ') : '-';
  287. // Sidebar CPU
  288. const sideCpuVal = document.getElementById('side-cpu-val');
  289. if (sideCpuVal) sideCpuVal.innerText = cpuPctStr;
  290. const sideCpuBar = document.getElementById('side-cpu-bar');
  291. if (sideCpuBar) {
  292. sideCpuBar.style.width = cpuWidth;
  293. sideCpuBar.title = `Container: ${cpuPctStr} | Host Loadavg: ${loadStr} (${s.cpu_cores || 1} cores)`;
  294. }
  295. // Dashboard CPU Card
  296. const dashCpuVal = document.getElementById('dash-cpu-val');
  297. if (dashCpuVal) dashCpuVal.innerText = cpuPctStr;
  298. const dashCpuBar = document.getElementById('dash-cpu-bar');
  299. if (dashCpuBar) {
  300. dashCpuBar.style.width = cpuWidth;
  301. if (cpuPct > 85) {
  302. dashCpuBar.className = 'h-full rounded-full bg-rose-500 transition-all duration-500';
  303. } else if (cpuPct > 65) {
  304. dashCpuBar.className = 'h-full rounded-full bg-amber-500 transition-all duration-500';
  305. } else {
  306. dashCpuBar.className = 'h-full rounded-full bg-emerald-500 transition-all duration-500';
  307. }
  308. }
  309. const dashCpuCores = document.getElementById('dash-cpu-cores');
  310. if (dashCpuCores) dashCpuCores.innerText = `${s.cpu_cores || 1} Cores`;
  311. const dashCpuLoad = document.getElementById('dash-cpu-load');
  312. if (dashCpuLoad) dashCpuLoad.innerText = loadStr;
  313. const dashCpuStatus = document.getElementById('dash-cpu-status');
  314. if (dashCpuStatus) {
  315. if (cpuPct > 85) {
  316. dashCpuStatus.innerText = 'High';
  317. dashCpuStatus.className = 'text-[11px] font-semibold text-rose-400 uppercase px-2 py-0.5 rounded bg-rose-500/10';
  318. } else if (cpuPct > 65) {
  319. dashCpuStatus.innerText = 'Heavy';
  320. dashCpuStatus.className = 'text-[11px] font-semibold text-amber-400 uppercase px-2 py-0.5 rounded bg-amber-500/10';
  321. } else {
  322. dashCpuStatus.innerText = 'Normal';
  323. dashCpuStatus.className = 'text-[11px] font-semibold text-emerald-400 uppercase px-2 py-0.5 rounded bg-emerald-500/10';
  324. }
  325. }
  326. // Compute RAM Metrics
  327. const memPct = Math.round(s.mem_usage_pct || 0);
  328. const memPctStr = `${memPct}%`;
  329. const memWidth = `${Math.max(3, Math.min(100, memPct))}%`;
  330. const usedMB = s.mem_used_mb || 0;
  331. const totalMB = s.mem_total_mb || 0;
  332. const freeMB = totalMB > usedMB ? totalMB - usedMB : 0;
  333. function fmtMemMB(mb) {
  334. if (mb >= 1024) {
  335. return `${(mb / 1024).toFixed(1)} GB`;
  336. }
  337. return `${mb} MB`;
  338. }
  339. // Sidebar RAM
  340. const sideRamVal = document.getElementById('side-ram-val');
  341. if (sideRamVal) sideRamVal.innerText = memPctStr;
  342. const sideRamBar = document.getElementById('side-ram-bar');
  343. if (sideRamBar) sideRamBar.style.width = memWidth;
  344. // Dashboard RAM Card
  345. const dashRamVal = document.getElementById('dash-ram-val');
  346. if (dashRamVal) dashRamVal.innerText = memPctStr;
  347. const dashRamBar = document.getElementById('dash-ram-bar');
  348. if (dashRamBar) {
  349. dashRamBar.style.width = memWidth;
  350. if (memPct > 85) {
  351. dashRamBar.className = 'h-full rounded-full bg-rose-500 transition-all duration-500';
  352. } else if (memPct > 70) {
  353. dashRamBar.className = 'h-full rounded-full bg-amber-500 transition-all duration-500';
  354. } else {
  355. dashRamBar.className = 'h-full rounded-full bg-indigo-500 transition-all duration-500';
  356. }
  357. }
  358. const dashRamUsedTotal = document.getElementById('dash-ram-used-total');
  359. if (dashRamUsedTotal) {
  360. dashRamUsedTotal.innerText = `${fmtMemMB(usedMB)} / ${fmtMemMB(totalMB)}`;
  361. }
  362. const dashRamFree = document.getElementById('dash-ram-free');
  363. if (dashRamFree) {
  364. dashRamFree.innerText = fmtMemMB(freeMB);
  365. }
  366. const dashRamStatus = document.getElementById('dash-ram-status');
  367. if (dashRamStatus) {
  368. if (memPct > 85) {
  369. dashRamStatus.innerText = 'High';
  370. dashRamStatus.className = 'text-[11px] font-semibold text-rose-400 uppercase px-2 py-0.5 rounded bg-rose-500/10';
  371. } else {
  372. dashRamStatus.innerText = 'Active';
  373. dashRamStatus.className = 'text-[11px] font-semibold text-indigo-400 uppercase px-2 py-0.5 rounded bg-indigo-500/10';
  374. }
  375. }
  376. // Legacy Dashboard Stats (Safe checks)
  377. const elIfacesUp = document.getElementById('stat-ifaces-up');
  378. if (elIfacesUp) elIfacesUp.innerText = s.up_ifaces || 0;
  379. const elIfacesTot = document.getElementById('stat-ifaces-total');
  380. if (elIfacesTot) elIfacesTot.innerText = `${s.total_ifaces || 0} Total`;
  381. const elIfacesDown = document.getElementById('stat-ifaces-down');
  382. if (elIfacesDown) elIfacesDown.innerText = `${s.down_ifaces || 0} DOWN`;
  383. const elVlans = document.getElementById('stat-vlans-count');
  384. if (elVlans) elVlans.innerText = s.vlan_ifaces || 0;
  385. // VPN Status Indicators
  386. if (v) {
  387. const totalActive = v.total_active_tunnels || 0;
  388. const statVpnActive = document.getElementById('stat-vpn-active');
  389. if (statVpnActive) statVpnActive.innerText = totalActive;
  390. const tunnelsDot = document.getElementById('tunnels-dot');
  391. const tunnelsLabel = document.getElementById('tunnels-label');
  392. if (tunnelsDot && tunnelsLabel) {
  393. if (totalActive > 0) {
  394. tunnelsDot.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  395. tunnelsLabel.innerText = `${totalActive} Active VPN Tunnel${totalActive > 1 ? 's' : ''}`;
  396. } else {
  397. tunnelsDot.className = 'w-2 h-2 rounded-full bg-slate-500';
  398. tunnelsLabel.innerText = '0 Active VPN Tunnels';
  399. }
  400. }
  401. setDotBadge('badge-pppoe-status', (v.active_pppoe || 0) > 0 || v.pppoe_connected);
  402. setDotBadge('badge-wg-status', (v.active_wireguard || 0) > 0 || v.wireguard_active);
  403. setDotBadge('badge-ipsec-status', (v.active_ipsec || 0) > 0 || v.ipsec_active);
  404. setDotBadge('badge-l2tp-status', (v.active_l2tp || 0) > 0 || v.l2tp_connected);
  405. setDotBadge('badge-pptp-status', (v.active_pptp || 0) > 0 || v.pptp_connected);
  406. }
  407. // Total Live Bandwidth Rate
  408. let totalRx = 0;
  409. let totalTx = 0;
  410. (state.interfaces || []).forEach(i => {
  411. if (i.rate) {
  412. totalRx += i.rate.rx_bytes_sec || 0;
  413. totalTx += i.rate.tx_bytes_sec || 0;
  414. }
  415. });
  416. document.getElementById('stat-traffic-rx').innerText = formatTraffic(totalRx);
  417. document.getElementById('stat-traffic-tx').innerText = formatTraffic(totalTx);
  418. }
  419. function setDotBadge(id, active) {
  420. const el = document.getElementById(id);
  421. if (!el) return;
  422. if (active) {
  423. el.className = 'w-2 h-2 rounded-full bg-emerald-400 shadow-sm shadow-emerald-400/80';
  424. } else {
  425. el.className = 'w-2 h-2 rounded-full bg-slate-600';
  426. }
  427. }
  428. function updateBadges() {
  429. const bIfaces = document.getElementById('badge-ifaces-count');
  430. if (bIfaces) bIfaces.innerText = (state.interfaces || []).length;
  431. const bVlans = document.getElementById('badge-vlans-count');
  432. if (bVlans) bVlans.innerText = (state.vlans || []).length;
  433. if (state.fwSummary) {
  434. const totalFwRules = (state.fwSummary.filter_rules_count || 0) + (state.fwSummary.nat_rules_count || 0) + (state.fwSummary.mangle_rules_count || 0);
  435. const badgeFw = document.getElementById('badge-firewall-count');
  436. if (badgeFw) badgeFw.innerText = totalFwRules;
  437. }
  438. if (state.vpnStatus) {
  439. const v = state.vpnStatus;
  440. const bEoIP = document.getElementById('badge-eoip-count');
  441. if (bEoIP) bEoIP.innerText = v.total_eoip || 0;
  442. const bAero = document.getElementById('badge-aerotun-count');
  443. if (bAero) bAero.innerText = v.total_aerotun || 0;
  444. const bPPPSess = document.getElementById('badge-ppp-sessions');
  445. if (bPPPSess) bPPPSess.innerText = v.total_ppp_sessions || 0;
  446. setDotBadge('badge-pppoe-status', v.active_pppoe > 0 || v.pppoe_server_running);
  447. setDotBadge('badge-wg-status', v.active_wireguard > 0);
  448. setDotBadge('badge-ipsec-status', v.active_ipsec > 0 || v.ipsec_server_running);
  449. setDotBadge('badge-l2tp-status', v.active_l2tp > 0 || v.l2tp_server_running);
  450. setDotBadge('badge-pptp-status', v.active_pptp > 0 || v.pptp_server_running);
  451. }
  452. if (state.dynSummary) {
  453. const d = state.dynSummary;
  454. setDotBadge('badge-bgp-dot', d.bgp_running);
  455. setDotBadge('badge-ospf-dot', d.ospf_running);
  456. const bBgp = document.getElementById('badge-bgp-count');
  457. if (bBgp) bBgp.innerText = (state.bgpPeers || []).length;
  458. const bOspf = document.getElementById('badge-ospf-count');
  459. if (bOspf) bOspf.innerText = (state.ospfInterfaces || []).length;
  460. const bFilters = document.getElementById('badge-filters-count');
  461. if (bFilters) bFilters.innerText = (state.routingFilters || []).length;
  462. }
  463. const bDhcpServer = document.getElementById('badge-dhcp-server-count');
  464. if (bDhcpServer) {
  465. bDhcpServer.innerText = state.dhcpServerSummary ? (state.dhcpServerSummary.active_leases || state.dhcpServerSummary.total_servers || 0) : (state.dhcpServers || []).length;
  466. }
  467. }
  468. // Render Dashboard View
  469. function renderDashboard() {
  470. const matrix = document.getElementById('port-matrix');
  471. matrix.innerHTML = '';
  472. (state.interfaces || []).forEach(iface => {
  473. const isUp = iface.state === 'UP';
  474. const isVlan = iface.is_vlan;
  475. const portCard = document.createElement('div');
  476. portCard.className = `p-3 rounded-xl border transition-all cursor-pointer select-none group ${
  477. isUp
  478. ? (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')
  479. : 'bg-slate-900/40 border-slate-800/60 opacity-60 hover:opacity-100 hover:border-slate-700'
  480. }`;
  481. portCard.onclick = () => openIfaceModal(iface.name);
  482. let statusPillClass = isUp ? 'bg-emerald-500 shadow-sm shadow-emerald-500/50' : 'bg-rose-500';
  483. if (isVlan) statusPillClass = isUp ? 'bg-cyan-400 shadow-sm shadow-cyan-400/50' : 'bg-rose-500';
  484. portCard.innerHTML = `
  485. <div class="flex items-center justify-between mb-2">
  486. <span class="font-bold text-xs font-mono text-white group-hover:text-brand-400 transition truncate">${iface.name}</span>
  487. <span class="w-2 h-2 rounded-full ${statusPillClass}"></span>
  488. </div>
  489. <div class="text-[11px] font-mono text-slate-300 truncate">${iface.ipv4 && iface.ipv4.length > 0 ? iface.ipv4[0] : (iface.mac || 'No IP')}</div>
  490. <div class="mt-2 flex items-center justify-between text-[10px] text-slate-400">
  491. <span class="uppercase tracking-wider font-semibold">${isVlan ? `VLAN ${iface.vlan_id}` : iface.type}</span>
  492. <span>${iface.rate?.rx_human || '0 B/s'}</span>
  493. </div>
  494. `;
  495. matrix.appendChild(portCard);
  496. });
  497. const ifaceTbody = document.getElementById('quick-interfaces-table');
  498. if (ifaceTbody) {
  499. ifaceTbody.innerHTML = '';
  500. (state.interfaces || []).forEach(i => {
  501. const isUp = i.state === 'UP';
  502. const tr = document.createElement('tr');
  503. tr.className = 'hover:bg-slate-800/40 transition cursor-pointer';
  504. tr.onclick = () => openIfaceModal(i.name);
  505. const rxStr = i.rate?.rx_human || '0 B/s';
  506. const txStr = i.rate?.tx_human || '0 B/s';
  507. tr.innerHTML = `
  508. <td class="py-2.5 font-bold text-white flex items-center gap-2">
  509. <span class="w-2 h-2 rounded-full ${isUp ? 'bg-emerald-400 shadow-sm shadow-emerald-400/50' : 'bg-rose-400'}"></span>
  510. <span>${i.name}</span>
  511. </td>
  512. <td class="py-2.5 text-slate-300 font-sans">
  513. <span class="px-2 py-0.5 rounded text-[10px] bg-slate-800 text-slate-300 font-medium">${i.role || i.type || 'Ethernet'}</span>
  514. </td>
  515. <td class="py-2.5 text-slate-400 text-[11px] font-mono">${i.mac || '-'}</td>
  516. <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>
  517. <td class="py-2.5 text-slate-300 text-[11px] font-mono">
  518. <span class="text-emerald-400">↓ ${rxStr}</span> <span class="text-slate-600">•</span> <span class="text-cyan-400">↑ ${txStr}</span>
  519. </td>
  520. <td class="py-2.5 text-right font-sans font-semibold">
  521. <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>
  522. </td>
  523. `;
  524. ifaceTbody.appendChild(tr);
  525. });
  526. }
  527. const vlanTbody = document.getElementById('quick-vlans-table');
  528. if (vlanTbody) {
  529. vlanTbody.innerHTML = '';
  530. }
  531. }
  532. // Expand / Collapse Handlers
  533. function toggleExpand(parentName) {
  534. if (state.expandedParents.has(parentName)) {
  535. state.expandedParents.delete(parentName);
  536. } else {
  537. state.expandedParents.add(parentName);
  538. }
  539. renderInterfacesList();
  540. }
  541. // VLAN Support Checker: 802.1Q sub-interfaces are only supported on physical ethernet, veth, bridge, bond
  542. function supportsVLAN(iface) {
  543. if (!iface) return false;
  544. if (iface.is_vlan) return false;
  545. const name = (iface.name || '').toLowerCase();
  546. const type = (iface.type || '').toLowerCase();
  547. const role = (iface.role || '').toLowerCase();
  548. // Exclude loopback
  549. if (name === 'lo' || type === 'loopback' || role === 'loopback') return false;
  550. // Exclude WireGuard (Layer 3 tunnel, no 802.1Q support)
  551. if (type === 'wireguard' || name.startsWith('wg')) return false;
  552. // Exclude PPP / PPPoE
  553. if (type === 'ppp' || name.startsWith('ppp')) return false;
  554. // Exclude other Layer 3 tunnels and dummy devices
  555. if (type === 'dummy' || type === 'gre' || type === 'sit' || type === 'tun' || type === 'tap' ||
  556. name.startsWith('gre') || name.startsWith('sit') || name.startsWith('ipsec') || name.startsWith('xfrm') || name.startsWith('dummy')) {
  557. return false;
  558. }
  559. // If name already contains a dot, it's already a sub-interface
  560. if (name.includes('.')) return false;
  561. return true;
  562. }
  563. // Expand / Collapse Handlers
  564. function toggleExpand(parentName) {
  565. const childVlans = (state.vlans || []).filter(v => v.parent_name === parentName || v.name.startsWith(parentName + '.'));
  566. if (childVlans.length === 0) {
  567. // Cannot expand an interface with no VLANs
  568. state.expandedParents.delete(parentName);
  569. return;
  570. }
  571. if (state.expandedParents.has(parentName)) {
  572. state.expandedParents.delete(parentName);
  573. } else {
  574. state.expandedParents.add(parentName);
  575. }
  576. renderInterfacesList();
  577. }
  578. function expandAllIfaces(expand) {
  579. if (expand) {
  580. (state.interfaces || []).forEach(i => {
  581. const hasVlans = (state.vlans || []).some(v => v.parent_name === i.name || v.name.startsWith(i.name + '.'));
  582. if (!i.is_vlan && hasVlans) state.expandedParents.add(i.name);
  583. });
  584. } else {
  585. state.expandedParents.clear();
  586. }
  587. renderInterfacesList();
  588. }
  589. // Filter and Render Hierarchical Interfaces List
  590. function filterIfaces(filter) {
  591. state.ifaceFilter = filter || 'all';
  592. renderInterfacesList();
  593. }
  594. function renderInterfacesList() {
  595. const tbody = document.getElementById('interfaces-tree-tbody');
  596. const emptyState = document.getElementById('interfaces-empty-state');
  597. const summary = document.getElementById('ifaces-list-summary');
  598. const query = (document.getElementById('iface-search')?.value || '').trim().toLowerCase();
  599. tbody.innerHTML = '';
  600. const allIfaces = state.interfaces || [];
  601. const allVlans = state.vlans || [];
  602. const parentIfaces = allIfaces.filter(i => !i.is_vlan);
  603. const filteredParents = parentIfaces.filter(parent => {
  604. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  605. if (query) {
  606. const matchName = parent.name.toLowerCase().includes(query);
  607. const matchIp = (parent.ipv4 || []).some(ip => ip.toLowerCase().includes(query));
  608. const matchRole = (parent.role || '').toLowerCase().includes(query);
  609. const matchType = (parent.type || '').toLowerCase().includes(query);
  610. const matchVlan = childVlans.some(v =>
  611. v.name.toLowerCase().includes(query) ||
  612. String(v.vlan_id).includes(query) ||
  613. (v.ipv4 || []).some(ip => ip.toLowerCase().includes(query)) ||
  614. (v.description || '').toLowerCase().includes(query)
  615. );
  616. if (!matchName && !matchIp && !matchRole && !matchType && !matchVlan) return false;
  617. }
  618. if (state.ifaceFilter === 'has_vlans') return childVlans.length > 0;
  619. if (state.ifaceFilter === 'physical') return parent.type !== 'loopback';
  620. if (state.ifaceFilter === 'up') return parent.state === 'UP';
  621. return true;
  622. });
  623. if (summary) {
  624. summary.innerText = `${parentIfaces.length} Interfaces • ${allVlans.length} Active VLANs`;
  625. }
  626. if (filteredParents.length === 0) {
  627. emptyState?.classList.remove('hidden');
  628. return;
  629. }
  630. emptyState?.classList.add('hidden');
  631. filteredParents.forEach(parent => {
  632. const isUp = parent.state === 'UP';
  633. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  634. const hasVlans = childVlans.length > 0;
  635. const isExpanded = hasVlans && state.expandedParents.has(parent.name);
  636. const canHaveVlan = supportsVLAN(parent);
  637. const parentRow = document.createElement('tr');
  638. parentRow.className = `hover:bg-slate-800/50 transition border-b border-slate-800/80 ${isExpanded ? 'bg-slate-900/80' : ''}`;
  639. parentRow.innerHTML = `
  640. <td class="py-3 px-3 text-center">
  641. ${hasVlans ? `
  642. <button onclick="toggleExpand('${parent.name}')" title="${isExpanded ? 'Collapse VLANs' : 'Expand VLANs'}"
  643. class="w-6 h-6 rounded flex items-center justify-center hover:bg-slate-800 text-slate-400 hover:text-white transition">
  644. <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">
  645. <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M9 5l7 7-7 7" />
  646. </svg>
  647. </button>
  648. ` : `
  649. <div class="w-6 h-6 flex items-center justify-center text-slate-700 select-none">
  650. <span class="w-1.5 h-1.5 rounded-full bg-slate-800"></span>
  651. </div>
  652. `}
  653. </td>
  654. <td class="py-3 px-4">
  655. <div class="flex items-center space-x-2.5">
  656. <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">
  657. ${parent.type === 'loopback' ? 'LO' : (parent.type === 'wireguard' ? 'WG' : (parent.type === 'bridge' ? 'BR' : 'NIC'))}
  658. </div>
  659. <div>
  660. <div class="flex items-center gap-2">
  661. <span class="font-bold text-white text-sm cursor-pointer hover:text-cyan-400 flex items-center gap-1.5" onclick="${hasVlans ? `toggleExpand('${parent.name}')` : `openIfaceModal('${parent.name}')`}" title="${hasVlans ? 'Click to expand VLANs, or click pencil to rename' : 'Click to configure or rename interface'}">
  662. <span>${parent.name}</span>
  663. <svg onclick="event.stopPropagation(); openIfaceModal('${parent.name}')" class="w-3.5 h-3.5 text-slate-500 hover:text-cyan-400 opacity-60 hover:opacity-100 cursor-pointer" title="Configure / Rename ${parent.name}" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"/></svg>
  664. </span>
  665. ${hasVlans ? `
  666. <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>
  667. ` : `
  668. <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>
  669. `}
  670. </div>
  671. <div class="text-[10px] text-slate-500 font-sans mt-0.5">${parent.type}</div>
  672. </div>
  673. </div>
  674. </td>
  675. <td class="py-3 px-4 font-sans">
  676. <div class="flex items-center gap-1.5">
  677. <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>
  678. <span class="text-xs text-slate-400 truncate max-w-[120px]">${parent.description || '-'}</span>
  679. </div>
  680. </td>
  681. <td class="py-3 px-4">
  682. ${parent.ipv4 && parent.ipv4.length > 0
  683. ? `<div class="text-white font-medium">${parent.ipv4[0]}</div>`
  684. : '<span class="text-slate-600 font-sans">Unassigned</span>'
  685. }
  686. ${(() => {
  687. const c = (state.dhcpClients || []).find(dc => dc.interface === parent.name);
  688. if (!c) return '';
  689. 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');
  690. 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>`;
  691. })()}
  692. </td>
  693. <td class="py-3 px-4 text-slate-400 text-[11px]">
  694. <div>${parent.mac || 'N/A'}</div>
  695. <div class="text-[10px] text-slate-500">MTU ${parent.mtu}</div>
  696. </td>
  697. <td class="py-3 px-4 text-[11px]">
  698. <div class="flex items-center space-x-2">
  699. <span class="text-emerald-400">↓ ${parent.rate?.rx_human || '0 B/s'}</span>
  700. <span class="text-cyan-400">↑ ${parent.rate?.tx_human || '0 B/s'}</span>
  701. </div>
  702. </td>
  703. <td class="py-3 px-4 font-sans">
  704. <button onclick="toggleInterfaceState('${parent.name}', '${isUp ? 'down' : 'up'}')"
  705. class="flex items-center gap-1.5 text-xs font-semibold px-2.5 py-1 rounded-full transition ${
  706. 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'
  707. }" title="Click to toggle link status">
  708. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  709. <span>${parent.state}</span>
  710. </button>
  711. </td>
  712. <td class="py-3 px-4 text-right space-x-2 font-sans">
  713. ${(() => {
  714. const c = (state.dhcpClients || []).find(dc => dc.interface === parent.name);
  715. if (c) {
  716. 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>`;
  717. }
  718. 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>`;
  719. })()}
  720. ${canHaveVlan ? `
  721. <button onclick="openVlanModal('${parent.name}')"
  722. 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">
  723. + Add VLAN
  724. </button>
  725. ` : ''}
  726. <button onclick="openIfaceModal('${parent.name}')"
  727. 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">
  728. Configure
  729. </button>
  730. </td>
  731. `;
  732. tbody.appendChild(parentRow);
  733. if (isExpanded) {
  734. const drawerRow = document.createElement('tr');
  735. drawerRow.className = 'bg-slate-950/80 border-b border-slate-800/90';
  736. const drawerCell = document.createElement('td');
  737. drawerCell.colSpan = 8;
  738. drawerCell.className = 'p-0';
  739. drawerCell.innerHTML = `
  740. <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">
  741. <div class="flex items-center justify-between mb-3">
  742. <div class="flex items-center space-x-3">
  743. <span class="font-bold text-xs text-white uppercase tracking-wider flex items-center gap-1.5 font-sans">
  744. <span>VLAN Sub-interfaces on <code class="text-cyan-300 lowercase">${parent.name}</code></span>
  745. </span>
  746. <span class="text-[11px] bg-cyan-950 text-cyan-400 px-2 py-0.5 rounded-full border border-cyan-800/60 font-mono">
  747. ${childVlans.length} Attached
  748. </span>
  749. </div>
  750. <button onclick="openVlanModal('${parent.name}')"
  751. 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">
  752. <span>+ Create VLAN on ${parent.name}</span>
  753. </button>
  754. </div>
  755. ${childVlans.length === 0 ? `
  756. <div class="p-6 text-center border border-dashed border-slate-800 rounded-xl bg-slate-900/40 font-sans">
  757. <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>
  758. <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">
  759. <span>+ Create Your First VLAN on ${parent.name}</span>
  760. </button>
  761. </div>
  762. ` : `
  763. <div class="overflow-x-auto rounded-lg border border-slate-800 bg-slate-900/90 shadow-inner">
  764. <table class="w-full text-left text-xs font-mono">
  765. <thead class="text-slate-400 bg-slate-950/70 border-b border-slate-800 uppercase tracking-wider text-[10px] font-sans">
  766. <tr>
  767. <th class="py-2.5 px-4">VLAN ID</th>
  768. <th class="py-2.5 px-4">Interface Device</th>
  769. <th class="py-2.5 px-4">Subnet Gateway</th>
  770. <th class="py-2.5 px-4">Role / Alias</th>
  771. <th class="py-2.5 px-4">MTU</th>
  772. <th class="py-2.5 px-4">Throughput</th>
  773. <th class="py-2.5 px-4">Status</th>
  774. <th class="py-2.5 px-4 text-right">Actions</th>
  775. </tr>
  776. </thead>
  777. <tbody class="divide-y divide-slate-800/70">
  778. ${childVlans.map(v => {
  779. const isVlanUp = v.state === 'UP';
  780. return `
  781. <tr class="hover:bg-slate-800/40 transition">
  782. <td class="py-2.5 px-4">
  783. <span class="px-2 py-0.5 rounded text-xs font-bold bg-cyan-950 text-cyan-300 border border-cyan-800 shadow-sm">
  784. VLAN ${v.vlan_id}
  785. </span>
  786. </td>
  787. <td class="py-2.5 px-4 font-bold text-white flex items-center gap-1.5">
  788. <span class="text-cyan-500">└─</span>
  789. <span class="cursor-pointer hover:text-cyan-400 flex items-center gap-1" onclick="openIfaceModal('${v.name}')" title="Configure / Rename ${v.name}">
  790. <span>${v.name}</span>
  791. <svg class="w-3 h-3 text-slate-500 hover:text-cyan-400 opacity-60 hover:opacity-100" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"/></svg>
  792. </span>
  793. </td>
  794. <td class="py-2.5 px-4 text-emerald-400 font-medium">
  795. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  796. ${(() => {
  797. const c = (state.dhcpClients || []).find(dc => dc.interface === v.name);
  798. if (!c) return '';
  799. 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';
  800. 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>`;
  801. })()}
  802. </td>
  803. <td class="py-2.5 px-4 font-sans text-slate-300">
  804. <span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 text-slate-300 mr-1.5">${v.role || 'VLAN'}</span>
  805. <span class="text-slate-400 text-xs">${v.description || '-'}</span>
  806. </td>
  807. <td class="py-2.5 px-4 text-slate-400">${v.mtu}</td>
  808. <td class="py-2.5 px-4 text-[11px]">
  809. <span class="text-emerald-400">↓ ${v.rate?.rx_human || '0 B/s'}</span>
  810. <span class="text-cyan-400 ml-1.5">↑ ${v.rate?.tx_human || '0 B/s'}</span>
  811. </td>
  812. <td class="py-2.5 px-4 font-sans">
  813. <button onclick="toggleInterfaceState('${v.name}', '${isVlanUp ? 'down' : 'up'}')"
  814. class="flex items-center gap-1 text-[11px] font-semibold px-2 py-0.5 rounded-full ${
  815. 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'
  816. }">
  817. <span class="w-1.5 h-1.5 rounded-full ${isVlanUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  818. <span>${v.state}</span>
  819. </button>
  820. </td>
  821. <td class="py-2.5 px-4 text-right space-x-1.5 font-sans">
  822. ${(() => {
  823. const c = (state.dhcpClients || []).find(dc => dc.interface === v.name);
  824. if (c) {
  825. 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>`;
  826. }
  827. 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>`;
  828. })()}
  829. <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>
  830. <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>
  831. </td>
  832. </tr>
  833. `;
  834. }).join('')}
  835. </tbody>
  836. </table>
  837. </div>
  838. `}
  839. </div>
  840. `;
  841. drawerRow.appendChild(drawerCell);
  842. tbody.appendChild(drawerRow);
  843. }
  844. });
  845. }
  846. // Render VLANs Dedicated View
  847. function renderVlansList() {
  848. const tbody = document.getElementById('vlans-table-body');
  849. if (!tbody) return;
  850. const emptyState = document.getElementById('vlans-empty-state');
  851. const countBadge = document.getElementById('vlans-table-count');
  852. const query = (document.getElementById('vlan-search')?.value || '').toLowerCase();
  853. tbody.innerHTML = '';
  854. const allVlans = state.vlans || [];
  855. if (countBadge) countBadge.innerText = allVlans.length;
  856. const filtered = allVlans.filter(v => {
  857. if (!query) return true;
  858. return v.name.toLowerCase().includes(query) ||
  859. String(v.vlan_id).includes(query) ||
  860. (v.description || '').toLowerCase().includes(query) ||
  861. (v.ipv4 && v.ipv4.some(ip => ip.includes(query)));
  862. });
  863. if (allVlans.length === 0) {
  864. emptyState.classList.remove('hidden');
  865. return;
  866. }
  867. emptyState.classList.add('hidden');
  868. filtered.forEach(v => {
  869. const isUp = v.state === 'UP';
  870. const tr = document.createElement('tr');
  871. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  872. tr.innerHTML = `
  873. <td class="py-3 px-4">
  874. <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">
  875. VLAN ${v.vlan_id}
  876. </span>
  877. </td>
  878. <td class="py-3 px-4 font-bold text-white">
  879. <span class="cursor-pointer hover:text-cyan-400 flex items-center gap-1.5" onclick="openIfaceModal('${v.name}')" title="Configure / Rename ${v.name}">
  880. <span>${v.name}</span>
  881. <svg class="w-3.5 h-3.5 text-slate-500 hover:text-cyan-400 opacity-60 hover:opacity-100" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"/></svg>
  882. </span>
  883. </td>
  884. <td class="py-3 px-4 text-slate-300">
  885. <span class="bg-slate-800 text-slate-200 px-2 py-0.5 rounded text-[11px]">${v.parent_name || 'eth0'}</span>
  886. </td>
  887. <td class="py-3 px-4 text-emerald-400 font-medium">
  888. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  889. </td>
  890. <td class="py-3 px-4 text-slate-300 font-sans">
  891. <span class="text-slate-400 text-xs">${v.description || v.role || '-'}</span>
  892. </td>
  893. <td class="py-3 px-4 text-slate-400">${v.mtu}</td>
  894. <td class="py-3 px-4 font-sans">
  895. <button onclick="toggleInterfaceState('${v.name}', '${isUp ? 'down' : 'up'}')"
  896. class="flex items-center gap-1.5 text-xs font-semibold px-2 py-0.5 rounded-full ${
  897. 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'
  898. }">
  899. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  900. <span>${v.state}</span>
  901. </button>
  902. </td>
  903. <td class="py-3 px-4 text-right space-x-2 font-sans">
  904. <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>
  905. <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>
  906. </td>
  907. `;
  908. tbody.appendChild(tr);
  909. });
  910. }
  911. // Toggle interface UP / DOWN
  912. async function toggleInterfaceState(name, newState) {
  913. try {
  914. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(name)}/state`, {
  915. method: 'POST',
  916. headers: { 'Content-Type': 'application/json' },
  917. body: JSON.stringify({ state: newState })
  918. });
  919. const data = await res.json();
  920. if (res.ok) {
  921. showToast('Interface Updated', `Interface ${name} is now ${newState.toUpperCase()}`, 'success');
  922. fetchData(false);
  923. } else {
  924. showToast('Error', data.message || 'Failed to toggle interface state', 'error');
  925. }
  926. } catch (err) {
  927. showToast('Error', err.message, 'error');
  928. }
  929. }
  930. // ---------------- MikroTik Flag & Utilities ----------------
  931. function renderMikroTikFlag(running, disabled) {
  932. if (running) {
  933. 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>`;
  934. }
  935. if (disabled) {
  936. 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>`;
  937. }
  938. 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>`;
  939. }
  940. function copyToClipboard(text, label = 'Text') {
  941. navigator.clipboard.writeText(text).then(() => {
  942. showToast('Copied', `${label} copied to clipboard`, 'success');
  943. }).catch(() => {
  944. prompt('Copy value:', text);
  945. });
  946. }
  947. // ======================== PPP Profiles Shared Helper ========================
  948. async function fetchPPPProfilesList() {
  949. try {
  950. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`);
  951. if (res.ok) {
  952. state.pppProfiles = await res.json();
  953. }
  954. } catch (err) {
  955. console.error('Failed to load PPP profiles:', err);
  956. }
  957. }
  958. function populateProfileSelect(selectId, selectedVal, defaultVal = 'default') {
  959. const sel = document.getElementById(selectId);
  960. if (!sel) return;
  961. const profiles = (state.pppProfiles && state.pppProfiles.length > 0) ? state.pppProfiles : [
  962. { name: 'default', use_encryption: 'no' },
  963. { name: 'default-encryption', use_encryption: 'required' }
  964. ];
  965. sel.innerHTML = '';
  966. profiles.forEach(p => {
  967. const opt = document.createElement('option');
  968. opt.value = p.name;
  969. const encBadge = p.use_encryption === 'required' ? ' (MPPE-128)' : (p.use_encryption === 'yes' ? ' (MPPE)' : '');
  970. opt.innerText = `${p.name}${encBadge}`;
  971. sel.appendChild(opt);
  972. });
  973. if (selectedVal) {
  974. sel.value = selectedVal;
  975. } else {
  976. sel.value = defaultVal;
  977. }
  978. if (!sel.value && sel.options.length > 0) {
  979. sel.selectedIndex = 0;
  980. }
  981. }
  982. // ======================== PPPoE Multi-Instance ========================
  983. async function loadPPPoE(populateInputs = true) {
  984. try {
  985. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  986. await fetchPPPProfilesList();
  987. }
  988. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`);
  989. const list = await res.json();
  990. state.pppoeList = Array.isArray(list) ? list : [];
  991. const badge = document.getElementById('pppoe-count-badge');
  992. if (badge) badge.innerText = `${state.pppoeList.length} Interface${state.pppoeList.length !== 1 ? 's' : ''}`;
  993. const tbody = document.getElementById('pppoe-table-body');
  994. const empty = document.getElementById('pppoe-empty');
  995. if (!tbody) return;
  996. tbody.innerHTML = '';
  997. if (state.pppoeList.length === 0) {
  998. if (empty) empty.classList.remove('hidden');
  999. } else {
  1000. if (empty) empty.classList.add('hidden');
  1001. state.pppoeList.forEach(inst => {
  1002. const tr = document.createElement('tr');
  1003. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1004. tr.innerHTML = `
  1005. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  1006. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  1007. <td class="py-2.5 px-3 text-cyan-400 font-mono">${escapeHtml(inst.interface)}</td>
  1008. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  1009. <td class="py-2.5 px-3 font-mono text-cyan-300"><span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 border border-slate-700">${escapeHtml(inst.profile || 'default')}</span></td>
  1010. <td class="py-2.5 px-3 font-mono ${inst.assigned_ip ? 'text-emerald-400 font-bold' : 'text-slate-500'}">${escapeHtml(inst.assigned_ip || '-')}</td>
  1011. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  1012. <td class="py-2.5 px-3 text-center">
  1013. <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'}">
  1014. ${inst.default_route ? 'Yes' : 'No'}
  1015. </span>
  1016. </td>
  1017. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  1018. ${inst.running ? `
  1019. <button onclick="disconnectPPPoEInstance('${inst.name}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  1020. ` : `
  1021. <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>
  1022. `}
  1023. <button onclick="togglePPPoEState('${inst.name}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  1024. ${inst.disabled ? 'Enable' : 'Disable'}
  1025. </button>
  1026. <button onclick="openEditPPPoEModal('${inst.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  1027. <button onclick="deletePPPoEInstance('${inst.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  1028. </td>
  1029. `;
  1030. tbody.appendChild(tr);
  1031. });
  1032. }
  1033. } catch (err) {
  1034. console.error('Failed to load PPPoE:', err);
  1035. }
  1036. }
  1037. function openAddPPPoEModal() {
  1038. document.getElementById('pppoe-modal-title').innerText = 'Add PPPoE Client Interface';
  1039. document.getElementById('pppoe-modal-edit-orig').value = '';
  1040. document.getElementById('pppoe-modal-name').value = `pppoe-out${(state.pppoeList || []).length + 1}`;
  1041. document.getElementById('pppoe-modal-name').readOnly = false;
  1042. document.getElementById('pppoe-modal-user').value = '';
  1043. document.getElementById('pppoe-modal-pass').value = '';
  1044. document.getElementById('pppoe-modal-service').value = '';
  1045. document.getElementById('pppoe-modal-mtu').value = '1492';
  1046. document.getElementById('pppoe-modal-defroute').checked = true;
  1047. document.getElementById('pppoe-modal-reconnect').checked = true;
  1048. document.getElementById('pppoe-modal-disabled').checked = false;
  1049. // Populate profiles
  1050. populateProfileSelect('pppoe-modal-profile', 'default', 'default');
  1051. // Populate interfaces
  1052. const sel = document.getElementById('pppoe-modal-iface');
  1053. sel.innerHTML = '';
  1054. (state.interfaces || []).forEach(i => {
  1055. if (i.name === 'lo') return;
  1056. const opt = document.createElement('option');
  1057. opt.value = i.name;
  1058. opt.innerText = `${i.name} (${i.role || i.type})`;
  1059. sel.appendChild(opt);
  1060. });
  1061. document.getElementById('pppoe-modal').classList.remove('hidden');
  1062. }
  1063. function openEditPPPoEModal(name) {
  1064. const inst = (state.pppoeList || []).find(i => i.name === name);
  1065. if (!inst) return;
  1066. document.getElementById('pppoe-modal-title').innerText = `Edit PPPoE Client: ${name}`;
  1067. document.getElementById('pppoe-modal-edit-orig').value = name;
  1068. document.getElementById('pppoe-modal-name').value = inst.name;
  1069. document.getElementById('pppoe-modal-name').readOnly = true;
  1070. document.getElementById('pppoe-modal-user').value = inst.username || '';
  1071. document.getElementById('pppoe-modal-pass').value = inst.password || '';
  1072. document.getElementById('pppoe-modal-service').value = inst.service_name || '';
  1073. document.getElementById('pppoe-modal-mtu').value = inst.mtu || 1492;
  1074. document.getElementById('pppoe-modal-defroute').checked = inst.default_route ?? true;
  1075. document.getElementById('pppoe-modal-reconnect').checked = inst.auto_reconnect ?? true;
  1076. document.getElementById('pppoe-modal-disabled').checked = !!inst.disabled;
  1077. // Populate profiles
  1078. populateProfileSelect('pppoe-modal-profile', inst.profile || 'default', 'default');
  1079. const sel = document.getElementById('pppoe-modal-iface');
  1080. sel.innerHTML = '';
  1081. (state.interfaces || []).forEach(i => {
  1082. if (i.name === 'lo') return;
  1083. const opt = document.createElement('option');
  1084. opt.value = i.name;
  1085. opt.innerText = `${i.name} (${i.role || i.type})`;
  1086. if (i.name === inst.interface) opt.selected = true;
  1087. sel.appendChild(opt);
  1088. });
  1089. document.getElementById('pppoe-modal').classList.remove('hidden');
  1090. }
  1091. function closePPPoEModal() {
  1092. document.getElementById('pppoe-modal').classList.add('hidden');
  1093. }
  1094. async function submitSavePPPoE(e) {
  1095. e.preventDefault();
  1096. const name = document.getElementById('pppoe-modal-name').value.trim();
  1097. const iface = document.getElementById('pppoe-modal-iface').value;
  1098. const user = document.getElementById('pppoe-modal-user').value.trim();
  1099. const pass = document.getElementById('pppoe-modal-pass').value;
  1100. const profile = document.getElementById('pppoe-modal-profile')?.value || 'default';
  1101. const service = document.getElementById('pppoe-modal-service').value.trim();
  1102. const mtu = parseInt(document.getElementById('pppoe-modal-mtu').value, 10) || 1492;
  1103. const defRoute = document.getElementById('pppoe-modal-defroute').checked;
  1104. const reconnect = document.getElementById('pppoe-modal-reconnect').checked;
  1105. const disabled = document.getElementById('pppoe-modal-disabled').checked;
  1106. try {
  1107. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`, {
  1108. method: 'POST',
  1109. headers: { 'Content-Type': 'application/json' },
  1110. body: JSON.stringify({
  1111. name,
  1112. interface: iface,
  1113. username: user,
  1114. password: pass,
  1115. profile: profile,
  1116. service_name: service,
  1117. mtu,
  1118. default_route: defRoute,
  1119. auto_reconnect: reconnect,
  1120. disabled
  1121. })
  1122. });
  1123. if (res.ok) {
  1124. showToast('PPPoE Saved', `Configuration for ${name} saved`, 'success');
  1125. closePPPoEModal();
  1126. loadPPPoE(false);
  1127. fetchData(false);
  1128. } else {
  1129. const err = await res.json();
  1130. showToast('Error', err.message || 'Failed to save PPPoE', 'error');
  1131. }
  1132. } catch (err) {
  1133. showToast('Error', err.message, 'error');
  1134. }
  1135. }
  1136. async function connectPPPoEInstance(name) {
  1137. try {
  1138. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  1139. if (res.ok) {
  1140. showToast('Connecting', `Dialing ${name}...`, 'info');
  1141. setTimeout(() => loadPPPoE(false), 2000);
  1142. }
  1143. } catch (err) {
  1144. showToast('Error', err.message, 'error');
  1145. }
  1146. }
  1147. async function disconnectPPPoEInstance(name) {
  1148. try {
  1149. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  1150. if (res.ok) {
  1151. showToast('Disconnected', `${name} session terminated`, 'info');
  1152. setTimeout(() => loadPPPoE(false), 1000);
  1153. }
  1154. } catch (err) {
  1155. showToast('Error', err.message, 'error');
  1156. }
  1157. }
  1158. async function togglePPPoEState(name, enable) {
  1159. try {
  1160. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/state`, {
  1161. method: 'POST',
  1162. headers: { 'Content-Type': 'application/json' },
  1163. body: JSON.stringify({ enabled: enable })
  1164. });
  1165. if (res.ok) {
  1166. showToast(enable ? 'Enabled' : 'Disabled', `${name} is now ${enable ? 'enabled' : 'disabled'}`, 'info');
  1167. loadPPPoE(false);
  1168. }
  1169. } catch (err) {
  1170. showToast('Error', err.message, 'error');
  1171. }
  1172. }
  1173. async function deletePPPoEInstance(name) {
  1174. if (!confirm(`Are you sure you want to delete PPPoE client ${name}?`)) return;
  1175. try {
  1176. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1177. if (res.ok) {
  1178. showToast('Deleted', `PPPoE client ${name} removed`, 'success');
  1179. loadPPPoE(false);
  1180. fetchData(false);
  1181. }
  1182. } catch (err) {
  1183. showToast('Error', err.message, 'error');
  1184. }
  1185. }
  1186. // ======================== WireGuard Multi-Interface & Multi-Peer ========================
  1187. state.wgSubTab = 'ifaces';
  1188. function switchWGSubTab(tab) {
  1189. state.wgSubTab = tab;
  1190. const ifacesPanel = document.getElementById('wg-subtab-ifaces');
  1191. const peersPanel = document.getElementById('wg-subtab-peers');
  1192. const ifacesBtn = document.getElementById('wg-subtab-btn-ifaces');
  1193. const peersBtn = document.getElementById('wg-subtab-btn-peers');
  1194. if (tab === 'ifaces') {
  1195. ifacesPanel?.classList.remove('hidden');
  1196. peersPanel?.classList.add('hidden');
  1197. 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';
  1198. 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';
  1199. } else {
  1200. ifacesPanel?.classList.add('hidden');
  1201. peersPanel?.classList.remove('hidden');
  1202. 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';
  1203. 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';
  1204. renderWGPeers();
  1205. }
  1206. }
  1207. async function loadWireGuard(populateInputs = true) {
  1208. try {
  1209. const [ifacesRes, peersRes] = await Promise.all([
  1210. fetch(`${API_BASE}/vpn/wireguard/interfaces`),
  1211. fetch(`${API_BASE}/vpn/wireguard/peers`)
  1212. ]);
  1213. const ifaces = ifacesRes.ok ? await ifacesRes.json() : [];
  1214. const peers = peersRes.ok ? await peersRes.json() : [];
  1215. state.wgInterfaces = Array.isArray(ifaces) ? ifaces : [];
  1216. state.wgPeers = Array.isArray(peers) ? peers : [];
  1217. // Badges
  1218. const ifacesCountBadge = document.getElementById('wg-ifaces-count');
  1219. if (ifacesCountBadge) ifacesCountBadge.innerText = `${state.wgInterfaces.length} Interfaces`;
  1220. const peersCountBadge = document.getElementById('wg-peers-count');
  1221. if (peersCountBadge) peersCountBadge.innerText = `${state.wgPeers.length} Peers`;
  1222. const subTabIfaces = document.getElementById('wg-subtab-badge-ifaces');
  1223. if (subTabIfaces) subTabIfaces.innerText = state.wgInterfaces.length;
  1224. const subTabPeers = document.getElementById('wg-subtab-badge-peers');
  1225. if (subTabPeers) subTabPeers.innerText = state.wgPeers.length;
  1226. // Render Interfaces
  1227. const ifacesTbody = document.getElementById('wg-ifaces-table-body');
  1228. const ifacesEmpty = document.getElementById('wg-ifaces-empty');
  1229. if (ifacesTbody) {
  1230. ifacesTbody.innerHTML = '';
  1231. if (state.wgInterfaces.length === 0) {
  1232. if (ifacesEmpty) ifacesEmpty.classList.remove('hidden');
  1233. } else {
  1234. if (ifacesEmpty) ifacesEmpty.classList.add('hidden');
  1235. state.wgInterfaces.forEach(iface => {
  1236. const peersOnIface = state.wgPeers.filter(p => p.interface === iface.name).length;
  1237. const tr = document.createElement('tr');
  1238. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1239. tr.innerHTML = `
  1240. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(iface.running, iface.disabled)}</td>
  1241. <td class="py-2.5 px-3">
  1242. <div class="flex items-center gap-1.5">
  1243. <span class="font-bold text-white">${escapeHtml(iface.name)}</span>
  1244. ${iface.comment ? `<span class="text-[10px] text-slate-400 font-sans italic">(${escapeHtml(iface.comment)})</span>` : ''}
  1245. </div>
  1246. </td>
  1247. <td class="py-2.5 px-3 text-amber-400 font-mono">${iface.listen_port}</td>
  1248. <td class="py-2.5 px-3 text-emerald-400 font-mono">${iface.address || '<span class="text-slate-600 font-sans">--</span>'}</td>
  1249. <td class="py-2.5 px-3 text-slate-300 font-mono">
  1250. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${iface.public_key}', 'Public Key')" title="Click to copy: ${iface.public_key}">
  1251. ${(iface.public_key || '').substring(0, 10)}... 📋
  1252. </span>
  1253. </td>
  1254. <td class="py-2.5 px-3 text-slate-400 font-mono">${iface.mtu || 1420}</td>
  1255. <td class="py-2.5 px-3 text-center">
  1256. <span class="px-2 py-0.5 rounded text-[10px] font-sans bg-slate-800 text-slate-300">${peersOnIface} peer${peersOnIface !== 1 ? 's' : ''}</span>
  1257. </td>
  1258. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  1259. ${iface.running ? `
  1260. <button onclick="stopWGInterface('${iface.name}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Stop</button>
  1261. ` : `
  1262. <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>
  1263. `}
  1264. <button onclick="toggleWGInterfaceState('${iface.name}', ${iface.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white font-medium">
  1265. ${iface.disabled ? 'Enable' : 'Disable'}
  1266. </button>
  1267. <button onclick="openEditWGInterfaceModal('${iface.name}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Edit</button>
  1268. <button onclick="deleteWGInterface('${iface.name}')" class="text-xs text-slate-500 hover:text-rose-400 font-medium">Delete</button>
  1269. </td>
  1270. `;
  1271. ifacesTbody.appendChild(tr);
  1272. });
  1273. }
  1274. }
  1275. // Populate filter dropdown in peers tab
  1276. const filterSel = document.getElementById('wg-peers-filter-iface');
  1277. if (filterSel) {
  1278. const currentVal = filterSel.value;
  1279. filterSel.innerHTML = '<option value="">All Interfaces</option>';
  1280. state.wgInterfaces.forEach(i => {
  1281. const opt = document.createElement('option');
  1282. opt.value = i.name;
  1283. opt.innerText = i.name;
  1284. if (i.name === currentVal) opt.selected = true;
  1285. filterSel.appendChild(opt);
  1286. });
  1287. }
  1288. renderWGPeers();
  1289. } catch (err) {
  1290. console.error('Failed to load WireGuard:', err);
  1291. }
  1292. }
  1293. function formatWGPeerEndpoint(address, port) {
  1294. if (!address || address === '(none)') return '--';
  1295. let addr = address.trim();
  1296. let p = port || 0;
  1297. while (addr.includes(':') && !addr.startsWith('[')) {
  1298. const lastColon = addr.lastIndexOf(':');
  1299. const maybePort = addr.substring(lastColon + 1);
  1300. if (!isNaN(parseInt(maybePort, 10)) && parseInt(maybePort, 10) > 0) {
  1301. if (!p) p = parseInt(maybePort, 10);
  1302. addr = addr.substring(0, lastColon);
  1303. } else {
  1304. break;
  1305. }
  1306. }
  1307. return p ? `${addr}:${p}` : addr;
  1308. }
  1309. function renderWGPeers() {
  1310. const filterSel = document.getElementById('wg-peers-filter-iface');
  1311. const selectedIface = filterSel ? filterSel.value : '';
  1312. const tbody = document.getElementById('wg-peers-table-body');
  1313. const empty = document.getElementById('wg-peers-empty');
  1314. if (!tbody) return;
  1315. tbody.innerHTML = '';
  1316. const filtered = selectedIface ? state.wgPeers.filter(p => p.interface === selectedIface) : state.wgPeers;
  1317. if (filtered.length === 0) {
  1318. if (empty) empty.classList.remove('hidden');
  1319. } else {
  1320. if (empty) empty.classList.add('hidden');
  1321. filtered.forEach(p => {
  1322. const isOnline = p.latest_handshake && !p.latest_handshake.includes('Never');
  1323. const tr = document.createElement('tr');
  1324. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1325. tr.innerHTML = `
  1326. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(isOnline, p.disabled)}</td>
  1327. <td class="py-2.5 px-3 font-mono font-bold text-rose-400">${escapeHtml(p.interface)}</td>
  1328. <td class="py-2.5 px-3 font-bold text-white font-sans">${escapeHtml(p.name || 'Unnamed')}</td>
  1329. <td class="py-2.5 px-3 text-slate-300 font-mono">
  1330. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${p.public_key}', 'Peer Public Key')" title="${p.public_key}">
  1331. ${(p.public_key || '').substring(0, 10)}... 📋
  1332. </span>
  1333. </td>
  1334. <td class="py-2.5 px-3 text-emerald-400 font-mono font-semibold">${(p.allowed_ips || []).join(', ')}</td>
  1335. <td class="py-2.5 px-3 text-slate-400 font-mono">${formatWGPeerEndpoint(p.endpoint_address, p.endpoint_port)}</td>
  1336. <td class="py-2.5 px-3 text-slate-300 font-sans">${p.latest_handshake || 'Never'}</td>
  1337. <td class="py-2.5 px-3 font-mono text-[11px]">
  1338. <span class="text-emerald-400">↓ ${p.transfer_rx_human || '0 B'}</span>
  1339. <span class="text-cyan-400 ml-1">↑ ${p.transfer_tx_human || '0 B'}</span>
  1340. </td>
  1341. <td class="py-2.5 px-3 text-right font-sans space-x-2 whitespace-nowrap">
  1342. <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">
  1343. ${p.disabled ? 'Enable' : 'Disable'}
  1344. </button>
  1345. <button onclick="openEditWGPeerModal('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Edit</button>
  1346. <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>
  1347. <button onclick="deleteWGPeer('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Delete</button>
  1348. </td>
  1349. `;
  1350. tbody.appendChild(tr);
  1351. });
  1352. }
  1353. }
  1354. function openAddWGInterfaceModal() {
  1355. document.getElementById('wg-iface-modal-title').innerText = 'Add WireGuard Interface';
  1356. document.getElementById('wg-iface-modal-edit-orig').value = '';
  1357. const nameEl = document.getElementById('wg-iface-modal-name');
  1358. nameEl.value = `wg${(state.wgInterfaces || []).length}`;
  1359. nameEl.readOnly = false;
  1360. document.getElementById('wg-iface-modal-port').value = 51820 + (state.wgInterfaces || []).length;
  1361. document.getElementById('wg-iface-modal-addr').value = `10.${10 + (state.wgInterfaces || []).length}.0.1/24`;
  1362. document.getElementById('wg-iface-modal-mtu').value = '1420';
  1363. document.getElementById('wg-iface-modal-comment').value = '';
  1364. document.getElementById('wg-iface-modal-pubkey').value = '';
  1365. document.getElementById('wg-iface-modal-privkey').value = '';
  1366. document.getElementById('wg-iface-modal-disabled').checked = false;
  1367. generateWGInterfaceKeys();
  1368. document.getElementById('wg-iface-modal').classList.remove('hidden');
  1369. }
  1370. function openEditWGInterfaceModal(name) {
  1371. const iface = (state.wgInterfaces || []).find(i => i.name === name);
  1372. if (!iface) return;
  1373. document.getElementById('wg-iface-modal-title').innerText = `Edit WireGuard Interface: ${name}`;
  1374. document.getElementById('wg-iface-modal-edit-orig').value = name;
  1375. const nameEl = document.getElementById('wg-iface-modal-name');
  1376. nameEl.value = iface.name;
  1377. nameEl.readOnly = false; // ALLOW RENAMING
  1378. document.getElementById('wg-iface-modal-port').value = iface.listen_port || 51820;
  1379. document.getElementById('wg-iface-modal-addr').value = iface.address || '';
  1380. document.getElementById('wg-iface-modal-mtu').value = iface.mtu || 1420;
  1381. document.getElementById('wg-iface-modal-comment').value = iface.comment || '';
  1382. document.getElementById('wg-iface-modal-pubkey').value = iface.public_key || '';
  1383. document.getElementById('wg-iface-modal-privkey').value = iface.private_key || '';
  1384. document.getElementById('wg-iface-modal-disabled').checked = !!iface.disabled;
  1385. document.getElementById('wg-iface-modal').classList.remove('hidden');
  1386. }
  1387. function closeAddWGInterfaceModal() {
  1388. document.getElementById('wg-iface-modal').classList.add('hidden');
  1389. }
  1390. async function generateWGInterfaceKeys() {
  1391. try {
  1392. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  1393. const keys = await res.json();
  1394. if (res.ok) {
  1395. document.getElementById('wg-iface-modal-privkey').value = keys.private_key;
  1396. document.getElementById('wg-iface-modal-pubkey').value = keys.public_key;
  1397. }
  1398. } catch (err) {
  1399. showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
  1400. }
  1401. }
  1402. async function onWGInterfacePrivKeyInput() {
  1403. const privKey = document.getElementById('wg-iface-modal-privkey').value.trim();
  1404. if (!privKey) return;
  1405. try {
  1406. const res = await fetch(`${API_BASE}/vpn/wireguard/calc-pubkey`, {
  1407. method: 'POST',
  1408. headers: { 'Content-Type': 'application/json' },
  1409. body: JSON.stringify({ private_key: privKey })
  1410. });
  1411. if (res.ok) {
  1412. const data = await res.json();
  1413. if (data.public_key) {
  1414. document.getElementById('wg-iface-modal-pubkey').value = data.public_key;
  1415. }
  1416. }
  1417. } catch (err) {
  1418. // Ignore while typing
  1419. }
  1420. }
  1421. function toggleWGPrivKeyVisibility() {
  1422. const el = document.getElementById('wg-iface-modal-privkey');
  1423. const btn = document.getElementById('btn-toggle-wg-privkey');
  1424. if (el.type === 'password') {
  1425. el.type = 'text';
  1426. btn.innerText = '🙈 Hide';
  1427. } else {
  1428. el.type = 'password';
  1429. btn.innerText = '👁️ Show';
  1430. }
  1431. }
  1432. function copyWGInterfacePubKey() {
  1433. const pub = document.getElementById('wg-iface-modal-pubkey').value;
  1434. if (pub) copyToClipboard(pub, 'Interface Public Key');
  1435. }
  1436. async function submitSaveWGInterface(e) {
  1437. e.preventDefault();
  1438. const origName = document.getElementById('wg-iface-modal-edit-orig').value.trim();
  1439. const name = document.getElementById('wg-iface-modal-name').value.trim();
  1440. const port = parseInt(document.getElementById('wg-iface-modal-port').value, 10) || 51820;
  1441. const addr = document.getElementById('wg-iface-modal-addr').value.trim();
  1442. const mtu = parseInt(document.getElementById('wg-iface-modal-mtu').value, 10) || 1420;
  1443. const comment = document.getElementById('wg-iface-modal-comment').value.trim();
  1444. const pub = document.getElementById('wg-iface-modal-pubkey').value.trim();
  1445. const priv = document.getElementById('wg-iface-modal-privkey').value.trim();
  1446. const disabled = document.getElementById('wg-iface-modal-disabled').checked;
  1447. try {
  1448. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces`, {
  1449. method: 'POST',
  1450. headers: { 'Content-Type': 'application/json' },
  1451. body: JSON.stringify({
  1452. orig_name: origName,
  1453. name,
  1454. listen_port: port,
  1455. address: addr,
  1456. mtu,
  1457. comment,
  1458. public_key: pub,
  1459. private_key: priv,
  1460. disabled
  1461. })
  1462. });
  1463. const data = await res.json();
  1464. if (res.ok) {
  1465. showToast('WireGuard Saved', `Interface ${name} configured successfully`, 'success');
  1466. closeAddWGInterfaceModal();
  1467. loadWireGuard(false);
  1468. fetchData(false);
  1469. } else {
  1470. showToast('Error', data.error || 'Failed to save interface', 'error');
  1471. }
  1472. } catch (err) {
  1473. showToast('Error', err.message, 'error');
  1474. }
  1475. }
  1476. async function startWGInterface(name) {
  1477. try {
  1478. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/start`, { method: 'POST' });
  1479. if (res.ok) {
  1480. showToast('Interface UP', `Started WireGuard interface ${name}`, 'success');
  1481. loadWireGuard(false);
  1482. fetchData(false);
  1483. }
  1484. } catch (err) {
  1485. showToast('Error', err.message, 'error');
  1486. }
  1487. }
  1488. async function stopWGInterface(name) {
  1489. try {
  1490. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  1491. if (res.ok) {
  1492. showToast('Interface DOWN', `Stopped WireGuard interface ${name}`, 'info');
  1493. loadWireGuard(false);
  1494. fetchData(false);
  1495. }
  1496. } catch (err) {
  1497. showToast('Error', err.message, 'error');
  1498. }
  1499. }
  1500. async function toggleWGInterfaceState(name, enable) {
  1501. try {
  1502. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/state`, {
  1503. method: 'POST',
  1504. headers: { 'Content-Type': 'application/json' },
  1505. body: JSON.stringify({ enabled: enable })
  1506. });
  1507. if (res.ok) {
  1508. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  1509. loadWireGuard(false);
  1510. fetchData(false);
  1511. }
  1512. } catch (err) {
  1513. showToast('Error', err.message, 'error');
  1514. }
  1515. }
  1516. async function deleteWGInterface(name) {
  1517. if (!confirm(`Are you sure you want to delete WireGuard interface ${name}? All associated peers will also be removed.`)) return;
  1518. try {
  1519. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1520. if (res.ok) {
  1521. showToast('Deleted', `Interface ${name} removed`, 'success');
  1522. loadWireGuard(false);
  1523. fetchData(false);
  1524. }
  1525. } catch (err) {
  1526. showToast('Error', err.message, 'error');
  1527. }
  1528. }
  1529. function populateWGPeerIfaceSelect(selectedIface = '') {
  1530. const sel = document.getElementById('wg-peer-modal-iface');
  1531. if (!sel) return;
  1532. sel.innerHTML = '';
  1533. (state.wgInterfaces || []).forEach(i => {
  1534. const opt = document.createElement('option');
  1535. opt.value = i.name;
  1536. opt.innerText = `${i.name} (${i.address || 'No IP'})`;
  1537. if (i.name === selectedIface) opt.selected = true;
  1538. sel.appendChild(opt);
  1539. });
  1540. }
  1541. function openAddWGPeerModal() {
  1542. if ((state.wgInterfaces || []).length === 0) {
  1543. showToast('No Interfaces', 'Please add a WireGuard interface first before adding peers', 'warning');
  1544. openAddWGInterfaceModal();
  1545. return;
  1546. }
  1547. document.getElementById('wg-peer-modal-title').innerText = 'Add WireGuard Peer';
  1548. document.getElementById('wg-peer-modal-edit-orig-iface').value = '';
  1549. document.getElementById('wg-peer-modal-edit-orig-pubkey').value = '';
  1550. populateWGPeerIfaceSelect();
  1551. document.getElementById('wg-peer-modal-name').value = '';
  1552. document.getElementById('wg-peer-modal-pubkey').value = '';
  1553. document.getElementById('wg-peer-modal-allowedips').value = '10.10.0.2/32';
  1554. document.getElementById('wg-peer-modal-endpoint').value = '';
  1555. document.getElementById('wg-peer-modal-port').value = '';
  1556. document.getElementById('wg-peer-modal-keepalive').value = '25';
  1557. document.getElementById('wg-peer-modal-preshared').value = '';
  1558. document.getElementById('wg-peer-modal-disabled').checked = false;
  1559. document.getElementById('wg-peer-key-warning').classList.add('hidden');
  1560. document.getElementById('wg-peer-gen-key-box').classList.add('hidden');
  1561. document.getElementById('wg-peer-modal').classList.remove('hidden');
  1562. }
  1563. function openEditWGPeerModal(ifaceName, pubKey) {
  1564. const peer = (state.wgPeers || []).find(p => p.interface === ifaceName && p.public_key === pubKey);
  1565. if (!peer) {
  1566. showToast('Not Found', 'Peer not found', 'warning');
  1567. return;
  1568. }
  1569. document.getElementById('wg-peer-modal-title').innerText = `Edit WireGuard Peer (${peer.name || ifaceName})`;
  1570. document.getElementById('wg-peer-modal-edit-orig-iface').value = peer.interface;
  1571. document.getElementById('wg-peer-modal-edit-orig-pubkey').value = peer.public_key;
  1572. populateWGPeerIfaceSelect(peer.interface);
  1573. document.getElementById('wg-peer-modal-name').value = peer.name || '';
  1574. document.getElementById('wg-peer-modal-pubkey').value = peer.public_key || '';
  1575. document.getElementById('wg-peer-modal-allowedips').value = (peer.allowed_ips || []).join(', ');
  1576. let epHost = (peer.endpoint_address || '').trim();
  1577. let epPort = peer.endpoint_port || '';
  1578. while (epHost.includes(':') && !epHost.startsWith('[')) {
  1579. const lastColon = epHost.lastIndexOf(':');
  1580. const maybePort = epHost.substring(lastColon + 1);
  1581. if (!isNaN(parseInt(maybePort, 10)) && parseInt(maybePort, 10) > 0) {
  1582. if (!epPort) epPort = parseInt(maybePort, 10);
  1583. epHost = epHost.substring(0, lastColon);
  1584. } else {
  1585. break;
  1586. }
  1587. }
  1588. document.getElementById('wg-peer-modal-endpoint').value = epHost;
  1589. document.getElementById('wg-peer-modal-port').value = epPort;
  1590. document.getElementById('wg-peer-modal-keepalive').value = peer.persistent_keepalive ?? 25;
  1591. document.getElementById('wg-peer-modal-preshared').value = peer.preshared_key || '';
  1592. document.getElementById('wg-peer-modal-disabled').checked = !!peer.disabled;
  1593. document.getElementById('wg-peer-key-warning').classList.add('hidden');
  1594. document.getElementById('wg-peer-gen-key-box').classList.add('hidden');
  1595. document.getElementById('wg-peer-modal').classList.remove('hidden');
  1596. }
  1597. function closeAddWGPeerModal() {
  1598. document.getElementById('wg-peer-modal').classList.add('hidden');
  1599. }
  1600. async function generatePeerKeypairHelper() {
  1601. try {
  1602. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  1603. const keys = await res.json();
  1604. if (res.ok) {
  1605. document.getElementById('wg-peer-modal-pubkey').value = keys.public_key;
  1606. document.getElementById('wg-peer-gen-privkey').value = keys.private_key;
  1607. document.getElementById('wg-peer-gen-key-box').classList.remove('hidden');
  1608. checkWGPeerKeyValidity();
  1609. showToast('Keypair Generated', 'Public key inserted and client private key ready to copy', 'info');
  1610. }
  1611. } catch (err) {
  1612. showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
  1613. }
  1614. }
  1615. function copyGeneratedPeerPrivKey() {
  1616. const priv = document.getElementById('wg-peer-gen-privkey').value;
  1617. if (priv) copyToClipboard(priv, 'Client Private Key');
  1618. }
  1619. async function generatePeerPSK() {
  1620. try {
  1621. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  1622. const keys = await res.json();
  1623. if (res.ok && keys.private_key) {
  1624. document.getElementById('wg-peer-modal-preshared').value = keys.private_key;
  1625. showToast('PSK Generated', 'Generated 256-bit preshared key', 'info');
  1626. }
  1627. } catch (err) {
  1628. showToast('Error', err.message, 'error');
  1629. }
  1630. }
  1631. function checkWGPeerKeyValidity() {
  1632. const ifaceName = document.getElementById('wg-peer-modal-iface').value;
  1633. const peerPubKey = document.getElementById('wg-peer-modal-pubkey').value.trim();
  1634. const warningEl = document.getElementById('wg-peer-key-warning');
  1635. if (!warningEl) return;
  1636. const targetIface = (state.wgInterfaces || []).find(i => i.name === ifaceName);
  1637. if (targetIface && targetIface.public_key && peerPubKey && targetIface.public_key === peerPubKey) {
  1638. warningEl.classList.remove('hidden');
  1639. } else {
  1640. warningEl.classList.add('hidden');
  1641. }
  1642. }
  1643. async function submitSaveWGPeer(e) {
  1644. e.preventDefault();
  1645. const origIface = document.getElementById('wg-peer-modal-edit-orig-iface').value.trim();
  1646. const origPubKey = document.getElementById('wg-peer-modal-edit-orig-pubkey').value.trim();
  1647. const iface = document.getElementById('wg-peer-modal-iface').value;
  1648. const name = document.getElementById('wg-peer-modal-name').value.trim();
  1649. const pub = document.getElementById('wg-peer-modal-pubkey').value.trim();
  1650. const allowed = document.getElementById('wg-peer-modal-allowedips').value
  1651. .split(',')
  1652. .map(s => s.trim())
  1653. .filter(s => s.length > 0);
  1654. let epHost = document.getElementById('wg-peer-modal-endpoint').value.trim();
  1655. let epPort = parseInt(document.getElementById('wg-peer-modal-port').value, 10) || 0;
  1656. while (epHost.includes(':') && !epHost.startsWith('[')) {
  1657. const lastColon = epHost.lastIndexOf(':');
  1658. const maybePort = epHost.substring(lastColon + 1);
  1659. if (!isNaN(parseInt(maybePort, 10)) && parseInt(maybePort, 10) > 0) {
  1660. if (!epPort) epPort = parseInt(maybePort, 10);
  1661. epHost = epHost.substring(0, lastColon);
  1662. } else {
  1663. break;
  1664. }
  1665. }
  1666. const keepalive = parseInt(document.getElementById('wg-peer-modal-keepalive').value, 10) || 0;
  1667. const psk = document.getElementById('wg-peer-modal-preshared').value.trim();
  1668. const disabled = document.getElementById('wg-peer-modal-disabled').checked;
  1669. // Validation
  1670. const targetIface = (state.wgInterfaces || []).find(i => i.name === iface);
  1671. if (targetIface && targetIface.public_key === pub) {
  1672. showToast('Invalid Peer Key', 'Peer public key cannot be the same as the interface public key!', 'error');
  1673. return;
  1674. }
  1675. try {
  1676. const res = await fetch(`${API_BASE}/vpn/wireguard/peers`, {
  1677. method: 'POST',
  1678. headers: { 'Content-Type': 'application/json' },
  1679. body: JSON.stringify({
  1680. orig_interface: origIface,
  1681. orig_public_key: origPubKey,
  1682. interface: iface,
  1683. name,
  1684. public_key: pub,
  1685. allowed_ips: allowed,
  1686. endpoint_address: epHost,
  1687. endpoint_port: epPort,
  1688. persistent_keepalive: keepalive,
  1689. preshared_key: psk,
  1690. disabled
  1691. })
  1692. });
  1693. const data = await res.json();
  1694. if (res.ok) {
  1695. showToast('Peer Saved', `Peer ${name} saved on ${iface}`, 'success');
  1696. closeAddWGPeerModal();
  1697. loadWireGuard(false);
  1698. } else {
  1699. showToast('Error', data.error || 'Failed to save peer', 'error');
  1700. }
  1701. } catch (err) {
  1702. showToast('Error', err.message, 'error');
  1703. }
  1704. }
  1705. async function toggleWGPeerState(iface, pubkey, enable) {
  1706. try {
  1707. const res = await fetch(`${API_BASE}/vpn/wireguard/peers/state`, {
  1708. method: 'POST',
  1709. headers: { 'Content-Type': 'application/json' },
  1710. body: JSON.stringify({ interface: iface, public_key: pubkey, enabled: enable })
  1711. });
  1712. const data = await res.json();
  1713. if (res.ok) {
  1714. showToast(enable ? 'Peer Enabled' : 'Peer Disabled', `Peer state updated on ${iface}`, 'info');
  1715. loadWireGuard(false);
  1716. } else {
  1717. showToast('Error', data.error || 'Failed to update peer state', 'error');
  1718. }
  1719. } catch (err) {
  1720. showToast('Error', err.message, 'error');
  1721. }
  1722. }
  1723. async function deleteWGPeer(iface, pubkey) {
  1724. if (!confirm(`Are you sure you want to remove peer from ${iface}?`)) return;
  1725. try {
  1726. const res = await fetch(`${API_BASE}/vpn/wireguard/peers/delete`, {
  1727. method: 'POST',
  1728. headers: { 'Content-Type': 'application/json' },
  1729. body: JSON.stringify({ interface: iface, public_key: pubkey })
  1730. });
  1731. const data = await res.json();
  1732. if (res.ok) {
  1733. showToast('Peer Deleted', 'WireGuard peer removed', 'success');
  1734. loadWireGuard(false);
  1735. } else {
  1736. showToast('Error', data.error || 'Failed to remove peer', 'error');
  1737. }
  1738. } catch (err) {
  1739. showToast('Error', err.message, 'error');
  1740. }
  1741. }
  1742. // ======================== IPSec FortiGate Phase 1 & 2 Multi-Tunnel Engine ========================
  1743. function switchIpsecModalTab(tab) {
  1744. const p1Tab = document.getElementById('tab-btn-ipsec-p1');
  1745. const p2Tab = document.getElementById('tab-btn-ipsec-p2');
  1746. const p1Content = document.getElementById('ipsec-tab-content-p1');
  1747. const p2Content = document.getElementById('ipsec-tab-content-p2');
  1748. const stepBtn = document.getElementById('btn-ipsec-switch-step');
  1749. if (tab === 'p1') {
  1750. if (p1Tab) {
  1751. p1Tab.className = 'px-4 py-2 text-xs font-bold border-b-2 border-amber-500 text-amber-300 transition flex items-center gap-2';
  1752. }
  1753. if (p2Tab) {
  1754. p2Tab.className = 'px-4 py-2 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition flex items-center gap-2';
  1755. }
  1756. if (p1Content) p1Content.classList.remove('hidden');
  1757. if (p2Content) p2Content.classList.add('hidden');
  1758. if (stepBtn) stepBtn.innerHTML = 'Next: Phase 2 Selectors &rarr;';
  1759. } else {
  1760. if (p1Tab) {
  1761. p1Tab.className = 'px-4 py-2 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition flex items-center gap-2';
  1762. }
  1763. if (p2Tab) {
  1764. p2Tab.className = 'px-4 py-2 text-xs font-bold border-b-2 border-cyan-500 text-cyan-300 transition flex items-center gap-2';
  1765. }
  1766. if (p1Content) p1Content.classList.add('hidden');
  1767. if (p2Content) p2Content.classList.remove('hidden');
  1768. if (stepBtn) stepBtn.innerHTML = '&larr; Back: Phase 1 (IKE)';
  1769. }
  1770. }
  1771. function toggleIpsecPhaseStep() {
  1772. const p1Content = document.getElementById('ipsec-tab-content-p1');
  1773. if (p1Content && !p1Content.classList.contains('hidden')) {
  1774. switchIpsecModalTab('p2');
  1775. } else {
  1776. switchIpsecModalTab('p1');
  1777. }
  1778. }
  1779. function toggleIpsecPskVisibility() {
  1780. const pskInput = document.getElementById('ipsec-modal-psk');
  1781. if (!pskInput) return;
  1782. pskInput.type = pskInput.type === 'password' ? 'text' : 'password';
  1783. }
  1784. function addIpsecLocalSubnet(val = '') {
  1785. const container = document.getElementById('ipsec-modal-local-subnets-container');
  1786. if (!container) return;
  1787. const row = document.createElement('div');
  1788. row.className = 'flex items-center gap-2 ipsec-subnet-row';
  1789. row.innerHTML = `
  1790. <input type="text" value="${escapeHtml(val)}" placeholder="e.g. 192.168.10.0/24 or 10.0.1.0/24" class="flex-1 bg-slate-900 border border-slate-700 rounded-lg px-3 py-1.5 text-white font-mono text-xs focus:outline-none focus:border-cyan-500">
  1791. <button type="button" onclick="this.closest('.ipsec-subnet-row').remove()" class="w-7 h-7 flex items-center justify-center bg-slate-800 hover:bg-rose-950 text-slate-400 hover:text-rose-400 border border-slate-700 rounded-lg text-base font-bold transition" title="Remove local subnet">-</button>
  1792. `;
  1793. container.appendChild(row);
  1794. }
  1795. function addIpsecRemoteSubnet(val = '') {
  1796. const container = document.getElementById('ipsec-modal-remote-subnets-container');
  1797. if (!container) return;
  1798. const row = document.createElement('div');
  1799. row.className = 'flex items-center gap-2 ipsec-subnet-row';
  1800. row.innerHTML = `
  1801. <input type="text" value="${escapeHtml(val)}" placeholder="e.g. 192.168.20.0/24 or 10.0.2.0/24" class="flex-1 bg-slate-900 border border-slate-700 rounded-lg px-3 py-1.5 text-white font-mono text-xs focus:outline-none focus:border-purple-500">
  1802. <button type="button" onclick="this.closest('.ipsec-subnet-row').remove()" class="w-7 h-7 flex items-center justify-center bg-slate-800 hover:bg-rose-950 text-slate-400 hover:text-rose-400 border border-slate-700 rounded-lg text-base font-bold transition" title="Remove remote subnet">-</button>
  1803. `;
  1804. container.appendChild(row);
  1805. }
  1806. function updateIpsecEspProposalFromPFS(val) {
  1807. const prop = document.getElementById('ipsec-modal-espprop');
  1808. if (!prop) return;
  1809. if (val === 'none') {
  1810. prop.value = 'aes256-sha256,aes128-sha256,default';
  1811. } else {
  1812. prop.value = `aes256-sha256-${val},aes128-sha256-${val},default`;
  1813. }
  1814. }
  1815. function updateIpsecIkeProposalFromDH(dh) {
  1816. const el = document.getElementById('ipsec-modal-ikeprop');
  1817. if (el) {
  1818. el.value = `aes256-sha256-${dh},aes128-sha256-${dh},default`;
  1819. }
  1820. }
  1821. function safeSetVal(id, val) {
  1822. const el = document.getElementById(id);
  1823. if (el) el.value = val;
  1824. }
  1825. function safeSetChecked(id, val) {
  1826. const el = document.getElementById(id);
  1827. if (el) el.checked = !!val;
  1828. }
  1829. function safeGetVal(id, def = '') {
  1830. const el = document.getElementById(id);
  1831. return el ? el.value : def;
  1832. }
  1833. async function loadIPSec(populateInputs = true) {
  1834. try {
  1835. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`);
  1836. const list = await res.json();
  1837. state.ipsecTunnels = Array.isArray(list) ? list : [];
  1838. const activeCount = state.ipsecTunnels.filter(t => t.running || t.status === 'ESTABLISHED').length;
  1839. const badge = document.getElementById('ipsec-sas-badge');
  1840. if (badge) badge.innerText = `${activeCount} Active SAs`;
  1841. const tbody = document.getElementById('ipsec-table-body');
  1842. const empty = document.getElementById('ipsec-empty');
  1843. if (!tbody) return;
  1844. tbody.innerHTML = '';
  1845. if (state.ipsecTunnels.length === 0) {
  1846. if (empty) empty.classList.remove('hidden');
  1847. } else {
  1848. if (empty) empty.classList.add('hidden');
  1849. state.ipsecTunnels.forEach(c => {
  1850. const isEstablished = c.running || c.status === 'ESTABLISHED';
  1851. const tr = document.createElement('tr');
  1852. tr.className = 'hover:bg-slate-800/40 transition text-xs select-none';
  1853. // Local subnets tags
  1854. const localList = (c.local_subnets && c.local_subnets.length > 0) ? c.local_subnets : (c.local_subnet ? [c.local_subnet] : ['0.0.0.0/0']);
  1855. const localBadges = localList.map(s => `<span class="px-1.5 py-0.5 rounded bg-cyan-950/60 border border-cyan-800/60 text-cyan-300 font-mono text-[10px] mr-1">${escapeHtml(s)}</span>`).join('');
  1856. // Remote subnets tags
  1857. const remoteList = (c.remote_subnets && c.remote_subnets.length > 0) ? c.remote_subnets : (c.remote_subnet ? [c.remote_subnet] : ['0.0.0.0/0']);
  1858. const remoteBadges = remoteList.map(s => `<span class="px-1.5 py-0.5 rounded bg-purple-950/60 border border-purple-800/60 text-purple-300 font-mono text-[10px] mr-1">${escapeHtml(s)}</span>`).join('');
  1859. const ikeVersionBadge = (c.ike_version || 'ikev2').toUpperCase();
  1860. const p2Name = c.phase2_name || `${c.name}_p2`;
  1861. tr.innerHTML = `
  1862. <td class="py-2.5 px-3 text-center">
  1863. ${isEstablished ? `
  1864. <span class="inline-flex items-center gap-1.5 text-emerald-400 font-mono font-bold text-[11px]" title="Active SA Established">
  1865. <span class="w-2.5 h-2.5 rounded-full bg-emerald-400 animate-pulse"></span>
  1866. <span>UP</span>
  1867. </span>
  1868. ` : (c.disabled ? `
  1869. <span class="inline-flex items-center gap-1.5 text-slate-500 font-mono text-[11px]" title="Tunnel Disabled">
  1870. <span class="w-2 h-2 rounded-full bg-rose-500"></span>
  1871. <span>DOWN</span>
  1872. </span>
  1873. ` : `
  1874. <span class="inline-flex items-center gap-1.5 text-amber-400 font-mono text-[11px]" title="Disconnected / Idle">
  1875. <span class="w-2 h-2 rounded-full bg-amber-400"></span>
  1876. <span>IDLE</span>
  1877. </span>
  1878. `)}
  1879. </td>
  1880. <td class="py-2.5 px-4 font-bold text-white">
  1881. <div class="flex items-center gap-2">
  1882. <span class="text-amber-400">🛡</span>
  1883. <div>
  1884. <div>${escapeHtml(c.name)}</div>
  1885. <div class="text-[10px] text-slate-500 font-normal">P2: ${escapeHtml(p2Name)}</div>
  1886. </div>
  1887. </div>
  1888. </td>
  1889. <td class="py-2.5 px-4 text-slate-300 font-mono font-medium">${escapeHtml(c.remote_addrs || '%any')}</td>
  1890. <td class="py-2.5 px-4 font-sans">
  1891. <div class="flex items-center gap-1.5">
  1892. <span class="px-1.5 py-0.5 rounded bg-amber-500/10 text-amber-300 border border-amber-500/30 font-mono text-[10px] font-semibold">${ikeVersionBadge}</span>
  1893. <span class="text-[10px] text-slate-400">${c.auth_method || 'PSK'}</span>
  1894. </div>
  1895. </td>
  1896. <td class="py-2.5 px-4">
  1897. <div class="space-y-1">
  1898. <div class="flex items-center flex-wrap gap-1">
  1899. <span class="text-[9px] text-cyan-400 uppercase font-bold mr-1">Local:</span>
  1900. ${localBadges}
  1901. </div>
  1902. <div class="flex items-center flex-wrap gap-1">
  1903. <span class="text-[9px] text-purple-400 uppercase font-bold mr-1">Remote:</span>
  1904. ${remoteBadges}
  1905. </div>
  1906. </div>
  1907. </td>
  1908. <td class="py-2.5 px-4 font-mono text-[11px] text-slate-400">
  1909. <div class="truncate max-w-[140px]" title="${escapeHtml(c.esp_proposals || '')}">
  1910. ${escapeHtml(c.esp_proposals || 'aes256-sha256')}
  1911. </div>
  1912. <div class="text-[10px] text-slate-500">PFS: ${escapeHtml(c.pfs_group || 'modp2048')}</div>
  1913. </td>
  1914. <td class="py-2.5 px-4 text-right space-x-2 font-sans">
  1915. ${isEstablished ? `
  1916. <button onclick="stopIPSecTunnel('${c.name}')" class="px-2 py-0.5 text-xs bg-rose-500/20 text-rose-400 hover:bg-rose-500/30 rounded border border-rose-500/30 font-medium">Bring Down</button>
  1917. ` : `
  1918. <button onclick="startIPSecTunnel('${c.name}')" class="px-2 py-0.5 text-xs bg-emerald-500/20 text-emerald-400 hover:bg-emerald-500/30 rounded border border-emerald-500/30 font-semibold">Bring Up</button>
  1919. `}
  1920. <button onclick="toggleIPSecState('${c.name}', ${c.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  1921. ${c.disabled ? 'Enable' : 'Disable'}
  1922. </button>
  1923. <button onclick="openEditIPSecModal('${c.name}')" class="text-xs text-amber-400 hover:text-amber-300">Edit</button>
  1924. <button onclick="deleteIPSecConn('${c.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  1925. </td>
  1926. `;
  1927. tbody.appendChild(tr);
  1928. });
  1929. }
  1930. } catch (err) {
  1931. console.error('Failed to load IPSec:', err);
  1932. }
  1933. }
  1934. function openAddIPSecModal() {
  1935. const modal = document.getElementById('ipsec-modal');
  1936. if (!modal) return;
  1937. const title = document.getElementById('ipsec-modal-title');
  1938. if (title) title.innerText = 'Configure IPSec Site-to-Site Tunnel';
  1939. // Phase 1 Fields
  1940. safeSetVal('ipsec-modal-name', `tunnel-${(state.ipsecTunnels || []).length + 1}`);
  1941. const nameEl = document.getElementById('ipsec-modal-name');
  1942. if (nameEl) nameEl.readOnly = false;
  1943. safeSetVal('ipsec-modal-ikeversion', 'ikev2');
  1944. safeSetVal('ipsec-modal-ikever', 'ikev2');
  1945. safeSetVal('ipsec-modal-remotegw', '');
  1946. safeSetVal('ipsec-modal-localaddrs', '');
  1947. safeSetVal('ipsec-modal-comments', '');
  1948. safeSetVal('ipsec-modal-psk', '');
  1949. safeSetVal('ipsec-modal-ikeprop', 'aes256-sha256-modp2048,aes128-sha256-modp2048,default');
  1950. safeSetVal('ipsec-modal-dhgroup', 'modp2048');
  1951. safeSetVal('ipsec-modal-ikekeylife', '86400');
  1952. safeSetVal('ipsec-modal-localid', '');
  1953. safeSetVal('ipsec-modal-remoteid', '');
  1954. safeSetVal('ipsec-modal-dpd', 'on-demand');
  1955. // Phase 2 Fields
  1956. safeSetVal('ipsec-modal-p2name', `tunnel-${(state.ipsecTunnels || []).length + 1}_p2`);
  1957. safeSetVal('ipsec-modal-espkeylife', '28800');
  1958. safeSetVal('ipsec-modal-espprop', 'aes256-sha256-modp2048,aes128-sha256-modp2048,default');
  1959. safeSetVal('ipsec-modal-pfsgroup', 'modp2048');
  1960. safeSetChecked('ipsec-modal-autostart', true);
  1961. safeSetChecked('ipsec-modal-disabled', false);
  1962. // Clear & Populate default dynamic subnets
  1963. const localContainer = document.getElementById('ipsec-modal-local-subnets-container');
  1964. const remoteContainer = document.getElementById('ipsec-modal-remote-subnets-container');
  1965. if (localContainer) {
  1966. localContainer.innerHTML = '';
  1967. addIpsecLocalSubnet('192.168.10.0/24');
  1968. }
  1969. if (remoteContainer) {
  1970. remoteContainer.innerHTML = '';
  1971. addIpsecRemoteSubnet('192.168.20.0/24');
  1972. }
  1973. switchIpsecModalTab('p1');
  1974. modal.classList.remove('hidden');
  1975. }
  1976. function openEditIPSecModal(name) {
  1977. const modal = document.getElementById('ipsec-modal');
  1978. if (!modal) return;
  1979. const conn = (state.ipsecTunnels || []).find(c => c.name === name);
  1980. if (!conn) return;
  1981. const title = document.getElementById('ipsec-modal-title');
  1982. if (title) title.innerText = `Edit IPSec Tunnel: ${name}`;
  1983. // Phase 1 Fields
  1984. safeSetVal('ipsec-modal-name', conn.name);
  1985. const nameEl = document.getElementById('ipsec-modal-name');
  1986. if (nameEl) nameEl.readOnly = true;
  1987. safeSetVal('ipsec-modal-ikeversion', conn.ike_version || 'ikev2');
  1988. safeSetVal('ipsec-modal-ikever', conn.ike_version || 'ikev2');
  1989. safeSetVal('ipsec-modal-remotegw', conn.remote_addrs || '');
  1990. safeSetVal('ipsec-modal-localaddrs', conn.local_addrs || '');
  1991. safeSetVal('ipsec-modal-comments', conn.comment || '');
  1992. safeSetVal('ipsec-modal-psk', conn.preshared_key || '');
  1993. safeSetVal('ipsec-modal-ikeprop', conn.ike_proposals || 'aes256-sha256-modp2048,default');
  1994. safeSetVal('ipsec-modal-ikekeylife', conn.ike_keylife || 86400);
  1995. safeSetVal('ipsec-modal-localid', conn.local_id || '');
  1996. safeSetVal('ipsec-modal-remoteid', conn.remote_id || '');
  1997. safeSetVal('ipsec-modal-dpd', conn.dpd || 'on-demand');
  1998. // Phase 2 Fields
  1999. safeSetVal('ipsec-modal-p2name', conn.phase2_name || `${conn.name}_p2`);
  2000. safeSetVal('ipsec-modal-espkeylife', conn.esp_keylife || 28800);
  2001. safeSetVal('ipsec-modal-espprop', conn.esp_proposals || 'aes256-sha256-modp2048,default');
  2002. safeSetVal('ipsec-modal-pfsgroup', conn.pfs_group || 'modp2048');
  2003. safeSetChecked('ipsec-modal-autostart', conn.auto_start ?? true);
  2004. safeSetChecked('ipsec-modal-disabled', !!conn.disabled);
  2005. // Populate dynamic subnets
  2006. const localContainer = document.getElementById('ipsec-modal-local-subnets-container');
  2007. const remoteContainer = document.getElementById('ipsec-modal-remote-subnets-container');
  2008. if (localContainer) {
  2009. localContainer.innerHTML = '';
  2010. const locals = (conn.local_subnets && conn.local_subnets.length > 0) ? conn.local_subnets : (conn.local_subnet ? [conn.local_subnet] : ['192.168.10.0/24']);
  2011. locals.forEach(s => addIpsecLocalSubnet(s));
  2012. }
  2013. if (remoteContainer) {
  2014. remoteContainer.innerHTML = '';
  2015. const remotes = (conn.remote_subnets && conn.remote_subnets.length > 0) ? conn.remote_subnets : (conn.remote_subnet ? [conn.remote_subnet] : ['192.168.20.0/24']);
  2016. remotes.forEach(s => addIpsecRemoteSubnet(s));
  2017. }
  2018. switchIpsecModalTab('p1');
  2019. modal.classList.remove('hidden');
  2020. }
  2021. function closeAddIPSecModal() {
  2022. const modal = document.getElementById('ipsec-modal');
  2023. if (modal) modal.classList.add('hidden');
  2024. }
  2025. async function submitSaveIPSec(e) {
  2026. if (e) e.preventDefault();
  2027. const name = safeGetVal('ipsec-modal-name').trim();
  2028. if (!name) {
  2029. showToast('Error', 'Tunnel name is required', 'error');
  2030. return;
  2031. }
  2032. const ikeVersion = safeGetVal('ipsec-modal-ikeversion') || safeGetVal('ipsec-modal-ikever', 'ikev2');
  2033. const remotegw = safeGetVal('ipsec-modal-remotegw').trim();
  2034. const localAddrs = safeGetVal('ipsec-modal-localaddrs').trim() || '%any';
  2035. const comments = safeGetVal('ipsec-modal-comments').trim();
  2036. const psk = safeGetVal('ipsec-modal-psk');
  2037. const ikeProposals = safeGetVal('ipsec-modal-ikeprop', 'aes256-sha256-modp2048,default').trim();
  2038. const ikeKeylife = parseInt(safeGetVal('ipsec-modal-ikekeylife', '86400'), 10) || 86400;
  2039. const localId = safeGetVal('ipsec-modal-localid').trim();
  2040. const remoteId = safeGetVal('ipsec-modal-remoteid').trim();
  2041. const dpd = safeGetVal('ipsec-modal-dpd', 'on-demand');
  2042. const phase2Name = safeGetVal('ipsec-modal-p2name').trim() || `${name}_p2`;
  2043. const espProposals = safeGetVal('ipsec-modal-espprop', 'aes256-sha256-modp2048,default').trim();
  2044. const espKeylife = parseInt(safeGetVal('ipsec-modal-espkeylife', '28800'), 10) || 28800;
  2045. const pfsGroup = safeGetVal('ipsec-modal-pfsgroup', 'modp2048');
  2046. const autostart = document.getElementById('ipsec-modal-autostart')?.checked ?? true;
  2047. const disabled = document.getElementById('ipsec-modal-disabled')?.checked ?? false;
  2048. // Scrape dynamic local and remote subnets
  2049. const localInputs = document.querySelectorAll('#ipsec-modal-local-subnets-container input');
  2050. const localSubnets = [];
  2051. localInputs.forEach(inp => {
  2052. const v = inp.value.trim();
  2053. if (v) localSubnets.push(v);
  2054. });
  2055. const remoteInputs = document.querySelectorAll('#ipsec-modal-remote-subnets-container input');
  2056. const remoteSubnets = [];
  2057. remoteInputs.forEach(inp => {
  2058. const v = inp.value.trim();
  2059. if (v) remoteSubnets.push(v);
  2060. });
  2061. try {
  2062. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`, {
  2063. method: 'POST',
  2064. headers: { 'Content-Type': 'application/json' },
  2065. body: JSON.stringify({
  2066. name,
  2067. comment: comments,
  2068. ike_version: ikeVersion,
  2069. local_addrs: localAddrs,
  2070. remote_addrs: remotegw,
  2071. preshared_key: psk,
  2072. ike_proposals: ikeProposals,
  2073. ike_keylife: ikeKeylife,
  2074. local_id: localId,
  2075. remote_id: remoteId,
  2076. dpd: dpd,
  2077. phase2_name: phase2Name,
  2078. esp_proposals: espProposals,
  2079. esp_keylife: espKeylife,
  2080. pfs_group: pfsGroup,
  2081. pfs: pfsGroup !== 'none',
  2082. local_subnets: localSubnets,
  2083. remote_subnets: remoteSubnets,
  2084. local_subnet: localSubnets[0] || '0.0.0.0/0',
  2085. remote_subnet: remoteSubnets[0] || '0.0.0.0/0',
  2086. auto_start: autostart,
  2087. disabled
  2088. })
  2089. });
  2090. if (res.ok) {
  2091. showToast('IPSec Saved', `FortiGate Tunnel ${name} configured`, 'success');
  2092. closeAddIPSecModal();
  2093. loadIPSec(false);
  2094. } else {
  2095. const err = await res.json();
  2096. showToast('Error', err.error || 'Failed to save IPSec tunnel', 'error');
  2097. }
  2098. } catch (err) {
  2099. showToast('Error', err.message, 'error');
  2100. }
  2101. }
  2102. async function startIPSecTunnel(name) {
  2103. try {
  2104. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/start`, { method: 'POST' });
  2105. if (res.ok) {
  2106. showToast('Initiating Tunnel', `Attempting SA handshake for ${name}...`, 'info');
  2107. setTimeout(() => loadIPSec(false), 2000);
  2108. }
  2109. } catch (err) {
  2110. showToast('Error', err.message, 'error');
  2111. }
  2112. }
  2113. async function stopIPSecTunnel(name) {
  2114. try {
  2115. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  2116. if (res.ok) {
  2117. showToast('Terminated', `IPSec SA for ${name} closed`, 'info');
  2118. loadIPSec(false);
  2119. }
  2120. } catch (err) {
  2121. showToast('Error', err.message, 'error');
  2122. }
  2123. }
  2124. async function toggleIPSecState(name, enable) {
  2125. try {
  2126. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/state`, {
  2127. method: 'POST',
  2128. headers: { 'Content-Type': 'application/json' },
  2129. body: JSON.stringify({ enabled: enable })
  2130. });
  2131. if (res.ok) {
  2132. showToast(enable ? 'Enabled' : 'Disabled', `IPSec tunnel ${name} updated`, 'info');
  2133. loadIPSec(false);
  2134. }
  2135. } catch (err) {
  2136. showToast('Error', err.message, 'error');
  2137. }
  2138. }
  2139. async function deleteIPSecConn(name) {
  2140. if (!confirm(`Are you sure you want to delete IPSec tunnel ${name}?`)) return;
  2141. try {
  2142. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2143. if (res.ok) {
  2144. showToast('Deleted', `IPSec connection ${name} removed`, 'success');
  2145. loadIPSec(false);
  2146. fetchData(false);
  2147. }
  2148. } catch (err) {
  2149. showToast('Error', err.message, 'error');
  2150. }
  2151. }
  2152. // ======================== L2TP Multi-Instance ========================
  2153. async function loadL2TP(populateInputs = true) {
  2154. try {
  2155. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2156. await fetchPPPProfilesList();
  2157. }
  2158. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`);
  2159. const list = await res.json();
  2160. state.l2tpList = Array.isArray(list) ? list : [];
  2161. const badge = document.getElementById('l2tp-count-badge');
  2162. if (badge) badge.innerText = `${state.l2tpList.length} Client${state.l2tpList.length !== 1 ? 's' : ''}`;
  2163. const tbody = document.getElementById('l2tp-table-body');
  2164. const empty = document.getElementById('l2tp-empty');
  2165. if (!tbody) return;
  2166. tbody.innerHTML = '';
  2167. if (state.l2tpList.length === 0) {
  2168. if (empty) empty.classList.remove('hidden');
  2169. } else {
  2170. if (empty) empty.classList.add('hidden');
  2171. state.l2tpList.forEach(inst => {
  2172. const tr = document.createElement('tr');
  2173. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  2174. tr.innerHTML = `
  2175. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  2176. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  2177. <td class="py-2.5 px-3 text-cyan-400 font-mono">${escapeHtml(inst.connect_to)}</td>
  2178. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  2179. <td class="py-2.5 px-3 font-mono text-cyan-300"><span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 border border-slate-700">${escapeHtml(inst.profile || 'default-encryption')}</span></td>
  2180. <td class="py-2.5 px-3 font-mono ${inst.assigned_ip ? 'text-emerald-400 font-bold' : 'text-slate-500'}">${escapeHtml(inst.assigned_ip || '-')}</td>
  2181. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  2182. <td class="py-2.5 px-3 text-center">
  2183. <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'}">
  2184. ${inst.default_route ? 'Yes' : 'No'}
  2185. </span>
  2186. </td>
  2187. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  2188. ${inst.running ? `
  2189. <button onclick="disconnectL2TPInstance('${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  2190. ` : `
  2191. <button onclick="connectL2TPInstance('${escapeHtml(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>
  2192. `}
  2193. <button onclick="toggleL2TPState('${escapeHtml(inst.name)}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  2194. ${inst.disabled ? 'Enable' : 'Disable'}
  2195. </button>
  2196. <button onclick="openEditL2TPModal('${escapeHtml(inst.name)}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2197. <button onclick="deleteL2TPInstance('${escapeHtml(inst.name)}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2198. </td>
  2199. `;
  2200. tbody.appendChild(tr);
  2201. });
  2202. }
  2203. } catch (err) {
  2204. console.error('Failed to load L2TP:', err);
  2205. }
  2206. }
  2207. async function openAddL2TPModal() {
  2208. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2209. await fetchPPPProfilesList();
  2210. }
  2211. document.getElementById('l2tp-modal-title').innerText = 'Add L2TP Client Interface';
  2212. document.getElementById('l2tp-modal-name').value = `l2tp-out${(state.l2tpList || []).length + 1}`;
  2213. document.getElementById('l2tp-modal-name').readOnly = false;
  2214. document.getElementById('l2tp-modal-server').value = '';
  2215. document.getElementById('l2tp-modal-user').value = '';
  2216. document.getElementById('l2tp-modal-pass').value = '';
  2217. document.getElementById('l2tp-modal-ipsec').value = '';
  2218. document.getElementById('l2tp-modal-defroute').checked = true;
  2219. document.getElementById('l2tp-modal-disabled').checked = false;
  2220. populateProfileSelect('l2tp-modal-profile', 'default-encryption', 'default-encryption');
  2221. document.getElementById('l2tp-modal').classList.remove('hidden');
  2222. }
  2223. async function openEditL2TPModal(name) {
  2224. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2225. await fetchPPPProfilesList();
  2226. }
  2227. const inst = (state.l2tpList || []).find(i => i.name === name);
  2228. if (!inst) return;
  2229. document.getElementById('l2tp-modal-title').innerText = `Edit L2TP Client: ${name}`;
  2230. document.getElementById('l2tp-modal-name').value = inst.name;
  2231. document.getElementById('l2tp-modal-name').readOnly = true;
  2232. document.getElementById('l2tp-modal-server').value = inst.connect_to || '';
  2233. document.getElementById('l2tp-modal-user').value = inst.username || '';
  2234. document.getElementById('l2tp-modal-pass').value = inst.password || '';
  2235. document.getElementById('l2tp-modal-ipsec').value = inst.ipsec_secret || '';
  2236. document.getElementById('l2tp-modal-defroute').checked = inst.default_route ?? true;
  2237. document.getElementById('l2tp-modal-disabled').checked = !!inst.disabled;
  2238. populateProfileSelect('l2tp-modal-profile', inst.profile || 'default-encryption', 'default-encryption');
  2239. document.getElementById('l2tp-modal').classList.remove('hidden');
  2240. }
  2241. function closeL2TPModal() {
  2242. document.getElementById('l2tp-modal').classList.add('hidden');
  2243. }
  2244. async function submitSaveL2TP(e) {
  2245. e.preventDefault();
  2246. const name = document.getElementById('l2tp-modal-name').value.trim();
  2247. const server = document.getElementById('l2tp-modal-server').value.trim();
  2248. const user = document.getElementById('l2tp-modal-user').value.trim();
  2249. const pass = document.getElementById('l2tp-modal-pass').value;
  2250. const profile = document.getElementById('l2tp-modal-profile')?.value || 'default-encryption';
  2251. const ipsec = document.getElementById('l2tp-modal-ipsec').value;
  2252. const defRoute = document.getElementById('l2tp-modal-defroute').checked;
  2253. const disabled = document.getElementById('l2tp-modal-disabled').checked;
  2254. try {
  2255. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`, {
  2256. method: 'POST',
  2257. headers: { 'Content-Type': 'application/json' },
  2258. body: JSON.stringify({
  2259. name,
  2260. connect_to: server,
  2261. username: user,
  2262. password: pass,
  2263. profile: profile,
  2264. ipsec_secret: ipsec,
  2265. default_route: defRoute,
  2266. disabled
  2267. })
  2268. });
  2269. if (res.ok) {
  2270. showToast('L2TP Saved', `Client ${name} configuration saved`, 'success');
  2271. closeL2TPModal();
  2272. loadL2TP(false);
  2273. fetchData(false);
  2274. }
  2275. } catch (err) {
  2276. showToast('Error', err.message, 'error');
  2277. }
  2278. }
  2279. async function connectL2TPInstance(name) {
  2280. try {
  2281. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  2282. if (res.ok) {
  2283. showToast('Connecting', `Dialing L2TP ${name}...`, 'info');
  2284. setTimeout(() => loadL2TP(false), 2000);
  2285. }
  2286. } catch (err) {
  2287. showToast('Error', err.message, 'error');
  2288. }
  2289. }
  2290. async function disconnectL2TPInstance(name) {
  2291. try {
  2292. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  2293. if (res.ok) {
  2294. showToast('Disconnected', `L2TP tunnel ${name} terminated`, 'info');
  2295. loadL2TP(false);
  2296. }
  2297. } catch (err) {
  2298. showToast('Error', err.message, 'error');
  2299. }
  2300. }
  2301. async function toggleL2TPState(name, enable) {
  2302. try {
  2303. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/state`, {
  2304. method: 'POST',
  2305. headers: { 'Content-Type': 'application/json' },
  2306. body: JSON.stringify({ enabled: enable })
  2307. });
  2308. if (res.ok) {
  2309. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  2310. loadL2TP(false);
  2311. }
  2312. } catch (err) {
  2313. showToast('Error', err.message, 'error');
  2314. }
  2315. }
  2316. async function deleteL2TPInstance(name) {
  2317. if (!confirm(`Are you sure you want to delete L2TP client ${name}?`)) return;
  2318. try {
  2319. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2320. if (res.ok) {
  2321. showToast('Deleted', `L2TP client ${name} removed`, 'success');
  2322. loadL2TP(false);
  2323. fetchData(false);
  2324. }
  2325. } catch (err) {
  2326. showToast('Error', err.message, 'error');
  2327. }
  2328. }
  2329. // ======================== PPTP Multi-Instance ========================
  2330. async function loadPPTP(populateInputs = true) {
  2331. try {
  2332. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2333. await fetchPPPProfilesList();
  2334. }
  2335. const res = await fetch(`${API_BASE}/vpn/pptp/clients`);
  2336. const list = await res.json();
  2337. state.pptpList = Array.isArray(list) ? list : [];
  2338. const badge = document.getElementById('pptp-count-badge');
  2339. if (badge) badge.innerText = `${state.pptpList.length} Client${state.pptpList.length !== 1 ? 's' : ''}`;
  2340. const tbody = document.getElementById('pptp-table-body');
  2341. const empty = document.getElementById('pptp-empty');
  2342. if (!tbody) return;
  2343. tbody.innerHTML = '';
  2344. if (state.pptpList.length === 0) {
  2345. if (empty) empty.classList.remove('hidden');
  2346. } else {
  2347. if (empty) empty.classList.add('hidden');
  2348. state.pptpList.forEach(inst => {
  2349. const tr = document.createElement('tr');
  2350. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  2351. tr.innerHTML = `
  2352. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  2353. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  2354. <td class="py-2.5 px-3 text-purple-400 font-mono">${escapeHtml(inst.connect_to)}</td>
  2355. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  2356. <td class="py-2.5 px-3 font-mono text-purple-300"><span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 border border-slate-700">${escapeHtml(inst.profile || 'default-encryption')}</span></td>
  2357. <td class="py-2.5 px-3 font-mono ${inst.assigned_ip ? 'text-emerald-400 font-bold' : 'text-slate-500'}">${escapeHtml(inst.assigned_ip || '-')}</td>
  2358. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  2359. <td class="py-2.5 px-3 text-center">
  2360. <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'}">
  2361. ${inst.require_mppe ? 'MPPE-128' : 'None'}
  2362. </span>
  2363. </td>
  2364. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  2365. ${inst.running ? `
  2366. <button onclick="disconnectPPTPInstance('${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  2367. ` : `
  2368. <button onclick="connectPPTPInstance('${escapeHtml(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>
  2369. `}
  2370. <button onclick="togglePPTPState('${escapeHtml(inst.name)}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  2371. ${inst.disabled ? 'Enable' : 'Disable'}
  2372. </button>
  2373. <button onclick="openEditPPTPModal('${escapeHtml(inst.name)}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2374. <button onclick="deletePPTPInstance('${escapeHtml(inst.name)}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2375. </td>
  2376. `;
  2377. tbody.appendChild(tr);
  2378. });
  2379. }
  2380. } catch (err) {
  2381. console.error('Failed to load PPTP:', err);
  2382. }
  2383. }
  2384. async function openAddPPTPModal() {
  2385. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2386. await fetchPPPProfilesList();
  2387. }
  2388. document.getElementById('pptp-modal-title').innerText = 'Add PPTP Client Interface';
  2389. document.getElementById('pptp-modal-name').value = `pptp-out${(state.pptpList || []).length + 1}`;
  2390. document.getElementById('pptp-modal-name').readOnly = false;
  2391. document.getElementById('pptp-modal-server').value = '';
  2392. document.getElementById('pptp-modal-user').value = '';
  2393. document.getElementById('pptp-modal-pass').value = '';
  2394. document.getElementById('pptp-modal-mppe').checked = true;
  2395. document.getElementById('pptp-modal-defroute').checked = true;
  2396. document.getElementById('pptp-modal-disabled').checked = false;
  2397. populateProfileSelect('pptp-modal-profile', 'default-encryption', 'default-encryption');
  2398. document.getElementById('pptp-modal').classList.remove('hidden');
  2399. }
  2400. async function openEditPPTPModal(name) {
  2401. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2402. await fetchPPPProfilesList();
  2403. }
  2404. const inst = (state.pptpList || []).find(i => i.name === name);
  2405. if (!inst) return;
  2406. document.getElementById('pptp-modal-title').innerText = `Edit PPTP Client: ${name}`;
  2407. document.getElementById('pptp-modal-name').value = inst.name;
  2408. document.getElementById('pptp-modal-name').readOnly = true;
  2409. document.getElementById('pptp-modal-server').value = inst.connect_to || '';
  2410. document.getElementById('pptp-modal-user').value = inst.username || '';
  2411. document.getElementById('pptp-modal-pass').value = inst.password || '';
  2412. document.getElementById('pptp-modal-mppe').checked = inst.require_mppe ?? true;
  2413. document.getElementById('pptp-modal-defroute').checked = inst.default_route ?? true;
  2414. document.getElementById('pptp-modal-disabled').checked = !!inst.disabled;
  2415. populateProfileSelect('pptp-modal-profile', inst.profile || 'default-encryption', 'default-encryption');
  2416. document.getElementById('pptp-modal').classList.remove('hidden');
  2417. }
  2418. function closePPTPModal() {
  2419. document.getElementById('pptp-modal').classList.add('hidden');
  2420. }
  2421. async function submitSavePPTP(e) {
  2422. e.preventDefault();
  2423. const name = document.getElementById('pptp-modal-name').value.trim();
  2424. const server = document.getElementById('pptp-modal-server').value.trim();
  2425. const user = document.getElementById('pptp-modal-user').value.trim();
  2426. const pass = document.getElementById('pptp-modal-pass').value;
  2427. const profile = document.getElementById('pptp-modal-profile')?.value || 'default-encryption';
  2428. const mppe = document.getElementById('pptp-modal-mppe').checked;
  2429. const defRoute = document.getElementById('pptp-modal-defroute').checked;
  2430. const disabled = document.getElementById('pptp-modal-disabled').checked;
  2431. try {
  2432. const res = await fetch(`${API_BASE}/vpn/pptp/clients`, {
  2433. method: 'POST',
  2434. headers: { 'Content-Type': 'application/json' },
  2435. body: JSON.stringify({
  2436. name,
  2437. connect_to: server,
  2438. username: user,
  2439. password: pass,
  2440. profile: profile,
  2441. require_mppe: mppe,
  2442. default_route: defRoute,
  2443. auto_reconnect: true,
  2444. disabled
  2445. })
  2446. });
  2447. if (res.ok) {
  2448. showToast('PPTP Saved', `Client ${name} configuration saved`, 'success');
  2449. closePPTPModal();
  2450. loadPPTP(false);
  2451. fetchData(false);
  2452. }
  2453. } catch (err) {
  2454. showToast('Error', err.message, 'error');
  2455. }
  2456. }
  2457. async function connectPPTPInstance(name) {
  2458. try {
  2459. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  2460. if (res.ok) {
  2461. showToast('Connecting', `Dialing PPTP ${name}...`, 'info');
  2462. setTimeout(() => loadPPTP(false), 2000);
  2463. }
  2464. } catch (err) {
  2465. showToast('Error', err.message, 'error');
  2466. }
  2467. }
  2468. async function disconnectPPTPInstance(name) {
  2469. try {
  2470. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  2471. if (res.ok) {
  2472. showToast('Disconnected', `PPTP tunnel ${name} terminated`, 'info');
  2473. loadPPTP(false);
  2474. }
  2475. } catch (err) {
  2476. showToast('Error', err.message, 'error');
  2477. }
  2478. }
  2479. async function togglePPTPState(name, enable) {
  2480. try {
  2481. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/state`, {
  2482. method: 'POST',
  2483. headers: { 'Content-Type': 'application/json' },
  2484. body: JSON.stringify({ enabled: enable })
  2485. });
  2486. if (res.ok) {
  2487. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  2488. loadPPTP(false);
  2489. }
  2490. } catch (err) {
  2491. showToast('Error', err.message, 'error');
  2492. }
  2493. }
  2494. async function deletePPTPInstance(name) {
  2495. if (!confirm(`Are you sure you want to delete PPTP client ${name}?`)) return;
  2496. try {
  2497. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2498. if (res.ok) {
  2499. showToast('Deleted', `PPTP client ${name} removed`, 'success');
  2500. loadPPTP(false);
  2501. fetchData(false);
  2502. }
  2503. } catch (err) {
  2504. showToast('Error', err.message, 'error');
  2505. }
  2506. }
  2507. // ---------------- Modal & Helper Functions ----------------
  2508. function openVlanModal(defaultParent = '') {
  2509. const select = document.getElementById('vlan-parent');
  2510. select.innerHTML = '';
  2511. const allIfaces = state.interfaces || [];
  2512. const eligible = allIfaces.filter(i => supportsVLAN(i));
  2513. if (eligible.length === 0) {
  2514. const opt = document.createElement('option');
  2515. opt.value = '';
  2516. opt.innerText = 'No VLAN-capable interfaces available';
  2517. select.appendChild(opt);
  2518. } else {
  2519. eligible.forEach(i => {
  2520. const opt = document.createElement('option');
  2521. opt.value = i.name;
  2522. opt.innerText = `${i.name} (${i.role || i.type || 'Ethernet'} - ${i.state})`;
  2523. if (i.name === defaultParent) opt.selected = true;
  2524. select.appendChild(opt);
  2525. });
  2526. }
  2527. document.getElementById('vlan-id').value = '';
  2528. document.getElementById('vlan-name').value = '';
  2529. document.getElementById('vlan-ip').value = '';
  2530. document.getElementById('vlan-desc').value = '';
  2531. autoSuggestVlanName();
  2532. document.getElementById('vlan-modal').classList.remove('hidden');
  2533. }
  2534. function closeVlanModal() {
  2535. document.getElementById('vlan-modal').classList.add('hidden');
  2536. }
  2537. function autoSuggestVlanName() {
  2538. const parent = document.getElementById('vlan-parent').value;
  2539. if (!parent) return;
  2540. const id = document.getElementById('vlan-id').value;
  2541. const nameInput = document.getElementById('vlan-name');
  2542. if (parent && id) nameInput.placeholder = `${parent}.${id}`;
  2543. }
  2544. function setSubnetPreset(cidr) {
  2545. const ipInput = document.getElementById('vlan-ip');
  2546. const id = document.getElementById('vlan-id').value || '10';
  2547. ipInput.value = `192.168.${id}.1${cidr}`;
  2548. }
  2549. async function submitCreateVlan(e) {
  2550. e.preventDefault();
  2551. const btn = document.getElementById('vlan-submit-btn');
  2552. btn.disabled = true;
  2553. btn.innerText = 'Creating...';
  2554. const parent = document.getElementById('vlan-parent').value;
  2555. if (!parent) {
  2556. showToast('Error', 'Please select a valid VLAN-capable parent interface', 'error');
  2557. btn.disabled = false;
  2558. btn.innerText = 'Create VLAN';
  2559. return;
  2560. }
  2561. const id = parseInt(document.getElementById('vlan-id').value, 10);
  2562. const name = document.getElementById('vlan-name').value.trim();
  2563. const ip = document.getElementById('vlan-ip').value.trim();
  2564. const role = document.getElementById('vlan-role').value;
  2565. const desc = document.getElementById('vlan-desc').value.trim();
  2566. try {
  2567. const res = await fetch(`${API_BASE}/vlans`, {
  2568. method: 'POST',
  2569. headers: { 'Content-Type': 'application/json' },
  2570. body: JSON.stringify({
  2571. parent_name: parent,
  2572. vlan_id: id,
  2573. name: name,
  2574. ip_address: ip,
  2575. role: role,
  2576. description: desc,
  2577. mtu: 1500,
  2578. auto_up: true
  2579. })
  2580. });
  2581. const data = await res.json();
  2582. if (res.ok) {
  2583. showToast('VLAN Created', `Created ${data.name} (VLAN ${data.vlan_id})`, 'success');
  2584. state.expandedParents.add(parent);
  2585. closeVlanModal();
  2586. await fetchData(true);
  2587. if (state.activeTab !== 'interfaces') navigate('interfaces');
  2588. } else {
  2589. showToast('Creation Failed', data.message || 'Failed to create VLAN', 'error');
  2590. }
  2591. } catch (err) {
  2592. showToast('Error', err.message, 'error');
  2593. } finally {
  2594. btn.disabled = false;
  2595. btn.innerText = 'Create VLAN';
  2596. }
  2597. }
  2598. async function confirmDeleteVlan(name) {
  2599. if (!confirm(`Delete VLAN interface ${name}?`)) return;
  2600. try {
  2601. const res = await fetch(`${API_BASE}/vlans/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2602. if (res.ok) {
  2603. showToast('VLAN Deleted', `Interface ${name} removed`, 'success');
  2604. closeIfaceModal();
  2605. fetchData(true);
  2606. }
  2607. } catch (err) {
  2608. showToast('Error', err.message, 'error');
  2609. }
  2610. }
  2611. function openIfaceModal(name) {
  2612. const iface = (state.interfaces || []).find(i => i.name === name);
  2613. if (!iface) return;
  2614. state.currentModalIface = iface.name;
  2615. document.getElementById('modal-iface-name').innerText = iface.name;
  2616. document.getElementById('modal-iface-badge').innerText = iface.is_vlan ? `VLAN ${iface.vlan_id}` : iface.type;
  2617. document.getElementById('modal-iface-mtu').value = iface.mtu;
  2618. document.getElementById('modal-iface-role').value = iface.role || 'LAN';
  2619. document.getElementById('modal-iface-desc').value = iface.description || '';
  2620. const nameInput = document.getElementById('modal-iface-new-name');
  2621. const renameBtn = document.getElementById('modal-btn-rename');
  2622. const renameHelp = document.getElementById('modal-iface-rename-help');
  2623. if (nameInput) {
  2624. nameInput.value = iface.name;
  2625. if (iface.name === 'lo' || iface.type === 'loopback') {
  2626. nameInput.disabled = true;
  2627. if (renameBtn) renameBtn.disabled = true;
  2628. if (renameHelp) renameHelp.innerText = 'Loopback interface cannot be renamed.';
  2629. } else {
  2630. nameInput.disabled = false;
  2631. if (renameBtn) renameBtn.disabled = false;
  2632. if (renameHelp) renameHelp.innerText = 'Device name in Linux (max 15 characters). Automatically preserves operational link state and metadata.';
  2633. }
  2634. }
  2635. const delBtn = document.getElementById('modal-delete-vlan-btn');
  2636. if (iface.is_vlan) {
  2637. delBtn.classList.remove('hidden');
  2638. } else {
  2639. delBtn.classList.add('hidden');
  2640. }
  2641. renderModalIPs(iface);
  2642. document.getElementById('iface-modal').classList.remove('hidden');
  2643. }
  2644. function renderModalIPs(iface) {
  2645. const container = document.getElementById('modal-ip-list');
  2646. container.innerHTML = '';
  2647. const addrs = [...(iface.ipv4 || []), ...(iface.ipv6 || [])];
  2648. if (addrs.length === 0) {
  2649. container.innerHTML = `<span class="text-slate-500 text-xs font-sans">No IP addresses currently bound</span>`;
  2650. return;
  2651. }
  2652. addrs.forEach(addr => {
  2653. const row = document.createElement('div');
  2654. row.className = 'flex items-center justify-between p-2 rounded bg-slate-900 border border-slate-800';
  2655. row.innerHTML = `
  2656. <span class="text-white">${addr}</span>
  2657. <button onclick="removeInterfaceIP('${addr}')" class="text-[11px] text-rose-400 hover:text-rose-300 font-sans">Remove</button>
  2658. `;
  2659. container.appendChild(row);
  2660. });
  2661. }
  2662. function closeIfaceModal() {
  2663. document.getElementById('iface-modal').classList.add('hidden');
  2664. state.currentModalIface = null;
  2665. }
  2666. async function setIfaceState(name, newState) {
  2667. const target = name || state.currentModalIface;
  2668. if (!target) return;
  2669. await toggleInterfaceState(target, newState);
  2670. const updated = (state.interfaces || []).find(i => i.name === target);
  2671. if (updated) openIfaceModal(target);
  2672. }
  2673. async function applyMTU() {
  2674. const mtu = parseInt(document.getElementById('modal-iface-mtu').value, 10);
  2675. try {
  2676. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/mtu`, {
  2677. method: 'POST',
  2678. headers: { 'Content-Type': 'application/json' },
  2679. body: JSON.stringify({ mtu })
  2680. });
  2681. if (res.ok) {
  2682. showToast('MTU Applied', `Set MTU to ${mtu} on ${state.currentModalIface}`, 'success');
  2683. fetchData(false);
  2684. }
  2685. } catch (err) {
  2686. showToast('Error', err.message, 'error');
  2687. }
  2688. }
  2689. async function addInterfaceIP() {
  2690. const ip = document.getElementById('modal-new-ip').value.trim();
  2691. if (!ip) return;
  2692. try {
  2693. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  2694. method: 'POST',
  2695. headers: { 'Content-Type': 'application/json' },
  2696. body: JSON.stringify({ ip })
  2697. });
  2698. if (res.ok) {
  2699. showToast('IP Added', `Bound ${ip} to ${state.currentModalIface}`, 'success');
  2700. document.getElementById('modal-new-ip').value = '';
  2701. await fetchData(false);
  2702. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  2703. if (iface) renderModalIPs(iface);
  2704. } else {
  2705. const err = await res.json();
  2706. showToast('Error', err.error || err.message || 'Failed to add IP address', 'error');
  2707. }
  2708. } catch (err) {
  2709. showToast('Error', err.message, 'error');
  2710. }
  2711. }
  2712. async function removeInterfaceIP(ip) {
  2713. if (!confirm(`Remove IP ${ip}?`)) return;
  2714. try {
  2715. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  2716. method: 'DELETE',
  2717. headers: { 'Content-Type': 'application/json' },
  2718. body: JSON.stringify({ ip })
  2719. });
  2720. if (res.ok) {
  2721. showToast('IP Removed', `Removed ${ip}`, 'success');
  2722. await fetchData(false);
  2723. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  2724. if (iface) renderModalIPs(iface);
  2725. }
  2726. } catch (err) {
  2727. showToast('Error', err.message, 'error');
  2728. }
  2729. }
  2730. async function renameInterface() {
  2731. const oldName = state.currentModalIface;
  2732. const newNameInput = document.getElementById('modal-iface-new-name');
  2733. const newName = (newNameInput?.value || '').trim();
  2734. if (!oldName) return;
  2735. if (!newName) {
  2736. showToast('Warning', 'Interface name cannot be empty', 'warning');
  2737. return;
  2738. }
  2739. if (newName === oldName) {
  2740. showToast('Info', `Interface name is already "${oldName}"`, 'info');
  2741. return;
  2742. }
  2743. if (newName.length > 15) {
  2744. showToast('Validation Error', 'Interface name cannot exceed 15 characters (Linux IFNAMSIZ)', 'error');
  2745. return;
  2746. }
  2747. if (!/^[a-zA-Z0-9_][a-zA-Z0-9_.-]*$/.test(newName)) {
  2748. showToast('Validation Error', 'Name must contain only alphanumeric characters, underscores, hyphens or dots', 'error');
  2749. return;
  2750. }
  2751. const renameBtn = document.getElementById('modal-btn-rename');
  2752. if (renameBtn) {
  2753. renameBtn.disabled = true;
  2754. renameBtn.innerHTML = `<span class="animate-spin inline-block mr-1">⟳</span> Renaming...`;
  2755. }
  2756. try {
  2757. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(oldName)}/rename`, {
  2758. method: 'POST',
  2759. headers: { 'Content-Type': 'application/json' },
  2760. body: JSON.stringify({ new_name: newName })
  2761. });
  2762. const data = await res.json();
  2763. if (!res.ok) {
  2764. showToast('Rename Failed', data.error || data.message || 'Failed to rename interface', 'error');
  2765. return;
  2766. }
  2767. showToast('Interface Renamed', `Successfully renamed ${oldName} → ${newName}`, 'success');
  2768. state.currentModalIface = newName;
  2769. document.getElementById('modal-iface-name').innerText = newName;
  2770. // Refresh application state
  2771. await fetchData(false);
  2772. const updated = (state.interfaces || []).find(i => i.name === newName);
  2773. if (updated) {
  2774. openIfaceModal(newName);
  2775. } else {
  2776. closeIfaceModal();
  2777. }
  2778. } catch (err) {
  2779. showToast('Error', err.message, 'error');
  2780. } finally {
  2781. if (renameBtn) {
  2782. renameBtn.disabled = false;
  2783. renameBtn.innerHTML = `
  2784. <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"/></svg>
  2785. <span>Rename</span>
  2786. `;
  2787. }
  2788. }
  2789. }
  2790. async function saveInterfaceMetadata() {
  2791. const oldName = state.currentModalIface;
  2792. const newName = (document.getElementById('modal-iface-new-name')?.value || '').trim();
  2793. const role = document.getElementById('modal-iface-role').value;
  2794. const desc = document.getElementById('modal-iface-desc').value.trim();
  2795. let targetName = oldName;
  2796. // If user changed the name before clicking Save Changes, execute rename first
  2797. if (newName && newName !== oldName && oldName !== 'lo') {
  2798. try {
  2799. const renameRes = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(oldName)}/rename`, {
  2800. method: 'POST',
  2801. headers: { 'Content-Type': 'application/json' },
  2802. body: JSON.stringify({ new_name: newName })
  2803. });
  2804. const data = await renameRes.json();
  2805. if (!renameRes.ok) {
  2806. showToast('Rename Failed', data.error || data.message || 'Could not rename interface', 'error');
  2807. return;
  2808. }
  2809. targetName = newName;
  2810. state.currentModalIface = newName;
  2811. showToast('Renamed', `Interface renamed from ${oldName} to ${newName}`, 'success');
  2812. } catch (err) {
  2813. showToast('Error', err.message, 'error');
  2814. return;
  2815. }
  2816. }
  2817. try {
  2818. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(targetName)}/metadata`, {
  2819. method: 'POST',
  2820. headers: { 'Content-Type': 'application/json' },
  2821. body: JSON.stringify({ role, description: desc })
  2822. });
  2823. if (res.ok) {
  2824. showToast('Saved', 'Interface configuration updated', 'success');
  2825. closeIfaceModal();
  2826. fetchData(false);
  2827. } else {
  2828. const err = await res.json();
  2829. showToast('Error', err.error || err.message || 'Failed to save metadata', 'error');
  2830. }
  2831. } catch (err) {
  2832. showToast('Error', err.message, 'error');
  2833. }
  2834. }
  2835. // ======================== MIKROTIK FIREWALL (/ip firewall) ========================
  2836. state.fwSubTab = 'filter';
  2837. state.routesSubTab = 'routes';
  2838. function renderRuleFlag(disabled, hasComment) {
  2839. let flags = '';
  2840. if (disabled) flags += '<span class="text-rose-400 font-bold" title="Disabled">X</span>';
  2841. if (hasComment) flags += '<span class="text-amber-400 font-bold ml-1" title="Has Comment">C</span>';
  2842. return flags || '<span class="text-slate-600">-</span>';
  2843. }
  2844. function renderActionBadge(action) {
  2845. const act = (action || '').toLowerCase();
  2846. let color = 'bg-slate-800 text-slate-300';
  2847. if (act === 'accept') color = 'bg-emerald-500/20 text-emerald-300 border border-emerald-500/30';
  2848. else if (act === 'drop' || act === 'reject') color = 'bg-rose-500/20 text-rose-300 border border-rose-500/30';
  2849. else if (act === 'masquerade' || act === 'src-nat' || act === 'dst-nat') color = 'bg-amber-500/20 text-amber-300 border border-amber-500/30';
  2850. else if (act.startsWith('mark-')) color = 'bg-purple-500/20 text-purple-300 border border-purple-500/30';
  2851. else if (act === 'log') color = 'bg-cyan-500/20 text-cyan-300 border border-cyan-500/30';
  2852. return `<span class="px-2 py-0.5 rounded text-[10px] font-mono font-semibold ${color}">${action}</span>`;
  2853. }
  2854. function switchFWSubTab(tab) {
  2855. state.fwSubTab = tab;
  2856. const tabs = ['filter', 'nat', 'mangle', 'addrlist', 'geo', 'connections'];
  2857. tabs.forEach(t => {
  2858. const panel = document.getElementById(`fw-subtab-${t}`);
  2859. const btn = document.getElementById(`fw-subtab-btn-${t}`);
  2860. if (panel) {
  2861. if (t === tab) panel.classList.remove('hidden');
  2862. else panel.classList.add('hidden');
  2863. }
  2864. if (btn) {
  2865. if (t === tab) {
  2866. 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';
  2867. } else {
  2868. 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';
  2869. }
  2870. }
  2871. });
  2872. const addBtn = document.getElementById('fw-primary-add-btn');
  2873. if (addBtn) {
  2874. if (tab === 'filter') addBtn.innerHTML = '<span>+ Add Filter Rule</span>';
  2875. else if (tab === 'nat') addBtn.innerHTML = '<span>+ Add NAT Rule</span>';
  2876. else if (tab === 'mangle') addBtn.innerHTML = '<span>+ Add Mangle Rule</span>';
  2877. else if (tab === 'addrlist') addBtn.innerHTML = '<span>+ Add Address List</span>';
  2878. else if (tab === 'geo') addBtn.innerHTML = '<span>⚙️ Schedule Settings</span>';
  2879. else if (tab === 'connections') addBtn.innerHTML = '<span>Refresh Flows</span>';
  2880. }
  2881. if (tab === 'geo') loadGeoIP();
  2882. if (tab === 'connections') loadConnections();
  2883. setTimeout(initTableSorting, 50);
  2884. }
  2885. function openCurrentFWModal() {
  2886. if (state.fwSubTab === 'filter') openAddFilterModal();
  2887. else if (state.fwSubTab === 'nat') openAddNATModal();
  2888. else if (state.fwSubTab === 'mangle') openAddMangleModal();
  2889. else if (state.fwSubTab === 'addrlist') openAddAddrListModal();
  2890. else if (state.fwSubTab === 'geo') openGeoIntervalModal();
  2891. else if (state.fwSubTab === 'connections') loadConnections();
  2892. }
  2893. async function loadFirewall(populateDropdowns = true) {
  2894. try {
  2895. const [summaryRes, filterRes, natRes, mangleRes, addrlistRes, geoStatusRes, geoCountriesRes] = await Promise.all([
  2896. fetch(`${API_BASE}/firewall/summary`),
  2897. fetch(`${API_BASE}/firewall/filter`),
  2898. fetch(`${API_BASE}/firewall/nat`),
  2899. fetch(`${API_BASE}/firewall/mangle`),
  2900. fetch(`${API_BASE}/firewall/address-lists`),
  2901. fetch(`${API_BASE}/firewall/geoip/status`),
  2902. fetch(`${API_BASE}/firewall/geoip/countries`)
  2903. ]);
  2904. if (summaryRes.ok) state.fwSummary = await summaryRes.json();
  2905. if (filterRes.ok) state.filterRules = await filterRes.json();
  2906. if (natRes.ok) state.natRules = await natRes.json();
  2907. if (mangleRes.ok) state.mangleRules = await mangleRes.json();
  2908. if (addrlistRes.ok) state.addressLists = await addrlistRes.json();
  2909. if (geoStatusRes.ok) state.geoStatus = await geoStatusRes.json();
  2910. if (geoCountriesRes.ok) state.geoCountries = await geoCountriesRes.json();
  2911. // Badges
  2912. const bFilter = document.getElementById('fw-badge-filter');
  2913. if (bFilter) bFilter.innerText = (state.filterRules || []).length;
  2914. const bNat = document.getElementById('fw-badge-nat');
  2915. if (bNat) bNat.innerText = (state.natRules || []).length;
  2916. const bMangle = document.getElementById('fw-badge-mangle');
  2917. if (bMangle) bMangle.innerText = (state.mangleRules || []).length;
  2918. const bAddr = document.getElementById('fw-badge-addrlist');
  2919. if (bAddr) bAddr.innerText = (state.addressLists || []).length;
  2920. const bGeo = document.getElementById('fw-badge-geo');
  2921. if (bGeo) bGeo.innerText = state.geoStatus?.enabled_count || 0;
  2922. renderFilterRules();
  2923. renderNATRules();
  2924. renderMangleRules();
  2925. renderAddressLists();
  2926. renderGeoCountries();
  2927. if (state.fwSubTab === 'connections') {
  2928. loadConnections();
  2929. }
  2930. } catch (err) {
  2931. console.error('Failed to load firewall:', err);
  2932. }
  2933. }
  2934. // ----------------- Filter Rules -----------------
  2935. function renderFilterRules() {
  2936. const chainFilter = document.getElementById('filter-filter-chain')?.value || '';
  2937. const tbody = document.getElementById('filter-table-body');
  2938. const empty = document.getElementById('filter-empty');
  2939. if (!tbody) return;
  2940. tbody.innerHTML = '';
  2941. const rules = (state.filterRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  2942. document.getElementById('filter-count-badge').innerText = `${rules.length} Rules`;
  2943. if (rules.length === 0) {
  2944. empty?.classList.remove('hidden');
  2945. return;
  2946. }
  2947. empty?.classList.add('hidden');
  2948. rules.forEach((r, idx) => {
  2949. const tr = document.createElement('tr');
  2950. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  2951. const ports = [r.src_port ? 's:' + r.src_port : '', r.dst_port ? 'd:' + r.dst_port : ''].filter(Boolean).join(' ');
  2952. const ifaces = [r.in_interface ? 'in:' + r.in_interface : '', r.out_interface ? 'out:' + r.out_interface : ''].filter(Boolean).join(' ');
  2953. let actionExtra = '';
  2954. if (r.action === 'reject') {
  2955. actionExtra = `<span class="block text-[10px] text-rose-300 font-mono mt-0.5">(${r.reject_with || 'icmp-net-unreach'})</span>`;
  2956. } else if (r.action === 'jump') {
  2957. actionExtra = `<span class="block text-[10px] text-yellow-300 font-mono mt-0.5">&rarr; ${r.jump_target || '-'}</span>`;
  2958. } else if (r.action.includes('address-list') || r.action.includes('address list')) {
  2959. actionExtra = `<span class="block text-[10px] text-emerald-300 font-mono mt-0.5">&rarr; ${r.address_list || '-'}</span>`;
  2960. } else if (r.action === 'log' && r.log_prefix) {
  2961. actionExtra = `<span class="block text-[10px] text-slate-400 font-mono mt-0.5">${r.log_prefix}</span>`;
  2962. }
  2963. tr.innerHTML = `
  2964. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  2965. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  2966. <td class="py-2.5 px-3 font-bold text-white">${r.chain}</td>
  2967. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  2968. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  2969. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}</td>
  2970. <td class="py-2.5 px-3 text-amber-400">${ports || '-'}</td>
  2971. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  2972. <td class="py-2.5 px-3">${renderActionBadge(r.action)}${actionExtra}</td>
  2973. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  2974. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  2975. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  2976. </td>
  2977. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  2978. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  2979. <button onclick="moveFilterRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  2980. <button onclick="moveFilterRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  2981. <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>
  2982. <button onclick="openEditFilterModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2983. <button onclick="deleteFilterRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2984. </td>
  2985. `;
  2986. tbody.appendChild(tr);
  2987. });
  2988. }
  2989. function formatTarget(addr, list, geo) {
  2990. const parts = [];
  2991. if (addr) parts.push(`<span>${addr}</span>`);
  2992. if (list) {
  2993. const inv = list.startsWith('!') ? '!' : '';
  2994. const clean = list.replace(/^!/, '');
  2995. 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>`);
  2996. }
  2997. if (geo) {
  2998. const inv = geo.startsWith('!') ? '!' : '';
  2999. const clean = geo.replace(/^!/, '').replace(/^geo:/, '');
  3000. 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>`);
  3001. }
  3002. if (parts.length === 0) return '<span class="text-slate-600">0.0.0.0/0</span>';
  3003. return parts.join(' ');
  3004. }
  3005. function populateInterfaceSelect(selectId, currentVal = '') {
  3006. const sel = document.getElementById(selectId);
  3007. if (!sel) return;
  3008. sel.innerHTML = '<option value="">(Any Interface)</option>';
  3009. (state.interfaces || []).forEach(i => {
  3010. const opt = document.createElement('option');
  3011. opt.value = i.name;
  3012. opt.innerText = `${i.name} (${i.role || i.type})`;
  3013. if (i.name === currentVal) opt.selected = true;
  3014. sel.appendChild(opt);
  3015. });
  3016. }
  3017. function populateAddressListSelect(selectId, currentVal = '') {
  3018. const sel = document.getElementById(selectId);
  3019. if (!sel) return;
  3020. sel.innerHTML = '<option value="">(None)</option>';
  3021. const cleanVal = (currentVal || '').replace(/^!/, '');
  3022. const customNames = Array.from(new Set((state.addressLists || []).map(a => a.name))).sort();
  3023. customNames.forEach(name => {
  3024. const count = (state.addressLists || []).filter(a => a.name === name).length;
  3025. const opt = document.createElement('option');
  3026. opt.value = name;
  3027. opt.innerText = `${name} (${count} entries)`;
  3028. if (name === cleanVal) opt.selected = true;
  3029. sel.appendChild(opt);
  3030. });
  3031. if (cleanVal && !sel.querySelector(`option[value="${cleanVal}"]`)) {
  3032. const opt = document.createElement('option');
  3033. opt.value = cleanVal;
  3034. opt.innerText = cleanVal;
  3035. opt.selected = true;
  3036. sel.appendChild(opt);
  3037. }
  3038. populateCommonAddrListDatalist();
  3039. }
  3040. function populateCommonAddrListDatalist() {
  3041. const dl = document.getElementById('fw-addrlist-datalist');
  3042. if (!dl) return;
  3043. dl.innerHTML = '';
  3044. const names = Array.from(new Set((state.addressLists || []).map(a => a.name).filter(Boolean))).sort();
  3045. names.forEach(name => {
  3046. const opt = document.createElement('option');
  3047. opt.value = name;
  3048. dl.appendChild(opt);
  3049. });
  3050. }
  3051. function populateGeoIPSelect(selectId, currentVal = '') {
  3052. const sel = document.getElementById(selectId);
  3053. if (!sel) return;
  3054. sel.innerHTML = '<option value="">(None)</option>';
  3055. const cleanVal = (currentVal || '').replace(/^!/, '').replace(/^geo:/, '').toUpperCase();
  3056. // Presets optgroup
  3057. const grpPresets = document.createElement('optgroup');
  3058. grpPresets.label = '⚡ Regional Presets';
  3059. const presets = [
  3060. { code: 'EU', label: '🇪🇺 European Union (EU - 27 countries)' },
  3061. { code: 'BALKANS', label: '🏛️ Balkans (GR, CY, BG, RO, AL, etc.)' },
  3062. { code: 'BLOCKLIST', label: '🛡️ High-Risk Blocklist (CN, RU, IR, KP, BY)' }
  3063. ];
  3064. presets.forEach(p => {
  3065. const opt = document.createElement('option');
  3066. opt.value = p.code;
  3067. opt.innerText = p.label;
  3068. if (p.code === cleanVal) opt.selected = true;
  3069. grpPresets.appendChild(opt);
  3070. });
  3071. sel.appendChild(grpPresets);
  3072. // All Countries optgroup
  3073. const grpCountries = document.createElement('optgroup');
  3074. grpCountries.label = '🌍 All Countries';
  3075. const countries = (state.geoCountries || []).slice().sort((a, b) => a.name.localeCompare(b.name));
  3076. countries.forEach(c => {
  3077. const opt = document.createElement('option');
  3078. opt.value = c.code;
  3079. const subnetsInfo = c.subnet_count ? ` [${c.subnet_count.toLocaleString()} subnets]` : '';
  3080. opt.innerText = `${c.name} (${c.code})${subnetsInfo}`;
  3081. if (c.code === cleanVal) opt.selected = true;
  3082. grpCountries.appendChild(opt);
  3083. });
  3084. sel.appendChild(grpCountries);
  3085. }
  3086. // ==================== FIREWALL FILTER MODAL (ROUTEROS WEBFIG / WINBOX V4) ====================
  3087. function switchFwRuleTab(tab) {
  3088. state.activeFwRuleTab = tab;
  3089. document.querySelectorAll('.fw-rule-tab-btn').forEach(btn => {
  3090. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  3091. btn.classList.add('text-slate-400', 'border-transparent');
  3092. });
  3093. const activeBtn = document.getElementById(`fw-tab-btn-${tab}`);
  3094. if (activeBtn) {
  3095. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  3096. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  3097. }
  3098. document.querySelectorAll('.fw-rule-pane').forEach(p => p.classList.add('hidden'));
  3099. const activePane = document.getElementById(`fw-pane-${tab}`);
  3100. if (activePane) activePane.classList.remove('hidden');
  3101. if (tab === 'statistics') {
  3102. startFwStatPolling();
  3103. } else {
  3104. stopFwStatPolling();
  3105. }
  3106. }
  3107. function toggleFwField(fieldKey, expand) {
  3108. const plusBtn = document.getElementById(`fw-plus-${fieldKey}`);
  3109. const fieldBox = document.getElementById(`fw-field-${fieldKey}`);
  3110. if (!plusBtn || !fieldBox) return;
  3111. if (expand) {
  3112. plusBtn.classList.add('hidden');
  3113. fieldBox.classList.remove('hidden');
  3114. const valInput = document.getElementById(`fw-val-${fieldKey}`);
  3115. if (valInput) valInput.focus();
  3116. } else {
  3117. fieldBox.classList.add('hidden');
  3118. plusBtn.classList.remove('hidden');
  3119. const valInput = document.getElementById(`fw-val-${fieldKey}`);
  3120. if (valInput) {
  3121. if (valInput.tagName === 'SELECT') {
  3122. valInput.selectedIndex = 0;
  3123. } else {
  3124. valInput.value = '';
  3125. }
  3126. }
  3127. const invInput = document.getElementById(`fw-inv-${fieldKey}`);
  3128. if (invInput) invInput.checked = false;
  3129. if (fieldKey === 'cs') {
  3130. ['filter-modal-cs-established', 'filter-modal-cs-related', 'filter-modal-cs-new', 'filter-modal-cs-invalid', 'filter-modal-cs-untracked'].forEach(id => {
  3131. const el = document.getElementById(id);
  3132. if (el) el.checked = false;
  3133. });
  3134. }
  3135. if (fieldKey === 'natstate') {
  3136. ['filter-modal-nat-srcnat', 'filter-modal-nat-dstnat'].forEach(id => {
  3137. const el = document.getElementById(id);
  3138. if (el) el.checked = false;
  3139. });
  3140. }
  3141. if (fieldKey === 'days') {
  3142. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3143. const el = document.getElementById(`fw-day-${d}`);
  3144. if (el) el.checked = true;
  3145. });
  3146. }
  3147. }
  3148. }
  3149. function setFwFieldVal(fieldKey, value, hasInvert = false) {
  3150. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  3151. toggleFwField(fieldKey, true);
  3152. let strVal = String(value);
  3153. if (hasInvert) {
  3154. const inv = strVal.startsWith('!');
  3155. if (inv) strVal = strVal.slice(1);
  3156. const invEl = document.getElementById(`fw-inv-${fieldKey}`);
  3157. if (invEl) invEl.checked = inv;
  3158. }
  3159. const valEl = document.getElementById(`fw-val-${fieldKey}`);
  3160. if (valEl) valEl.value = strVal;
  3161. } else {
  3162. toggleFwField(fieldKey, false);
  3163. }
  3164. }
  3165. function getFwFieldVal(fieldKey, hasInvert = false) {
  3166. const fieldBox = document.getElementById(`fw-field-${fieldKey}`);
  3167. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  3168. const valEl = document.getElementById(`fw-val-${fieldKey}`);
  3169. let v = valEl ? valEl.value.trim() : '';
  3170. if (!v) return '';
  3171. if (hasInvert) {
  3172. const invEl = document.getElementById(`fw-inv-${fieldKey}`);
  3173. if (invEl && invEl.checked) {
  3174. v = '!' + v.replace(/^!/, '');
  3175. }
  3176. }
  3177. return v;
  3178. }
  3179. function toggleMaximizeFilterModal() {
  3180. const win = document.getElementById('filter-modal-window');
  3181. if (!win) return;
  3182. if (win.classList.contains('max-w-[720px]')) {
  3183. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  3184. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  3185. } else {
  3186. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  3187. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  3188. }
  3189. }
  3190. function openAddFilterModal() {
  3191. switchFwRuleTab('general');
  3192. const badge = document.getElementById('fw-modal-badge');
  3193. if (badge) badge.innerText = 'New...';
  3194. document.getElementById('filter-modal-id').value = '';
  3195. document.getElementById('filter-modal-enabled').checked = true;
  3196. document.getElementById('filter-modal-comment').value = '';
  3197. document.getElementById('filter-modal-chain').value = 'forward';
  3198. document.getElementById('filter-modal-action').value = 'accept';
  3199. document.getElementById('filter-modal-log').checked = false;
  3200. populateInterfaceSelect('fw-val-iniface');
  3201. populateInterfaceSelect('fw-val-outiface');
  3202. populateAddressListSelect('fw-val-srclist');
  3203. populateAddressListSelect('fw-val-dstlist');
  3204. populateGeoIPSelect('fw-val-srcgeo');
  3205. populateGeoIPSelect('fw-val-dstgeo');
  3206. const allFieldKeys = [
  3207. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  3208. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  3209. 'routingmark', 'conntype', 'cs', 'natstate',
  3210. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  3211. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  3212. 'ipsec', 'tlshost', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  3213. 'pktsize', 'random', 'tcpflags', 'icmpoptions', 'ipv4options', 'ttl',
  3214. 'time', 'days', 'limit', 'dstlimit', 'psd', 'logprefix'
  3215. ];
  3216. allFieldKeys.forEach(k => toggleFwField(k, false));
  3217. resetCurrentRuleCounters();
  3218. toggleFilterActionFields();
  3219. document.getElementById('filter-modal').classList.remove('hidden');
  3220. }
  3221. function openEditFilterModal(id) {
  3222. const r = (state.filterRules || []).find(rule => rule.id === id);
  3223. if (!r) return;
  3224. switchFwRuleTab('general');
  3225. const badge = document.getElementById('fw-modal-badge');
  3226. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  3227. document.getElementById('filter-modal-id').value = r.id;
  3228. document.getElementById('filter-modal-enabled').checked = !r.disabled;
  3229. document.getElementById('filter-modal-comment').value = r.comment || '';
  3230. document.getElementById('filter-modal-chain').value = r.chain || 'forward';
  3231. document.getElementById('filter-modal-action').value = r.action || 'accept';
  3232. document.getElementById('filter-modal-log').checked = !!r.log;
  3233. populateInterfaceSelect('fw-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  3234. populateInterfaceSelect('fw-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  3235. populateAddressListSelect('fw-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  3236. populateAddressListSelect('fw-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  3237. populateGeoIPSelect('fw-val-srcgeo', r.src_geoip || '');
  3238. populateGeoIPSelect('fw-val-dstgeo', r.dst_geoip || '');
  3239. setFwFieldVal('src', r.src_address, true);
  3240. setFwFieldVal('dst', r.dst_address, true);
  3241. setFwFieldVal('srclist', r.src_address_list, true);
  3242. setFwFieldVal('dstlist', r.dst_address_list, true);
  3243. setFwFieldVal('srcgeo', r.src_geoip, true);
  3244. setFwFieldVal('dstgeo', r.dst_geoip, true);
  3245. if (r.protocol && r.protocol !== 'all') {
  3246. setFwFieldVal('proto', r.protocol, true);
  3247. } else {
  3248. toggleFwField('proto', false);
  3249. }
  3250. setFwFieldVal('sport', r.src_port, true);
  3251. setFwFieldVal('dport', r.dst_port, true);
  3252. setFwFieldVal('anyport', r.any_port, true);
  3253. setFwFieldVal('iniface', r.in_interface, true);
  3254. setFwFieldVal('outiface', r.out_interface, true);
  3255. setFwFieldVal('inifacelist', r.in_interface_list, true);
  3256. setFwFieldVal('outifacelist', r.out_interface_list, true);
  3257. setFwFieldVal('pktmark', r.packet_mark, true);
  3258. setFwFieldVal('connmark', r.connection_mark, true);
  3259. setFwFieldVal('routingmark', r.routing_mark, true);
  3260. setFwFieldVal('conntype', r.connection_type, false);
  3261. const states = r.connection_state || [];
  3262. if (states.length > 0) {
  3263. toggleFwField('cs', true);
  3264. document.getElementById('filter-modal-cs-established').checked = states.includes('established');
  3265. document.getElementById('filter-modal-cs-related').checked = states.includes('related');
  3266. document.getElementById('filter-modal-cs-new').checked = states.includes('new');
  3267. document.getElementById('filter-modal-cs-invalid').checked = states.includes('invalid');
  3268. document.getElementById('filter-modal-cs-untracked').checked = states.includes('untracked');
  3269. } else {
  3270. toggleFwField('cs', false);
  3271. }
  3272. const natStates = r.connection_nat_state || [];
  3273. if (natStates.length > 0) {
  3274. toggleFwField('natstate', true);
  3275. document.getElementById('filter-modal-nat-srcnat').checked = natStates.includes('srcnat');
  3276. document.getElementById('filter-modal-nat-dstnat').checked = natStates.includes('dstnat');
  3277. } else {
  3278. toggleFwField('natstate', false);
  3279. }
  3280. // Advanced tab fields
  3281. setFwFieldVal('layer7', r.layer7_protocol, false);
  3282. setFwFieldVal('content', r.content, false);
  3283. setFwFieldVal('connbytes', r.connection_bytes, false);
  3284. setFwFieldVal('connrate', r.connection_rate, false);
  3285. setFwFieldVal('pcc', r.pcc, false);
  3286. setFwFieldVal('srcmac', r.src_mac_address, true);
  3287. setFwFieldVal('outbridgeport', r.out_bridge_port, false);
  3288. setFwFieldVal('inbridgeport', r.in_bridge_port, false);
  3289. setFwFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  3290. setFwFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  3291. setFwFieldVal('ipsec', r.ipsec_policy, false);
  3292. setFwFieldVal('tlshost', r.tls_host, false);
  3293. setFwFieldVal('ingresspriority', r.ingress_priority, false);
  3294. setFwFieldVal('priority', r.priority, false);
  3295. setFwFieldVal('dscp', r.dscp, false);
  3296. setFwFieldVal('tcpmss', r.tcp_mss, false);
  3297. if (r.tos) {
  3298. const tosEl = document.getElementById('fw-val-tos');
  3299. if (tosEl) tosEl.value = r.tos;
  3300. }
  3301. setFwFieldVal('pktsize', r.packet_size, false);
  3302. setFwFieldVal('random', r.random, false);
  3303. setFwFieldVal('tcpflags', r.tcp_flags, false);
  3304. setFwFieldVal('icmpoptions', r.icmp_options, false);
  3305. setFwFieldVal('ipv4options', r.ipv4_options, false);
  3306. setFwFieldVal('ttl', r.ttl, false);
  3307. // Extra tab fields
  3308. setFwFieldVal('time', r.time, false);
  3309. if (r.days) {
  3310. toggleFwField('days', true);
  3311. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3312. const chk = document.getElementById(`fw-day-${d}`);
  3313. if (chk) chk.checked = r.days.includes(d);
  3314. });
  3315. } else {
  3316. toggleFwField('days', false);
  3317. }
  3318. setFwFieldVal('limit', r.limit, false);
  3319. setFwFieldVal('dstlimit', r.dst_limit, false);
  3320. setFwFieldVal('psd', r.psd, false);
  3321. // Action fields
  3322. if (r.reject_with) {
  3323. const rwEl = document.getElementById('filter-modal-rejectwith');
  3324. if (rwEl) rwEl.value = r.reject_with;
  3325. }
  3326. if (r.jump_target) {
  3327. const jtEl = document.getElementById('filter-modal-jumptarget');
  3328. if (jtEl) jtEl.value = r.jump_target;
  3329. }
  3330. if (r.address_list) {
  3331. const alEl = document.getElementById('filter-modal-action-addrlist');
  3332. if (alEl) alEl.value = r.address_list;
  3333. }
  3334. if (r.address_list_timeout) {
  3335. const toEl = document.getElementById('filter-modal-action-timeout');
  3336. if (toEl) toEl.value = r.address_list_timeout;
  3337. }
  3338. setFwFieldVal('logprefix', r.log_prefix, false);
  3339. // Statistics
  3340. const bEl = document.getElementById('fw-stat-bytes');
  3341. const pEl = document.getElementById('fw-stat-packets');
  3342. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  3343. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  3344. state.fwLastBytes = r.bytes || 0;
  3345. state.fwLastPackets = r.packets || 0;
  3346. state.fwLastTimestamp = Date.now();
  3347. state.fwStatRateHistory = new Array(30).fill(0);
  3348. state.fwStatPktHistory = new Array(30).fill(0);
  3349. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  3350. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  3351. toggleFilterActionFields();
  3352. document.getElementById('filter-modal').classList.remove('hidden');
  3353. }
  3354. function closeFilterModal() {
  3355. stopFwStatPolling();
  3356. document.getElementById('filter-modal').classList.add('hidden');
  3357. }
  3358. function toggleFilterActionFields() {
  3359. const act = document.getElementById('filter-modal-action')?.value || 'accept';
  3360. const rejectBox = document.getElementById('filter-action-reject-box');
  3361. const jumpBox = document.getElementById('filter-action-jump-box');
  3362. const addrBox = document.getElementById('filter-action-addrlist-box');
  3363. if (rejectBox) {
  3364. if (act === 'reject') rejectBox.classList.remove('hidden');
  3365. else rejectBox.classList.add('hidden');
  3366. }
  3367. if (jumpBox) {
  3368. if (act === 'jump') jumpBox.classList.remove('hidden');
  3369. else jumpBox.classList.add('hidden');
  3370. }
  3371. if (addrBox) {
  3372. if (act === 'add-dst-to-address-list' || act === 'add-src-to-address-list' || act.includes('address-list') || act.includes('address list')) {
  3373. addrBox.classList.remove('hidden');
  3374. } else {
  3375. addrBox.classList.add('hidden');
  3376. }
  3377. }
  3378. if (act === 'log') {
  3379. const logEl = document.getElementById('filter-modal-log');
  3380. if (logEl) logEl.checked = true;
  3381. toggleFwField('logprefix', true);
  3382. }
  3383. }
  3384. function toggleFwLogPrefix() {
  3385. const isLog = document.getElementById('filter-modal-log')?.checked;
  3386. toggleFwField('logprefix', !!isLog);
  3387. }
  3388. function copyFilterRule() {
  3389. document.getElementById('filter-modal-id').value = '';
  3390. const badge = document.getElementById('fw-modal-badge');
  3391. if (badge) badge.innerText = 'New...';
  3392. showToast('Rule Cloned', 'Ready to save as a new rule copy', 'info');
  3393. }
  3394. function resetCurrentRuleCounters() {
  3395. state.fwStatRateHistory = new Array(30).fill(0);
  3396. state.fwStatPktHistory = new Array(30).fill(0);
  3397. state.fwLastBytes = 0;
  3398. state.fwLastPackets = 0;
  3399. state.fwLastTimestamp = Date.now();
  3400. const bEl = document.getElementById('fw-stat-bytes');
  3401. const pEl = document.getElementById('fw-stat-packets');
  3402. const rEl = document.getElementById('fw-stat-rate');
  3403. const prEl = document.getElementById('fw-stat-pktrate');
  3404. if (bEl) bEl.value = '0 B';
  3405. if (pEl) pEl.value = '0';
  3406. if (rEl) rEl.value = '0 bps';
  3407. if (prEl) prEl.value = '0 p/s';
  3408. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  3409. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  3410. showToast('Counters Reset', 'Rule counter display reset to 0', 'info');
  3411. }
  3412. async function resetAllFwCounters() {
  3413. try {
  3414. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  3415. if (res.ok) {
  3416. resetCurrentRuleCounters();
  3417. showToast('All Counters Reset', 'All firewall counters zeroed', 'success');
  3418. loadFirewall(false);
  3419. }
  3420. } catch (err) {
  3421. showToast('Error', err.message, 'error');
  3422. }
  3423. }
  3424. async function applyFilterRule(closeAfter = false) {
  3425. const id = document.getElementById('filter-modal-id').value;
  3426. const chain = document.getElementById('filter-modal-chain').value;
  3427. const action = document.getElementById('filter-modal-action').value;
  3428. const comment = document.getElementById('filter-modal-comment').value.trim();
  3429. const enabled = document.getElementById('filter-modal-enabled').checked;
  3430. const src = getFwFieldVal('src', true);
  3431. const dst = getFwFieldVal('dst', true);
  3432. const srclist = getFwFieldVal('srclist', true);
  3433. const dstlist = getFwFieldVal('dstlist', true);
  3434. const srcgeo = getFwFieldVal('srcgeo', true);
  3435. const dstgeo = getFwFieldVal('dstgeo', true);
  3436. const proto = getFwFieldVal('proto', true);
  3437. const sport = getFwFieldVal('sport', true);
  3438. const dport = getFwFieldVal('dport', true);
  3439. const anyport = getFwFieldVal('anyport', true);
  3440. const iniface = getFwFieldVal('iniface', true);
  3441. const outiface = getFwFieldVal('outiface', true);
  3442. const inifacelist = getFwFieldVal('inifacelist', true);
  3443. const outifacelist = getFwFieldVal('outifacelist', true);
  3444. const pktmark = getFwFieldVal('pktmark', true);
  3445. const connmark = getFwFieldVal('connmark', true);
  3446. const routingmark = getFwFieldVal('routingmark', true);
  3447. const conntype = getFwFieldVal('conntype', false);
  3448. const states = [];
  3449. const csBox = document.getElementById('fw-field-cs');
  3450. if (csBox && !csBox.classList.contains('hidden')) {
  3451. if (document.getElementById('filter-modal-cs-established')?.checked) states.push('established');
  3452. if (document.getElementById('filter-modal-cs-related')?.checked) states.push('related');
  3453. if (document.getElementById('filter-modal-cs-new')?.checked) states.push('new');
  3454. if (document.getElementById('filter-modal-cs-invalid')?.checked) states.push('invalid');
  3455. if (document.getElementById('filter-modal-cs-untracked')?.checked) states.push('untracked');
  3456. }
  3457. const natStates = [];
  3458. const natBox = document.getElementById('fw-field-natstate');
  3459. if (natBox && !natBox.classList.contains('hidden')) {
  3460. if (document.getElementById('filter-modal-nat-srcnat')?.checked) natStates.push('srcnat');
  3461. if (document.getElementById('filter-modal-nat-dstnat')?.checked) natStates.push('dstnat');
  3462. }
  3463. const payload = {
  3464. id,
  3465. chain,
  3466. action,
  3467. protocol: proto || 'all',
  3468. src_address: src,
  3469. dst_address: dst,
  3470. src_port: sport,
  3471. dst_port: dport,
  3472. any_port: anyport,
  3473. in_interface: iniface,
  3474. out_interface: outiface,
  3475. in_interface_list: inifacelist,
  3476. out_interface_list: outifacelist,
  3477. packet_mark: pktmark,
  3478. connection_mark: connmark,
  3479. routing_mark: routingmark,
  3480. connection_type: conntype,
  3481. connection_state: states,
  3482. connection_nat_state: natStates,
  3483. src_address_list: srclist,
  3484. dst_address_list: dstlist,
  3485. src_geoip: srcgeo,
  3486. dst_geoip: dstgeo,
  3487. comment,
  3488. disabled: !enabled,
  3489. // Advanced tab
  3490. layer7_protocol: getFwFieldVal('layer7', false),
  3491. content: getFwFieldVal('content', false),
  3492. connection_bytes: getFwFieldVal('connbytes', false),
  3493. connection_rate: getFwFieldVal('connrate', false),
  3494. pcc: getFwFieldVal('pcc', false),
  3495. src_mac_address: getFwFieldVal('srcmac', true),
  3496. out_bridge_port: getFwFieldVal('outbridgeport', false),
  3497. in_bridge_port: getFwFieldVal('inbridgeport', false),
  3498. in_bridge_port_list: getFwFieldVal('inbridgeportlist', false),
  3499. out_bridge_port_list: getFwFieldVal('outbridgeportlist', false),
  3500. ipsec_policy: getFwFieldVal('ipsec', false),
  3501. tls_host: getFwFieldVal('tlshost', false),
  3502. ingress_priority: getFwFieldVal('ingresspriority', false),
  3503. priority: getFwFieldVal('priority', false),
  3504. dscp: getFwFieldVal('dscp', false),
  3505. tcp_mss: getFwFieldVal('tcpmss', false),
  3506. tos: document.getElementById('fw-val-tos')?.value || '',
  3507. packet_size: getFwFieldVal('pktsize', false),
  3508. random: getFwFieldVal('random', false),
  3509. tcp_flags: getFwFieldVal('tcpflags', false),
  3510. icmp_options: getFwFieldVal('icmpoptions', false),
  3511. ipv4_options: getFwFieldVal('ipv4options', false),
  3512. ttl: getFwFieldVal('ttl', false),
  3513. // Extra tab
  3514. time: getFwFieldVal('time', false),
  3515. limit: getFwFieldVal('limit', false),
  3516. dst_limit: getFwFieldVal('dstlimit', false),
  3517. psd: getFwFieldVal('psd', false),
  3518. // Action tab
  3519. reject_with: action === 'reject' ? (document.getElementById('filter-modal-rejectwith')?.value || '') : '',
  3520. jump_target: action === 'jump' ? (document.getElementById('filter-modal-jumptarget')?.value || '') : '',
  3521. address_list: action.startsWith('add-') ? (document.getElementById('filter-modal-action-addrlist')?.value || '') : '',
  3522. address_list_timeout: action.startsWith('add-') ? (document.getElementById('filter-modal-action-timeout')?.value || '') : '',
  3523. log: document.getElementById('filter-modal-log')?.checked || false,
  3524. log_prefix: getFwFieldVal('logprefix', false)
  3525. };
  3526. try {
  3527. const res = await fetch(`${API_BASE}/firewall/filter`, {
  3528. method: 'POST',
  3529. headers: { 'Content-Type': 'application/json' },
  3530. body: JSON.stringify(payload)
  3531. });
  3532. if (res.ok) {
  3533. const data = await res.json();
  3534. showToast('Filter Rule Saved', 'Rule applied successfully to firewall', 'success');
  3535. loadFirewall(false);
  3536. if (closeAfter) {
  3537. closeFilterModal();
  3538. } else {
  3539. if (data.id) {
  3540. document.getElementById('filter-modal-id').value = data.id;
  3541. const badge = document.getElementById('fw-modal-badge');
  3542. if (badge) badge.innerText = `#${data.id}`;
  3543. }
  3544. }
  3545. } else {
  3546. const err = await res.json();
  3547. showToast('Error', err.message || 'Failed to save rule', 'error');
  3548. }
  3549. } catch (err) {
  3550. showToast('Error', err.message, 'error');
  3551. }
  3552. }
  3553. function submitSaveFilterRule(e) {
  3554. if (e && e.preventDefault) e.preventDefault();
  3555. return applyFilterRule(true);
  3556. }
  3557. function startFwStatPolling() {
  3558. stopFwStatPolling();
  3559. pollRuleStats();
  3560. state.fwStatInterval = setInterval(pollRuleStats, 1000);
  3561. }
  3562. function stopFwStatPolling() {
  3563. if (state.fwStatInterval) {
  3564. clearInterval(state.fwStatInterval);
  3565. state.fwStatInterval = null;
  3566. }
  3567. }
  3568. async function pollRuleStats() {
  3569. const id = document.getElementById('filter-modal-id')?.value;
  3570. if (!id) {
  3571. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory || new Array(30).fill(0), 'bps', 'fw-stat-legend-rate');
  3572. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory || new Array(30).fill(0), 'p/s', 'fw-stat-legend-pktrate');
  3573. return;
  3574. }
  3575. try {
  3576. const res = await fetch(`${API_BASE}/firewall/filter`);
  3577. if (!res.ok) return;
  3578. const rules = await res.json();
  3579. const r = rules.find(x => x.id === id);
  3580. if (!r) return;
  3581. const now = Date.now();
  3582. const dt = Math.max(0.2, (now - (state.fwLastTimestamp || now)) / 1000);
  3583. state.fwLastTimestamp = now;
  3584. const curBytes = r.bytes || 0;
  3585. const curPackets = r.packets || 0;
  3586. const deltaBytes = Math.max(0, curBytes - (state.fwLastBytes || curBytes));
  3587. const deltaPkts = Math.max(0, curPackets - (state.fwLastPackets || curPackets));
  3588. state.fwLastBytes = curBytes;
  3589. state.fwLastPackets = curPackets;
  3590. const rateBps = Math.round((deltaBytes * 8) / dt);
  3591. const ratePkt = Math.round(deltaPkts / dt);
  3592. if (!state.fwStatRateHistory) state.fwStatRateHistory = new Array(30).fill(0);
  3593. if (!state.fwStatPktHistory) state.fwStatPktHistory = new Array(30).fill(0);
  3594. state.fwStatRateHistory.push(rateBps);
  3595. if (state.fwStatRateHistory.length > 30) state.fwStatRateHistory.shift();
  3596. state.fwStatPktHistory.push(ratePkt);
  3597. if (state.fwStatPktHistory.length > 30) state.fwStatPktHistory.shift();
  3598. const bEl = document.getElementById('fw-stat-bytes');
  3599. const pEl = document.getElementById('fw-stat-packets');
  3600. const rEl = document.getElementById('fw-stat-rate');
  3601. const prEl = document.getElementById('fw-stat-pktrate');
  3602. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  3603. if (pEl) pEl.value = curPackets.toLocaleString();
  3604. if (rEl) rEl.value = formatBps(rateBps);
  3605. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  3606. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  3607. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  3608. } catch (e) {
  3609. console.error('Error polling rule stats', e);
  3610. }
  3611. }
  3612. function formatBps(bps) {
  3613. if (bps >= 1000000000) return (bps / 1000000000).toFixed(1) + ' Gbps';
  3614. if (bps >= 1000000) return (bps / 1000000).toFixed(1) + ' Mbps';
  3615. if (bps >= 1000) return (bps / 1000).toFixed(1) + ' kbps';
  3616. return bps + ' bps';
  3617. }
  3618. function renderFwSparkline(svgId, dataArray, unit, legendId) {
  3619. const svg = document.getElementById(svgId);
  3620. if (!svg) return;
  3621. const w = 500;
  3622. const h = 100;
  3623. const paddingRight = 45;
  3624. const graphWidth = w - paddingRight;
  3625. const maxVal = Math.max(5, ...dataArray);
  3626. const currentVal = dataArray[dataArray.length - 1] || 0;
  3627. const leg = document.getElementById(legendId);
  3628. if (leg) {
  3629. leg.innerText = unit === 'bps' ? formatBps(currentVal) : `${currentVal.toLocaleString()} p/s`;
  3630. }
  3631. let gridLines = '';
  3632. for (let i = 0; i <= 5; i++) {
  3633. const y = 8 + (i * (h - 18) / 5);
  3634. const valAtLevel = Math.round(maxVal * (5 - i) / 5);
  3635. const label = unit === 'bps' ? formatBps(valAtLevel) : `${valAtLevel} p/s`;
  3636. gridLines += `
  3637. <line x1="0" y1="${y.toFixed(1)}" x2="${graphWidth}" y2="${y.toFixed(1)}" stroke="#1e2c3e" stroke-width="1" />
  3638. <text x="${w - 2}" y="${(y + 3).toFixed(1)}" fill="#64748b" font-size="9" font-family="monospace" text-anchor="end">${label}</text>
  3639. `;
  3640. }
  3641. const step = graphWidth / (dataArray.length - 1);
  3642. const points = dataArray.map((val, idx) => {
  3643. const x = idx * step;
  3644. const y = (h - 10) - (val / maxVal) * (h - 20);
  3645. return `${x.toFixed(1)},${y.toFixed(1)}`;
  3646. });
  3647. const polylineStr = points.join(' ');
  3648. const areaPath = `M 0,${h - 10} L ${polylineStr} L ${graphWidth},${h - 10} Z`;
  3649. svg.innerHTML = `
  3650. ${gridLines}
  3651. <path d="${areaPath}" fill="rgba(14, 165, 233, 0.12)" />
  3652. <polyline fill="none" stroke="#38bdf8" stroke-width="1.8" stroke-linejoin="round" points="${polylineStr}" />
  3653. <circle cx="${graphWidth}" cy="${points[points.length - 1].split(',')[1]}" r="3" fill="#38bdf8" />
  3654. `;
  3655. }
  3656. async function moveFilterRule(id, dir) {
  3657. try {
  3658. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/move`, {
  3659. method: 'POST',
  3660. headers: { 'Content-Type': 'application/json' },
  3661. body: JSON.stringify({ direction: dir })
  3662. });
  3663. if (res.ok) loadFirewall(false);
  3664. } catch (err) {
  3665. showToast('Error', err.message, 'error');
  3666. }
  3667. }
  3668. async function toggleFilterRuleState(id, disabled) {
  3669. try {
  3670. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/state`, {
  3671. method: 'POST',
  3672. headers: { 'Content-Type': 'application/json' },
  3673. body: JSON.stringify({ disabled })
  3674. });
  3675. if (res.ok) loadFirewall(false);
  3676. } catch (err) {
  3677. showToast('Error', err.message, 'error');
  3678. }
  3679. }
  3680. async function deleteFilterRule(id) {
  3681. if (!confirm('Are you sure you want to delete this filter rule?')) return;
  3682. try {
  3683. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}`, { method: 'DELETE' });
  3684. if (res.ok) {
  3685. showToast('Deleted', 'Filter rule removed', 'success');
  3686. loadFirewall(false);
  3687. }
  3688. } catch (err) {
  3689. showToast('Error', err.message, 'error');
  3690. }
  3691. }
  3692. // ----------------- NAT Rules -----------------
  3693. function renderNATRules() {
  3694. const chainFilter = document.getElementById('nat-filter-chain')?.value || '';
  3695. const tbody = document.getElementById('nat-table-body');
  3696. const empty = document.getElementById('nat-empty');
  3697. if (!tbody) return;
  3698. tbody.innerHTML = '';
  3699. const rules = (state.natRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  3700. document.getElementById('nat-count-badge').innerText = `${rules.length} Rules`;
  3701. if (rules.length === 0) {
  3702. empty?.classList.remove('hidden');
  3703. return;
  3704. }
  3705. empty?.classList.add('hidden');
  3706. rules.forEach((r, idx) => {
  3707. const tr = document.createElement('tr');
  3708. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  3709. let toTarget = '-';
  3710. if (r.action === 'jump') {
  3711. toTarget = `<span class="text-yellow-300 font-mono font-bold">&rarr; ${r.jump_target || '-'}</span>`;
  3712. } else if (r.action.includes('address-list') || r.action.includes('address list')) {
  3713. toTarget = `<span class="text-emerald-300 font-mono font-bold">&rarr; ${r.address_list || '-'}</span>`;
  3714. } else if (r.action === 'redirect') {
  3715. toTarget = `<span class="text-amber-300 font-mono font-bold">ports:${r.to_ports || 'all'}</span>`;
  3716. } else if (r.action === 'masquerade') {
  3717. toTarget = r.to_ports ? `<span class="text-amber-300 font-mono font-bold">ports:${r.to_ports}</span>` : `<span class="text-slate-500 font-mono">-</span>`;
  3718. } else if (r.action === 'log') {
  3719. toTarget = `<span class="text-slate-400 font-mono font-bold">${r.log_prefix || 'log'}</span>`;
  3720. } else {
  3721. const parts = [r.to_addresses, r.to_ports].filter(Boolean);
  3722. toTarget = parts.length ? `<span class="text-amber-300 font-mono font-bold">${parts.join(':')}</span>` : '-';
  3723. }
  3724. const ifaces = [r.out_interface ? 'out:' + r.out_interface : '', r.in_interface ? 'in:' + r.in_interface : ''].filter(Boolean).join(' ');
  3725. tr.innerHTML = `
  3726. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  3727. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  3728. <td class="py-2.5 px-3 font-bold text-amber-400">${r.chain}</td>
  3729. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  3730. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  3731. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}${r.dst_port ? ':' + r.dst_port : ''}</td>
  3732. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  3733. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  3734. <td class="py-2.5 px-3 font-mono text-xs">${toTarget}</td>
  3735. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  3736. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  3737. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  3738. </td>
  3739. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  3740. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  3741. <button onclick="moveNATRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  3742. <button onclick="moveNATRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  3743. <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>
  3744. <button onclick="openEditNATModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  3745. <button onclick="deleteNATRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  3746. </td>
  3747. `;
  3748. tbody.appendChild(tr);
  3749. });
  3750. }
  3751. // ==================== FIREWALL NAT MODAL (ROUTEROS WEBFIG / WINBOX V4) ====================
  3752. function switchNATRuleTab(tab) {
  3753. state.activeNATRuleTab = tab;
  3754. document.querySelectorAll('.nat-rule-tab-btn').forEach(btn => {
  3755. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  3756. btn.classList.add('text-slate-400', 'border-transparent');
  3757. });
  3758. const activeBtn = document.getElementById(`nat-tab-btn-${tab}`);
  3759. if (activeBtn) {
  3760. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  3761. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  3762. }
  3763. document.querySelectorAll('.nat-rule-pane').forEach(p => p.classList.add('hidden'));
  3764. const activePane = document.getElementById(`nat-pane-${tab}`);
  3765. if (activePane) activePane.classList.remove('hidden');
  3766. if (tab === 'statistics') {
  3767. startNATStatPolling();
  3768. } else {
  3769. stopNATStatPolling();
  3770. }
  3771. }
  3772. function toggleNATField(fieldKey, expand) {
  3773. const plusBtn = document.getElementById(`nat-plus-${fieldKey}`);
  3774. const fieldBox = document.getElementById(`nat-field-${fieldKey}`);
  3775. if (!plusBtn || !fieldBox) return;
  3776. if (expand) {
  3777. plusBtn.classList.add('hidden');
  3778. fieldBox.classList.remove('hidden');
  3779. const valInput = document.getElementById(`nat-val-${fieldKey}`);
  3780. if (valInput) valInput.focus();
  3781. } else {
  3782. fieldBox.classList.add('hidden');
  3783. plusBtn.classList.remove('hidden');
  3784. const valInput = document.getElementById(`nat-val-${fieldKey}`);
  3785. if (valInput) {
  3786. if (valInput.tagName === 'SELECT') {
  3787. valInput.selectedIndex = 0;
  3788. } else {
  3789. valInput.value = '';
  3790. }
  3791. }
  3792. const invInput = document.getElementById(`nat-inv-${fieldKey}`);
  3793. if (invInput) invInput.checked = false;
  3794. if (fieldKey === 'days') {
  3795. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3796. const el = document.getElementById(`nat-day-${d}`);
  3797. if (el) el.checked = true;
  3798. });
  3799. }
  3800. }
  3801. }
  3802. function setNATFieldVal(fieldKey, value, hasInvert = false) {
  3803. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  3804. toggleNATField(fieldKey, true);
  3805. let strVal = String(value);
  3806. if (hasInvert) {
  3807. const inv = strVal.startsWith('!');
  3808. if (inv) strVal = strVal.slice(1);
  3809. const invEl = document.getElementById(`nat-inv-${fieldKey}`);
  3810. if (invEl) invEl.checked = inv;
  3811. }
  3812. const valEl = document.getElementById(`nat-val-${fieldKey}`);
  3813. if (valEl) valEl.value = strVal;
  3814. } else {
  3815. toggleNATField(fieldKey, false);
  3816. }
  3817. }
  3818. function getNATFieldVal(fieldKey, hasInvert = false) {
  3819. const fieldBox = document.getElementById(`nat-field-${fieldKey}`);
  3820. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  3821. const valEl = document.getElementById(`nat-val-${fieldKey}`);
  3822. let v = valEl ? valEl.value.trim() : '';
  3823. if (!v) return '';
  3824. if (hasInvert) {
  3825. const invEl = document.getElementById(`nat-inv-${fieldKey}`);
  3826. if (invEl && invEl.checked) {
  3827. v = '!' + v.replace(/^!/, '');
  3828. }
  3829. }
  3830. return v;
  3831. }
  3832. function toggleMaximizeNATModal() {
  3833. const win = document.getElementById('nat-modal-window');
  3834. if (!win) return;
  3835. if (win.classList.contains('max-w-[720px]')) {
  3836. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  3837. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  3838. } else {
  3839. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  3840. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  3841. }
  3842. }
  3843. function handleNATChainChange() {
  3844. const ch = document.getElementById('nat-modal-chain')?.value || 'srcnat';
  3845. const actSel = document.getElementById('nat-modal-action');
  3846. if (actSel) {
  3847. if (ch === 'srcnat' && (actSel.value === 'dst-nat' || actSel.value === 'redirect')) {
  3848. actSel.value = 'masquerade';
  3849. } else if (ch === 'dstnat' && (actSel.value === 'masquerade' || actSel.value === 'src-nat')) {
  3850. actSel.value = 'dst-nat';
  3851. }
  3852. }
  3853. toggleNATActionFields();
  3854. }
  3855. function toggleNATActionFields() {
  3856. const act = document.getElementById('nat-modal-action')?.value || 'masquerade';
  3857. const rowAddr = document.getElementById('nat-row-toaddr');
  3858. const rowPort = document.getElementById('nat-row-toport');
  3859. const jumpBox = document.getElementById('nat-action-jump-box');
  3860. const addrBox = document.getElementById('nat-action-addrlist-box');
  3861. // Hide all dynamic rows first
  3862. if (rowAddr) rowAddr.classList.add('hidden');
  3863. if (rowPort) rowPort.classList.add('hidden');
  3864. if (jumpBox) jumpBox.classList.add('hidden');
  3865. if (addrBox) addrBox.classList.add('hidden');
  3866. if (['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat'].includes(act)) {
  3867. if (rowAddr) rowAddr.classList.remove('hidden');
  3868. if (rowPort) rowPort.classList.remove('hidden');
  3869. } else if (act === 'redirect' || act === 'masquerade') {
  3870. if (rowPort) rowPort.classList.remove('hidden');
  3871. } else if (act === 'jump') {
  3872. if (jumpBox) jumpBox.classList.remove('hidden');
  3873. } else if (act.includes('address-list') || act.includes('address list')) {
  3874. if (addrBox) addrBox.classList.remove('hidden');
  3875. }
  3876. if (act === 'log') {
  3877. const logEl = document.getElementById('nat-modal-log');
  3878. if (logEl) logEl.checked = true;
  3879. toggleNATField('logprefix', true);
  3880. }
  3881. }
  3882. function toggleNATLogPrefix() {
  3883. const isLog = document.getElementById('nat-modal-log')?.checked;
  3884. toggleNATField('logprefix', !!isLog);
  3885. }
  3886. function openAddNATModal() {
  3887. switchNATRuleTab('general');
  3888. const badge = document.getElementById('nat-modal-badge');
  3889. if (badge) badge.innerText = 'New...';
  3890. document.getElementById('nat-modal-id').value = '';
  3891. document.getElementById('nat-modal-enabled').checked = true;
  3892. document.getElementById('nat-modal-comment').value = '';
  3893. document.getElementById('nat-modal-chain').value = 'srcnat';
  3894. document.getElementById('nat-modal-action').value = 'masquerade';
  3895. document.getElementById('nat-modal-toaddr').value = '';
  3896. document.getElementById('nat-modal-toport').value = '';
  3897. document.getElementById('nat-modal-log').checked = false;
  3898. populateInterfaceSelect('nat-val-iniface');
  3899. populateInterfaceSelect('nat-val-outiface');
  3900. populateAddressListSelect('nat-val-srclist');
  3901. populateAddressListSelect('nat-val-dstlist');
  3902. populateGeoIPSelect('nat-val-srcgeo');
  3903. populateGeoIPSelect('nat-val-dstgeo');
  3904. const allFieldKeys = [
  3905. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  3906. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  3907. 'routingmark', 'conntype',
  3908. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  3909. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  3910. 'ipsec', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  3911. 'pktsize', 'random', 'icmpoptions', 'ipv4options', 'ttl',
  3912. 'time', 'days', 'limit', 'dstlimit', 'psd', 'logprefix'
  3913. ];
  3914. allFieldKeys.forEach(k => toggleNATField(k, false));
  3915. resetCurrentNATRuleCounters();
  3916. toggleNATActionFields();
  3917. document.getElementById('nat-modal').classList.remove('hidden');
  3918. }
  3919. function openEditNATModal(id) {
  3920. const r = (state.natRules || []).find(rule => rule.id === id);
  3921. if (!r) return;
  3922. switchNATRuleTab('general');
  3923. const badge = document.getElementById('nat-modal-badge');
  3924. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  3925. document.getElementById('nat-modal-id').value = r.id;
  3926. document.getElementById('nat-modal-enabled').checked = !r.disabled;
  3927. document.getElementById('nat-modal-comment').value = r.comment || '';
  3928. document.getElementById('nat-modal-chain').value = r.chain || 'srcnat';
  3929. document.getElementById('nat-modal-action').value = r.action || 'masquerade';
  3930. document.getElementById('nat-modal-toaddr').value = r.to_addresses || '';
  3931. document.getElementById('nat-modal-toport').value = r.to_ports || '';
  3932. document.getElementById('nat-modal-log').checked = !!r.log;
  3933. populateInterfaceSelect('nat-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  3934. populateInterfaceSelect('nat-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  3935. populateAddressListSelect('nat-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  3936. populateAddressListSelect('nat-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  3937. populateGeoIPSelect('nat-val-srcgeo', r.src_geoip || '');
  3938. populateGeoIPSelect('nat-val-dstgeo', r.dst_geoip || '');
  3939. setNATFieldVal('src', r.src_address, true);
  3940. setNATFieldVal('dst', r.dst_address, true);
  3941. setNATFieldVal('srclist', r.src_address_list, true);
  3942. setNATFieldVal('dstlist', r.dst_address_list, true);
  3943. setNATFieldVal('srcgeo', r.src_geoip, true);
  3944. setNATFieldVal('dstgeo', r.dst_geoip, true);
  3945. if (r.protocol && r.protocol !== 'all') {
  3946. setNATFieldVal('proto', r.protocol, true);
  3947. } else {
  3948. toggleNATField('proto', false);
  3949. }
  3950. setNATFieldVal('sport', r.src_port, true);
  3951. setNATFieldVal('dport', r.dst_port, true);
  3952. setNATFieldVal('anyport', r.any_port, true);
  3953. setNATFieldVal('iniface', r.in_interface, true);
  3954. setNATFieldVal('outiface', r.out_interface, true);
  3955. setNATFieldVal('inifacelist', r.in_interface_list, true);
  3956. setNATFieldVal('outifacelist', r.out_interface_list, true);
  3957. setNATFieldVal('pktmark', r.packet_mark, true);
  3958. setNATFieldVal('connmark', r.connection_mark, true);
  3959. setNATFieldVal('routingmark', r.routing_mark, true);
  3960. setNATFieldVal('conntype', r.connection_type, false);
  3961. // Advanced tab fields
  3962. setNATFieldVal('layer7', r.layer7_protocol, false);
  3963. setNATFieldVal('content', r.content, false);
  3964. setNATFieldVal('connbytes', r.connection_bytes, false);
  3965. setNATFieldVal('connrate', r.connection_rate, false);
  3966. setNATFieldVal('pcc', r.pcc, false);
  3967. setNATFieldVal('srcmac', r.src_mac_address, true);
  3968. setNATFieldVal('outbridgeport', r.out_bridge_port, false);
  3969. setNATFieldVal('inbridgeport', r.in_bridge_port, false);
  3970. setNATFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  3971. setNATFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  3972. setNATFieldVal('ipsec', r.ipsec_policy, false);
  3973. setNATFieldVal('ingresspriority', r.ingress_priority, false);
  3974. setNATFieldVal('priority', r.priority, false);
  3975. setNATFieldVal('dscp', r.dscp, false);
  3976. setNATFieldVal('tcpmss', r.tcp_mss, false);
  3977. if (r.tos) {
  3978. const tosEl = document.getElementById('nat-val-tos');
  3979. if (tosEl) tosEl.value = r.tos;
  3980. }
  3981. setNATFieldVal('pktsize', r.packet_size, false);
  3982. setNATFieldVal('random', r.random, false);
  3983. setNATFieldVal('icmpoptions', r.icmp_options, false);
  3984. setNATFieldVal('ipv4options', r.ipv4_options, false);
  3985. setNATFieldVal('ttl', r.ttl, false);
  3986. // Extra tab fields
  3987. setNATFieldVal('time', r.time, false);
  3988. if (r.days) {
  3989. toggleNATField('days', true);
  3990. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3991. const chk = document.getElementById(`nat-day-${d}`);
  3992. if (chk) chk.checked = r.days.includes(d);
  3993. });
  3994. } else {
  3995. toggleNATField('days', false);
  3996. }
  3997. setNATFieldVal('limit', r.limit, false);
  3998. setNATFieldVal('dstlimit', r.dst_limit, false);
  3999. setNATFieldVal('psd', r.psd, false);
  4000. // Action fields
  4001. if (r.jump_target) {
  4002. const jtEl = document.getElementById('nat-modal-jumptarget');
  4003. if (jtEl) jtEl.value = r.jump_target;
  4004. }
  4005. if (r.address_list) {
  4006. const alEl = document.getElementById('nat-modal-action-addrlist');
  4007. if (alEl) alEl.value = r.address_list;
  4008. }
  4009. if (r.address_list_timeout) {
  4010. const toEl = document.getElementById('nat-modal-action-timeout');
  4011. if (toEl) toEl.value = r.address_list_timeout;
  4012. }
  4013. setNATFieldVal('logprefix', r.log_prefix, false);
  4014. // Statistics
  4015. const bEl = document.getElementById('nat-stat-bytes');
  4016. const pEl = document.getElementById('nat-stat-packets');
  4017. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  4018. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  4019. state.natLastBytes = r.bytes || 0;
  4020. state.natLastPackets = r.packets || 0;
  4021. state.natLastTimestamp = Date.now();
  4022. state.natStatRateHistory = new Array(30).fill(0);
  4023. state.natStatPktHistory = new Array(30).fill(0);
  4024. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  4025. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  4026. toggleNATActionFields();
  4027. document.getElementById('nat-modal').classList.remove('hidden');
  4028. }
  4029. function closeNATModal() {
  4030. stopNATStatPolling();
  4031. document.getElementById('nat-modal').classList.add('hidden');
  4032. }
  4033. function copyNATRule() {
  4034. document.getElementById('nat-modal-id').value = '';
  4035. const badge = document.getElementById('nat-modal-badge');
  4036. if (badge) badge.innerText = 'New...';
  4037. showToast('Rule Cloned', 'Ready to save as a new NAT rule copy', 'info');
  4038. }
  4039. function resetCurrentNATRuleCounters() {
  4040. state.natStatRateHistory = new Array(30).fill(0);
  4041. state.natStatPktHistory = new Array(30).fill(0);
  4042. state.natLastBytes = 0;
  4043. state.natLastPackets = 0;
  4044. state.natLastTimestamp = Date.now();
  4045. const bEl = document.getElementById('nat-stat-bytes');
  4046. const pEl = document.getElementById('nat-stat-packets');
  4047. const rEl = document.getElementById('nat-stat-rate');
  4048. const prEl = document.getElementById('nat-stat-pktrate');
  4049. if (bEl) bEl.value = '0 B';
  4050. if (pEl) pEl.value = '0';
  4051. if (rEl) rEl.value = '0 bps';
  4052. if (prEl) prEl.value = '0 p/s';
  4053. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  4054. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  4055. showToast('Counters Reset', 'NAT rule counter display reset to 0', 'info');
  4056. }
  4057. async function applyNATRule(closeAfter = false) {
  4058. const id = document.getElementById('nat-modal-id').value;
  4059. const chain = document.getElementById('nat-modal-chain').value;
  4060. const action = document.getElementById('nat-modal-action').value;
  4061. const comment = document.getElementById('nat-modal-comment').value.trim();
  4062. const enabled = document.getElementById('nat-modal-enabled').checked;
  4063. const src = getNATFieldVal('src', true);
  4064. const dst = getNATFieldVal('dst', true);
  4065. const srclist = getNATFieldVal('srclist', true);
  4066. const dstlist = getNATFieldVal('dstlist', true);
  4067. const srcgeo = getNATFieldVal('srcgeo', true);
  4068. const dstgeo = getNATFieldVal('dstgeo', true);
  4069. const proto = getNATFieldVal('proto', true);
  4070. const sport = getNATFieldVal('sport', true);
  4071. const dport = getNATFieldVal('dport', true);
  4072. const anyport = getNATFieldVal('anyport', true);
  4073. const iniface = getNATFieldVal('iniface', true);
  4074. const outiface = getNATFieldVal('outiface', true);
  4075. const inifacelist = getNATFieldVal('inifacelist', true);
  4076. const outifacelist = getNATFieldVal('outifacelist', true);
  4077. const pktmark = getNATFieldVal('pktmark', true);
  4078. const connmark = getNATFieldVal('connmark', true);
  4079. const routingmark = getNATFieldVal('routingmark', true);
  4080. const conntype = getNATFieldVal('conntype', false);
  4081. const usesAddr = ['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat'].includes(action);
  4082. const usesPort = ['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat', 'redirect', 'masquerade'].includes(action);
  4083. const payload = {
  4084. id,
  4085. chain,
  4086. action,
  4087. to_addresses: usesAddr ? (document.getElementById('nat-modal-toaddr')?.value.trim() || '') : '',
  4088. to_ports: usesPort ? (document.getElementById('nat-modal-toport')?.value.trim() || '') : '',
  4089. protocol: proto || 'all',
  4090. src_address: src,
  4091. dst_address: dst,
  4092. src_port: sport,
  4093. dst_port: dport,
  4094. any_port: anyport,
  4095. in_interface: iniface,
  4096. out_interface: outiface,
  4097. in_interface_list: inifacelist,
  4098. out_interface_list: outifacelist,
  4099. packet_mark: pktmark,
  4100. connection_mark: connmark,
  4101. routing_mark: routingmark,
  4102. connection_type: conntype,
  4103. src_address_list: srclist,
  4104. dst_address_list: dstlist,
  4105. src_geoip: srcgeo,
  4106. dst_geoip: dstgeo,
  4107. comment,
  4108. disabled: !enabled,
  4109. // Advanced tab
  4110. layer7_protocol: getNATFieldVal('layer7', false),
  4111. content: getNATFieldVal('content', false),
  4112. connection_bytes: getNATFieldVal('connbytes', false),
  4113. connection_rate: getNATFieldVal('connrate', false),
  4114. pcc: getNATFieldVal('pcc', false),
  4115. src_mac_address: getNATFieldVal('srcmac', true),
  4116. out_bridge_port: getNATFieldVal('outbridgeport', false),
  4117. in_bridge_port: getNATFieldVal('inbridgeport', false),
  4118. in_bridge_port_list: getNATFieldVal('inbridgeportlist', false),
  4119. out_bridge_port_list: getNATFieldVal('outbridgeportlist', false),
  4120. ipsec_policy: getNATFieldVal('ipsec', false),
  4121. ingress_priority: getNATFieldVal('ingresspriority', false),
  4122. priority: getNATFieldVal('priority', false),
  4123. dscp: getNATFieldVal('dscp', false),
  4124. tcp_mss: getNATFieldVal('tcpmss', false),
  4125. tos: document.getElementById('nat-val-tos')?.value || '',
  4126. packet_size: getNATFieldVal('pktsize', false),
  4127. random: getNATFieldVal('random', false),
  4128. icmp_options: getNATFieldVal('icmpoptions', false),
  4129. ipv4_options: getNATFieldVal('ipv4options', false),
  4130. ttl: getNATFieldVal('ttl', false),
  4131. // Extra tab
  4132. time: getNATFieldVal('time', false),
  4133. limit: getNATFieldVal('limit', false),
  4134. dst_limit: getNATFieldVal('dstlimit', false),
  4135. psd: getNATFieldVal('psd', false),
  4136. // Action tab
  4137. jump_target: action === 'jump' ? (document.getElementById('nat-modal-jumptarget')?.value || '') : '',
  4138. address_list: action.includes('address') ? (document.getElementById('nat-modal-action-addrlist')?.value || '') : '',
  4139. address_list_timeout: action.includes('address') ? (document.getElementById('nat-modal-action-timeout')?.value || '') : '',
  4140. log: document.getElementById('nat-modal-log')?.checked || false,
  4141. log_prefix: getNATFieldVal('logprefix', false)
  4142. };
  4143. try {
  4144. const res = await fetch(`${API_BASE}/firewall/nat`, {
  4145. method: 'POST',
  4146. headers: { 'Content-Type': 'application/json' },
  4147. body: JSON.stringify(payload)
  4148. });
  4149. if (res.ok) {
  4150. const data = await res.json();
  4151. showToast('NAT Rule Saved', 'NAT mapping updated', 'success');
  4152. loadFirewall(false);
  4153. if (closeAfter) {
  4154. closeNATModal();
  4155. } else {
  4156. if (data.id) {
  4157. document.getElementById('nat-modal-id').value = data.id;
  4158. const badge = document.getElementById('nat-modal-badge');
  4159. if (badge) badge.innerText = `#${data.id}`;
  4160. }
  4161. }
  4162. } else {
  4163. const err = await res.json();
  4164. showToast('Error', err.message || 'Failed to save rule', 'error');
  4165. }
  4166. } catch (err) {
  4167. showToast('Error', err.message, 'error');
  4168. }
  4169. }
  4170. function submitSaveNATRule(e) {
  4171. if (e && e.preventDefault) e.preventDefault();
  4172. return applyNATRule(true);
  4173. }
  4174. function startNATStatPolling() {
  4175. stopNATStatPolling();
  4176. pollNATRuleStats();
  4177. state.natStatInterval = setInterval(pollNATRuleStats, 1000);
  4178. }
  4179. function stopNATStatPolling() {
  4180. if (state.natStatInterval) {
  4181. clearInterval(state.natStatInterval);
  4182. state.natStatInterval = null;
  4183. }
  4184. }
  4185. async function pollNATRuleStats() {
  4186. const id = document.getElementById('nat-modal-id')?.value;
  4187. if (!id) {
  4188. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory || new Array(30).fill(0), 'bps', 'nat-stat-legend-rate');
  4189. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory || new Array(30).fill(0), 'p/s', 'nat-stat-legend-pktrate');
  4190. return;
  4191. }
  4192. try {
  4193. const res = await fetch(`${API_BASE}/firewall/nat`);
  4194. if (!res.ok) return;
  4195. const rules = await res.json();
  4196. const r = rules.find(x => x.id === id);
  4197. if (!r) return;
  4198. const now = Date.now();
  4199. const dt = Math.max(0.2, (now - (state.natLastTimestamp || now)) / 1000);
  4200. state.natLastTimestamp = now;
  4201. const curBytes = r.bytes || 0;
  4202. const curPackets = r.packets || 0;
  4203. const deltaBytes = Math.max(0, curBytes - (state.natLastBytes || curBytes));
  4204. const deltaPkts = Math.max(0, curPackets - (state.natLastPackets || curPackets));
  4205. state.natLastBytes = curBytes;
  4206. state.natLastPackets = curPackets;
  4207. const rateBps = Math.round((deltaBytes * 8) / dt);
  4208. const ratePkt = Math.round(deltaPkts / dt);
  4209. if (!state.natStatRateHistory) state.natStatRateHistory = new Array(30).fill(0);
  4210. if (!state.natStatPktHistory) state.natStatPktHistory = new Array(30).fill(0);
  4211. state.natStatRateHistory.push(rateBps);
  4212. if (state.natStatRateHistory.length > 30) state.natStatRateHistory.shift();
  4213. state.natStatPktHistory.push(ratePkt);
  4214. if (state.natStatPktHistory.length > 30) state.natStatPktHistory.shift();
  4215. const bEl = document.getElementById('nat-stat-bytes');
  4216. const pEl = document.getElementById('nat-stat-packets');
  4217. const rEl = document.getElementById('nat-stat-rate');
  4218. const prEl = document.getElementById('nat-stat-pktrate');
  4219. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  4220. if (pEl) pEl.value = curPackets.toLocaleString();
  4221. if (rEl) rEl.value = formatBps(rateBps);
  4222. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  4223. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  4224. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  4225. } catch (e) {
  4226. console.error('Error polling NAT rule stats', e);
  4227. }
  4228. }
  4229. async function moveNATRule(id, dir) {
  4230. try {
  4231. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/move`, {
  4232. method: 'POST',
  4233. headers: { 'Content-Type': 'application/json' },
  4234. body: JSON.stringify({ direction: dir })
  4235. });
  4236. if (res.ok) loadFirewall(false);
  4237. } catch (err) {
  4238. showToast('Error', err.message, 'error');
  4239. }
  4240. }
  4241. async function toggleNATRuleState(id, disabled) {
  4242. try {
  4243. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/state`, {
  4244. method: 'POST',
  4245. headers: { 'Content-Type': 'application/json' },
  4246. body: JSON.stringify({ disabled })
  4247. });
  4248. if (res.ok) loadFirewall(false);
  4249. } catch (err) {
  4250. showToast('Error', err.message, 'error');
  4251. }
  4252. }
  4253. async function deleteNATRule(id) {
  4254. if (!confirm('Are you sure you want to delete this NAT rule?')) return;
  4255. try {
  4256. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4257. if (res.ok) {
  4258. showToast('Deleted', 'NAT rule removed', 'success');
  4259. loadFirewall(false);
  4260. }
  4261. } catch (err) {
  4262. showToast('Error', err.message, 'error');
  4263. }
  4264. }
  4265. // ----------------- Mangle Rules -----------------
  4266. function renderMangleRules() {
  4267. const chainFilter = document.getElementById('mangle-filter-chain')?.value || '';
  4268. const tbody = document.getElementById('mangle-table-body');
  4269. const empty = document.getElementById('mangle-empty');
  4270. if (!tbody) return;
  4271. tbody.innerHTML = '';
  4272. const rules = (state.mangleRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  4273. document.getElementById('mangle-count-badge').innerText = `${rules.length} Rules`;
  4274. if (rules.length === 0) {
  4275. empty?.classList.remove('hidden');
  4276. return;
  4277. }
  4278. empty?.classList.add('hidden');
  4279. rules.forEach((r, idx) => {
  4280. const tr = document.createElement('tr');
  4281. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  4282. let markVal = '<span class="text-slate-500">-</span>';
  4283. if (r.new_connection_mark) markVal = `<span class="text-cyan-300 font-mono font-bold">${r.new_connection_mark}</span>`;
  4284. else if (r.new_routing_mark) markVal = `<span class="text-amber-300 font-mono font-bold">${r.new_routing_mark}</span>`;
  4285. else if (r.new_packet_mark) markVal = `<span class="text-emerald-300 font-mono font-bold">${r.new_packet_mark}</span>`;
  4286. else if (r.new_mss) markVal = `<span class="text-sky-300 font-mono font-bold">mss:${r.new_mss}</span>`;
  4287. else if (r.new_dscp) markVal = `<span class="text-purple-300 font-mono font-bold">dscp:${r.new_dscp}</span>`;
  4288. else if (r.new_ttl) markVal = `<span class="text-blue-300 font-mono font-bold">ttl:${r.new_ttl}</span>`;
  4289. else if (r.new_priority) markVal = `<span class="text-indigo-300 font-mono font-bold">prio:${r.new_priority}</span>`;
  4290. else if (r.route) markVal = `<span class="text-orange-300 font-mono font-bold">route:${r.route}</span>`;
  4291. else if (r.sniff_target) markVal = `<span class="text-pink-300 font-mono font-bold">sniff:${r.sniff_target}</span>`;
  4292. else if (r.action === 'jump') markVal = `<span class="text-yellow-300 font-mono font-bold">&rarr; ${r.jump_target || '-'}</span>`;
  4293. else if (r.action.includes('address-list') || r.action.includes('address list')) markVal = `<span class="text-emerald-300 font-mono font-bold">&rarr; ${r.address_list || '-'}</span>`;
  4294. else if (r.action === 'log') markVal = `<span class="text-slate-400 font-mono font-bold">${r.log_prefix || 'log'}</span>`;
  4295. tr.innerHTML = `
  4296. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  4297. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  4298. <td class="py-2.5 px-3 font-bold text-purple-400">${r.chain}</td>
  4299. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  4300. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  4301. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  4302. <td class="py-2.5 px-3 font-mono text-xs">${markVal}</td>
  4303. <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>
  4304. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  4305. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  4306. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  4307. </td>
  4308. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  4309. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  4310. <button onclick="moveMangleRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  4311. <button onclick="moveMangleRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  4312. <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>
  4313. <button onclick="openEditMangleModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  4314. <button onclick="deleteMangleRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  4315. </td>
  4316. `;
  4317. tbody.appendChild(tr);
  4318. });
  4319. }
  4320. // ==================== FIREWALL MANGLE MODAL (ROUTEROS WEBFIG / WINBOX V4) ====================
  4321. function switchMangleRuleTab(tab) {
  4322. state.activeMangleRuleTab = tab;
  4323. document.querySelectorAll('.mangle-rule-tab-btn').forEach(btn => {
  4324. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  4325. btn.classList.add('text-slate-400', 'border-transparent');
  4326. });
  4327. const activeBtn = document.getElementById(`mangle-tab-btn-${tab}`);
  4328. if (activeBtn) {
  4329. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  4330. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  4331. }
  4332. document.querySelectorAll('.mangle-rule-pane').forEach(p => p.classList.add('hidden'));
  4333. const activePane = document.getElementById(`mangle-pane-${tab}`);
  4334. if (activePane) activePane.classList.remove('hidden');
  4335. if (tab === 'statistics') {
  4336. startMangleStatPolling();
  4337. } else {
  4338. stopMangleStatPolling();
  4339. }
  4340. }
  4341. function toggleMangleField(fieldKey, expand) {
  4342. const plusBtn = document.getElementById(`mangle-plus-${fieldKey}`);
  4343. const fieldBox = document.getElementById(`mangle-field-${fieldKey}`);
  4344. if (!plusBtn || !fieldBox) return;
  4345. if (expand) {
  4346. plusBtn.classList.add('hidden');
  4347. fieldBox.classList.remove('hidden');
  4348. const valInput = document.getElementById(`mangle-val-${fieldKey}`);
  4349. if (valInput) valInput.focus();
  4350. } else {
  4351. fieldBox.classList.add('hidden');
  4352. plusBtn.classList.remove('hidden');
  4353. const valInput = document.getElementById(`mangle-val-${fieldKey}`);
  4354. if (valInput) {
  4355. if (valInput.tagName === 'SELECT') {
  4356. valInput.selectedIndex = 0;
  4357. } else {
  4358. valInput.value = '';
  4359. }
  4360. }
  4361. const invInput = document.getElementById(`mangle-inv-${fieldKey}`);
  4362. if (invInput) invInput.checked = false;
  4363. if (fieldKey === 'cs') {
  4364. ['mangle-modal-cs-established', 'mangle-modal-cs-related', 'mangle-modal-cs-new', 'mangle-modal-cs-invalid', 'mangle-modal-cs-untracked'].forEach(id => {
  4365. const el = document.getElementById(id);
  4366. if (el) el.checked = false;
  4367. });
  4368. }
  4369. if (fieldKey === 'natstate') {
  4370. ['mangle-modal-nat-srcnat', 'mangle-modal-nat-dstnat'].forEach(id => {
  4371. const el = document.getElementById(id);
  4372. if (el) el.checked = false;
  4373. });
  4374. }
  4375. }
  4376. }
  4377. function setMangleFieldVal(fieldKey, value, hasInvert = false) {
  4378. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  4379. toggleMangleField(fieldKey, true);
  4380. let strVal = String(value);
  4381. if (hasInvert) {
  4382. const inv = strVal.startsWith('!');
  4383. if (inv) strVal = strVal.slice(1);
  4384. const invEl = document.getElementById(`mangle-inv-${fieldKey}`);
  4385. if (invEl) invEl.checked = inv;
  4386. }
  4387. const valEl = document.getElementById(`mangle-val-${fieldKey}`);
  4388. if (valEl) valEl.value = strVal;
  4389. } else {
  4390. toggleMangleField(fieldKey, false);
  4391. }
  4392. }
  4393. function getMangleFieldVal(fieldKey, hasInvert = false) {
  4394. const fieldBox = document.getElementById(`mangle-field-${fieldKey}`);
  4395. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  4396. const valEl = document.getElementById(`mangle-val-${fieldKey}`);
  4397. let v = valEl ? valEl.value.trim() : '';
  4398. if (!v) return '';
  4399. if (hasInvert) {
  4400. const invEl = document.getElementById(`mangle-inv-${fieldKey}`);
  4401. if (invEl && invEl.checked) {
  4402. v = '!' + v.replace(/^!/, '');
  4403. }
  4404. }
  4405. return v;
  4406. }
  4407. function toggleMaximizeMangleModal() {
  4408. const win = document.getElementById('mangle-modal-window');
  4409. if (!win) return;
  4410. if (win.classList.contains('max-w-[720px]')) {
  4411. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  4412. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  4413. } else {
  4414. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  4415. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  4416. }
  4417. }
  4418. function toggleMangleActionFields() {
  4419. const act = document.getElementById('mangle-modal-action')?.value || 'mark-connection';
  4420. // Hide all dynamic rows first
  4421. ['newconnmark', 'newroutingmark', 'newpktmark', 'newmss', 'newdscp', 'newttl', 'newpriority', 'route', 'sniff', 'passthrough'].forEach(id => {
  4422. const el = document.getElementById(`mangle-row-${id}`);
  4423. if (el) el.classList.add('hidden');
  4424. });
  4425. const jumpBox = document.getElementById('mangle-action-jump-box');
  4426. const addrBox = document.getElementById('mangle-action-addrlist-box');
  4427. if (jumpBox) jumpBox.classList.add('hidden');
  4428. if (addrBox) addrBox.classList.add('hidden');
  4429. // Activate matching rows
  4430. if (act === 'mark-connection') {
  4431. document.getElementById('mangle-row-newconnmark')?.classList.remove('hidden');
  4432. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4433. } else if (act === 'mark-routing') {
  4434. document.getElementById('mangle-row-newroutingmark')?.classList.remove('hidden');
  4435. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4436. } else if (act === 'mark-packet') {
  4437. document.getElementById('mangle-row-newpktmark')?.classList.remove('hidden');
  4438. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4439. } else if (act === 'change-mss') {
  4440. document.getElementById('mangle-row-newmss')?.classList.remove('hidden');
  4441. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4442. } else if (act === 'change-dscp') {
  4443. document.getElementById('mangle-row-newdscp')?.classList.remove('hidden');
  4444. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4445. } else if (act === 'change-ttl') {
  4446. document.getElementById('mangle-row-newttl')?.classList.remove('hidden');
  4447. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4448. } else if (act === 'set-priority') {
  4449. document.getElementById('mangle-row-newpriority')?.classList.remove('hidden');
  4450. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4451. } else if (act === 'route') {
  4452. document.getElementById('mangle-row-route')?.classList.remove('hidden');
  4453. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4454. } else if (act === 'sniff-pc' || act === 'sniff-tzsp') {
  4455. document.getElementById('mangle-row-sniff')?.classList.remove('hidden');
  4456. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4457. } else if (act === 'clear-df' || act === 'strip-ipv4-options') {
  4458. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4459. } else if (act === 'jump') {
  4460. if (jumpBox) jumpBox.classList.remove('hidden');
  4461. } else if (act.includes('address-list') || act.includes('address list')) {
  4462. if (addrBox) addrBox.classList.remove('hidden');
  4463. }
  4464. if (act === 'log') {
  4465. const logEl = document.getElementById('mangle-modal-log');
  4466. if (logEl) logEl.checked = true;
  4467. toggleMangleField('logprefix', true);
  4468. }
  4469. }
  4470. function toggleMangleLogPrefix() {
  4471. const isLog = document.getElementById('mangle-modal-log')?.checked;
  4472. toggleMangleField('logprefix', !!isLog);
  4473. }
  4474. const allMangleFieldKeys = [
  4475. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  4476. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  4477. 'routingmark', 'conntype', 'cs', 'natstate',
  4478. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  4479. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  4480. 'ipsec', 'tlshost', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  4481. 'pktsize', 'random', 'tcpflags', 'icmpoptions', 'ipv4options', 'ttl',
  4482. 'nth', 'connlimit', 'srcaddrtype', 'dstaddrtype', 'hotspot', 'ipfragment',
  4483. 'limit', 'dstlimit', 'time', 'psd', 'logprefix'
  4484. ];
  4485. function openAddMangleModal() {
  4486. switchMangleRuleTab('general');
  4487. const badge = document.getElementById('mangle-modal-badge');
  4488. if (badge) badge.innerText = 'New...';
  4489. document.getElementById('mangle-modal-id').value = '';
  4490. document.getElementById('mangle-modal-enabled').checked = true;
  4491. document.getElementById('mangle-modal-comment').value = '';
  4492. document.getElementById('mangle-modal-chain').value = 'prerouting';
  4493. document.getElementById('mangle-modal-action').value = 'mark-connection';
  4494. if (document.getElementById('mangle-modal-newconnmark')) document.getElementById('mangle-modal-newconnmark').value = '';
  4495. if (document.getElementById('mangle-modal-newroutingmark')) document.getElementById('mangle-modal-newroutingmark').value = '';
  4496. if (document.getElementById('mangle-modal-newpktmark')) document.getElementById('mangle-modal-newpktmark').value = '';
  4497. if (document.getElementById('mangle-modal-newmss')) document.getElementById('mangle-modal-newmss').value = '';
  4498. if (document.getElementById('mangle-modal-newdscp')) document.getElementById('mangle-modal-newdscp').value = '';
  4499. if (document.getElementById('mangle-modal-newttl')) document.getElementById('mangle-modal-newttl').value = '';
  4500. if (document.getElementById('mangle-modal-newpriority')) document.getElementById('mangle-modal-newpriority').value = '';
  4501. if (document.getElementById('mangle-modal-route')) document.getElementById('mangle-modal-route').value = '';
  4502. if (document.getElementById('mangle-modal-sniff')) document.getElementById('mangle-modal-sniff').value = '';
  4503. if (document.getElementById('mangle-modal-jumptarget')) document.getElementById('mangle-modal-jumptarget').value = '';
  4504. if (document.getElementById('mangle-modal-action-addrlist')) document.getElementById('mangle-modal-action-addrlist').value = '';
  4505. if (document.getElementById('mangle-modal-action-timeout')) document.getElementById('mangle-modal-action-timeout').value = '';
  4506. if (document.getElementById('mangle-modal-passthrough')) document.getElementById('mangle-modal-passthrough').checked = true;
  4507. if (document.getElementById('mangle-modal-log')) document.getElementById('mangle-modal-log').checked = false;
  4508. populateInterfaceSelect('mangle-val-iniface');
  4509. populateInterfaceSelect('mangle-val-outiface');
  4510. populateAddressListSelect('mangle-val-srclist');
  4511. populateAddressListSelect('mangle-val-dstlist');
  4512. populateGeoIPSelect('mangle-val-srcgeo');
  4513. populateGeoIPSelect('mangle-val-dstgeo');
  4514. allMangleFieldKeys.forEach(k => toggleMangleField(k, false));
  4515. resetCurrentMangleRuleCounters();
  4516. toggleMangleActionFields();
  4517. document.getElementById('mangle-modal').classList.remove('hidden');
  4518. }
  4519. function openEditMangleModal(id) {
  4520. const r = (state.mangleRules || []).find(rule => rule.id === id);
  4521. if (!r) return;
  4522. switchMangleRuleTab('general');
  4523. const badge = document.getElementById('mangle-modal-badge');
  4524. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  4525. document.getElementById('mangle-modal-id').value = r.id;
  4526. document.getElementById('mangle-modal-enabled').checked = !r.disabled;
  4527. document.getElementById('mangle-modal-comment').value = r.comment || '';
  4528. document.getElementById('mangle-modal-chain').value = r.chain || 'prerouting';
  4529. document.getElementById('mangle-modal-action').value = r.action || 'mark-connection';
  4530. if (document.getElementById('mangle-modal-newconnmark')) document.getElementById('mangle-modal-newconnmark').value = r.new_connection_mark || '';
  4531. if (document.getElementById('mangle-modal-newroutingmark')) document.getElementById('mangle-modal-newroutingmark').value = r.new_routing_mark || '';
  4532. if (document.getElementById('mangle-modal-newpktmark')) document.getElementById('mangle-modal-newpktmark').value = r.new_packet_mark || '';
  4533. if (document.getElementById('mangle-modal-newmss')) document.getElementById('mangle-modal-newmss').value = r.new_mss || '';
  4534. if (document.getElementById('mangle-modal-newdscp')) document.getElementById('mangle-modal-newdscp').value = r.new_dscp != null ? r.new_dscp : '';
  4535. if (document.getElementById('mangle-modal-newttl')) document.getElementById('mangle-modal-newttl').value = r.new_ttl || '';
  4536. if (document.getElementById('mangle-modal-newpriority')) document.getElementById('mangle-modal-newpriority').value = r.new_priority || '';
  4537. if (document.getElementById('mangle-modal-route')) document.getElementById('mangle-modal-route').value = r.route || '';
  4538. if (document.getElementById('mangle-modal-sniff')) document.getElementById('mangle-modal-sniff').value = r.sniff_target || '';
  4539. if (document.getElementById('mangle-modal-jumptarget')) document.getElementById('mangle-modal-jumptarget').value = r.jump_target || '';
  4540. if (document.getElementById('mangle-modal-action-addrlist')) document.getElementById('mangle-modal-action-addrlist').value = r.address_list || '';
  4541. if (document.getElementById('mangle-modal-action-timeout')) document.getElementById('mangle-modal-action-timeout').value = r.address_list_timeout || '';
  4542. if (document.getElementById('mangle-modal-passthrough')) document.getElementById('mangle-modal-passthrough').checked = r.passthrough ?? true;
  4543. if (document.getElementById('mangle-modal-log')) document.getElementById('mangle-modal-log').checked = !!r.log;
  4544. populateInterfaceSelect('mangle-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  4545. populateInterfaceSelect('mangle-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  4546. populateAddressListSelect('mangle-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  4547. populateAddressListSelect('mangle-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  4548. populateGeoIPSelect('mangle-val-srcgeo', r.src_geoip || '');
  4549. populateGeoIPSelect('mangle-val-dstgeo', r.dst_geoip || '');
  4550. setMangleFieldVal('src', r.src_address, true);
  4551. setMangleFieldVal('dst', r.dst_address, true);
  4552. setMangleFieldVal('srclist', r.src_address_list, true);
  4553. setMangleFieldVal('dstlist', r.dst_address_list, true);
  4554. setMangleFieldVal('srcgeo', r.src_geoip, true);
  4555. setMangleFieldVal('dstgeo', r.dst_geoip, true);
  4556. if (r.protocol && r.protocol !== 'all') {
  4557. setMangleFieldVal('proto', r.protocol, true);
  4558. } else {
  4559. toggleMangleField('proto', false);
  4560. }
  4561. setMangleFieldVal('sport', r.src_port, true);
  4562. setMangleFieldVal('dport', r.dst_port, true);
  4563. setMangleFieldVal('anyport', r.any_port, true);
  4564. setMangleFieldVal('iniface', r.in_interface, true);
  4565. setMangleFieldVal('outiface', r.out_interface, true);
  4566. setMangleFieldVal('inifacelist', r.in_interface_list, true);
  4567. setMangleFieldVal('outifacelist', r.out_interface_list, true);
  4568. setMangleFieldVal('pktmark', r.packet_mark, true);
  4569. setMangleFieldVal('connmark', r.connection_mark, true);
  4570. setMangleFieldVal('routingmark', r.routing_mark, true);
  4571. setMangleFieldVal('conntype', r.connection_type, false);
  4572. // Connection State
  4573. const states = r.connection_state || [];
  4574. if (states.length > 0) {
  4575. toggleMangleField('cs', true);
  4576. ['established', 'related', 'new', 'invalid', 'untracked'].forEach(s => {
  4577. const el = document.getElementById(`mangle-modal-cs-${s}`);
  4578. if (el) el.checked = states.includes(s);
  4579. });
  4580. } else {
  4581. toggleMangleField('cs', false);
  4582. }
  4583. // Connection NAT State
  4584. const natStates = r.connection_nat_state || [];
  4585. if (natStates.length > 0) {
  4586. toggleMangleField('natstate', true);
  4587. ['srcnat', 'dstnat'].forEach(s => {
  4588. const el = document.getElementById(`mangle-modal-nat-${s}`);
  4589. if (el) el.checked = natStates.includes(s);
  4590. });
  4591. } else {
  4592. toggleMangleField('natstate', false);
  4593. }
  4594. // Advanced tab fields
  4595. setMangleFieldVal('layer7', r.layer7_protocol, false);
  4596. setMangleFieldVal('content', r.content, false);
  4597. setMangleFieldVal('connbytes', r.connection_bytes, false);
  4598. setMangleFieldVal('connrate', r.connection_rate, false);
  4599. setMangleFieldVal('pcc', r.pcc, false);
  4600. setMangleFieldVal('srcmac', r.src_mac_address, true);
  4601. setMangleFieldVal('outbridgeport', r.out_bridge_port, false);
  4602. setMangleFieldVal('inbridgeport', r.in_bridge_port, false);
  4603. setMangleFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  4604. setMangleFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  4605. setMangleFieldVal('ipsec', r.ipsec_policy, false);
  4606. setMangleFieldVal('tlshost', r.tls_host, false);
  4607. setMangleFieldVal('ingresspriority', r.ingress_priority, false);
  4608. setMangleFieldVal('priority', r.priority, false);
  4609. setMangleFieldVal('dscp', r.dscp, false);
  4610. setMangleFieldVal('tcpmss', r.tcp_mss, false);
  4611. if (r.tos) {
  4612. const tosEl = document.getElementById('mangle-val-tos');
  4613. if (tosEl) tosEl.value = r.tos;
  4614. }
  4615. setMangleFieldVal('pktsize', r.packet_size, false);
  4616. setMangleFieldVal('random', r.random, false);
  4617. setMangleFieldVal('tcpflags', r.tcp_flags, false);
  4618. setMangleFieldVal('icmpoptions', r.icmp_options, false);
  4619. setMangleFieldVal('ipv4options', r.ipv4_options, false);
  4620. setMangleFieldVal('ttl', r.ttl, false);
  4621. // Extra tab fields
  4622. setMangleFieldVal('nth', r.nth, false);
  4623. setMangleFieldVal('connlimit', r.connection_limit, false);
  4624. setMangleFieldVal('srcaddrtype', r.src_address_type, false);
  4625. setMangleFieldVal('dstaddrtype', r.dst_address_type, false);
  4626. setMangleFieldVal('hotspot', r.hotspot, false);
  4627. setMangleFieldVal('ipfragment', r.ip_fragment, false);
  4628. setMangleFieldVal('limit', r.limit, false);
  4629. setMangleFieldVal('dstlimit', r.dst_limit, false);
  4630. setMangleFieldVal('time', r.time, false);
  4631. setMangleFieldVal('psd', r.psd, false);
  4632. // Action fields
  4633. if (r.jump_target) {
  4634. const jtEl = document.getElementById('mangle-modal-jumptarget');
  4635. if (jtEl) jtEl.value = r.jump_target;
  4636. }
  4637. if (r.address_list) {
  4638. const alEl = document.getElementById('mangle-modal-action-addrlist');
  4639. if (alEl) alEl.value = r.address_list;
  4640. }
  4641. if (r.address_list_timeout) {
  4642. const toEl = document.getElementById('mangle-modal-action-timeout');
  4643. if (toEl) toEl.value = r.address_list_timeout;
  4644. }
  4645. setMangleFieldVal('logprefix', r.log_prefix, false);
  4646. // Statistics
  4647. const bEl = document.getElementById('mangle-stat-bytes');
  4648. const pEl = document.getElementById('mangle-stat-packets');
  4649. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  4650. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  4651. state.mangleLastBytes = r.bytes || 0;
  4652. state.mangleLastPackets = r.packets || 0;
  4653. state.mangleLastTimestamp = Date.now();
  4654. state.mangleStatRateHistory = new Array(30).fill(0);
  4655. state.mangleStatPktHistory = new Array(30).fill(0);
  4656. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  4657. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  4658. toggleMangleActionFields();
  4659. document.getElementById('mangle-modal').classList.remove('hidden');
  4660. }
  4661. function closeMangleModal() {
  4662. stopMangleStatPolling();
  4663. document.getElementById('mangle-modal').classList.add('hidden');
  4664. }
  4665. function copyMangleRule() {
  4666. document.getElementById('mangle-modal-id').value = '';
  4667. const badge = document.getElementById('mangle-modal-badge');
  4668. if (badge) badge.innerText = 'New...';
  4669. showToast('Rule Cloned', 'Ready to save as a new Mangle rule copy', 'info');
  4670. }
  4671. function resetCurrentMangleRuleCounters() {
  4672. state.mangleStatRateHistory = new Array(30).fill(0);
  4673. state.mangleStatPktHistory = new Array(30).fill(0);
  4674. state.mangleLastBytes = 0;
  4675. state.mangleLastPackets = 0;
  4676. state.mangleLastTimestamp = Date.now();
  4677. const bEl = document.getElementById('mangle-stat-bytes');
  4678. const pEl = document.getElementById('mangle-stat-packets');
  4679. const rEl = document.getElementById('mangle-stat-rate');
  4680. const prEl = document.getElementById('mangle-stat-pktrate');
  4681. if (bEl) bEl.value = '0 B';
  4682. if (pEl) pEl.value = '0';
  4683. if (rEl) rEl.value = '0 bps';
  4684. if (prEl) prEl.value = '0 p/s';
  4685. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  4686. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  4687. showToast('Counters Reset', 'Mangle rule counter display reset to 0', 'info');
  4688. }
  4689. async function applyMangleRule(closeAfter = false) {
  4690. const id = document.getElementById('mangle-modal-id').value;
  4691. const chain = document.getElementById('mangle-modal-chain').value;
  4692. const action = document.getElementById('mangle-modal-action').value;
  4693. const comment = document.getElementById('mangle-modal-comment').value.trim();
  4694. const enabled = document.getElementById('mangle-modal-enabled').checked;
  4695. const src = getMangleFieldVal('src', true);
  4696. const dst = getMangleFieldVal('dst', true);
  4697. const srclist = getMangleFieldVal('srclist', true);
  4698. const dstlist = getMangleFieldVal('dstlist', true);
  4699. const srcgeo = getMangleFieldVal('srcgeo', true);
  4700. const dstgeo = getMangleFieldVal('dstgeo', true);
  4701. const proto = getMangleFieldVal('proto', true);
  4702. const sport = getMangleFieldVal('sport', true);
  4703. const dport = getMangleFieldVal('dport', true);
  4704. const anyport = getMangleFieldVal('anyport', true);
  4705. const iniface = getMangleFieldVal('iniface', true);
  4706. const outiface = getMangleFieldVal('outiface', true);
  4707. const inifacelist = getMangleFieldVal('inifacelist', true);
  4708. const outifacelist = getMangleFieldVal('outifacelist', true);
  4709. const pktmark = getMangleFieldVal('pktmark', true);
  4710. const connmark = getMangleFieldVal('connmark', true);
  4711. const routingmark = getMangleFieldVal('routingmark', true);
  4712. const conntype = getMangleFieldVal('conntype', false);
  4713. const states = [];
  4714. const csBox = document.getElementById('mangle-field-cs');
  4715. if (csBox && !csBox.classList.contains('hidden')) {
  4716. ['established', 'related', 'new', 'invalid', 'untracked'].forEach(s => {
  4717. if (document.getElementById(`mangle-modal-cs-${s}`)?.checked) states.push(s);
  4718. });
  4719. }
  4720. const natStates = [];
  4721. const natBox = document.getElementById('mangle-field-natstate');
  4722. if (natBox && !natBox.classList.contains('hidden')) {
  4723. ['srcnat', 'dstnat'].forEach(s => {
  4724. if (document.getElementById(`mangle-modal-nat-${s}`)?.checked) natStates.push(s);
  4725. });
  4726. }
  4727. const payload = {
  4728. id,
  4729. chain,
  4730. action,
  4731. protocol: proto || 'all',
  4732. src_address: src,
  4733. dst_address: dst,
  4734. src_port: sport,
  4735. dst_port: dport,
  4736. any_port: anyport,
  4737. in_interface: iniface,
  4738. out_interface: outiface,
  4739. in_interface_list: inifacelist,
  4740. out_interface_list: outifacelist,
  4741. packet_mark: pktmark,
  4742. connection_mark: connmark,
  4743. routing_mark: routingmark,
  4744. connection_type: conntype,
  4745. connection_state: states,
  4746. connection_nat_state: natStates,
  4747. src_address_list: srclist,
  4748. dst_address_list: dstlist,
  4749. src_geoip: srcgeo,
  4750. dst_geoip: dstgeo,
  4751. comment,
  4752. disabled: !enabled,
  4753. // Advanced tab
  4754. layer7_protocol: getMangleFieldVal('layer7', false),
  4755. content: getMangleFieldVal('content', false),
  4756. connection_bytes: getMangleFieldVal('connbytes', false),
  4757. connection_rate: getMangleFieldVal('connrate', false),
  4758. pcc: getMangleFieldVal('pcc', false),
  4759. src_mac_address: getMangleFieldVal('srcmac', true),
  4760. out_bridge_port: getMangleFieldVal('outbridgeport', false),
  4761. in_bridge_port: getMangleFieldVal('inbridgeport', false),
  4762. in_bridge_port_list: getMangleFieldVal('inbridgeportlist', false),
  4763. out_bridge_port_list: getMangleFieldVal('outbridgeportlist', false),
  4764. ipsec_policy: getMangleFieldVal('ipsec', false),
  4765. tls_host: getMangleFieldVal('tlshost', false),
  4766. ingress_priority: getMangleFieldVal('ingresspriority', false),
  4767. priority: getMangleFieldVal('priority', false),
  4768. dscp: getMangleFieldVal('dscp', false),
  4769. tcp_mss: getMangleFieldVal('tcpmss', false),
  4770. tos: document.getElementById('mangle-val-tos')?.value || '',
  4771. packet_size: getMangleFieldVal('pktsize', false),
  4772. random: getMangleFieldVal('random', false),
  4773. tcp_flags: getMangleFieldVal('tcpflags', false),
  4774. icmp_options: getMangleFieldVal('icmpoptions', false),
  4775. ipv4_options: getMangleFieldVal('ipv4options', false),
  4776. ttl: getMangleFieldVal('ttl', false),
  4777. // Extra tab
  4778. nth: getMangleFieldVal('nth', false),
  4779. connection_limit: getMangleFieldVal('connlimit', false),
  4780. src_address_type: getMangleFieldVal('srcaddrtype', false),
  4781. dst_address_type: getMangleFieldVal('dstaddrtype', false),
  4782. hotspot: getMangleFieldVal('hotspot', false),
  4783. ip_fragment: getMangleFieldVal('ipfragment', false),
  4784. limit: getMangleFieldVal('limit', false),
  4785. dst_limit: getMangleFieldVal('dstlimit', false),
  4786. time: getMangleFieldVal('time', false),
  4787. psd: getMangleFieldVal('psd', false),
  4788. // Action tab
  4789. new_connection_mark: action === 'mark-connection' ? (document.getElementById('mangle-modal-newconnmark')?.value.trim() || '') : '',
  4790. new_routing_mark: action === 'mark-routing' ? (document.getElementById('mangle-modal-newroutingmark')?.value.trim() || '') : '',
  4791. new_packet_mark: action === 'mark-packet' ? (document.getElementById('mangle-modal-newpktmark')?.value.trim() || '') : '',
  4792. new_mss: action === 'change-mss' ? (document.getElementById('mangle-modal-newmss')?.value.trim() || '') : '',
  4793. new_dscp: action === 'change-dscp' ? parseInt(document.getElementById('mangle-modal-newdscp')?.value || '0', 10) : 0,
  4794. new_ttl: action === 'change-ttl' ? (document.getElementById('mangle-modal-newttl')?.value.trim() || '') : '',
  4795. new_priority: action === 'set-priority' ? (document.getElementById('mangle-modal-newpriority')?.value.trim() || '') : '',
  4796. route: action === 'route' ? (document.getElementById('mangle-modal-route')?.value.trim() || '') : '',
  4797. sniff_target: (action === 'sniff-pc' || action === 'sniff-tzsp') ? (document.getElementById('mangle-modal-sniff')?.value.trim() || '') : '',
  4798. passthrough: document.getElementById('mangle-modal-passthrough')?.checked ?? true,
  4799. jump_target: action === 'jump' ? (document.getElementById('mangle-modal-jumptarget')?.value || '') : '',
  4800. address_list: action.includes('address') ? (document.getElementById('mangle-modal-action-addrlist')?.value || '') : '',
  4801. address_list_timeout: action.includes('address') ? (document.getElementById('mangle-modal-action-timeout')?.value || '') : '',
  4802. log: document.getElementById('mangle-modal-log')?.checked || false,
  4803. log_prefix: getMangleFieldVal('logprefix', false)
  4804. };
  4805. try {
  4806. const res = await fetch(`${API_BASE}/firewall/mangle`, {
  4807. method: 'POST',
  4808. headers: { 'Content-Type': 'application/json' },
  4809. body: JSON.stringify(payload)
  4810. });
  4811. if (res.ok) {
  4812. const data = await res.json();
  4813. showToast('Mangle Rule Saved', 'Marking rule updated', 'success');
  4814. loadFirewall(false);
  4815. if (closeAfter) {
  4816. closeMangleModal();
  4817. } else {
  4818. if (data.id) {
  4819. document.getElementById('mangle-modal-id').value = data.id;
  4820. const badge = document.getElementById('mangle-modal-badge');
  4821. if (badge) badge.innerText = `#${data.id}`;
  4822. }
  4823. }
  4824. } else {
  4825. const err = await res.json();
  4826. showToast('Error', err.message || 'Failed to save mangle rule', 'error');
  4827. }
  4828. } catch (err) {
  4829. showToast('Error', err.message, 'error');
  4830. }
  4831. }
  4832. function submitSaveMangleRule(e) {
  4833. if (e && e.preventDefault) e.preventDefault();
  4834. return applyMangleRule(true);
  4835. }
  4836. function startMangleStatPolling() {
  4837. stopMangleStatPolling();
  4838. pollMangleRuleStats();
  4839. state.mangleStatInterval = setInterval(pollMangleRuleStats, 1000);
  4840. }
  4841. function stopMangleStatPolling() {
  4842. if (state.mangleStatInterval) {
  4843. clearInterval(state.mangleStatInterval);
  4844. state.mangleStatInterval = null;
  4845. }
  4846. }
  4847. async function pollMangleRuleStats() {
  4848. const id = document.getElementById('mangle-modal-id')?.value;
  4849. if (!id) {
  4850. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory || new Array(30).fill(0), 'bps', 'mangle-stat-legend-rate');
  4851. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory || new Array(30).fill(0), 'p/s', 'mangle-stat-legend-pktrate');
  4852. return;
  4853. }
  4854. try {
  4855. const res = await fetch(`${API_BASE}/firewall/mangle`);
  4856. if (!res.ok) return;
  4857. const rules = await res.json();
  4858. const r = rules.find(x => x.id === id);
  4859. if (!r) return;
  4860. const now = Date.now();
  4861. const dt = Math.max(0.2, (now - (state.mangleLastTimestamp || now)) / 1000);
  4862. state.mangleLastTimestamp = now;
  4863. const curBytes = r.bytes || 0;
  4864. const curPackets = r.packets || 0;
  4865. const deltaBytes = Math.max(0, curBytes - (state.mangleLastBytes || curBytes));
  4866. const deltaPkts = Math.max(0, curPackets - (state.mangleLastPackets || curPackets));
  4867. state.mangleLastBytes = curBytes;
  4868. state.mangleLastPackets = curPackets;
  4869. const rateBps = Math.round((deltaBytes * 8) / dt);
  4870. const ratePkt = Math.round(deltaPkts / dt);
  4871. if (!state.mangleStatRateHistory) state.mangleStatRateHistory = new Array(30).fill(0);
  4872. if (!state.mangleStatPktHistory) state.mangleStatPktHistory = new Array(30).fill(0);
  4873. state.mangleStatRateHistory.push(rateBps);
  4874. if (state.mangleStatRateHistory.length > 30) state.mangleStatRateHistory.shift();
  4875. state.mangleStatPktHistory.push(ratePkt);
  4876. if (state.mangleStatPktHistory.length > 30) state.mangleStatPktHistory.shift();
  4877. const bEl = document.getElementById('mangle-stat-bytes');
  4878. const pEl = document.getElementById('mangle-stat-packets');
  4879. const rEl = document.getElementById('mangle-stat-rate');
  4880. const prEl = document.getElementById('mangle-stat-pktrate');
  4881. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  4882. if (pEl) pEl.value = curPackets.toLocaleString();
  4883. if (rEl) rEl.value = formatBps(rateBps);
  4884. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  4885. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  4886. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  4887. } catch (e) {
  4888. console.error('Error polling Mangle rule stats', e);
  4889. }
  4890. }
  4891. async function moveMangleRule(id, dir) {
  4892. try {
  4893. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/move`, {
  4894. method: 'POST',
  4895. headers: { 'Content-Type': 'application/json' },
  4896. body: JSON.stringify({ direction: dir })
  4897. });
  4898. if (res.ok) loadFirewall(false);
  4899. } catch (err) {
  4900. showToast('Error', err.message, 'error');
  4901. }
  4902. }
  4903. async function toggleMangleRuleState(id, disabled) {
  4904. try {
  4905. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/state`, {
  4906. method: 'POST',
  4907. headers: { 'Content-Type': 'application/json' },
  4908. body: JSON.stringify({ disabled })
  4909. });
  4910. if (res.ok) loadFirewall(false);
  4911. } catch (err) {
  4912. showToast('Error', err.message, 'error');
  4913. }
  4914. }
  4915. async function deleteMangleRule(id) {
  4916. if (!confirm('Are you sure you want to delete this mangle rule?')) return;
  4917. try {
  4918. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4919. if (res.ok) {
  4920. showToast('Deleted', 'Mangle rule removed', 'success');
  4921. loadFirewall(false);
  4922. }
  4923. } catch (err) {
  4924. showToast('Error', err.message, 'error');
  4925. }
  4926. }
  4927. // ----------------- Address Lists -----------------
  4928. function renderAddressLists() {
  4929. const filterList = document.getElementById('addrlist-filter-name')?.value || '';
  4930. const tbody = document.getElementById('addrlist-table-body');
  4931. const empty = document.getElementById('addrlist-empty');
  4932. if (!tbody) return;
  4933. tbody.innerHTML = '';
  4934. const entries = (state.addressLists || []).filter(e => !filterList || e.name === filterList);
  4935. document.getElementById('addrlist-count-badge').innerText = `${entries.length} Entries`;
  4936. // Update filter select
  4937. const sel = document.getElementById('addrlist-filter-name');
  4938. if (sel) {
  4939. const cur = sel.value;
  4940. sel.innerHTML = '<option value="">All Lists</option>';
  4941. const set = new Set((state.addressLists || []).map(a => a.name));
  4942. set.forEach(n => {
  4943. const opt = document.createElement('option');
  4944. opt.value = n;
  4945. opt.innerText = n;
  4946. if (n === cur) opt.selected = true;
  4947. sel.appendChild(opt);
  4948. });
  4949. }
  4950. if (entries.length === 0) {
  4951. empty?.classList.remove('hidden');
  4952. return;
  4953. }
  4954. empty?.classList.add('hidden');
  4955. entries.forEach((e, idx) => {
  4956. const tr = document.createElement('tr');
  4957. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${e.disabled ? 'opacity-50' : ''}`;
  4958. tr.setAttribute('ondblclick', `openEditAddrListModal('${e.id}')`);
  4959. tr.innerHTML = `
  4960. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  4961. <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>
  4962. <td class="py-2.5 px-3 font-bold text-white font-mono">${e.name}</td>
  4963. <td class="py-2.5 px-3 font-mono font-bold text-emerald-400">${e.address}</td>
  4964. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[150px]">${e.comment || '-'}</td>
  4965. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  4966. <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>
  4967. <button onclick="openEditAddrListModal('${e.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-medium">Edit</button>
  4968. <button onclick="deleteAddrList('${e.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  4969. </td>
  4970. `;
  4971. tbody.appendChild(tr);
  4972. });
  4973. populateCommonAddrListDatalist();
  4974. }
  4975. function openAddAddrListModal() {
  4976. document.getElementById('addrlist-modal-title').innerText = 'Add Address List Entry';
  4977. document.getElementById('addrlist-modal-id').value = '';
  4978. document.getElementById('addrlist-modal-name').value = '';
  4979. document.getElementById('addrlist-modal-addr').value = '';
  4980. document.getElementById('addrlist-modal-comment').value = '';
  4981. document.getElementById('addrlist-modal-disabled').checked = false;
  4982. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  4983. if (submitBtn) submitBtn.innerText = 'Add to List';
  4984. document.getElementById('addrlist-modal').classList.remove('hidden');
  4985. }
  4986. function openEditAddrListModal(id) {
  4987. const e = (state.addressLists || []).find(item => item.id === id);
  4988. if (!e) return;
  4989. document.getElementById('addrlist-modal-title').innerText = `Edit Address List Entry: ${e.name}`;
  4990. document.getElementById('addrlist-modal-id').value = e.id;
  4991. document.getElementById('addrlist-modal-name').value = e.name;
  4992. document.getElementById('addrlist-modal-addr').value = e.address;
  4993. document.getElementById('addrlist-modal-comment').value = e.comment || '';
  4994. document.getElementById('addrlist-modal-disabled').checked = !!e.disabled;
  4995. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  4996. if (submitBtn) submitBtn.innerText = 'Save Changes';
  4997. document.getElementById('addrlist-modal').classList.remove('hidden');
  4998. }
  4999. function closeAddrListModal() {
  5000. document.getElementById('addrlist-modal').classList.add('hidden');
  5001. }
  5002. async function submitSaveAddrList(e) {
  5003. e.preventDefault();
  5004. const id = document.getElementById('addrlist-modal-id').value;
  5005. const name = document.getElementById('addrlist-modal-name').value.trim();
  5006. const addr = document.getElementById('addrlist-modal-addr').value.trim();
  5007. const comment = document.getElementById('addrlist-modal-comment').value.trim();
  5008. const disabled = document.getElementById('addrlist-modal-disabled').checked;
  5009. try {
  5010. const res = await fetch(`${API_BASE}/firewall/address-lists`, {
  5011. method: 'POST',
  5012. headers: { 'Content-Type': 'application/json' },
  5013. body: JSON.stringify({ id, name, address: addr, comment, disabled })
  5014. });
  5015. if (res.ok) {
  5016. showToast('Address List Item Saved', `Saved ${addr} in ${name}`, 'success');
  5017. closeAddrListModal();
  5018. loadFirewall(false);
  5019. } else {
  5020. const err = await res.json();
  5021. showToast('Error', err.message || 'Failed to save address list', 'error');
  5022. }
  5023. } catch (err) {
  5024. showToast('Error', err.message, 'error');
  5025. }
  5026. }
  5027. async function toggleAddrListState(id, disabled) {
  5028. try {
  5029. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}/state`, {
  5030. method: 'POST',
  5031. headers: { 'Content-Type': 'application/json' },
  5032. body: JSON.stringify({ disabled })
  5033. });
  5034. if (res.ok) {
  5035. loadFirewall(false);
  5036. }
  5037. } catch (err) {
  5038. showToast('Error', err.message, 'error');
  5039. }
  5040. }
  5041. async function deleteAddrList(id) {
  5042. if (!confirm('Are you sure you want to delete this address list item?')) return;
  5043. try {
  5044. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5045. if (res.ok) {
  5046. showToast('Deleted', 'Address list item removed', 'info');
  5047. loadFirewall(false);
  5048. }
  5049. } catch (err) {
  5050. showToast('Error', err.message, 'error');
  5051. }
  5052. }
  5053. // ----------------- Geo-Location IP Management -----------------
  5054. async function loadGeoIP() {
  5055. try {
  5056. const [statusRes, countriesRes] = await Promise.all([
  5057. fetch(`${API_BASE}/firewall/geoip/status`),
  5058. fetch(`${API_BASE}/firewall/geoip/countries`)
  5059. ]);
  5060. if (statusRes.ok) state.geoStatus = await statusRes.json();
  5061. if (countriesRes.ok) state.geoCountries = await countriesRes.json();
  5062. updateGeoHeader();
  5063. renderGeoCountries();
  5064. } catch (err) {
  5065. console.error('Failed to load GeoIP:', err);
  5066. }
  5067. }
  5068. function getGeoUsageMap() {
  5069. const usage = {};
  5070. const checkRule = (r, type) => {
  5071. ['src_geoip', 'dst_geoip'].forEach(field => {
  5072. let val = (r && r[field]) || '';
  5073. let code = val.replace(/^!/, '').replace(/^geo:/, '').replace(/^geo_/, '').toUpperCase().trim();
  5074. if (code) {
  5075. if (!usage[code]) usage[code] = [];
  5076. const label = `${type} #${r.priority !== undefined ? r.priority : (r.id || '')}`;
  5077. if (!usage[code].includes(label)) usage[code].push(label);
  5078. }
  5079. });
  5080. };
  5081. (state.filterRules || []).forEach(r => checkRule(r, 'Filter'));
  5082. (state.natRules || []).forEach(r => checkRule(r, 'NAT'));
  5083. (state.mangleRules || []).forEach(r => checkRule(r, 'Mangle'));
  5084. return usage;
  5085. }
  5086. function updateGeoHeader() {
  5087. const s = state.geoStatus || {};
  5088. const statusBadge = document.getElementById('geo-status-badge');
  5089. if (statusBadge) {
  5090. statusBadge.innerText = s.auto_update ? 'Auto-Update ON' : 'Auto-Update OFF';
  5091. statusBadge.className = s.auto_update
  5092. ? 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-emerald-500/20 text-emerald-300 border border-emerald-500/30'
  5093. : 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 text-slate-400';
  5094. }
  5095. const intervalLabel = document.getElementById('geo-interval-label');
  5096. if (intervalLabel) {
  5097. intervalLabel.innerText = `Every ${s.interval_hours || 24}h`;
  5098. }
  5099. const usageMap = getGeoUsageMap();
  5100. const inUseCount = Object.keys(usageMap).length;
  5101. const activeCountEl = document.getElementById('geo-stat-active-countries');
  5102. if (activeCountEl) activeCountEl.innerText = inUseCount.toLocaleString();
  5103. const totalSubnetsEl = document.getElementById('geo-stat-total-subnets');
  5104. if (totalSubnetsEl) totalSubnetsEl.innerText = (s.total_subnets || 0).toLocaleString();
  5105. const lastSyncEl = document.getElementById('geo-stat-last-sync');
  5106. if (lastSyncEl) {
  5107. if (s.last_updated && !s.last_updated.startsWith('0001')) {
  5108. const d = new Date(s.last_updated);
  5109. lastSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  5110. } else {
  5111. lastSyncEl.innerText = 'Never (Sync Pending)';
  5112. }
  5113. }
  5114. const nextSyncEl = document.getElementById('geo-stat-next-sync');
  5115. if (nextSyncEl) {
  5116. if (s.next_update && !s.next_update.startsWith('0001')) {
  5117. const d = new Date(s.next_update);
  5118. nextSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  5119. } else {
  5120. nextSyncEl.innerText = '-';
  5121. }
  5122. }
  5123. const badge = document.getElementById('fw-badge-geo');
  5124. if (badge) badge.innerText = inUseCount || (state.geoCountries || []).filter(c => c.subnet_count > 0).length || 0;
  5125. }
  5126. function renderGeoCountries() {
  5127. const tbody = document.getElementById('geo-table-body');
  5128. const empty = document.getElementById('geo-empty');
  5129. if (!tbody) return;
  5130. tbody.innerHTML = '';
  5131. const q = (document.getElementById('geo-search-input')?.value || '').trim().toLowerCase();
  5132. const continent = document.getElementById('geo-continent-filter')?.value || '';
  5133. const inUseOnly = document.getElementById('geo-filter-inuse-only')?.checked;
  5134. const cachedOnly = document.getElementById('geo-filter-cached-only')?.checked;
  5135. const usageMap = getGeoUsageMap();
  5136. const countries = (state.geoCountries || []).filter(c => {
  5137. const isUsed = !!usageMap[c.code];
  5138. if (inUseOnly && !isUsed) return false;
  5139. if (cachedOnly && (!c.subnet_count || c.subnet_count === 0)) return false;
  5140. if (continent && c.continent !== continent) return false;
  5141. if (q) {
  5142. const matchCode = c.code.toLowerCase().includes(q);
  5143. const matchName = c.name.toLowerCase().includes(q);
  5144. if (!matchCode && !matchName) return false;
  5145. }
  5146. return true;
  5147. });
  5148. if (countries.length === 0) {
  5149. empty?.classList.remove('hidden');
  5150. return;
  5151. }
  5152. empty?.classList.add('hidden');
  5153. countries.forEach(c => {
  5154. const tr = document.createElement('tr');
  5155. const isUsed = !!usageMap[c.code];
  5156. const rulesUsing = usageMap[c.code] || [];
  5157. tr.className = `hover:bg-slate-800/40 transition text-xs ${isUsed ? 'bg-emerald-950/20' : ''}`;
  5158. let statusHtml = '';
  5159. if (isUsed) {
  5160. 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>`;
  5161. } else if (c.subnet_count > 0) {
  5162. 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>';
  5163. } else {
  5164. statusHtml = '<span class="px-2 py-0.5 rounded text-[10px] font-mono text-slate-500 bg-slate-800/60">READY</span>';
  5165. }
  5166. tr.innerHTML = `
  5167. <td class="py-2.5 px-3 text-center">
  5168. <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'}">
  5169. ${c.code}
  5170. </span>
  5171. </td>
  5172. <td class="py-2.5 px-3 font-bold text-white">${c.name}</td>
  5173. <td class="py-2.5 px-3 text-slate-400">${c.continent}</td>
  5174. <td class="py-2.5 px-3 font-mono ${c.subnet_count > 0 ? 'text-emerald-400 font-bold' : 'text-slate-500'}">
  5175. ${c.subnet_count > 0 ? c.subnet_count.toLocaleString() + ' CIDRs' : 'Not Cached'}
  5176. </td>
  5177. <td class="py-2.5 px-3 font-mono text-purple-300">${c.ipset_name}</td>
  5178. <td class="py-2.5 px-3">
  5179. ${statusHtml}
  5180. </td>
  5181. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  5182. <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>
  5183. <button onclick="viewGeoSubnets('${c.code}')" class="text-xs text-slate-400 hover:text-white" title="Preview Subnet Ranges">View</button>
  5184. </td>
  5185. `;
  5186. tbody.appendChild(tr);
  5187. });
  5188. }
  5189. function quickFilterGeo(preset) {
  5190. const searchInput = document.getElementById('geo-search-input');
  5191. const continentSel = document.getElementById('geo-continent-filter');
  5192. const inUseCheck = document.getElementById('geo-filter-inuse-only');
  5193. const cachedCheck = document.getElementById('geo-filter-cached-only');
  5194. if (searchInput) searchInput.value = '';
  5195. if (continentSel) continentSel.value = '';
  5196. if (inUseCheck) inUseCheck.checked = false;
  5197. if (cachedCheck) cachedCheck.checked = false;
  5198. if (preset === 'GR') {
  5199. if (searchInput) searchInput.value = 'Greece';
  5200. } else if (preset === 'Europe') {
  5201. if (continentSel) continentSel.value = 'Europe';
  5202. } else if (preset === 'HIGHRISK') {
  5203. if (searchInput) searchInput.value = 'China';
  5204. }
  5205. renderGeoCountries();
  5206. }
  5207. async function toggleGeoCountry(code, enabled) {
  5208. try {
  5209. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/toggle`, {
  5210. method: 'POST',
  5211. headers: { 'Content-Type': 'application/json' },
  5212. body: JSON.stringify({ enabled })
  5213. });
  5214. if (res.ok) {
  5215. showToast(enabled ? 'Country Enabled' : 'Country Disabled', `${code} ${enabled ? 'active in firewall' : 'removed from firewall'}`, 'success');
  5216. loadGeoIP();
  5217. } else {
  5218. const err = await res.json();
  5219. showToast('Error', err.message || 'Failed to toggle country', 'error');
  5220. }
  5221. } catch (err) {
  5222. showToast('Error', err.message, 'error');
  5223. }
  5224. }
  5225. async function updateGeoCountry(code) {
  5226. try {
  5227. showToast('Syncing Country', `Downloading latest IP blocks for ${code}...`, 'info');
  5228. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/update`, { method: 'POST' });
  5229. if (res.ok) {
  5230. const data = await res.json();
  5231. showToast('Synced', `Loaded ${data.subnets} CIDR blocks for ${code}`, 'success');
  5232. loadGeoIP();
  5233. } else {
  5234. const err = await res.json();
  5235. showToast('Sync Error', err.message || 'Failed to sync country', 'error');
  5236. }
  5237. } catch (err) {
  5238. showToast('Error', err.message, 'error');
  5239. }
  5240. }
  5241. async function triggerGeoUpdateNow() {
  5242. const spinner = document.getElementById('geo-update-spinner');
  5243. if (spinner) spinner.classList.remove('hidden');
  5244. try {
  5245. const res = await fetch(`${API_BASE}/firewall/geoip/update-now`, { method: 'POST' });
  5246. if (res.ok) {
  5247. showToast('Update Started', 'Updating all active GeoIP country zones in background...', 'info');
  5248. setTimeout(() => {
  5249. loadGeoIP();
  5250. if (spinner) spinner.classList.add('hidden');
  5251. }, 2500);
  5252. } else {
  5253. const err = await res.json();
  5254. showToast('Notice', err.message || 'Update in progress', 'info');
  5255. if (spinner) spinner.classList.add('hidden');
  5256. }
  5257. } catch (err) {
  5258. showToast('Error', err.message, 'error');
  5259. if (spinner) spinner.classList.add('hidden');
  5260. }
  5261. }
  5262. async function applyGeoPreset(preset) {
  5263. try {
  5264. const res = await fetch(`${API_BASE}/firewall/geoip/batch-toggle`, {
  5265. method: 'POST',
  5266. headers: { 'Content-Type': 'application/json' },
  5267. body: JSON.stringify({ preset, enabled: preset !== 'NONE' })
  5268. });
  5269. if (res.ok) {
  5270. showToast('Preset Applied', `Preset ${preset} updated in firewall`, 'success');
  5271. loadGeoIP();
  5272. }
  5273. } catch (err) {
  5274. showToast('Error', err.message, 'error');
  5275. }
  5276. }
  5277. function openGeoIntervalModal() {
  5278. const s = state.geoStatus || {};
  5279. document.getElementById('geo-cfg-autoupdate').checked = s.auto_update !== false;
  5280. const sel = document.getElementById('geo-cfg-interval');
  5281. const customBox = document.getElementById('geo-cfg-custom-box');
  5282. const customHoursInput = document.getElementById('geo-cfg-custom-hours');
  5283. const curHours = s.interval_hours || 24;
  5284. const matchOption = Array.from(sel.options).find(o => parseInt(o.value, 10) === curHours);
  5285. if (matchOption) {
  5286. sel.value = String(curHours);
  5287. customBox.classList.add('hidden');
  5288. } else {
  5289. sel.value = 'custom';
  5290. customHoursInput.value = curHours;
  5291. customBox.classList.remove('hidden');
  5292. }
  5293. document.getElementById('geo-interval-modal').classList.remove('hidden');
  5294. }
  5295. function closeGeoIntervalModal() {
  5296. document.getElementById('geo-interval-modal').classList.add('hidden');
  5297. }
  5298. function toggleCustomGeoInterval() {
  5299. const val = document.getElementById('geo-cfg-interval').value;
  5300. const customBox = document.getElementById('geo-cfg-custom-box');
  5301. if (val === 'custom') {
  5302. customBox.classList.remove('hidden');
  5303. } else {
  5304. customBox.classList.add('hidden');
  5305. }
  5306. }
  5307. async function submitGeoIntervalSettings(e) {
  5308. e.preventDefault();
  5309. const autoUpdate = document.getElementById('geo-cfg-autoupdate').checked;
  5310. const intervalVal = document.getElementById('geo-cfg-interval').value;
  5311. let hours = 24;
  5312. if (intervalVal === 'custom') {
  5313. hours = parseInt(document.getElementById('geo-cfg-custom-hours').value, 10) || 24;
  5314. } else {
  5315. hours = parseInt(intervalVal, 10) || 24;
  5316. }
  5317. try {
  5318. const res = await fetch(`${API_BASE}/firewall/geoip/config`, {
  5319. method: 'POST',
  5320. headers: { 'Content-Type': 'application/json' },
  5321. body: JSON.stringify({ auto_update: autoUpdate, interval_hours: hours })
  5322. });
  5323. if (res.ok) {
  5324. showToast('Schedule Saved', `Auto-update set to every ${hours} hours`, 'success');
  5325. closeGeoIntervalModal();
  5326. loadGeoIP();
  5327. } else {
  5328. const err = await res.json();
  5329. showToast('Error', err.message || 'Failed to save schedule', 'error');
  5330. }
  5331. } catch (err) {
  5332. showToast('Error', err.message, 'error');
  5333. }
  5334. }
  5335. async function viewGeoSubnets(code, name) {
  5336. if (!name) {
  5337. const found = (state.geoCountries || []).find(x => x.code === code);
  5338. name = found ? found.name : code;
  5339. }
  5340. document.getElementById('geo-subnets-title').innerText = `${name} (${code}) Subnets`;
  5341. document.getElementById('geo-subnets-subtitle').innerText = `Kernel IPSet: mk_geo_${code}`;
  5342. const listEl = document.getElementById('geo-subnets-list');
  5343. listEl.innerHTML = '<span class="text-slate-500">Loading subnets...</span>';
  5344. document.getElementById('geo-subnets-modal').classList.remove('hidden');
  5345. try {
  5346. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/subnets`);
  5347. if (res.ok) {
  5348. const data = await res.json();
  5349. const subnets = data.subnets || [];
  5350. if (subnets.length === 0) {
  5351. listEl.innerHTML = '<span class="text-slate-500">No cached subnets found. Click Sync to download this zone.</span>';
  5352. } else {
  5353. listEl.innerHTML = subnets.map(s => `<div>${s}</div>`).join('');
  5354. }
  5355. } else {
  5356. listEl.innerHTML = '<span class="text-rose-400">Failed to load subnets.</span>';
  5357. }
  5358. } catch (err) {
  5359. listEl.innerHTML = `<span class="text-rose-400">Error: ${err.message}</span>`;
  5360. }
  5361. }
  5362. function closeGeoSubnetsModal() {
  5363. document.getElementById('geo-subnets-modal').classList.add('hidden');
  5364. }
  5365. // ----------------- Active Connections Tracking -----------------
  5366. async function loadConnections() {
  5367. try {
  5368. const res = await fetch(`${API_BASE}/firewall/connections`);
  5369. const data = await res.json();
  5370. state.connections = Array.isArray(data) ? data : [];
  5371. document.getElementById('fw-badge-connections').innerText = state.connections.length;
  5372. document.getElementById('conns-count-badge').innerText = `${state.connections.length} Flows`;
  5373. renderConnections();
  5374. } catch (err) {
  5375. console.error('Failed to load connections:', err);
  5376. }
  5377. }
  5378. function renderConnections() {
  5379. const search = (document.getElementById('conns-search-input')?.value || '').toLowerCase();
  5380. const protoFilter = document.getElementById('conns-filter-proto')?.value || '';
  5381. const tbody = document.getElementById('conns-table-body');
  5382. const empty = document.getElementById('conns-empty');
  5383. if (!tbody) return;
  5384. tbody.innerHTML = '';
  5385. const conns = (state.connections || []).filter(c => {
  5386. if (protoFilter && c.protocol !== protoFilter) return false;
  5387. if (search) {
  5388. const line = `${c.protocol} ${c.src_address} ${c.dst_address} ${c.src_port} ${c.dst_port} ${c.tcp_state} ${c.connection_mark}`.toLowerCase();
  5389. if (!line.includes(search)) return false;
  5390. }
  5391. return true;
  5392. });
  5393. if (conns.length === 0) {
  5394. empty?.classList.remove('hidden');
  5395. return;
  5396. }
  5397. empty?.classList.add('hidden');
  5398. conns.slice(0, 150).forEach(c => {
  5399. const tr = document.createElement('tr');
  5400. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  5401. let stateColor = 'text-slate-400';
  5402. if (c.tcp_state === 'ESTABLISHED') stateColor = 'text-emerald-400 font-bold';
  5403. else if (c.tcp_state === 'TIME_WAIT' || c.tcp_state === 'SYN_SENT') stateColor = 'text-amber-400';
  5404. tr.innerHTML = `
  5405. <td class="py-2.5 px-3 font-bold text-cyan-400">${c.protocol}</td>
  5406. <td class="py-2.5 px-3 font-mono text-white">${c.src_address}:${c.src_port}</td>
  5407. <td class="py-2.5 px-3 font-mono text-white">${c.dst_address}:${c.dst_port}</td>
  5408. <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>
  5409. <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>
  5410. <td class="py-2.5 px-3 font-mono ${stateColor}">${c.tcp_state}</td>
  5411. <td class="py-2.5 px-3 font-mono text-purple-300">${c.connection_mark || '-'}</td>
  5412. <td class="py-2.5 px-3 text-slate-500">${c.timeout ? c.timeout + 's' : '-'}</td>
  5413. <td class="py-2.5 px-3 text-right font-sans">
  5414. <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>
  5415. </td>
  5416. `;
  5417. tbody.appendChild(tr);
  5418. });
  5419. }
  5420. async function killConnection(protocol, src, sport, dst, dport) {
  5421. try {
  5422. const res = await fetch(`${API_BASE}/firewall/connections/kill`, {
  5423. method: 'POST',
  5424. headers: { 'Content-Type': 'application/json' },
  5425. body: JSON.stringify({ protocol, src, sport, dst, dport })
  5426. });
  5427. if (res.ok) {
  5428. showToast('Terminated', `Killed flow ${src}:${sport} -> ${dst}:${dport}`, 'info');
  5429. loadConnections();
  5430. }
  5431. } catch (err) {
  5432. showToast('Error', err.message, 'error');
  5433. }
  5434. }
  5435. async function resetFirewallCounters() {
  5436. if (!confirm('Reset all firewall packet and byte counters to zero?')) return;
  5437. try {
  5438. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  5439. if (res.ok) {
  5440. showToast('Counters Reset', 'All rules counters reset to 0', 'success');
  5441. loadFirewall(false);
  5442. }
  5443. } catch (err) {
  5444. showToast('Error', err.message, 'error');
  5445. }
  5446. }
  5447. // ======================== MIKROTIK ROUTING & POLICY (/ip route) ========================
  5448. function switchRoutesSubTab(tab) {
  5449. state.routesSubTab = tab;
  5450. const tabs = ['routes', 'rules', 'tables'];
  5451. tabs.forEach(t => {
  5452. const panel = document.getElementById(`routes-subtab-${t}`);
  5453. const btn = document.getElementById(`routes-subtab-btn-${t}`);
  5454. if (panel) {
  5455. if (t === tab) panel.classList.remove('hidden');
  5456. else panel.classList.add('hidden');
  5457. }
  5458. if (btn) {
  5459. if (t === tab) {
  5460. 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';
  5461. } else {
  5462. 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';
  5463. }
  5464. }
  5465. });
  5466. setTimeout(initTableSorting, 50);
  5467. }
  5468. async function loadRoutes() {
  5469. try {
  5470. const [routesRes, rulesRes, tablesRes] = await Promise.all([
  5471. fetch(`${API_BASE}/routes`),
  5472. fetch(`${API_BASE}/routing/rules`),
  5473. fetch(`${API_BASE}/routing/tables`)
  5474. ]);
  5475. if (routesRes.ok) state.routes = await routesRes.json();
  5476. if (rulesRes.ok) state.policyRules = await rulesRes.json();
  5477. if (tablesRes.ok) state.routingTables = await tablesRes.json();
  5478. const bRoutes = document.getElementById('routes-badge-routes');
  5479. if (bRoutes) bRoutes.innerText = (state.routes || []).length;
  5480. const showSystem = document.getElementById('prule-show-system')?.checked;
  5481. const userRules = (state.policyRules || []).filter(pr => showSystem || (!pr.is_default && !pr.is_system));
  5482. const bRules = document.getElementById('routes-badge-rules');
  5483. if (bRules) bRules.innerText = userRules.length;
  5484. const bTables = document.getElementById('routes-badge-tables');
  5485. if (bTables) bTables.innerText = (state.routingTables || []).length;
  5486. const bRoutesCount = document.getElementById('badge-routes-count');
  5487. if (bRoutesCount) bRoutesCount.innerText = (state.routes || []).length;
  5488. renderRoutesList();
  5489. renderPolicyRules();
  5490. renderRoutingTables();
  5491. } catch (err) {
  5492. console.error('Failed to load routing:', err);
  5493. }
  5494. }
  5495. function getRouteProtocolBadge(proto) {
  5496. const p = (proto || 'static').toLowerCase();
  5497. switch (p) {
  5498. case 'bgp':
  5499. return `<span class="px-2 py-0.5 rounded text-[10px] font-bold font-mono uppercase bg-amber-500/20 text-amber-300 border border-amber-500/30">bgp</span>`;
  5500. case 'ibgp':
  5501. return `<span class="px-2 py-0.5 rounded text-[10px] font-bold font-mono uppercase bg-yellow-500/20 text-yellow-300 border border-yellow-500/30">ibgp</span>`;
  5502. case 'ospf':
  5503. return `<span class="px-2 py-0.5 rounded text-[10px] font-bold font-mono uppercase bg-emerald-500/20 text-emerald-300 border border-emerald-500/30">ospf</span>`;
  5504. case 'rip':
  5505. return `<span class="px-2 py-0.5 rounded text-[10px] font-bold font-mono uppercase bg-orange-500/20 text-orange-300 border border-orange-500/30">rip</span>`;
  5506. case 'static':
  5507. return `<span class="px-2 py-0.5 rounded text-[10px] font-bold font-mono uppercase bg-blue-500/20 text-blue-300 border border-blue-500/30">static</span>`;
  5508. case 'connected':
  5509. return `<span class="px-2 py-0.5 rounded text-[10px] font-bold font-mono uppercase bg-slate-800 text-slate-300 border border-slate-700">connected</span>`;
  5510. case 'dhcp':
  5511. return `<span class="px-2 py-0.5 rounded text-[10px] font-bold font-mono uppercase bg-cyan-500/20 text-cyan-300 border border-cyan-500/30">dhcp</span>`;
  5512. case 'multicast':
  5513. return `<span class="px-2 py-0.5 rounded text-[10px] font-bold font-mono uppercase bg-purple-500/20 text-purple-300 border border-purple-500/30">igmp</span>`;
  5514. default:
  5515. return `<span class="px-2 py-0.5 rounded text-[10px] font-bold font-mono uppercase bg-slate-800 text-slate-400 border border-slate-700">${escapeHtml(p)}</span>`;
  5516. }
  5517. }
  5518. function renderRoutesList() {
  5519. const tableFilter = document.getElementById('routes-filter-table')?.value || '';
  5520. const typeFilter = document.getElementById('routes-filter-type')?.value || '';
  5521. const tbody = document.getElementById('routes-table-body');
  5522. const empty = document.getElementById('routes-empty');
  5523. if (!tbody) return;
  5524. tbody.innerHTML = '';
  5525. // Update table filter select
  5526. const sel = document.getElementById('routes-filter-table');
  5527. if (sel) {
  5528. const cur = sel.value;
  5529. sel.innerHTML = '<option value="">All Tables</option>';
  5530. (state.routingTables || []).forEach(t => {
  5531. const opt = document.createElement('option');
  5532. opt.value = t.name;
  5533. opt.innerText = t.name;
  5534. if (t.name === cur) opt.selected = true;
  5535. sel.appendChild(opt);
  5536. });
  5537. }
  5538. const routes = (state.routes || []).filter(r => {
  5539. if (tableFilter && r.routing_table !== tableFilter) return false;
  5540. if (typeFilter === 'ecmp' && !r.ecmp) return false;
  5541. if (typeFilter === 'multicast' && !r.multicast) return false;
  5542. if (typeFilter === 'static' && !r.static) return false;
  5543. if (typeFilter === 'dynamic' && !r.dynamic) return false;
  5544. if (typeFilter === 'connected' && !r.connect) return false;
  5545. if (typeFilter === 'bgp' && (r.protocol || '').toLowerCase() !== 'bgp' && (r.protocol || '').toLowerCase() !== 'ibgp') return false;
  5546. if (typeFilter === 'ospf' && (r.protocol || '').toLowerCase() !== 'ospf') return false;
  5547. if (typeFilter === 'dhcp' && (r.protocol || '').toLowerCase() !== 'dhcp') return false;
  5548. return true;
  5549. });
  5550. const ecmpCount = (state.routes || []).filter(r => r.ecmp).length;
  5551. const mcCount = (state.routes || []).filter(r => r.multicast).length;
  5552. let summaryText = `${routes.length} Routes`;
  5553. if (ecmpCount > 0) summaryText += ` • ${ecmpCount} ECMP`;
  5554. if (mcCount > 0) summaryText += ` • ${mcCount} Multicast/IGMP`;
  5555. const badgeEl = document.getElementById('routes-count-badge');
  5556. if (badgeEl) badgeEl.innerText = summaryText;
  5557. if (routes.length === 0) {
  5558. empty?.classList.remove('hidden');
  5559. return;
  5560. }
  5561. empty?.classList.add('hidden');
  5562. routes.forEach(r => {
  5563. const tr = document.createElement('tr');
  5564. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${r.disabled ? 'opacity-50' : ''}`;
  5565. tr.setAttribute('ondblclick', `openEditRouteModal('${r.id}')`);
  5566. // Routing Flags string: D=Dynamic, A=Active, C=Connect, S=Static, E=ECMP, M=Multicast, X=Disabled
  5567. let flags = '';
  5568. if (r.dynamic) flags += 'D';
  5569. if (r.active) flags += 'A';
  5570. if (r.connect) flags += 'C';
  5571. if (r.static) flags += 'S';
  5572. if (r.ecmp) flags += 'E';
  5573. if (r.multicast) flags += 'M';
  5574. if (r.disabled) flags += 'X';
  5575. const isDefault = r.dst_address === 'default' || r.dst_address === '0.0.0.0/0';
  5576. let healthCell = `<span class="text-slate-600 font-mono text-[11px]">-</span>`;
  5577. if (r.check_gateway === 'internet') {
  5578. if (r.health_status === 'online') {
  5579. const ms = (r.health_rtt_ms || 0).toFixed(0);
  5580. healthCell = `
  5581. <span class="px-2 py-0.5 rounded text-[10px] font-mono bg-emerald-500/20 text-emerald-300 border border-emerald-500/30 font-semibold inline-flex items-center gap-1.5" title="Internet Verified via ${escapeHtml(r.check_target || '1.1.1.1')} (${r.health_loss_pct || 0}% loss)">
  5582. <span class="w-1.5 h-1.5 rounded-full bg-emerald-400 animate-pulse"></span>
  5583. <span>Internet OK (${ms}ms)</span>
  5584. </span>
  5585. `;
  5586. } else if (r.health_status === 'offline') {
  5587. healthCell = `
  5588. <span class="px-2 py-0.5 rounded text-[10px] font-mono bg-rose-500/20 text-rose-300 border border-rose-500/40 font-bold inline-flex items-center gap-1.5 animate-pulse" title="Internet probe to ${escapeHtml(r.check_target || '1.1.1.1')} failed! Route withdrawn for failover.">
  5589. <span class="w-1.5 h-1.5 rounded-full bg-rose-400"></span>
  5590. <span>Internet Down</span>
  5591. </span>
  5592. `;
  5593. } else {
  5594. healthCell = `
  5595. <span class="px-2 py-0.5 rounded text-[10px] font-mono bg-slate-800 text-slate-400 border border-slate-700 inline-flex items-center gap-1.5">
  5596. <span class="w-1.5 h-1.5 rounded-full bg-amber-400 animate-ping"></span>
  5597. <span>Checking...</span>
  5598. </span>
  5599. `;
  5600. }
  5601. } else if (r.check_gateway === 'ping') {
  5602. if (r.health_status === 'online') {
  5603. healthCell = `
  5604. <span class="px-2 py-0.5 rounded text-[10px] font-mono bg-cyan-500/20 text-cyan-300 border border-cyan-500/30 font-semibold inline-flex items-center gap-1.5">
  5605. <span class="w-1.5 h-1.5 rounded-full bg-cyan-400"></span>
  5606. <span>Gateway OK (${(r.health_rtt_ms || 0).toFixed(0)}ms)</span>
  5607. </span>
  5608. `;
  5609. } else if (r.health_status === 'offline') {
  5610. healthCell = `
  5611. <span class="px-2 py-0.5 rounded text-[10px] font-mono bg-rose-500/20 text-rose-300 border border-rose-500/40 font-bold inline-flex items-center gap-1.5">
  5612. <span class="w-1.5 h-1.5 rounded-full bg-rose-400"></span>
  5613. <span>Gateway Dead</span>
  5614. </span>
  5615. `;
  5616. }
  5617. }
  5618. const flagDescriptions = [];
  5619. if (r.dynamic) flagDescriptions.push('Dynamic (D)');
  5620. if (r.active) flagDescriptions.push('Active (A)');
  5621. if (r.connect) flagDescriptions.push('Connected (C)');
  5622. if (r.static) flagDescriptions.push('Static (S)');
  5623. if (r.ecmp) flagDescriptions.push('ECMP - Equal-Cost Multi-Path (E)');
  5624. if (r.multicast) flagDescriptions.push('Multicast / IGMP Group (M)');
  5625. if (r.disabled) flagDescriptions.push('Disabled (X)');
  5626. tr.innerHTML = `
  5627. <td class="py-2.5 px-3 text-center">
  5628. <span class="px-1.5 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 ${
  5629. r.active ? (r.ecmp ? 'text-purple-300 border border-purple-500/40' : (r.multicast ? 'text-amber-300 border border-amber-500/40' : 'text-cyan-400 border border-cyan-800/40')) : (r.health_status === 'offline' ? 'text-rose-400 border border-rose-800/40' : 'text-slate-500')
  5630. }" title="Flags: ${flagDescriptions.join(', ')}">
  5631. ${flags || '-'}
  5632. </span>
  5633. </td>
  5634. <td class="py-2.5 px-3">
  5635. <div class="flex items-center gap-1.5 flex-wrap">
  5636. <span class="font-bold ${isDefault ? 'text-cyan-300' : 'text-white'}">${escapeHtml(r.dst_address)}</span>
  5637. ${r.ecmp ? `
  5638. <span class="px-1.5 py-0.2 rounded text-[9px] font-mono font-bold bg-purple-500/20 text-purple-300 border border-purple-500/30 inline-flex items-center gap-1" title="Equal-Cost Multi-Path (ECMP / Multi-gateway)">
  5639. <span>⚡ ECMP</span>
  5640. </span>
  5641. ` : ''}
  5642. ${r.multicast ? `
  5643. <span class="px-1.5 py-0.2 rounded text-[9px] font-mono font-bold bg-amber-500/20 text-amber-300 border border-amber-500/30 inline-flex items-center gap-1" title="Multicast / IGMP Group Route">
  5644. <span>IGMP</span>
  5645. </span>
  5646. ` : ''}
  5647. </div>
  5648. </td>
  5649. <td class="py-2.5 px-3">${getRouteProtocolBadge(r.protocol)}</td>
  5650. <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>
  5651. <td class="py-2.5 px-3 text-slate-400 font-mono">${(r.distance !== undefined && r.distance !== null) ? r.distance : 0}</td>
  5652. <td class="py-2.5 px-3 font-mono font-semibold text-purple-300">${r.routing_table || 'main'}</td>
  5653. <td class="py-2.5 px-3 text-emerald-400 font-mono">${r.interface || '-'}</td>
  5654. <td class="py-2.5 px-3">${healthCell}</td>
  5655. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]">${r.comment || '-'}</td>
  5656. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  5657. ${r.static ? `
  5658. <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>
  5659. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold">Edit</button>
  5660. <button onclick="deleteRoute('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  5661. ` : `
  5662. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">View</button>
  5663. `}
  5664. </td>
  5665. `;
  5666. tbody.appendChild(tr);
  5667. });
  5668. }
  5669. function openAddRouteModal() {
  5670. document.getElementById('route-modal-title').innerText = 'Add Static Route';
  5671. document.getElementById('route-modal-id').value = '';
  5672. document.getElementById('route-modal-old-dst').value = '';
  5673. document.getElementById('route-modal-old-gw').value = '';
  5674. document.getElementById('route-modal-old-distance').value = '';
  5675. document.getElementById('route-modal-old-table').value = '';
  5676. document.getElementById('route-modal-old-iface').value = '';
  5677. const dstInput = document.getElementById('route-modal-dst');
  5678. const gwInput = document.getElementById('route-modal-gw');
  5679. const distInput = document.getElementById('route-modal-distance');
  5680. const ifaceSelect = document.getElementById('route-modal-iface');
  5681. const tableSelect = document.getElementById('route-modal-table');
  5682. const commentInput = document.getElementById('route-modal-comment');
  5683. const disCheck = document.getElementById('route-modal-disabled');
  5684. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  5685. dstInput.disabled = false;
  5686. dstInput.value = '0.0.0.0/0';
  5687. gwInput.disabled = false;
  5688. gwInput.value = '';
  5689. distInput.disabled = false;
  5690. distInput.value = '1';
  5691. ifaceSelect.disabled = false;
  5692. tableSelect.disabled = false;
  5693. commentInput.disabled = false;
  5694. commentInput.value = '';
  5695. disCheck.disabled = false;
  5696. disCheck.checked = false;
  5697. if (saveBtn) saveBtn.classList.remove('hidden');
  5698. const checkGw = document.getElementById('route-modal-check-gw');
  5699. if (checkGw) checkGw.value = 'internet';
  5700. const checkTarget = document.getElementById('route-modal-check-target');
  5701. if (checkTarget) checkTarget.value = '1.1.1.1';
  5702. const checkInterval = document.getElementById('route-modal-check-interval');
  5703. if (checkInterval) checkInterval.value = '5';
  5704. const checkThresh = document.getElementById('route-modal-check-threshold');
  5705. if (checkThresh) checkThresh.value = '3';
  5706. toggleRouteCheckModeUI();
  5707. populateInterfaceSelect('route-modal-iface');
  5708. // Populate tables
  5709. tableSelect.innerHTML = '';
  5710. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  5711. const opt = document.createElement('option');
  5712. opt.value = t.name;
  5713. opt.innerText = t.name;
  5714. if (t.name === 'main') opt.selected = true;
  5715. tableSelect.appendChild(opt);
  5716. });
  5717. document.getElementById('route-modal').classList.remove('hidden');
  5718. }
  5719. function openEditRouteModal(id) {
  5720. const r = (state.routes || []).find(route => route.id === id);
  5721. if (!r) return;
  5722. const isStatic = !!r.static;
  5723. document.getElementById('route-modal-title').innerText = isStatic
  5724. ? `Edit Route: ${r.dst_address}`
  5725. : `Route Properties (Read Only): ${r.dst_address}`;
  5726. document.getElementById('route-modal-id').value = r.id;
  5727. document.getElementById('route-modal-old-dst').value = r.dst_address || '';
  5728. document.getElementById('route-modal-old-gw').value = r.gateway || '';
  5729. document.getElementById('route-modal-old-distance').value = (r.distance !== undefined && r.distance !== null) ? r.distance : '';
  5730. document.getElementById('route-modal-old-table').value = r.routing_table || 'main';
  5731. document.getElementById('route-modal-old-iface').value = r.interface || '';
  5732. const dstInput = document.getElementById('route-modal-dst');
  5733. const gwInput = document.getElementById('route-modal-gw');
  5734. const distInput = document.getElementById('route-modal-distance');
  5735. const ifaceSelect = document.getElementById('route-modal-iface');
  5736. const tableSelect = document.getElementById('route-modal-table');
  5737. const commentInput = document.getElementById('route-modal-comment');
  5738. const disCheck = document.getElementById('route-modal-disabled');
  5739. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  5740. dstInput.value = r.dst_address;
  5741. gwInput.value = r.gateway || '';
  5742. distInput.value = (r.distance !== undefined && r.distance !== null) ? r.distance : 1;
  5743. commentInput.value = r.comment || '';
  5744. disCheck.checked = !!r.disabled;
  5745. const checkGw = document.getElementById('route-modal-check-gw');
  5746. if (checkGw) checkGw.value = r.check_gateway || 'none';
  5747. const checkTarget = document.getElementById('route-modal-check-target');
  5748. if (checkTarget) checkTarget.value = r.check_target || '1.1.1.1';
  5749. const checkInterval = document.getElementById('route-modal-check-interval');
  5750. if (checkInterval) checkInterval.value = r.check_interval || 5;
  5751. const checkThresh = document.getElementById('route-modal-check-threshold');
  5752. if (checkThresh) checkThresh.value = r.check_threshold || 3;
  5753. toggleRouteCheckModeUI();
  5754. dstInput.disabled = !isStatic;
  5755. gwInput.disabled = !isStatic;
  5756. distInput.disabled = !isStatic;
  5757. ifaceSelect.disabled = !isStatic;
  5758. tableSelect.disabled = !isStatic;
  5759. commentInput.disabled = !isStatic;
  5760. disCheck.disabled = !isStatic;
  5761. if (checkGw) checkGw.disabled = !isStatic;
  5762. if (checkTarget) checkTarget.disabled = !isStatic;
  5763. if (checkInterval) checkInterval.disabled = !isStatic;
  5764. if (checkThresh) checkThresh.disabled = !isStatic;
  5765. if (saveBtn) {
  5766. if (isStatic) {
  5767. saveBtn.classList.remove('hidden');
  5768. } else {
  5769. saveBtn.classList.add('hidden');
  5770. }
  5771. }
  5772. populateInterfaceSelect('route-modal-iface', r.interface);
  5773. tableSelect.innerHTML = '';
  5774. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  5775. const opt = document.createElement('option');
  5776. opt.value = t.name;
  5777. opt.innerText = t.name;
  5778. if (t.name === (r.routing_table || 'main')) opt.selected = true;
  5779. tableSelect.appendChild(opt);
  5780. });
  5781. document.getElementById('route-modal').classList.remove('hidden');
  5782. }
  5783. function closeRouteModal() {
  5784. document.getElementById('route-modal').classList.add('hidden');
  5785. }
  5786. function setRouteCheckTarget(ip) {
  5787. const inp = document.getElementById('route-modal-check-target');
  5788. if (inp) inp.value = ip;
  5789. }
  5790. function toggleRouteCheckModeUI() {
  5791. const mode = document.getElementById('route-modal-check-gw')?.value || 'none';
  5792. const targetRow = document.getElementById('route-row-check-target');
  5793. const paramsRow = document.getElementById('route-row-check-params');
  5794. if (mode === 'none') {
  5795. if (targetRow) targetRow.classList.add('opacity-40', 'pointer-events-none');
  5796. if (paramsRow) paramsRow.classList.add('opacity-40', 'pointer-events-none');
  5797. } else if (mode === 'ping') {
  5798. if (targetRow) targetRow.classList.add('opacity-40', 'pointer-events-none');
  5799. if (paramsRow) paramsRow.classList.remove('opacity-40', 'pointer-events-none');
  5800. } else { // internet
  5801. if (targetRow) targetRow.classList.remove('opacity-40', 'pointer-events-none');
  5802. if (paramsRow) paramsRow.classList.remove('opacity-40', 'pointer-events-none');
  5803. }
  5804. }
  5805. async function submitSaveRoute(e) {
  5806. e.preventDefault();
  5807. const id = document.getElementById('route-modal-id').value;
  5808. const oldDst = document.getElementById('route-modal-old-dst')?.value || '';
  5809. const oldGw = document.getElementById('route-modal-old-gw')?.value || '';
  5810. const oldDistStr = document.getElementById('route-modal-old-distance')?.value;
  5811. const oldTable = document.getElementById('route-modal-old-table')?.value || '';
  5812. const oldIface = document.getElementById('route-modal-old-iface')?.value || '';
  5813. const dst = document.getElementById('route-modal-dst').value.trim();
  5814. const gw = document.getElementById('route-modal-gw').value.trim();
  5815. const table = document.getElementById('route-modal-table').value;
  5816. const distance = parseInt(document.getElementById('route-modal-distance').value, 10) || 0;
  5817. const iface = document.getElementById('route-modal-iface').value;
  5818. const comment = document.getElementById('route-modal-comment').value.trim();
  5819. const disabled = document.getElementById('route-modal-disabled').checked;
  5820. const check_gateway = document.getElementById('route-modal-check-gw')?.value || 'none';
  5821. const check_target = document.getElementById('route-modal-check-target')?.value.trim() || '1.1.1.1';
  5822. const check_interval = parseInt(document.getElementById('route-modal-check-interval')?.value, 10) || 5;
  5823. const check_threshold = parseInt(document.getElementById('route-modal-check-threshold')?.value, 10) || 3;
  5824. if (!dst) {
  5825. showToast('Error', 'Destination address is required', 'error');
  5826. return;
  5827. }
  5828. if (!gw && !iface) {
  5829. showToast('Error', 'Either Gateway IP or Interface must be specified', 'error');
  5830. return;
  5831. }
  5832. const payload = {
  5833. id,
  5834. old_dst_address: oldDst,
  5835. old_gateway: oldGw,
  5836. old_routing_table: oldTable,
  5837. old_interface: oldIface,
  5838. dst_address: dst,
  5839. gateway: gw || iface,
  5840. routing_table: table,
  5841. distance,
  5842. interface: iface,
  5843. comment,
  5844. disabled,
  5845. check_gateway,
  5846. check_target,
  5847. check_interval,
  5848. check_threshold
  5849. };
  5850. if (oldDistStr !== undefined && oldDistStr !== '') {
  5851. payload.old_distance = parseInt(oldDistStr, 10);
  5852. }
  5853. try {
  5854. const res = await fetch(`${API_BASE}/routes`, {
  5855. method: 'POST',
  5856. headers: { 'Content-Type': 'application/json' },
  5857. body: JSON.stringify(payload)
  5858. });
  5859. if (res.ok) {
  5860. showToast('Route Saved', `Route to ${dst} installed`, 'success');
  5861. closeRouteModal();
  5862. loadRoutes();
  5863. } else {
  5864. const err = await res.json();
  5865. showToast('Error', err.message || 'Failed to save route', 'error');
  5866. }
  5867. } catch (err) {
  5868. showToast('Error', err.message, 'error');
  5869. }
  5870. }
  5871. async function toggleRouteState(id, disabled) {
  5872. try {
  5873. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}/state`, {
  5874. method: 'POST',
  5875. headers: { 'Content-Type': 'application/json' },
  5876. body: JSON.stringify({ disabled })
  5877. });
  5878. if (res.ok) loadRoutes();
  5879. } catch (err) {
  5880. showToast('Error', err.message, 'error');
  5881. }
  5882. }
  5883. async function deleteRoute(id) {
  5884. if (!confirm('Are you sure you want to delete this route?')) return;
  5885. try {
  5886. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5887. if (res.ok) {
  5888. showToast('Deleted', 'Route removed', 'success');
  5889. loadRoutes();
  5890. }
  5891. } catch (err) {
  5892. showToast('Error', err.message, 'error');
  5893. }
  5894. }
  5895. // ----------------- Policy Rules (/ip route rule) -----------------
  5896. function renderPolicyRules() {
  5897. const tbody = document.getElementById('rules-table-body');
  5898. const empty = document.getElementById('rules-empty');
  5899. if (!tbody) return;
  5900. tbody.innerHTML = '';
  5901. const showSystem = document.getElementById('prule-show-system')?.checked;
  5902. const filtered = (state.policyRules || []).filter(pr => showSystem || (!pr.is_default && !pr.is_system));
  5903. const countBadge = document.getElementById('rules-count-badge');
  5904. if (countBadge) countBadge.innerText = `${filtered.length} Rules`;
  5905. const bRules = document.getElementById('routes-badge-rules');
  5906. if (bRules) bRules.innerText = filtered.length;
  5907. if (filtered.length === 0) {
  5908. empty?.classList.remove('hidden');
  5909. return;
  5910. }
  5911. empty?.classList.add('hidden');
  5912. filtered.forEach(pr => {
  5913. const isSys = pr.is_default || pr.is_system;
  5914. const tr = document.createElement('tr');
  5915. tr.className = `hover:bg-slate-800/40 transition text-xs ${isSys ? 'opacity-70 bg-slate-950/20' : ''}`;
  5916. tr.innerHTML = `
  5917. <td class="py-2.5 px-3 font-mono text-cyan-400 font-bold">${pr.priority}</td>
  5918. <td class="py-2.5 px-3 font-mono text-white">${pr.src_address || '<span class="text-slate-600">all</span>'}</td>
  5919. <td class="py-2.5 px-3 font-mono text-white">${pr.dst_address || '<span class="text-slate-600">all</span>'}</td>
  5920. <td class="py-2.5 px-3 font-mono font-bold text-purple-300">${pr.routing_mark || '<span class="text-slate-600">-</span>'}</td>
  5921. <td class="py-2.5 px-3 font-mono font-bold text-amber-300">${pr.table}</td>
  5922. <td class="py-2.5 px-3 font-mono text-slate-300">${pr.action}</td>
  5923. <td class="py-2.5 px-3 text-right font-sans">
  5924. ${!pr.is_default ? `
  5925. <button onclick="deletePolicyRule('${pr.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  5926. ` : `<span class="text-slate-600 text-[10px]">Default</span>`}
  5927. </td>
  5928. `;
  5929. tbody.appendChild(tr);
  5930. });
  5931. }
  5932. function openAddPolicyRuleModal() {
  5933. const userRules = (state.policyRules || []).filter(pr => !pr.is_default && !pr.is_system);
  5934. document.getElementById('prule-modal-pref').value = userRules.length * 10 + 1000;
  5935. document.getElementById('prule-modal-mark').value = '';
  5936. document.getElementById('prule-modal-src').value = '';
  5937. document.getElementById('prule-modal-dst').value = '';
  5938. const sel = document.getElementById('prule-modal-table');
  5939. sel.innerHTML = '';
  5940. (state.routingTables || []).forEach(t => {
  5941. const opt = document.createElement('option');
  5942. opt.value = t.name;
  5943. opt.innerText = t.name;
  5944. sel.appendChild(opt);
  5945. });
  5946. document.getElementById('prule-modal').classList.remove('hidden');
  5947. }
  5948. function closePolicyRuleModal() {
  5949. document.getElementById('prule-modal').classList.add('hidden');
  5950. }
  5951. async function submitSavePolicyRule(e) {
  5952. e.preventDefault();
  5953. const pref = parseInt(document.getElementById('prule-modal-pref').value, 10) || 1000;
  5954. const mark = document.getElementById('prule-modal-mark').value.trim();
  5955. const src = document.getElementById('prule-modal-src').value.trim();
  5956. const dst = document.getElementById('prule-modal-dst').value.trim();
  5957. const table = document.getElementById('prule-modal-table').value;
  5958. const action = document.getElementById('prule-modal-action').value;
  5959. try {
  5960. const res = await fetch(`${API_BASE}/routing/rules`, {
  5961. method: 'POST',
  5962. headers: { 'Content-Type': 'application/json' },
  5963. body: JSON.stringify({ priority: pref, routing_mark: mark, src_address: src, dst_address: dst, table, action })
  5964. });
  5965. if (res.ok) {
  5966. showToast('Rule Added', `Policy rule installed for table ${table}`, 'success');
  5967. closePolicyRuleModal();
  5968. loadRoutes();
  5969. } else {
  5970. const err = await res.json();
  5971. showToast('Error', err.message, 'error');
  5972. }
  5973. } catch (err) {
  5974. showToast('Error', err.message, 'error');
  5975. }
  5976. }
  5977. async function deletePolicyRule(id) {
  5978. if (!confirm('Are you sure you want to remove this policy rule?')) return;
  5979. try {
  5980. const res = await fetch(`${API_BASE}/routing/rules/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5981. if (res.ok) {
  5982. showToast('Rule Removed', 'Policy rule deleted', 'success');
  5983. loadRoutes();
  5984. }
  5985. } catch (err) {
  5986. showToast('Error', err.message, 'error');
  5987. }
  5988. }
  5989. // ----------------- Routing Tables -----------------
  5990. function renderRoutingTables() {
  5991. const tbody = document.getElementById('tables-table-body');
  5992. if (!tbody) return;
  5993. tbody.innerHTML = '';
  5994. (state.routingTables || []).forEach(t => {
  5995. const tr = document.createElement('tr');
  5996. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  5997. tr.innerHTML = `
  5998. <td class="py-2.5 px-3 text-cyan-400 font-bold">${t.table_id}</td>
  5999. <td class="py-2.5 px-3 font-bold text-white">${t.name}</td>
  6000. <td class="py-2.5 px-3 text-slate-400 italic">${t.comment || '-'}</td>
  6001. `;
  6002. tbody.appendChild(tr);
  6003. });
  6004. }
  6005. function openAddTableModal() {
  6006. document.getElementById('table-modal-name').value = '';
  6007. document.getElementById('table-modal-id').value = '';
  6008. document.getElementById('table-modal-comment').value = '';
  6009. document.getElementById('table-modal').classList.remove('hidden');
  6010. }
  6011. function closeTableModal() {
  6012. document.getElementById('table-modal').classList.add('hidden');
  6013. }
  6014. async function submitSaveTable(e) {
  6015. e.preventDefault();
  6016. const name = document.getElementById('table-modal-name').value.trim();
  6017. const id = parseInt(document.getElementById('table-modal-id').value, 10) || 0;
  6018. const comment = document.getElementById('table-modal-comment').value.trim();
  6019. try {
  6020. const res = await fetch(`${API_BASE}/routing/tables`, {
  6021. method: 'POST',
  6022. headers: { 'Content-Type': 'application/json' },
  6023. body: JSON.stringify({ name, table_id: id, comment })
  6024. });
  6025. if (res.ok) {
  6026. showToast('Table Created', `Routing table ${name} registered`, 'success');
  6027. closeTableModal();
  6028. loadRoutes();
  6029. } else {
  6030. const err = await res.json();
  6031. showToast('Error', err.message, 'error');
  6032. }
  6033. } catch (err) {
  6034. showToast('Error', err.message, 'error');
  6035. }
  6036. }
  6037. async function loadDebianConfig() {
  6038. const view = document.getElementById('debian-config-view');
  6039. view.innerText = 'Generating live configuration...';
  6040. try {
  6041. const res = await fetch(`${API_BASE}/debian/config`);
  6042. const data = await res.json();
  6043. view.innerText = data.content || '# Empty config';
  6044. } catch (err) {
  6045. view.innerText = 'Failed to generate Debian network config.';
  6046. }
  6047. }
  6048. async function saveDebianConfig() {
  6049. try {
  6050. const res = await fetch(`${API_BASE}/debian/apply`, { method: 'POST' });
  6051. const data = await res.json();
  6052. if (res.ok) {
  6053. showToast('Configuration Saved', data.message || 'Saved to /etc/network/interfaces.d/vlans.cfg', 'success');
  6054. loadDebianConfig();
  6055. }
  6056. } catch (err) {
  6057. showToast('Error', err.message, 'error');
  6058. }
  6059. }
  6060. function showToast(title, message, type = 'info') {
  6061. const container = document.getElementById('toast-container');
  6062. const toast = document.createElement('div');
  6063. const borderColors = {
  6064. success: 'border-emerald-500/40 bg-slate-900/95 text-emerald-400',
  6065. error: 'border-rose-500/40 bg-slate-900/95 text-rose-400',
  6066. info: 'border-cyan-500/40 bg-slate-900/95 text-cyan-400'
  6067. };
  6068. 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}`;
  6069. toast.innerHTML = `
  6070. <div class="flex-1">
  6071. <div class="font-bold text-xs text-white">${title}</div>
  6072. <div class="text-[11px] text-slate-300 mt-0.5 leading-relaxed font-sans">${message}</div>
  6073. </div>
  6074. `;
  6075. container.appendChild(toast);
  6076. requestAnimationFrame(() => toast.classList.remove('translate-y-2', 'opacity-0'));
  6077. setTimeout(() => {
  6078. toast.classList.add('opacity-0', 'translate-y-2');
  6079. setTimeout(() => toast.remove(), 300);
  6080. }, 4000);
  6081. }
  6082. function formatTraffic(bytesPerSec) {
  6083. if (bytesPerSec < 1024) return `${Math.round(bytesPerSec)} B/s`;
  6084. const kb = bytesPerSec / 1024;
  6085. if (kb < 1024) return `${kb.toFixed(1)} KB/s`;
  6086. const mb = kb / 1024;
  6087. return `${mb.toFixed(2)} MB/s`;
  6088. }
  6089. function toggleSidebar() {
  6090. const sb = document.getElementById('sidebar');
  6091. sb.classList.toggle('-translate-x-full');
  6092. }
  6093. // ======================== EoIP (Ethernet over IP) ========================
  6094. async function loadEoIP(populate = true) {
  6095. try {
  6096. const res = await fetch(`${API_BASE}/vpn/eoip`);
  6097. const data = await res.json();
  6098. state.eoipTunnels = Array.isArray(data) ? data : [];
  6099. const badge = document.getElementById('eoip-count-badge');
  6100. if (badge) badge.innerText = `${state.eoipTunnels.length} Tunnels`;
  6101. const sideBadge = document.getElementById('badge-eoip-count');
  6102. if (sideBadge) sideBadge.innerText = state.eoipTunnels.length;
  6103. renderEoIPTunnels();
  6104. } catch (err) {
  6105. console.error('Failed to load EoIP:', err);
  6106. }
  6107. }
  6108. function renderEoIPTunnels() {
  6109. const tbody = document.getElementById('eoip-table-body');
  6110. const empty = document.getElementById('eoip-empty');
  6111. if (!tbody) return;
  6112. tbody.innerHTML = '';
  6113. const tunnels = state.eoipTunnels || [];
  6114. if (tunnels.length === 0) {
  6115. empty?.classList.remove('hidden');
  6116. return;
  6117. }
  6118. empty?.classList.add('hidden');
  6119. tunnels.forEach(t => {
  6120. const tr = document.createElement('tr');
  6121. tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
  6122. tr.innerHTML = `
  6123. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.running, t.disabled)}</td>
  6124. <td class="py-2.5 px-3 font-bold text-white font-mono">${t.name}</td>
  6125. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${t.tunnel_id}</td>
  6126. <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>
  6127. <td class="py-2.5 px-3 text-cyan-300 font-mono">${t.remote_address}</td>
  6128. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.local_address || '(any)'}</td>
  6129. <td class="py-2.5 px-3 text-slate-300 font-mono text-[11px]">${t.mac_address || '-'}</td>
  6130. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.mtu || 1500}</td>
  6131. <td class="py-2.5 px-3 font-mono text-[11px]">
  6132. <span class="text-emerald-400">↓ ${t.rx_human || '0 B'}</span>
  6133. <span class="text-cyan-400 ml-1">↑ ${t.tx_human || '0 B'}</span>
  6134. </td>
  6135. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${t.comment || ''}">${t.comment || '-'}</td>
  6136. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  6137. <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>
  6138. <button onclick="openEditEoIPModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  6139. <button onclick="deleteEoIP('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  6140. </td>
  6141. `;
  6142. tbody.appendChild(tr);
  6143. });
  6144. }
  6145. function openAddEoIPModal() {
  6146. document.getElementById('eoip-modal-title').innerText = 'Add EoIP Tunnel';
  6147. document.getElementById('eoip-modal-id').value = '';
  6148. document.getElementById('eoip-modal-name').value = `eoip-tunnel${(state.eoipTunnels || []).length + 1}`;
  6149. document.getElementById('eoip-modal-tunnelid').value = (state.eoipTunnels || []).length + 10;
  6150. document.getElementById('eoip-modal-remote').value = '';
  6151. document.getElementById('eoip-modal-ip').value = '';
  6152. document.getElementById('eoip-modal-local').value = '';
  6153. document.getElementById('eoip-modal-mac').value = '';
  6154. document.getElementById('eoip-modal-mtu').value = '1500';
  6155. document.getElementById('eoip-modal-comment').value = '';
  6156. document.getElementById('eoip-modal-clampmss').checked = true;
  6157. document.getElementById('eoip-modal-disabled').checked = false;
  6158. document.getElementById('eoip-modal').classList.remove('hidden');
  6159. }
  6160. function openEditEoIPModal(id) {
  6161. const t = (state.eoipTunnels || []).find(tun => tun.id === id);
  6162. if (!t) return;
  6163. document.getElementById('eoip-modal-title').innerText = `Edit EoIP Tunnel (${t.name})`;
  6164. document.getElementById('eoip-modal-id').value = t.id;
  6165. document.getElementById('eoip-modal-name').value = t.name;
  6166. document.getElementById('eoip-modal-tunnelid').value = t.tunnel_id;
  6167. document.getElementById('eoip-modal-remote').value = t.remote_address;
  6168. document.getElementById('eoip-modal-ip').value = t.ip_address || '';
  6169. document.getElementById('eoip-modal-local').value = t.local_address || '';
  6170. document.getElementById('eoip-modal-mac').value = t.mac_address || '';
  6171. document.getElementById('eoip-modal-mtu').value = t.mtu || 1500;
  6172. document.getElementById('eoip-modal-comment').value = t.comment || '';
  6173. document.getElementById('eoip-modal-clampmss').checked = !!t.clamp_mss;
  6174. document.getElementById('eoip-modal-disabled').checked = !!t.disabled;
  6175. document.getElementById('eoip-modal').classList.remove('hidden');
  6176. }
  6177. function closeEoIPModal() {
  6178. document.getElementById('eoip-modal').classList.add('hidden');
  6179. }
  6180. async function submitSaveEoIP(e) {
  6181. e.preventDefault();
  6182. const id = document.getElementById('eoip-modal-id').value;
  6183. const name = document.getElementById('eoip-modal-name').value.trim();
  6184. const tunnelId = parseInt(document.getElementById('eoip-modal-tunnelid').value);
  6185. const remote = document.getElementById('eoip-modal-remote').value.trim();
  6186. const ipAddress = document.getElementById('eoip-modal-ip').value.trim();
  6187. const local = document.getElementById('eoip-modal-local').value.trim();
  6188. const mac = document.getElementById('eoip-modal-mac').value.trim();
  6189. const mtu = parseInt(document.getElementById('eoip-modal-mtu').value) || 1500;
  6190. const comment = document.getElementById('eoip-modal-comment').value.trim();
  6191. const clampMss = document.getElementById('eoip-modal-clampmss').checked;
  6192. const disabled = document.getElementById('eoip-modal-disabled').checked;
  6193. try {
  6194. const res = await fetch(`${API_BASE}/vpn/eoip`, {
  6195. method: 'POST',
  6196. headers: { 'Content-Type': 'application/json' },
  6197. body: JSON.stringify({
  6198. id,
  6199. name,
  6200. tunnel_id: tunnelId,
  6201. remote_address: remote,
  6202. ip_address: ipAddress,
  6203. local_address: local,
  6204. mac_address: mac,
  6205. mtu,
  6206. clamp_mss: clampMss,
  6207. comment,
  6208. disabled
  6209. })
  6210. });
  6211. if (res.ok) {
  6212. showToast('EoIP Saved', `Tunnel ${name} configured successfully`, 'success');
  6213. closeEoIPModal();
  6214. loadEoIP(false);
  6215. fetchData(false);
  6216. } else {
  6217. const err = await res.json();
  6218. showToast('Error', err.message, 'error');
  6219. }
  6220. } catch (err) {
  6221. showToast('Error', err.message, 'error');
  6222. }
  6223. }
  6224. async function toggleEoIPState(id, disabled) {
  6225. try {
  6226. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}/state`, {
  6227. method: 'POST',
  6228. headers: { 'Content-Type': 'application/json' },
  6229. body: JSON.stringify({ disabled })
  6230. });
  6231. if (res.ok) {
  6232. showToast(disabled ? 'Disabled' : 'Enabled', 'EoIP tunnel state updated', 'info');
  6233. loadEoIP(false);
  6234. fetchData(false);
  6235. }
  6236. } catch (err) {
  6237. showToast('Error', err.message, 'error');
  6238. }
  6239. }
  6240. async function deleteEoIP(id) {
  6241. if (!confirm('Are you sure you want to delete this EoIP tunnel?')) return;
  6242. try {
  6243. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6244. if (res.ok) {
  6245. showToast('Deleted', 'EoIP tunnel removed', 'success');
  6246. loadEoIP(false);
  6247. fetchData(false);
  6248. }
  6249. } catch (err) {
  6250. showToast('Error', err.message, 'error');
  6251. }
  6252. }
  6253. // ======================== AeroTUN (Custom Encrypted VPN with Adaptive LZ4) ========================
  6254. async function loadAeroTUN(populate = true) {
  6255. try {
  6256. const [tunnelsRes, statsRes] = await Promise.all([
  6257. fetch(`${API_BASE}/vpn/aerotun/tunnels`),
  6258. fetch(`${API_BASE}/vpn/aerotun/stats`)
  6259. ]);
  6260. if (tunnelsRes.ok) {
  6261. const data = await tunnelsRes.json();
  6262. state.aerotunTunnels = Array.isArray(data) ? data : [];
  6263. }
  6264. if (statsRes.ok) {
  6265. state.aerotunStats = await statsRes.json();
  6266. }
  6267. const countBadge = document.getElementById('aerotun-count-badge');
  6268. if (countBadge) countBadge.innerText = `${(state.aerotunTunnels || []).length} Tunnels`;
  6269. const sideBadge = document.getElementById('badge-aerotun-count');
  6270. if (sideBadge) sideBadge.innerText = (state.aerotunTunnels || []).length;
  6271. renderAeroTUN();
  6272. } catch (err) {
  6273. console.error('Failed to load AeroTUN:', err);
  6274. }
  6275. }
  6276. function renderAeroTUN() {
  6277. const tbody = document.getElementById('aerotun-table-body');
  6278. const empty = document.getElementById('aerotun-empty');
  6279. // Update summary cards
  6280. const stats = state.aerotunStats || {};
  6281. const tunnels = state.aerotunTunnels || [];
  6282. const statActive = document.getElementById('aerotun-stat-active');
  6283. if (statActive) {
  6284. const activeCount = tunnels.filter(t => t.running).length;
  6285. statActive.innerText = `${activeCount} / ${tunnels.length}`;
  6286. }
  6287. const statSaved = document.getElementById('aerotun-stat-saved');
  6288. if (statSaved) {
  6289. statSaved.innerText = formatBytes(stats.total_saved_bytes || 0);
  6290. }
  6291. const statRatio = document.getElementById('aerotun-stat-ratio');
  6292. if (statRatio) {
  6293. statRatio.innerText = stats.average_ratio || '1.00x (0% saved)';
  6294. }
  6295. const statTraffic = document.getElementById('aerotun-stat-traffic');
  6296. if (statTraffic) {
  6297. statTraffic.innerText = `↓ ${formatBytes(stats.total_rx_bytes || 0)} / ↑ ${formatBytes(stats.total_tx_bytes || 0)}`;
  6298. }
  6299. if (!tbody) return;
  6300. tbody.innerHTML = '';
  6301. if (tunnels.length === 0) {
  6302. empty?.classList.remove('hidden');
  6303. return;
  6304. }
  6305. empty?.classList.add('hidden');
  6306. tunnels.forEach(t => {
  6307. const tr = document.createElement('tr');
  6308. tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
  6309. const modeBadge = t.mode === 'server'
  6310. ? `<span class="px-2 py-0.5 rounded text-[10px] font-mono bg-sky-500/20 text-sky-300 border border-sky-500/30 font-semibold uppercase">Server</span>`
  6311. : `<span class="px-2 py-0.5 rounded text-[10px] font-mono bg-indigo-500/20 text-indigo-300 border border-indigo-500/30 font-semibold uppercase">Client</span>`;
  6312. const endpointInfo = t.mode === 'server'
  6313. ? `<span class="text-sky-300 font-mono">Port :${t.listen_port || 51830}</span>`
  6314. : `<span class="text-indigo-300 font-mono">${escapeHtml(t.remote_endpoint || '(not set)')}</span>`;
  6315. const compBadge = t.compression
  6316. ? `<span class="px-1.5 py-0.5 rounded text-[10px] font-mono bg-emerald-500/20 text-emerald-300 border border-emerald-500/30 font-semibold" title="Adaptive LZ4 active">${t.compression_ratio || 'LZ4'}</span>`
  6317. : `<span class="text-slate-500 text-[10px]">Off</span>`;
  6318. const activePeer = t.active_peer_endpoint
  6319. ? `<span class="text-emerald-400 font-mono text-[11px]" title="Last seen: ${t.last_handshake || 'just now'}">● ${escapeHtml(t.active_peer_endpoint)}</span>`
  6320. : `<span class="text-slate-500 text-[11px]">${t.mode === 'server' ? 'Waiting for peer...' : 'Connecting...'}</span>`;
  6321. const rawRx = formatBytes(t.rx_bytes || 0);
  6322. const rawTx = formatBytes(t.tx_bytes || 0);
  6323. const wireRx = formatBytes(t.wire_bytes_in || 0);
  6324. const wireTx = formatBytes(t.wire_bytes_out || 0);
  6325. tr.innerHTML = `
  6326. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.running, t.disabled)}</td>
  6327. <td class="py-2.5 px-3 font-bold text-white font-mono flex items-center gap-1.5">
  6328. <span>${escapeHtml(t.name)}</span>
  6329. ${t.default_route ? '<span class="text-[9px] px-1 rounded bg-amber-500/20 text-amber-300 border border-amber-500/30">DEF</span>' : ''}
  6330. </td>
  6331. <td class="py-2.5 px-3">${modeBadge}</td>
  6332. <td class="py-2.5 px-3 text-xs font-mono">${endpointInfo}</td>
  6333. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${escapeHtml(t.local_address || '-')}</td>
  6334. <td class="py-2.5 px-3">${compBadge}</td>
  6335. <td class="py-2.5 px-3">${activePeer}</td>
  6336. <td class="py-2.5 px-3 font-mono text-[11px]">
  6337. <span class="text-emerald-400">↓ ${rawRx}</span>
  6338. <span class="text-cyan-400 ml-1">↑ ${rawTx}</span>
  6339. </td>
  6340. <td class="py-2.5 px-3 font-mono text-[11px]">
  6341. <span class="text-slate-400">↓ ${wireRx}</span>
  6342. <span class="text-slate-400 ml-1">↑ ${wireTx}</span>
  6343. </td>
  6344. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(t.comment || '')}">${escapeHtml(t.comment || '-')}</td>
  6345. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  6346. ${t.running
  6347. ? `<button onclick="stopAeroTUNTunnel('${t.id}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Stop</button>`
  6348. : `<button onclick="startAeroTUNTunnel('${t.id}')" class="text-xs text-emerald-400 hover:text-emerald-300 font-medium">Start</button>`
  6349. }
  6350. <button onclick="toggleAeroTUNState('${t.id}', ${!t.disabled})" class="text-xs ${t.disabled ? 'text-emerald-400' : 'text-slate-400'} hover:underline">${t.disabled ? 'Enable' : 'Disable'}</button>
  6351. <button onclick="openEditAeroTUNModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  6352. <button onclick="deleteAeroTUN('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  6353. </td>
  6354. `;
  6355. tbody.appendChild(tr);
  6356. });
  6357. }
  6358. function onAeroTUNModeChange() {
  6359. const mode = document.getElementById('aerotun-modal-mode').value;
  6360. const endpointInput = document.getElementById('aerotun-modal-endpoint');
  6361. const portInput = document.getElementById('aerotun-modal-port');
  6362. if (mode === 'server') {
  6363. if (!portInput.value) portInput.value = '51830';
  6364. endpointInput.placeholder = 'Optional / learned roaming peer';
  6365. } else {
  6366. endpointInput.placeholder = 'vpn.example.com:51830 (required)';
  6367. if (!portInput.value) portInput.value = '';
  6368. }
  6369. }
  6370. async function generateAeroTUNKey() {
  6371. try {
  6372. const res = await fetch(`${API_BASE}/vpn/aerotun/genkey`);
  6373. if (res.ok) {
  6374. const data = await res.json();
  6375. document.getElementById('aerotun-modal-psk').value = data.key;
  6376. showToast('Key Generated', 'Cryptographic 256-bit PSK generated', 'success');
  6377. }
  6378. } catch (err) {
  6379. const arr = new Uint8Array(32);
  6380. crypto.getRandomValues(arr);
  6381. const hex = Array.from(arr).map(b => b.toString(16).padStart(2, '0')).join('');
  6382. document.getElementById('aerotun-modal-psk').value = hex;
  6383. }
  6384. }
  6385. function openAddAeroTUNModal() {
  6386. const tunnels = state.aerotunTunnels || [];
  6387. document.getElementById('aerotun-modal-title').innerText = 'Add AeroTUN Interface';
  6388. document.getElementById('aerotun-modal-id').value = '';
  6389. document.getElementById('aerotun-modal-name').value = `aerotun${tunnels.length}`;
  6390. document.getElementById('aerotun-modal-mode').value = 'server';
  6391. document.getElementById('aerotun-modal-port').value = 51830 + tunnels.length;
  6392. document.getElementById('aerotun-modal-endpoint').value = '';
  6393. document.getElementById('aerotun-modal-local').value = `10.99.${tunnels.length}.1/24`;
  6394. document.getElementById('aerotun-modal-peer').value = `10.99.${tunnels.length}.2/24`;
  6395. document.getElementById('aerotun-modal-psk').value = '';
  6396. document.getElementById('aerotun-modal-mtu').value = '1420';
  6397. document.getElementById('aerotun-modal-comment').value = '';
  6398. document.getElementById('aerotun-modal-compression').checked = true;
  6399. document.getElementById('aerotun-modal-defroute').checked = false;
  6400. document.getElementById('aerotun-modal-disabled').checked = false;
  6401. generateAeroTUNKey();
  6402. onAeroTUNModeChange();
  6403. document.getElementById('aerotun-modal').classList.remove('hidden');
  6404. }
  6405. function openEditAeroTUNModal(id) {
  6406. const t = (state.aerotunTunnels || []).find(tun => tun.id === id);
  6407. if (!t) return;
  6408. document.getElementById('aerotun-modal-title').innerText = `Edit AeroTUN Interface (${t.name})`;
  6409. document.getElementById('aerotun-modal-id').value = t.id;
  6410. document.getElementById('aerotun-modal-name').value = t.name;
  6411. document.getElementById('aerotun-modal-mode').value = t.mode || 'server';
  6412. document.getElementById('aerotun-modal-port').value = t.listen_port || '';
  6413. document.getElementById('aerotun-modal-endpoint').value = t.remote_endpoint || '';
  6414. document.getElementById('aerotun-modal-local').value = t.local_address || '';
  6415. document.getElementById('aerotun-modal-peer').value = t.peer_address || '';
  6416. document.getElementById('aerotun-modal-psk').value = t.psk || '';
  6417. document.getElementById('aerotun-modal-mtu').value = t.mtu || 1420;
  6418. document.getElementById('aerotun-modal-comment').value = t.comment || '';
  6419. document.getElementById('aerotun-modal-compression').checked = !!t.compression;
  6420. document.getElementById('aerotun-modal-defroute').checked = !!t.default_route;
  6421. document.getElementById('aerotun-modal-disabled').checked = !!t.disabled;
  6422. onAeroTUNModeChange();
  6423. document.getElementById('aerotun-modal').classList.remove('hidden');
  6424. }
  6425. function closeAeroTUNModal() {
  6426. document.getElementById('aerotun-modal').classList.add('hidden');
  6427. }
  6428. async function submitSaveAeroTUN(e) {
  6429. e.preventDefault();
  6430. const id = document.getElementById('aerotun-modal-id').value;
  6431. const name = document.getElementById('aerotun-modal-name').value.trim();
  6432. const mode = document.getElementById('aerotun-modal-mode').value;
  6433. const port = parseInt(document.getElementById('aerotun-modal-port').value) || 0;
  6434. const endpoint = document.getElementById('aerotun-modal-endpoint').value.trim();
  6435. const local = document.getElementById('aerotun-modal-local').value.trim();
  6436. const peer = document.getElementById('aerotun-modal-peer').value.trim();
  6437. const psk = document.getElementById('aerotun-modal-psk').value.trim();
  6438. const mtu = parseInt(document.getElementById('aerotun-modal-mtu').value) || 1420;
  6439. const comment = document.getElementById('aerotun-modal-comment').value.trim();
  6440. const compression = document.getElementById('aerotun-modal-compression').checked;
  6441. const defaultRoute = document.getElementById('aerotun-modal-defroute').checked;
  6442. const disabled = document.getElementById('aerotun-modal-disabled').checked;
  6443. if (mode === 'client' && !endpoint) {
  6444. showToast('Validation Error', 'Remote endpoint (host:port) is required in client mode', 'error');
  6445. return;
  6446. }
  6447. if (!psk) {
  6448. showToast('Validation Error', 'Pre-shared key (PSK) is required', 'error');
  6449. return;
  6450. }
  6451. try {
  6452. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels`, {
  6453. method: 'POST',
  6454. headers: { 'Content-Type': 'application/json' },
  6455. body: JSON.stringify({
  6456. id,
  6457. name,
  6458. mode,
  6459. listen_port: port,
  6460. remote_endpoint: endpoint,
  6461. local_address: local,
  6462. peer_address: peer,
  6463. psk,
  6464. mtu,
  6465. compression,
  6466. default_route: defaultRoute,
  6467. comment,
  6468. disabled
  6469. })
  6470. });
  6471. if (res.ok) {
  6472. showToast('AeroTUN Saved', `Tunnel ${name} configured successfully`, 'success');
  6473. closeAeroTUNModal();
  6474. loadAeroTUN(false);
  6475. fetchData(false);
  6476. } else {
  6477. const err = await res.text();
  6478. showToast('Error Saving Tunnel', err, 'error');
  6479. }
  6480. } catch (err) {
  6481. showToast('Network Error', err.message, 'error');
  6482. }
  6483. }
  6484. async function startAeroTUNTunnel(id) {
  6485. try {
  6486. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/start`, { method: 'POST' });
  6487. if (res.ok) {
  6488. showToast('AeroTUN Started', 'Tunnel interface is active', 'success');
  6489. loadAeroTUN(false);
  6490. fetchData(false);
  6491. } else {
  6492. const err = await res.text();
  6493. showToast('Failed to Start', err, 'error');
  6494. }
  6495. } catch (err) {
  6496. showToast('Error', err.message, 'error');
  6497. }
  6498. }
  6499. async function stopAeroTUNTunnel(id) {
  6500. try {
  6501. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/stop`, { method: 'POST' });
  6502. if (res.ok) {
  6503. showToast('AeroTUN Stopped', 'Tunnel stopped', 'info');
  6504. loadAeroTUN(false);
  6505. fetchData(false);
  6506. } else {
  6507. const err = await res.text();
  6508. showToast('Failed to Stop', err, 'error');
  6509. }
  6510. } catch (err) {
  6511. showToast('Error', err.message, 'error');
  6512. }
  6513. }
  6514. async function toggleAeroTUNState(id, disabled) {
  6515. try {
  6516. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/state`, {
  6517. method: 'POST',
  6518. headers: { 'Content-Type': 'application/json' },
  6519. body: JSON.stringify({ disabled })
  6520. });
  6521. if (res.ok) {
  6522. showToast('State Updated', disabled ? 'Tunnel disabled' : 'Tunnel enabled', 'info');
  6523. loadAeroTUN(false);
  6524. fetchData(false);
  6525. }
  6526. } catch (err) {
  6527. showToast('Error', err.message, 'error');
  6528. }
  6529. }
  6530. async function deleteAeroTUN(id) {
  6531. if (!confirm('Are you sure you want to delete this AeroTUN tunnel?')) return;
  6532. try {
  6533. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6534. if (res.ok) {
  6535. showToast('Deleted', 'AeroTUN tunnel removed', 'success');
  6536. loadAeroTUN(false);
  6537. fetchData(false);
  6538. }
  6539. } catch (err) {
  6540. showToast('Error', err.message, 'error');
  6541. }
  6542. }
  6543. // ======================== PPP Central Hub & Servers ========================
  6544. function switchPPPSubTab(tab) {
  6545. state.pppSubTab = tab;
  6546. const tabs = ['secrets', 'profiles', 'pppoe', 'pptp', 'l2tp', 'active'];
  6547. tabs.forEach(t => {
  6548. const panel = document.getElementById(`ppp-subtab-${t}`);
  6549. const btn = document.getElementById(`ppp-subtab-btn-${t}`);
  6550. if (panel) {
  6551. if (t === tab) panel.classList.remove('hidden');
  6552. else panel.classList.add('hidden');
  6553. }
  6554. if (btn) {
  6555. if (t === tab) {
  6556. 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';
  6557. } else {
  6558. 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';
  6559. }
  6560. }
  6561. });
  6562. const addBtn = document.getElementById('ppp-primary-add-btn');
  6563. if (addBtn) {
  6564. if (tab === 'secrets') addBtn.innerHTML = '<span>+ Add User (Secret)</span>';
  6565. else if (tab === 'profiles') addBtn.innerHTML = '<span>+ Add Profile</span>';
  6566. else if (tab === 'active') addBtn.innerHTML = '<span>Refresh Sessions</span>';
  6567. else addBtn.innerHTML = '<span>Save Config</span>';
  6568. }
  6569. if (tab === 'active') loadPPPSessions();
  6570. }
  6571. function openCurrentPPPModal() {
  6572. if (state.pppSubTab === 'secrets') openAddPPPSecretModal();
  6573. else if (state.pppSubTab === 'profiles') openAddPPPProfileModal();
  6574. else if (state.pppSubTab === 'active') loadPPPSessions();
  6575. else if (state.pppSubTab === 'pppoe') document.querySelector('#ppp-subtab-pppoe form')?.requestSubmit();
  6576. else if (state.pppSubTab === 'pptp') document.querySelector('#ppp-subtab-pptp form')?.requestSubmit();
  6577. else if (state.pppSubTab === 'l2tp') document.querySelector('#ppp-subtab-l2tp form')?.requestSubmit();
  6578. }
  6579. async function loadPPP(populateDropdowns = true) {
  6580. await Promise.all([
  6581. loadPPPSecrets(),
  6582. loadPPPProfiles(),
  6583. loadPPPServers(),
  6584. loadPPPSessions()
  6585. ]);
  6586. }
  6587. async function loadPPPSecrets() {
  6588. try {
  6589. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`);
  6590. const data = await res.json();
  6591. state.pppSecrets = Array.isArray(data) ? data : [];
  6592. const b = document.getElementById('ppp-badge-secrets');
  6593. if (b) b.innerText = state.pppSecrets.length;
  6594. const b2 = document.getElementById('secrets-count-badge');
  6595. if (b2) b2.innerText = `${state.pppSecrets.length} Users`;
  6596. renderPPPSecrets();
  6597. } catch (err) {
  6598. console.error('Failed to load PPP secrets:', err);
  6599. }
  6600. }
  6601. function renderPPPSecrets() {
  6602. const tbody = document.getElementById('secrets-table-body');
  6603. const empty = document.getElementById('secrets-empty');
  6604. if (!tbody) return;
  6605. tbody.innerHTML = '';
  6606. const secrets = state.pppSecrets || [];
  6607. if (secrets.length === 0) {
  6608. empty?.classList.remove('hidden');
  6609. return;
  6610. }
  6611. empty?.classList.add('hidden');
  6612. secrets.forEach(s => {
  6613. const tr = document.createElement('tr');
  6614. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  6615. tr.innerHTML = `
  6616. <td class="py-2.5 px-3 text-center">${renderRuleFlag(s.disabled, !!s.comment)}</td>
  6617. <td class="py-2.5 px-3 font-bold text-white font-mono">${s.name}</td>
  6618. <td class="py-2.5 px-3 text-purple-300 font-mono font-semibold">${s.service}</td>
  6619. <td class="py-2.5 px-3 text-amber-300 font-mono">${s.profile}</td>
  6620. <td class="py-2.5 px-3 text-slate-400 font-mono">${s.local_address || '(profile)'}</td>
  6621. <td class="py-2.5 px-3 text-cyan-400 font-mono font-bold">${s.remote_address || '(profile)'}</td>
  6622. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]">${s.comment || '-'}</td>
  6623. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  6624. <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>
  6625. <button onclick="openEditPPPSecretModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  6626. <button onclick="deletePPPSecret('${s.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  6627. </td>
  6628. `;
  6629. tbody.appendChild(tr);
  6630. });
  6631. }
  6632. async function loadPPPProfiles() {
  6633. try {
  6634. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`);
  6635. const data = await res.json();
  6636. state.pppProfiles = Array.isArray(data) ? data : [];
  6637. const b = document.getElementById('ppp-badge-profiles');
  6638. if (b) b.innerText = state.pppProfiles.length;
  6639. const b2 = document.getElementById('profiles-count-badge');
  6640. if (b2) b2.innerText = `${state.pppProfiles.length} Profiles`;
  6641. // Populate profile selects across modals
  6642. const selects = ['secret-modal-profile', 'pppoe-server-profile', 'pptp-server-profile', 'l2tp-server-profile'];
  6643. selects.forEach(sid => {
  6644. const el = document.getElementById(sid);
  6645. if (!el) return;
  6646. const cur = el.value;
  6647. el.innerHTML = '';
  6648. state.pppProfiles.forEach(p => {
  6649. const opt = document.createElement('option');
  6650. opt.value = p.name;
  6651. opt.innerText = `${p.name} (${p.remote_address})`;
  6652. if (p.name === cur) opt.selected = true;
  6653. el.appendChild(opt);
  6654. });
  6655. });
  6656. renderPPPProfiles();
  6657. } catch (err) {
  6658. console.error('Failed to load PPP profiles:', err);
  6659. }
  6660. }
  6661. function renderPPPProfiles() {
  6662. const tbody = document.getElementById('profiles-table-body');
  6663. if (!tbody) return;
  6664. tbody.innerHTML = '';
  6665. (state.pppProfiles || []).forEach(p => {
  6666. const isDefault = p.name.startsWith('default');
  6667. const tr = document.createElement('tr');
  6668. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  6669. tr.innerHTML = `
  6670. <td class="py-2.5 px-3 font-bold text-white">${p.name}</td>
  6671. <td class="py-2.5 px-3 text-slate-300">${p.local_address}</td>
  6672. <td class="py-2.5 px-3 text-cyan-400 font-bold">${p.remote_address}</td>
  6673. <td class="py-2.5 px-3 text-slate-400">${p.dns_servers || '-'}</td>
  6674. <td class="py-2.5 px-3 text-purple-300 font-semibold">${p.use_encryption}</td>
  6675. <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>
  6676. <td class="py-2.5 px-3 text-slate-400 italic">${p.comment || '-'}</td>
  6677. <td class="py-2.5 px-3 text-right font-sans whitespace-nowrap">
  6678. ${!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>`}
  6679. </td>
  6680. `;
  6681. tbody.appendChild(tr);
  6682. });
  6683. }
  6684. async function loadPPPServers() {
  6685. try {
  6686. const [pppoeRes, pptpRes, l2tpRes, ipsecRes] = await Promise.all([
  6687. fetch(`${API_BASE}/vpn/servers/pppoe`),
  6688. fetch(`${API_BASE}/vpn/servers/pptp`),
  6689. fetch(`${API_BASE}/vpn/servers/l2tp`),
  6690. fetch(`${API_BASE}/vpn/servers/ipsec`)
  6691. ]);
  6692. if (pppoeRes.ok) {
  6693. state.pppoeServer = await pppoeRes.json();
  6694. const s = state.pppoeServer;
  6695. document.getElementById('pppoe-server-enabled').checked = !!s.enabled;
  6696. document.getElementById('pppoe-server-name').value = s.service_name || 'proxmox-pppoe';
  6697. populateInterfaceSelect('pppoe-server-iface', s.interface || 'eth0');
  6698. document.getElementById('pppoe-server-profile').value = s.default_profile || 'default';
  6699. document.getElementById('pppoe-server-mtu').value = s.max_mtu || 1480;
  6700. document.getElementById('pppoe-server-onesession').checked = !!s.one_session_per_host;
  6701. const pill = document.getElementById('pppoe-server-status-pill');
  6702. if (pill) {
  6703. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  6704. 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';
  6705. }
  6706. setDotBadge('ppp-badge-pppoe-state', s.running);
  6707. }
  6708. if (pptpRes.ok) {
  6709. state.pptpServer = await pptpRes.json();
  6710. const s = state.pptpServer;
  6711. document.getElementById('pptp-server-enabled').checked = !!s.enabled;
  6712. document.getElementById('pptp-server-port').value = s.port || 1723;
  6713. document.getElementById('pptp-server-profile').value = s.default_profile || 'default-encryption';
  6714. document.getElementById('pptp-server-mppe').checked = s.require_mppe !== false;
  6715. const pill = document.getElementById('pptp-server-status-pill');
  6716. if (pill) {
  6717. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  6718. 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';
  6719. }
  6720. setDotBadge('ppp-badge-pptp-state', s.running);
  6721. }
  6722. if (l2tpRes.ok) {
  6723. state.l2tpServer = await l2tpRes.json();
  6724. const s = state.l2tpServer;
  6725. document.getElementById('l2tp-server-enabled').checked = !!s.enabled;
  6726. document.getElementById('l2tp-server-port').value = s.port || 1701;
  6727. document.getElementById('l2tp-server-profile').value = s.default_profile || 'default';
  6728. document.getElementById('l2tp-server-useipsec').value = s.use_ipsec || 'no';
  6729. document.getElementById('l2tp-server-ipsecsecret').value = s.ipsec_secret || '';
  6730. const pill = document.getElementById('l2tp-server-status-pill');
  6731. if (pill) {
  6732. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  6733. 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';
  6734. }
  6735. setDotBadge('ppp-badge-l2tp-state', s.running);
  6736. }
  6737. if (ipsecRes.ok) {
  6738. state.ipsecServer = await ipsecRes.json();
  6739. const s = state.ipsecServer;
  6740. const modalEn = document.getElementById('modal-ipsec-server-enabled');
  6741. if (modalEn) modalEn.checked = !!s.enabled;
  6742. const modalPsk = document.getElementById('modal-ipsec-server-psk');
  6743. if (modalPsk) modalPsk.value = s.preshared_key || '';
  6744. const modalPool = document.getElementById('modal-ipsec-server-pool');
  6745. if (modalPool) modalPool.value = s.pool_address || '10.10.30.0/24';
  6746. const modalDns = document.getElementById('modal-ipsec-server-dns');
  6747. if (modalDns) modalDns.value = s.dns_servers || '1.1.1.1,8.8.8.8';
  6748. const modalSubnet = document.getElementById('modal-ipsec-server-subnet');
  6749. if (modalSubnet) modalSubnet.value = s.local_subnet || '0.0.0.0/0';
  6750. const pill = document.getElementById('modal-ipsec-server-status');
  6751. if (pill) {
  6752. pill.innerText = s.running ? 'ACTIVE RESPONDER' : 'STOPPED';
  6753. 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';
  6754. }
  6755. }
  6756. } catch (err) {
  6757. console.error('Failed to load VPN servers:', err);
  6758. }
  6759. }
  6760. async function loadPPPSessions() {
  6761. try {
  6762. const res = await fetch(`${API_BASE}/vpn/ppp/active`);
  6763. const data = await res.json();
  6764. state.pppActiveSessions = Array.isArray(data) ? data : [];
  6765. const b = document.getElementById('ppp-badge-active');
  6766. if (b) b.innerText = state.pppActiveSessions.length;
  6767. const sideB = document.getElementById('badge-ppp-sessions');
  6768. if (sideB) sideB.innerText = state.pppActiveSessions.length;
  6769. renderPPPSessions();
  6770. } catch (err) {
  6771. console.error('Failed to load active PPP sessions:', err);
  6772. }
  6773. }
  6774. function renderPPPSessions() {
  6775. const tbody = document.getElementById('active-ppp-table-body');
  6776. const empty = document.getElementById('active-ppp-empty');
  6777. if (!tbody) return;
  6778. tbody.innerHTML = '';
  6779. const list = state.pppActiveSessions || [];
  6780. if (list.length === 0) {
  6781. empty?.classList.remove('hidden');
  6782. return;
  6783. }
  6784. empty?.classList.add('hidden');
  6785. list.forEach(s => {
  6786. const tr = document.createElement('tr');
  6787. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  6788. tr.innerHTML = `
  6789. <td class="py-2.5 px-3 font-bold text-white">${s.interface}</td>
  6790. <td class="py-2.5 px-3 font-semibold text-violet-300">${s.username}</td>
  6791. <td class="py-2.5 px-3 text-cyan-400 uppercase">${s.service}</td>
  6792. <td class="py-2.5 px-3 text-emerald-400 font-bold">${s.address || '-'}</td>
  6793. <td class="py-2.5 px-3 text-slate-400">${s.uptime}</td>
  6794. <td class="py-2.5 px-3 text-[11px]">
  6795. <span class="text-emerald-400">↓ ${s.rx_human || '0 B'}</span>
  6796. <span class="text-cyan-400 ml-1">↑ ${s.tx_human || '0 B'}</span>
  6797. </td>
  6798. <td class="py-2.5 px-3 text-right font-sans">
  6799. <button onclick="disconnectPPPSession('${s.interface}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  6800. </td>
  6801. `;
  6802. tbody.appendChild(tr);
  6803. });
  6804. }
  6805. async function disconnectPPPSession(iface) {
  6806. if (!confirm(`Disconnect session ${iface}?`)) return;
  6807. try {
  6808. const res = await fetch(`${API_BASE}/vpn/ppp/active/${encodeURIComponent(iface)}`, { method: 'DELETE' });
  6809. if (res.ok) {
  6810. showToast('Disconnected', `Session ${iface} terminated`, 'info');
  6811. loadPPPSessions();
  6812. }
  6813. } catch (err) {
  6814. showToast('Error', err.message, 'error');
  6815. }
  6816. }
  6817. // PPP Secret Modal handlers
  6818. function openAddPPPSecretModal() {
  6819. document.getElementById('secret-modal-title').innerText = 'Add PPP Secret';
  6820. document.getElementById('secret-modal-id').value = '';
  6821. document.getElementById('secret-modal-name').value = '';
  6822. document.getElementById('secret-modal-password').value = '';
  6823. document.getElementById('secret-modal-service').value = 'any';
  6824. document.getElementById('secret-modal-profile').value = 'default';
  6825. document.getElementById('secret-modal-local').value = '';
  6826. document.getElementById('secret-modal-remote').value = '';
  6827. document.getElementById('secret-modal-comment').value = '';
  6828. document.getElementById('secret-modal-disabled').checked = false;
  6829. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  6830. }
  6831. function openEditPPPSecretModal(id) {
  6832. const s = (state.pppSecrets || []).find(sec => sec.id === id);
  6833. if (!s) return;
  6834. document.getElementById('secret-modal-title').innerText = `Edit PPP Secret (${s.name})`;
  6835. document.getElementById('secret-modal-id').value = s.id;
  6836. document.getElementById('secret-modal-name').value = s.name;
  6837. document.getElementById('secret-modal-password').value = s.password;
  6838. document.getElementById('secret-modal-service').value = s.service || 'any';
  6839. document.getElementById('secret-modal-profile').value = s.profile || 'default';
  6840. document.getElementById('secret-modal-local').value = s.local_address || '';
  6841. document.getElementById('secret-modal-remote').value = s.remote_address || '';
  6842. document.getElementById('secret-modal-comment').value = s.comment || '';
  6843. document.getElementById('secret-modal-disabled').checked = !!s.disabled;
  6844. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  6845. }
  6846. function closePPPSecretModal() {
  6847. document.getElementById('ppp-secret-modal').classList.add('hidden');
  6848. }
  6849. async function submitSavePPPSecret(e) {
  6850. e.preventDefault();
  6851. const id = document.getElementById('secret-modal-id').value;
  6852. const name = document.getElementById('secret-modal-name').value.trim();
  6853. const password = document.getElementById('secret-modal-password').value.trim();
  6854. const service = document.getElementById('secret-modal-service').value;
  6855. const profile = document.getElementById('secret-modal-profile').value;
  6856. const local = document.getElementById('secret-modal-local').value.trim();
  6857. const remote = document.getElementById('secret-modal-remote').value.trim();
  6858. const comment = document.getElementById('secret-modal-comment').value.trim();
  6859. const disabled = document.getElementById('secret-modal-disabled').checked;
  6860. try {
  6861. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`, {
  6862. method: 'POST',
  6863. headers: { 'Content-Type': 'application/json' },
  6864. body: JSON.stringify({
  6865. id,
  6866. name,
  6867. password,
  6868. service,
  6869. profile,
  6870. local_address: local,
  6871. remote_address: remote,
  6872. comment,
  6873. disabled
  6874. })
  6875. });
  6876. if (res.ok) {
  6877. showToast('Secret Saved', `User ${name} saved to PPP database`, 'success');
  6878. closePPPSecretModal();
  6879. loadPPPSecrets();
  6880. } else {
  6881. const err = await res.json();
  6882. showToast('Error', err.message, 'error');
  6883. }
  6884. } catch (err) {
  6885. showToast('Error', err.message, 'error');
  6886. }
  6887. }
  6888. async function togglePPPSecretState(id, disabled) {
  6889. try {
  6890. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}/state`, {
  6891. method: 'POST',
  6892. headers: { 'Content-Type': 'application/json' },
  6893. body: JSON.stringify({ disabled })
  6894. });
  6895. if (res.ok) {
  6896. showToast(disabled ? 'Disabled' : 'Enabled', 'Secret user state updated', 'info');
  6897. loadPPPSecrets();
  6898. }
  6899. } catch (err) {
  6900. showToast('Error', err.message, 'error');
  6901. }
  6902. }
  6903. async function deletePPPSecret(id) {
  6904. if (!confirm('Are you sure you want to delete this secret account?')) return;
  6905. try {
  6906. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6907. if (res.ok) {
  6908. showToast('Deleted', 'Secret account removed', 'success');
  6909. loadPPPSecrets();
  6910. }
  6911. } catch (err) {
  6912. showToast('Error', err.message, 'error');
  6913. }
  6914. }
  6915. // PPP Profile Modal handlers
  6916. function openAddPPPProfileModal() {
  6917. document.getElementById('profile-modal-name').value = '';
  6918. document.getElementById('profile-modal-local').value = '10.10.10.1';
  6919. document.getElementById('profile-modal-remote').value = '10.10.10.10-10.10.10.50';
  6920. document.getElementById('profile-modal-dns').value = '1.1.1.1,8.8.8.8';
  6921. document.getElementById('profile-modal-encryption').value = 'required';
  6922. document.getElementById('profile-modal-onlyone').checked = true;
  6923. document.getElementById('profile-modal-comment').value = '';
  6924. document.getElementById('ppp-profile-modal').classList.remove('hidden');
  6925. }
  6926. function closePPPProfileModal() {
  6927. document.getElementById('ppp-profile-modal').classList.add('hidden');
  6928. }
  6929. async function submitSavePPPProfile(e) {
  6930. e.preventDefault();
  6931. const name = document.getElementById('profile-modal-name').value.trim();
  6932. const local = document.getElementById('profile-modal-local').value.trim();
  6933. const remote = document.getElementById('profile-modal-remote').value.trim();
  6934. const dns = document.getElementById('profile-modal-dns').value.trim();
  6935. const enc = document.getElementById('profile-modal-encryption').value;
  6936. const onlyone = document.getElementById('profile-modal-onlyone').checked;
  6937. const comment = document.getElementById('profile-modal-comment').value.trim();
  6938. try {
  6939. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`, {
  6940. method: 'POST',
  6941. headers: { 'Content-Type': 'application/json' },
  6942. body: JSON.stringify({
  6943. id: name,
  6944. name,
  6945. local_address: local,
  6946. remote_address: remote,
  6947. dns_servers: dns,
  6948. use_encryption: enc,
  6949. only_one: onlyone,
  6950. comment
  6951. })
  6952. });
  6953. if (res.ok) {
  6954. showToast('Profile Saved', `PPP profile ${name} created`, 'success');
  6955. closePPPProfileModal();
  6956. loadPPPProfiles();
  6957. } else {
  6958. const err = await res.json();
  6959. showToast('Error', err.message, 'error');
  6960. }
  6961. } catch (err) {
  6962. showToast('Error', err.message, 'error');
  6963. }
  6964. }
  6965. async function deletePPPProfile(name) {
  6966. if (!confirm(`Delete PPP profile ${name}?`)) return;
  6967. try {
  6968. const res = await fetch(`${API_BASE}/vpn/ppp/profiles/${encodeURIComponent(name)}`, { method: 'DELETE' });
  6969. if (res.ok) {
  6970. showToast('Deleted', 'Profile removed', 'success');
  6971. loadPPPProfiles();
  6972. } else {
  6973. const err = await res.json();
  6974. showToast('Error', err.message, 'error');
  6975. }
  6976. } catch (err) {
  6977. showToast('Error', err.message, 'error');
  6978. }
  6979. }
  6980. // Server Config submissions
  6981. async function savePPPoEServerConfig(e) {
  6982. e.preventDefault();
  6983. const enabled = document.getElementById('pppoe-server-enabled').checked;
  6984. const name = document.getElementById('pppoe-server-name').value.trim();
  6985. const iface = document.getElementById('pppoe-server-iface').value;
  6986. const profile = document.getElementById('pppoe-server-profile').value;
  6987. const mtu = parseInt(document.getElementById('pppoe-server-mtu').value) || 1480;
  6988. const onesession = document.getElementById('pppoe-server-onesession').checked;
  6989. try {
  6990. const res = await fetch(`${API_BASE}/vpn/servers/pppoe`, {
  6991. method: 'POST',
  6992. headers: { 'Content-Type': 'application/json' },
  6993. body: JSON.stringify({
  6994. enabled,
  6995. service_name: name,
  6996. interface: iface,
  6997. default_profile: profile,
  6998. max_mtu: mtu,
  6999. max_mru: mtu,
  7000. one_session_per_host: onesession
  7001. })
  7002. });
  7003. if (res.ok) {
  7004. showToast('PPPoE Server', enabled ? 'PPPoE Server started' : 'PPPoE Server stopped', 'success');
  7005. loadPPPServers();
  7006. fetchData(false);
  7007. } else {
  7008. const err = await res.json();
  7009. showToast('Error', err.message, 'error');
  7010. }
  7011. } catch (err) {
  7012. showToast('Error', err.message, 'error');
  7013. }
  7014. }
  7015. async function savePPTPServerConfig(e) {
  7016. e.preventDefault();
  7017. const enabled = document.getElementById('pptp-server-enabled').checked;
  7018. const port = parseInt(document.getElementById('pptp-server-port').value) || 1723;
  7019. const profile = document.getElementById('pptp-server-profile').value;
  7020. const mppe = document.getElementById('pptp-server-mppe').checked;
  7021. try {
  7022. const res = await fetch(`${API_BASE}/vpn/servers/pptp`, {
  7023. method: 'POST',
  7024. headers: { 'Content-Type': 'application/json' },
  7025. body: JSON.stringify({
  7026. enabled,
  7027. port,
  7028. default_profile: profile,
  7029. require_mppe: mppe
  7030. })
  7031. });
  7032. if (res.ok) {
  7033. showToast('PPTP Server', enabled ? 'PPTP Server started' : 'PPTP Server stopped', 'success');
  7034. loadPPPServers();
  7035. fetchData(false);
  7036. } else {
  7037. const err = await res.json();
  7038. showToast('Error', err.message, 'error');
  7039. }
  7040. } catch (err) {
  7041. showToast('Error', err.message, 'error');
  7042. }
  7043. }
  7044. async function saveL2TPServerConfig(e) {
  7045. e.preventDefault();
  7046. const enabled = document.getElementById('l2tp-server-enabled').checked;
  7047. const port = parseInt(document.getElementById('l2tp-server-port').value) || 1701;
  7048. const profile = document.getElementById('l2tp-server-profile').value;
  7049. const useipsec = document.getElementById('l2tp-server-useipsec').value;
  7050. const psk = document.getElementById('l2tp-server-ipsecsecret').value.trim();
  7051. try {
  7052. const res = await fetch(`${API_BASE}/vpn/servers/l2tp`, {
  7053. method: 'POST',
  7054. headers: { 'Content-Type': 'application/json' },
  7055. body: JSON.stringify({
  7056. enabled,
  7057. port,
  7058. default_profile: profile,
  7059. use_ipsec: useipsec,
  7060. ipsec_secret: psk
  7061. })
  7062. });
  7063. if (res.ok) {
  7064. showToast('L2TP Server', enabled ? 'L2TP Server started' : 'L2TP Server stopped', 'success');
  7065. loadPPPServers();
  7066. fetchData(false);
  7067. } else {
  7068. const err = await res.json();
  7069. showToast('Error', err.message, 'error');
  7070. }
  7071. } catch (err) {
  7072. showToast('Error', err.message, 'error');
  7073. }
  7074. }
  7075. // IPSec Server Modal
  7076. function openIPSecServerModal() {
  7077. loadPPPServers();
  7078. document.getElementById('ipsec-server-modal').classList.remove('hidden');
  7079. }
  7080. function closeIPSecServerModal() {
  7081. document.getElementById('ipsec-server-modal').classList.add('hidden');
  7082. }
  7083. async function submitSaveIPSecServer(e) {
  7084. e.preventDefault();
  7085. const enabled = document.getElementById('modal-ipsec-server-enabled').checked;
  7086. const psk = document.getElementById('modal-ipsec-server-psk').value.trim();
  7087. const pool = document.getElementById('modal-ipsec-server-pool').value.trim();
  7088. const dns = document.getElementById('modal-ipsec-server-dns').value.trim();
  7089. const subnet = document.getElementById('modal-ipsec-server-subnet').value.trim();
  7090. try {
  7091. const res = await fetch(`${API_BASE}/vpn/servers/ipsec`, {
  7092. method: 'POST',
  7093. headers: { 'Content-Type': 'application/json' },
  7094. body: JSON.stringify({
  7095. enabled,
  7096. preshared_key: psk,
  7097. pool_address: pool,
  7098. dns_servers: dns,
  7099. local_subnet: subnet
  7100. })
  7101. });
  7102. if (res.ok) {
  7103. showToast('IPSec Server', enabled ? 'IKEv2 Roadwarrior responder active' : 'IPSec Server stopped', 'success');
  7104. closeIPSecServerModal();
  7105. loadPPPServers();
  7106. fetchData(false);
  7107. } else {
  7108. const err = await res.json();
  7109. showToast('Error', err.message, 'error');
  7110. }
  7111. } catch (err) {
  7112. showToast('Error', err.message, 'error');
  7113. }
  7114. }
  7115. // WireGuard Client Config Viewer
  7116. let currentWGClientConf = '';
  7117. async function openWGClientConfModal(iface, clientIP) {
  7118. try {
  7119. const res = await fetch(`${API_BASE}/vpn/wireguard/client-config`, {
  7120. method: 'POST',
  7121. headers: { 'Content-Type': 'application/json' },
  7122. body: JSON.stringify({
  7123. interface: iface,
  7124. address: clientIP || '10.10.0.2/32',
  7125. dns: '1.1.1.1, 8.8.8.8'
  7126. })
  7127. });
  7128. if (res.ok) {
  7129. const data = await res.json();
  7130. currentWGClientConf = data.config;
  7131. document.getElementById('wg-client-conf-text').value = currentWGClientConf;
  7132. document.getElementById('wg-client-conf-modal').classList.remove('hidden');
  7133. } else {
  7134. const err = await res.json();
  7135. showToast('Error', err.message, 'error');
  7136. }
  7137. } catch (err) {
  7138. showToast('Error', err.message, 'error');
  7139. }
  7140. }
  7141. function closeWGClientConfModal() {
  7142. document.getElementById('wg-client-conf-modal').classList.add('hidden');
  7143. }
  7144. function copyWGClientConf() {
  7145. if (!currentWGClientConf) return;
  7146. copyToClipboard(currentWGClientConf, 'WireGuard Client Profile');
  7147. }
  7148. function downloadWGClientConf() {
  7149. if (!currentWGClientConf) return;
  7150. const blob = new Blob([currentWGClientConf], { type: 'text/plain;charset=utf-8' });
  7151. const a = document.createElement('a');
  7152. a.href = URL.createObjectURL(blob);
  7153. a.download = 'wireguard-client.conf';
  7154. document.body.appendChild(a);
  7155. a.click();
  7156. document.body.removeChild(a);
  7157. showToast('Downloaded', 'wireguard-client.conf saved', 'success');
  7158. }
  7159. // =========================================================================
  7160. // DYNAMIC ROUTING (FRRouting BGP & OSPFv2)
  7161. // =========================================================================
  7162. state.activeDynSubTab = 'bgp-peers';
  7163. state.activeBgpSubTab = 'bgp-peers';
  7164. state.activeOspfTab = 'instances';
  7165. state.bgpInstance = null;
  7166. state.bgpPeers = [];
  7167. state.bgpNets = [];
  7168. state.bgpRoutes = [];
  7169. state.ospfInstance = null;
  7170. state.ospfInstances = [];
  7171. state.ospfAreas = [];
  7172. state.ospfAreaRanges = [];
  7173. state.ospfTemplates = [];
  7174. state.ospfLiveInterfaces = [];
  7175. state.ospfStaticNbrs = [];
  7176. state.ospfNeighbors = [];
  7177. state.ospfLSA = [];
  7178. state.ospfRoutes = [];
  7179. state.selectedOspfRow = {
  7180. instances: null,
  7181. areas: null,
  7182. 'area-ranges': null,
  7183. templates: null,
  7184. interfaces: null,
  7185. 'static-nbrs': null,
  7186. neighbors: null,
  7187. lsa: null,
  7188. };
  7189. state.ospfSort = {
  7190. instances: { col: 'name', asc: true },
  7191. areas: { col: 'name', asc: true },
  7192. ranges: { col: 'area', asc: true },
  7193. templates: { col: 'interfaces', asc: true },
  7194. live_ifaces: { col: 'interface', asc: true },
  7195. snbrs: { col: 'address', asc: true },
  7196. neighbors: { col: 'address', asc: true },
  7197. lsa: { col: 'instance', asc: true },
  7198. };
  7199. function switchBgpSubTab(subTab) {
  7200. state.activeBgpSubTab = subTab;
  7201. const tabs = ['bgp-peers', 'bgp-nets', 'bgp-routes'];
  7202. tabs.forEach(t => {
  7203. const el = document.getElementById(`dyn-subtab-${t}`);
  7204. const btn = document.getElementById(`bgp-subtab-btn-${t}`);
  7205. if (el) el.classList.toggle('hidden', t !== subTab);
  7206. if (btn) {
  7207. if (t === subTab) {
  7208. 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';
  7209. } else {
  7210. 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';
  7211. }
  7212. }
  7213. });
  7214. }
  7215. function switchOspfTab(tabName) {
  7216. state.activeOspfTab = tabName;
  7217. const tabs = ['instances', 'areas', 'area-ranges', 'templates', 'interfaces', 'static-nbrs', 'neighbors', 'lsa'];
  7218. tabs.forEach(t => {
  7219. const pane = document.getElementById(`ospf-pane-${t}`);
  7220. const btn = document.getElementById(`ospf-tab-btn-${t}`);
  7221. if (pane) pane.classList.toggle('hidden', t !== tabName);
  7222. if (btn) {
  7223. if (t === tabName) {
  7224. btn.className = 'px-3 py-2 text-xs font-semibold border-b-2 border-sky-500 text-white transition flex items-center gap-1.5 whitespace-nowrap';
  7225. } else {
  7226. btn.className = 'px-3 py-2 text-xs font-semibold border-b-2 border-transparent text-slate-400 hover:text-white transition flex items-center gap-1.5 whitespace-nowrap';
  7227. }
  7228. }
  7229. });
  7230. }
  7231. function switchOspfSubTab(tab) {
  7232. // Legacy alias
  7233. if (tab === 'ospf-ifaces') switchOspfTab('templates');
  7234. else if (tab === 'ospf-areas') switchOspfTab('areas');
  7235. else if (tab === 'ospf-nbrs') switchOspfTab('neighbors');
  7236. else switchOspfTab('instances');
  7237. }
  7238. function switchDynSubTab(subTab) {
  7239. if (subTab.startsWith('bgp')) {
  7240. if (state.activeTab !== 'bgp') navigate('bgp');
  7241. switchBgpSubTab(subTab);
  7242. } else if (subTab.startsWith('ospf')) {
  7243. if (state.activeTab !== 'ospf') navigate('ospf');
  7244. switchOspfTab('instances');
  7245. }
  7246. }
  7247. async function loadDynamicRouting(showToastMsg = false) {
  7248. try {
  7249. const fetchSafeJson = async (url) => {
  7250. try {
  7251. const r = await fetch(url);
  7252. return r.ok ? await r.json() : null;
  7253. } catch (e) {
  7254. return null;
  7255. }
  7256. };
  7257. const [
  7258. sum, bgpInst, bgpPeers, bgpNets, bgpRoutes,
  7259. ospfInsts, ospfAreas, ospfRanges, ospfTemplates, ospfLiveIfaces, ospfStaticNbrs, ospfNbrs, ospfLsa, filters,
  7260. selectRules, commLists, asLists
  7261. ] = await Promise.all([
  7262. fetchSafeJson(`${API_BASE}/routing/dynamic/summary`),
  7263. fetchSafeJson(`${API_BASE}/routing/bgp/instance`),
  7264. fetchSafeJson(`${API_BASE}/routing/bgp/peers`),
  7265. fetchSafeJson(`${API_BASE}/routing/bgp/networks`),
  7266. fetchSafeJson(`${API_BASE}/routing/bgp/routes`),
  7267. fetchSafeJson(`${API_BASE}/routing/ospf/instances`),
  7268. fetchSafeJson(`${API_BASE}/routing/ospf/areas`),
  7269. fetchSafeJson(`${API_BASE}/routing/ospf/area-ranges`),
  7270. fetchSafeJson(`${API_BASE}/routing/ospf/templates`),
  7271. fetchSafeJson(`${API_BASE}/routing/ospf/interfaces-live`),
  7272. fetchSafeJson(`${API_BASE}/routing/ospf/static-neighbors`),
  7273. fetchSafeJson(`${API_BASE}/routing/ospf/neighbors`),
  7274. fetchSafeJson(`${API_BASE}/routing/ospf/lsa`),
  7275. fetchSafeJson(`${API_BASE}/routing/filters`),
  7276. fetchSafeJson(`${API_BASE}/routing/filters/select-rules`),
  7277. fetchSafeJson(`${API_BASE}/routing/filters/community-lists`),
  7278. fetchSafeJson(`${API_BASE}/routing/filters/as-lists`)
  7279. ]);
  7280. if (sum) state.dynSummary = sum;
  7281. if (bgpInst) state.bgpInstance = bgpInst;
  7282. if (bgpPeers) state.bgpPeers = bgpPeers;
  7283. if (bgpNets) state.bgpNets = bgpNets;
  7284. if (bgpRoutes) state.bgpRoutes = bgpRoutes;
  7285. if (ospfInsts) state.ospfInstances = ospfInsts;
  7286. if (ospfAreas) state.ospfAreas = ospfAreas;
  7287. if (ospfRanges) state.ospfAreaRanges = ospfRanges;
  7288. if (ospfTemplates) state.ospfTemplates = ospfTemplates;
  7289. if (ospfLiveIfaces) state.ospfLiveInterfaces = ospfLiveIfaces;
  7290. if (ospfStaticNbrs) state.ospfStaticNbrs = ospfStaticNbrs;
  7291. if (ospfNbrs) state.ospfNeighbors = ospfNbrs;
  7292. if (ospfLsa) state.ospfLSA = ospfLsa;
  7293. if (filters) state.routingFilters = filters;
  7294. if (selectRules) state.routingSelectRules = selectRules;
  7295. if (commLists) state.routingCommunityLists = commLists;
  7296. if (asLists) state.routingASLists = asLists;
  7297. try { renderBgpStatusPill(); } catch(e) { console.error('renderBgpStatusPill error:', e); }
  7298. try { renderBgpPeers(); } catch(e) { console.error('renderBgpPeers error:', e); }
  7299. try { renderBgpNetworks(); } catch(e) { console.error('renderBgpNetworks error:', e); }
  7300. try { renderBgpRoutes(); } catch(e) { console.error('renderBgpRoutes error:', e); }
  7301. try { renderOspfInstances(); } catch(e) { console.error('renderOspfInstances error:', e); }
  7302. try { renderOspfAreas(); } catch(e) { console.error('renderOspfAreas error:', e); }
  7303. try { renderOspfAreaRanges(); } catch(e) { console.error('renderOspfAreaRanges error:', e); }
  7304. try { renderOspfTemplates(); } catch(e) { console.error('renderOspfTemplates error:', e); }
  7305. try { renderOspfLiveInterfaces(); } catch(e) { console.error('renderOspfLiveInterfaces error:', e); }
  7306. try { renderOspfStaticNbrs(); } catch(e) { console.error('renderOspfStaticNbrs error:', e); }
  7307. try { renderOspfNeighbors(); } catch(e) { console.error('renderOspfNeighbors error:', e); }
  7308. try { renderOspfLSA(); } catch(e) { console.error('renderOspfLSA error:', e); }
  7309. try { renderRoutingFilters(); } catch(e) { console.error('renderRoutingFilters error:', e); }
  7310. try { updateBadges(); } catch(e) { console.error('updateBadges error:', e); }
  7311. if (showToastMsg) showToast('Refreshed', 'Dynamic routing telemetry updated', 'info');
  7312. } catch (err) {
  7313. console.error('Failed to load dynamic routing:', err);
  7314. if (showToastMsg) showToast('Notice', 'Unable to refresh dynamic routing telemetry', 'warning');
  7315. }
  7316. }
  7317. async function loadOspfAll() {
  7318. await loadDynamicRouting(true);
  7319. }
  7320. function renderBgpStatusPill() {
  7321. const pill = document.getElementById('bgp-live-status-pill');
  7322. if (!pill) return;
  7323. const inst = state.bgpInstance;
  7324. if (!inst || !inst.enabled) {
  7325. pill.className = 'text-[10px] px-2 py-0.5 rounded font-mono bg-slate-800 text-slate-400 border border-slate-700';
  7326. pill.innerText = 'BGP DISABLED';
  7327. } else if (inst.running) {
  7328. 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';
  7329. pill.innerText = `BGP ACTIVE (AS ${inst.as})`;
  7330. } else {
  7331. 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';
  7332. pill.innerText = 'BGP STARTING...';
  7333. }
  7334. }
  7335. function renderBgpPeers() {
  7336. const tbody = document.getElementById('bgp-peers-table-body');
  7337. if (!tbody) return;
  7338. const empty = document.getElementById('bgp-peers-empty');
  7339. const countBadge = document.getElementById('bgp-peers-count-badge');
  7340. const navBadge = document.getElementById('dyn-badge-bgp-peers');
  7341. const peers = state.bgpPeers || [];
  7342. if (countBadge) countBadge.innerText = `${peers.length} Peers`;
  7343. if (navBadge) navBadge.innerText = peers.length;
  7344. if (peers.length === 0) {
  7345. tbody.innerHTML = '';
  7346. if (empty) empty.classList.remove('hidden');
  7347. return;
  7348. }
  7349. if (empty) empty.classList.add('hidden');
  7350. tbody.innerHTML = peers.map(p => {
  7351. let flagA = !p.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  7352. let flagE = p.state === 'Established' ? '<span class="text-emerald-400 font-bold ml-1" title="Established">E</span>' : '';
  7353. let flagX = p.disabled ? '<span class="text-rose-400 font-bold ml-1" title="Disabled">X</span>' : '';
  7354. let stateBadge = '';
  7355. if (p.disabled) {
  7356. 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>';
  7357. } else if (p.state === 'Established') {
  7358. 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>';
  7359. } else if (p.state === 'Connect' || p.state === 'Active') {
  7360. 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>`;
  7361. } else {
  7362. 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>`;
  7363. }
  7364. return `
  7365. <tr class="hover:bg-slate-800/40 transition">
  7366. <td class="py-2.5 px-3 text-center tracking-wider">${flagA}${flagE}${flagX}</td>
  7367. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(p.name)}</td>
  7368. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(p.remote_address)}</td>
  7369. <td class="py-2.5 px-3">
  7370. <div class="font-bold text-slate-200">AS ${p.remote_as}</div>
  7371. ${p.local_as ? `<div class="text-[10px] text-purple-400 font-mono font-semibold" title="Custom Multi-Instance AS">Local: AS ${p.local_as}</div>` : `<div class="text-[10px] text-slate-500 font-mono">Global AS</div>`}
  7372. </td>
  7373. <td class="py-2.5 px-3">${stateBadge}</td>
  7374. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(p.uptime || '-')}</td>
  7375. <td class="py-2.5 px-3 text-slate-300">
  7376. <span class="text-emerald-400 font-bold">↓ ${p.prefix_received || 0}</span> /
  7377. <span class="text-blue-400 font-bold">↑ ${p.prefix_sent || 0}</span>
  7378. </td>
  7379. <td class="py-2.5 px-3 font-mono text-[11px] whitespace-nowrap">
  7380. ${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> ` : ''}
  7381. ${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>` : ''}
  7382. ${!p.in_filter && !p.out_filter ? '<span class="text-slate-600">-</span>' : ''}
  7383. </td>
  7384. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(p.comment || '')}</td>
  7385. <td class="py-2.5 px-3 text-right space-x-1.5 whitespace-nowrap font-sans">
  7386. <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'}">
  7387. ${p.disabled ? 'Enable' : 'Disable'}
  7388. </button>
  7389. <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">
  7390. Edit
  7391. </button>
  7392. <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">
  7393. Delete
  7394. </button>
  7395. </td>
  7396. </tr>
  7397. `;
  7398. }).join('');
  7399. }
  7400. function renderBgpNetworks() {
  7401. const tbody = document.getElementById('bgp-nets-table-body');
  7402. if (!tbody) return;
  7403. const empty = document.getElementById('bgp-nets-empty');
  7404. const countBadge = document.getElementById('bgp-nets-count-badge');
  7405. const navBadge = document.getElementById('dyn-badge-bgp-nets');
  7406. const nets = state.bgpNets || [];
  7407. if (countBadge) countBadge.innerText = `${nets.length} Networks`;
  7408. if (navBadge) navBadge.innerText = nets.length;
  7409. if (nets.length === 0) {
  7410. tbody.innerHTML = '';
  7411. if (empty) empty.classList.remove('hidden');
  7412. return;
  7413. }
  7414. if (empty) empty.classList.add('hidden');
  7415. tbody.innerHTML = nets.map(n => `
  7416. <tr class="hover:bg-slate-800/40 transition">
  7417. <td class="py-2.5 px-3 font-semibold text-purple-300 font-mono">${escapeHtml(n.network)}</td>
  7418. <td class="py-2.5 px-3">
  7419. ${n.disabled
  7420. ? '<span class="px-2 py-0.5 rounded-full text-[10px] bg-slate-800 text-slate-400 border border-slate-700">Disabled</span>'
  7421. : '<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>'}
  7422. </td>
  7423. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(n.comment || '')}</td>
  7424. <td class="py-2.5 px-3 text-right space-x-1 font-sans">
  7425. <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">
  7426. Delete
  7427. </button>
  7428. </td>
  7429. </tr>
  7430. `).join('');
  7431. }
  7432. function renderBgpRoutes() {
  7433. const tbody = document.getElementById('bgp-routes-table-body');
  7434. if (!tbody) return;
  7435. const empty = document.getElementById('bgp-routes-empty');
  7436. const countBadge = document.getElementById('bgp-routes-count-badge');
  7437. const navBadge = document.getElementById('dyn-badge-bgp-routes');
  7438. const routes = state.bgpRoutes || [];
  7439. if (countBadge) countBadge.innerText = `${routes.length} Routes`;
  7440. if (navBadge) navBadge.innerText = routes.length;
  7441. if (routes.length === 0) {
  7442. tbody.innerHTML = '';
  7443. if (empty) empty.classList.remove('hidden');
  7444. return;
  7445. }
  7446. if (empty) empty.classList.add('hidden');
  7447. tbody.innerHTML = routes.map(r => `
  7448. <tr class="hover:bg-slate-800/40 transition">
  7449. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.prefix)}</td>
  7450. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(r.next_hop || '-')}</td>
  7451. <td class="py-2.5 px-3 text-slate-300">${r.metric}</td>
  7452. <td class="py-2.5 px-3 text-slate-300">${r.weight}</td>
  7453. <td class="py-2.5 px-3 text-amber-300">${escapeHtml(r.path || 'i')}</td>
  7454. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.origin || 'IGP')}</td>
  7455. </tr>
  7456. `).join('');
  7457. }
  7458. // =========================================================================
  7459. // ROUTEROS v7 OSPF TABLE RENDERING & SORTING
  7460. // =========================================================================
  7461. function sortOspfTable(tab, col) {
  7462. if (!state.ospfSort) state.ospfSort = {};
  7463. if (!state.ospfSort[tab]) state.ospfSort[tab] = { col: col, asc: true };
  7464. if (state.ospfSort[tab].col === col) {
  7465. state.ospfSort[tab].asc = !state.ospfSort[tab].asc;
  7466. } else {
  7467. state.ospfSort[tab].col = col;
  7468. state.ospfSort[tab].asc = true;
  7469. }
  7470. const asc = state.ospfSort[tab].asc;
  7471. let list = [];
  7472. if (tab === 'instances') list = state.ospfInstances || [];
  7473. else if (tab === 'areas') list = state.ospfAreas || [];
  7474. else if (tab === 'ranges') list = state.ospfAreaRanges || [];
  7475. else if (tab === 'templates') list = state.ospfTemplates || [];
  7476. else if (tab === 'live_ifaces') list = state.ospfLiveInterfaces || [];
  7477. else if (tab === 'snbrs') list = state.ospfStaticNbrs || [];
  7478. else if (tab === 'neighbors') list = state.ospfNeighbors || [];
  7479. else if (tab === 'lsa') list = state.ospfLSA || [];
  7480. list.sort((a, b) => {
  7481. let valA = a[col] ?? '';
  7482. let valB = b[col] ?? '';
  7483. if (typeof valA === 'number' && typeof valB === 'number') {
  7484. return asc ? valA - valB : valB - valA;
  7485. }
  7486. return asc ? String(valA).localeCompare(String(valB)) : String(valB).localeCompare(String(valA));
  7487. });
  7488. if (tab === 'instances') renderOspfInstances();
  7489. else if (tab === 'areas') renderOspfAreas();
  7490. else if (tab === 'ranges') renderOspfAreaRanges();
  7491. else if (tab === 'templates') renderOspfTemplates();
  7492. else if (tab === 'live_ifaces') renderOspfLiveInterfaces();
  7493. else if (tab === 'snbrs') renderOspfStaticNbrs();
  7494. else if (tab === 'neighbors') renderOspfNeighbors();
  7495. else if (tab === 'lsa') renderOspfLSA();
  7496. }
  7497. function selectOspfRow(tab, id) {
  7498. if (!state.selectedOspfRow) state.selectedOspfRow = {};
  7499. state.selectedOspfRow[tab] = id;
  7500. if (tab === 'instances') {
  7501. renderOspfInstances();
  7502. const btnEn = document.getElementById('btn-ospf-inst-enable');
  7503. const btnDis = document.getElementById('btn-ospf-inst-disable');
  7504. const btnRem = document.getElementById('btn-ospf-inst-remove');
  7505. const btnCom = document.getElementById('btn-ospf-inst-comment');
  7506. if (btnEn) btnEn.disabled = false;
  7507. if (btnDis) btnDis.disabled = false;
  7508. if (btnRem) btnRem.disabled = false;
  7509. if (btnCom) btnCom.disabled = false;
  7510. } else if (tab === 'areas') {
  7511. renderOspfAreas();
  7512. const btnEn = document.getElementById('btn-ospf-area-enable');
  7513. const btnDis = document.getElementById('btn-ospf-area-disable');
  7514. const btnRem = document.getElementById('btn-ospf-area-remove');
  7515. const btnCom = document.getElementById('btn-ospf-area-comment');
  7516. if (btnEn) btnEn.disabled = false;
  7517. if (btnDis) btnDis.disabled = false;
  7518. if (btnRem) btnRem.disabled = false;
  7519. if (btnCom) btnCom.disabled = false;
  7520. } else if (tab === 'ranges') {
  7521. renderOspfAreaRanges();
  7522. const btnEn = document.getElementById('btn-ospf-range-enable');
  7523. const btnDis = document.getElementById('btn-ospf-range-disable');
  7524. const btnRem = document.getElementById('btn-ospf-range-remove');
  7525. const btnCom = document.getElementById('btn-ospf-range-comment');
  7526. if (btnEn) btnEn.disabled = false;
  7527. if (btnDis) btnDis.disabled = false;
  7528. if (btnRem) btnRem.disabled = false;
  7529. if (btnCom) btnCom.disabled = false;
  7530. } else if (tab === 'templates') {
  7531. renderOspfTemplates();
  7532. const btnEn = document.getElementById('btn-ospf-tmpl-enable');
  7533. const btnDis = document.getElementById('btn-ospf-tmpl-disable');
  7534. const btnRem = document.getElementById('btn-ospf-tmpl-remove');
  7535. const btnCom = document.getElementById('btn-ospf-tmpl-comment');
  7536. if (btnEn) btnEn.disabled = false;
  7537. if (btnDis) btnDis.disabled = false;
  7538. if (btnRem) btnRem.disabled = false;
  7539. if (btnCom) btnCom.disabled = false;
  7540. } else if (tab === 'snbrs') {
  7541. renderOspfStaticNbrs();
  7542. const btnEn = document.getElementById('btn-ospf-snbr-enable');
  7543. const btnDis = document.getElementById('btn-ospf-snbr-disable');
  7544. const btnRem = document.getElementById('btn-ospf-snbr-remove');
  7545. const btnCom = document.getElementById('btn-ospf-snbr-comment');
  7546. if (btnEn) btnEn.disabled = false;
  7547. if (btnDis) btnDis.disabled = false;
  7548. if (btnRem) btnRem.disabled = false;
  7549. if (btnCom) btnCom.disabled = false;
  7550. }
  7551. }
  7552. // TAB 1: INSTANCES
  7553. function renderOspfInstances() {
  7554. const tbody = document.getElementById('ospf-instances-table-body');
  7555. if (!tbody) return;
  7556. const countEl = document.getElementById('ospf-instances-footer-count');
  7557. const filter = (document.getElementById('filter-ospf-instances')?.value || '').toLowerCase();
  7558. let list = state.ospfInstances || [];
  7559. if (filter) {
  7560. list = list.filter(i => (i.name || '').toLowerCase().includes(filter) || (i.router_id || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  7561. }
  7562. if (countEl) countEl.innerText = list.length;
  7563. const selId = state.selectedOspfRow?.instances;
  7564. tbody.innerHTML = list.map((inst, idx) => {
  7565. const isSel = inst.id === selId;
  7566. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  7567. const flagD = inst.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  7568. return `
  7569. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('instances', '${inst.id}')" ondblclick="openEditOspfInstanceModal('${inst.id}')">
  7570. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  7571. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🔀'}</td>
  7572. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(inst.comment || '')}</td>
  7573. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  7574. <span class="text-sky-400">↳</span> <span>${escapeHtml(inst.name || 'Default')}</span>
  7575. </td>
  7576. <td class="py-1.5 px-3">${inst.version || 2}</td>
  7577. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(inst.vrf || 'main')}</td>
  7578. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(inst.router_id || '192.168.131.56')}</td>
  7579. </tr>
  7580. `;
  7581. }).join('');
  7582. }
  7583. // TAB 2: AREAS
  7584. function renderOspfAreas() {
  7585. const tbody = document.getElementById('ospf-areas-table-body');
  7586. if (!tbody) return;
  7587. const countEl = document.getElementById('ospf-areas-footer-count');
  7588. const filter = (document.getElementById('filter-ospf-areas')?.value || '').toLowerCase();
  7589. let list = state.ospfAreas || [];
  7590. if (filter) {
  7591. list = list.filter(a => (a.name || '').toLowerCase().includes(filter) || (a.area_id || '').toLowerCase().includes(filter) || (a.comment || '').toLowerCase().includes(filter));
  7592. }
  7593. if (countEl) countEl.innerText = list.length;
  7594. const selId = state.selectedOspfRow?.areas;
  7595. tbody.innerHTML = list.map((a, idx) => {
  7596. const isSel = a.id === selId;
  7597. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  7598. const flagD = a.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  7599. return `
  7600. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('areas', '${a.id}')" ondblclick="openEditOspfAreaModal('${a.id}')">
  7601. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  7602. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🌐'}</td>
  7603. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(a.comment || '')}</td>
  7604. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  7605. <span class="text-sky-400">↳</span> <span>${escapeHtml(a.name || 'Default')}</span>
  7606. </td>
  7607. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(a.instance || 'Default')}</td>
  7608. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(a.area_id || '0.0.0.0')}</td>
  7609. <td class="py-1.5 px-3 font-mono text-slate-400">${escapeHtml(a.area_type || 'default')}</td>
  7610. </tr>
  7611. `;
  7612. }).join('');
  7613. }
  7614. // TAB 3: AREA RANGES
  7615. function renderOspfAreaRanges() {
  7616. const tbody = document.getElementById('ospf-ranges-table-body');
  7617. if (!tbody) return;
  7618. const countEl = document.getElementById('ospf-ranges-footer-count');
  7619. const filter = (document.getElementById('filter-ospf-area-ranges')?.value || '').toLowerCase();
  7620. let list = state.ospfAreaRanges || [];
  7621. if (filter) {
  7622. list = list.filter(r => (r.prefix || '').toLowerCase().includes(filter) || (r.area || '').toLowerCase().includes(filter) || (r.comment || '').toLowerCase().includes(filter));
  7623. }
  7624. if (countEl) countEl.innerText = list.length;
  7625. const selId = state.selectedOspfRow?.['area-ranges'];
  7626. tbody.innerHTML = list.map((r, idx) => {
  7627. const isSel = r.id === selId;
  7628. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  7629. const flagD = r.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  7630. return `
  7631. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('ranges', '${r.id}')" ondblclick="openEditOspfAreaRangeModal('${r.id}')">
  7632. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  7633. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🏷'}</td>
  7634. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(r.comment || '')}</td>
  7635. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(r.area || 'Default')}</td>
  7636. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(r.prefix || '')}</td>
  7637. <td class="py-1.5 px-3">${r.cost || 1}</td>
  7638. <td class="py-1.5 px-3">${r.advertise !== false ? 'yes' : 'no'}</td>
  7639. </tr>
  7640. `;
  7641. }).join('');
  7642. }
  7643. // TAB 4: INTERFACE TEMPLATES
  7644. function renderOspfTemplates() {
  7645. const tbody = document.getElementById('ospf-templates-table-body');
  7646. if (!tbody) return;
  7647. const countEl = document.getElementById('ospf-templates-footer-count');
  7648. const filter = (document.getElementById('filter-ospf-templates')?.value || '').toLowerCase();
  7649. let list = state.ospfTemplates || [];
  7650. if (filter) {
  7651. list = list.filter(t => (t.interfaces || t.interface || '').toLowerCase().includes(filter) || (t.networks || t.network || '').toLowerCase().includes(filter) || (t.comment || '').toLowerCase().includes(filter));
  7652. }
  7653. if (countEl) countEl.innerText = list.length;
  7654. const selId = state.selectedOspfRow?.templates;
  7655. tbody.innerHTML = list.map((t, idx) => {
  7656. const isSel = t.id === selId;
  7657. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  7658. const ifaces = t.interfaces || t.interface || 'all';
  7659. const nets = t.networks || t.network || '';
  7660. const flagD = t.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  7661. return `
  7662. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('templates', '${t.id}')" ondblclick="openEditOspfTemplateModal('${t.id}')">
  7663. <td class="py-1.5 px-3 w-8 text-center text-slate-500 font-bold">${idx}</td>
  7664. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🔀'}</td>
  7665. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(t.comment || '')}</td>
  7666. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  7667. <span class="text-sky-400">↳</span> <span>${escapeHtml(ifaces)}</span>
  7668. </td>
  7669. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(t.area || 'Default')}</td>
  7670. <td class="py-1.5 px-3 font-mono text-sky-300">${escapeHtml(nets)}</td>
  7671. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(t.network_type || 'broadcast')}</td>
  7672. <td class="py-1.5 px-3">${t.cost || 1}</td>
  7673. <td class="py-1.5 px-3">${t.priority || 128}</td>
  7674. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(t.auth || t.auth_type || '')}</td>
  7675. </tr>
  7676. `;
  7677. }).join('');
  7678. }
  7679. // TAB 5: LIVE INTERFACES
  7680. function renderOspfLiveInterfaces() {
  7681. const tbody = document.getElementById('ospf-live-interfaces-table-body');
  7682. if (!tbody) return;
  7683. const countEl = document.getElementById('ospf-live-interfaces-footer-count');
  7684. const filter = (document.getElementById('filter-ospf-interfaces')?.value || '').toLowerCase();
  7685. let list = state.ospfLiveInterfaces || [];
  7686. if (filter) {
  7687. list = list.filter(i => (i.interface || '').toLowerCase().includes(filter) || (i.address || '').toLowerCase().includes(filter) || (i.state || '').toLowerCase().includes(filter));
  7688. }
  7689. if (countEl) countEl.innerText = list.length;
  7690. tbody.innerHTML = list.map(i => `
  7691. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  7692. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(i.flags || 'D')}</td>
  7693. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(i.interface || '')}</td>
  7694. <td class="py-1.5 px-3 font-mono text-sky-300 font-medium">${escapeHtml(i.address || '')}</td>
  7695. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(i.area || 'Default')}</td>
  7696. <td class="py-1.5 px-3 text-center text-slate-400">${i.instance_id || 0}</td>
  7697. <td class="py-1.5 px-3 font-mono text-amber-300 lowercase">${escapeHtml(i.state || 'waiting')}</td>
  7698. <td class="py-1.5 px-3">${i.cost || 1}</td>
  7699. <td class="py-1.5 px-3">${i.priority || 128}</td>
  7700. </tr>
  7701. `).join('');
  7702. }
  7703. // TAB 6: STATIC NEIGHBORS
  7704. function renderOspfStaticNbrs() {
  7705. const tbody = document.getElementById('ospf-snbrs-table-body');
  7706. if (!tbody) return;
  7707. const countEl = document.getElementById('ospf-snbrs-footer-count');
  7708. const filter = (document.getElementById('filter-ospf-static-nbrs')?.value || '').toLowerCase();
  7709. let list = state.ospfStaticNbrs || [];
  7710. if (filter) {
  7711. list = list.filter(n => (n.address || '').toLowerCase().includes(filter) || (n.area || '').toLowerCase().includes(filter) || (n.comment || '').toLowerCase().includes(filter));
  7712. }
  7713. if (countEl) countEl.innerText = list.length;
  7714. const selId = state.selectedOspfRow?.['static-nbrs'];
  7715. tbody.innerHTML = list.map((n, idx) => {
  7716. const isSel = n.id === selId;
  7717. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  7718. const flagD = n.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  7719. return `
  7720. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('snbrs', '${n.id}')" ondblclick="openEditOspfStaticNbrModal('${n.id}')">
  7721. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  7722. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '📡'}</td>
  7723. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(n.comment || '')}</td>
  7724. <td class="py-1.5 px-3 font-semibold font-mono text-sky-300">${escapeHtml(n.address || '')}</td>
  7725. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(n.area || 'Default')}</td>
  7726. <td class="py-1.5 px-3">${n.poll_interval || 120}s</td>
  7727. <td class="py-1.5 px-3">${n.cost || 1}</td>
  7728. </tr>
  7729. `;
  7730. }).join('');
  7731. }
  7732. // TAB 7: LIVE NEIGHBORS
  7733. function renderOspfNeighbors() {
  7734. const tbody = document.getElementById('ospf-neighbors-table-body');
  7735. if (!tbody) return;
  7736. const countEl = document.getElementById('ospf-neighbors-footer-count');
  7737. const filter = (document.getElementById('filter-ospf-neighbors')?.value || '').toLowerCase();
  7738. let list = state.ospfNeighbors || [];
  7739. if (filter) {
  7740. list = list.filter(n => (n.address || '').toLowerCase().includes(filter) || (n.state || '').toLowerCase().includes(filter) || (n.instance || '').toLowerCase().includes(filter));
  7741. }
  7742. if (countEl) countEl.innerText = list.length;
  7743. tbody.innerHTML = list.map(n => `
  7744. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  7745. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(n.flags || 'D')}</td>
  7746. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(n.comment || '')}</td>
  7747. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  7748. <span class="text-sky-400">↳</span> <span>${escapeHtml(n.instance || 'Default')}</span>
  7749. </td>
  7750. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(n.area || 'Default')}</td>
  7751. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(n.address || '')}</td>
  7752. <td class="py-1.5 px-3 font-mono font-bold text-emerald-400">${escapeHtml(n.state || 'Full')}</td>
  7753. <td class="py-1.5 px-3 text-slate-400">${n.state_changes ?? 6}</td>
  7754. </tr>
  7755. `).join('');
  7756. }
  7757. // TAB 8: LINK-STATE DATABASE (LSA)
  7758. function renderOspfLSA() {
  7759. const tbody = document.getElementById('ospf-lsa-table-body');
  7760. if (!tbody) return;
  7761. const countEl = document.getElementById('ospf-lsa-footer-count');
  7762. const filter = (document.getElementById('filter-ospf-lsa')?.value || '').toLowerCase();
  7763. let list = state.ospfLSA || [];
  7764. if (filter) {
  7765. list = list.filter(l => (l.type || '').toLowerCase().includes(filter) || (l.originator || '').toLowerCase().includes(filter) || (l.id || '').toLowerCase().includes(filter));
  7766. }
  7767. if (countEl) countEl.innerText = list.length;
  7768. tbody.innerHTML = list.map(l => `
  7769. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  7770. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(l.flags || 'D')}</td>
  7771. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  7772. <span class="text-sky-400">↳</span> <span>${escapeHtml(l.instance || 'Default')}</span>
  7773. </td>
  7774. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(l.area || 'Default')}</td>
  7775. <td class="py-1.5 px-3 font-mono text-amber-300">${escapeHtml(l.type || 'router')}</td>
  7776. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(l.originator || '')}</td>
  7777. <td class="py-1.5 px-3 font-mono text-sky-300 font-medium">${escapeHtml(l.id || '')}</td>
  7778. <td class="py-1.5 px-3 text-slate-500">${escapeHtml(l.link || '')}</td>
  7779. <td class="py-1.5 px-3 text-slate-500">${l.link_index ?? 0}</td>
  7780. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(l.sequence || '')}</td>
  7781. <td class="py-1.5 px-3 text-slate-400">${l.age ?? 0}</td>
  7782. </tr>
  7783. `).join('');
  7784. }
  7785. function renderOspfStatusPill() {
  7786. // Maintained for backward compatibility
  7787. const pill = document.getElementById('ospf-live-status-pill');
  7788. if (!pill) return;
  7789. 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';
  7790. pill.innerText = 'OSPF ACTIVE';
  7791. }
  7792. function renderOspfInterfaces() {
  7793. renderOspfTemplates();
  7794. }
  7795. function renderOspfRoutes() {
  7796. // Routes retained in background
  7797. }
  7798. // BGP Modals & Actions
  7799. function openBgpInstanceModal() {
  7800. const inst = state.bgpInstance || { enabled: false, as: 65001, router_id: '192.168.131.56', hold_time: 180, keepalive_time: 60 };
  7801. document.getElementById('modal-bgp-enabled').checked = !!inst.enabled;
  7802. document.getElementById('modal-bgp-as').value = inst.as || 65001;
  7803. document.getElementById('modal-bgp-router-id').value = inst.router_id || '';
  7804. document.getElementById('modal-bgp-keepalive').value = inst.keepalive_time || 60;
  7805. document.getElementById('modal-bgp-holdtime').value = inst.hold_time || 180;
  7806. document.getElementById('modal-bgp-redist-conn').checked = !!inst.redistribute_connected;
  7807. document.getElementById('modal-bgp-redist-static').checked = !!inst.redistribute_static;
  7808. document.getElementById('modal-bgp-redist-ospf').checked = !!inst.redistribute_ospf;
  7809. document.getElementById('bgp-instance-modal').classList.remove('hidden');
  7810. }
  7811. function closeBgpInstanceModal() {
  7812. document.getElementById('bgp-instance-modal').classList.add('hidden');
  7813. }
  7814. async function submitBgpInstance(e) {
  7815. e.preventDefault();
  7816. const payload = {
  7817. enabled: document.getElementById('modal-bgp-enabled').checked,
  7818. as: parseInt(document.getElementById('modal-bgp-as').value, 10),
  7819. router_id: document.getElementById('modal-bgp-router-id').value.trim(),
  7820. keepalive_time: parseInt(document.getElementById('modal-bgp-keepalive').value, 10),
  7821. hold_time: parseInt(document.getElementById('modal-bgp-holdtime').value, 10),
  7822. redistribute_connected: document.getElementById('modal-bgp-redist-conn').checked,
  7823. redistribute_static: document.getElementById('modal-bgp-redist-static').checked,
  7824. redistribute_ospf: document.getElementById('modal-bgp-redist-ospf').checked
  7825. };
  7826. try {
  7827. const res = await fetch(`${API_BASE}/routing/bgp/instance`, {
  7828. method: 'POST',
  7829. headers: { 'Content-Type': 'application/json' },
  7830. body: JSON.stringify(payload)
  7831. });
  7832. if (res.ok) {
  7833. closeBgpInstanceModal();
  7834. showToast('Success', 'BGP instance configuration updated', 'success');
  7835. loadDynamicRouting();
  7836. } else {
  7837. const err = await res.json();
  7838. showToast('Error', err.error || 'Failed to update BGP instance', 'error');
  7839. }
  7840. } catch (err) {
  7841. showToast('Error', err.message, 'error');
  7842. }
  7843. }
  7844. // ----------------- BGP Peer Connection Modal (RouterOS v7) -----------------
  7845. function switchBgpPeerModalTab(tab) {
  7846. const tabs = ['general', 'extra', 'attributes', 'filter'];
  7847. tabs.forEach(t => {
  7848. const pane = document.getElementById(`bgp-peer-tab-${t}`);
  7849. const btn = document.getElementById(`bgp-peer-tab-btn-${t}`);
  7850. if (t === tab) {
  7851. if (pane) pane.classList.remove('hidden');
  7852. if (btn) btn.className = 'px-4 py-2 text-xs font-bold border-b-2 border-cyan-500 text-white transition';
  7853. } else {
  7854. if (pane) pane.classList.add('hidden');
  7855. if (btn) btn.className = 'px-4 py-2 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition';
  7856. }
  7857. });
  7858. }
  7859. function addOutputNetworkRow(val = '') {
  7860. const container = document.getElementById('modal-bgp-output-networks-container');
  7861. if (!container) return;
  7862. const row = document.createElement('div');
  7863. row.className = 'flex items-center gap-2 output-net-row';
  7864. row.innerHTML = `
  7865. <input type="text" value="${escapeHtml(val)}" placeholder="e.g. 10.2.51.0/24 or BGP-AWMN" class="flex-1 bg-slate-900 border border-slate-700 rounded-lg px-3 py-1.5 text-white font-mono text-xs focus:outline-none focus:border-cyan-500">
  7866. <button type="button" onclick="this.closest('.output-net-row').remove()" class="w-7 h-7 flex items-center justify-center bg-slate-800 hover:bg-rose-950 text-slate-400 hover:text-rose-400 border border-slate-700 rounded-lg text-base font-bold transition" title="Remove network">-</button>
  7867. `;
  7868. container.appendChild(row);
  7869. }
  7870. function parseBgpTime(val) {
  7871. if (!val) return 0;
  7872. val = String(val).trim();
  7873. if (val.includes(':')) {
  7874. const parts = val.split(':').map(x => parseInt(x, 10) || 0);
  7875. if (parts.length === 3) return parts[0] * 3600 + parts[1] * 60 + parts[2];
  7876. if (parts.length === 2) return parts[0] * 60 + parts[1];
  7877. }
  7878. return parseInt(val, 10) || 0;
  7879. }
  7880. function formatBgpTime(secs) {
  7881. if (!secs || secs <= 0) return '00:00:00';
  7882. const h = Math.floor(secs / 3600);
  7883. const m = Math.floor((secs % 3600) / 60);
  7884. const s = secs % 60;
  7885. return `${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`;
  7886. }
  7887. function populateBgpRoutingTables() {
  7888. const sel = document.getElementById('modal-bgp-peer-routing-table');
  7889. if (!sel) return;
  7890. const cur = sel.value || 'main';
  7891. sel.innerHTML = '<option value="main">main</option>';
  7892. (state.routingTables || []).forEach(t => {
  7893. if (t.name !== 'main') {
  7894. const opt = document.createElement('option');
  7895. opt.value = t.name;
  7896. opt.innerText = t.name;
  7897. sel.appendChild(opt);
  7898. }
  7899. });
  7900. sel.value = cur;
  7901. }
  7902. function openAddBgpPeerModal() {
  7903. document.getElementById('bgp-peer-form').reset();
  7904. document.getElementById('modal-bgp-peer-id').value = '';
  7905. document.getElementById('bgp-peer-modal-title').innerText = 'New...';
  7906. // General Tab
  7907. document.getElementById('modal-bgp-peer-enabled').checked = true;
  7908. document.getElementById('modal-bgp-peer-comment').value = '';
  7909. document.getElementById('modal-bgp-peer-name').value = '';
  7910. if (document.getElementById('modal-bgp-peer-instance')) document.getElementById('modal-bgp-peer-instance').value = 'bgp-instance-1';
  7911. if (document.getElementById('modal-bgp-peer-template')) document.getElementById('modal-bgp-peer-template').value = '';
  7912. document.getElementById('modal-bgp-peer-local-as').value = '';
  7913. document.getElementById('modal-bgp-peer-afi-ip').checked = true;
  7914. document.getElementById('modal-bgp-peer-afi-ipv6').checked = false;
  7915. if (document.getElementById('modal-bgp-peer-afi-l2vpn')) document.getElementById('modal-bgp-peer-afi-l2vpn').checked = false;
  7916. if (document.getElementById('modal-bgp-peer-afi-vpnv4')) document.getElementById('modal-bgp-peer-afi-vpnv4').checked = false;
  7917. if (document.getElementById('modal-bgp-peer-afi-l2vpn-cisco')) document.getElementById('modal-bgp-peer-afi-l2vpn-cisco').checked = false;
  7918. document.getElementById('modal-bgp-peer-router-id').value = '';
  7919. document.getElementById('modal-bgp-peer-remote-addr').value = '';
  7920. document.getElementById('modal-bgp-peer-remote-port').value = '';
  7921. document.getElementById('modal-bgp-peer-remote-as').value = '';
  7922. if (document.getElementById('modal-bgp-peer-remote-allow-as')) document.getElementById('modal-bgp-peer-remote-allow-as').value = '';
  7923. document.getElementById('modal-bgp-peer-local-addr').value = '';
  7924. document.getElementById('modal-bgp-peer-local-port').value = '';
  7925. document.getElementById('modal-bgp-peer-local-role').value = 'ebgp';
  7926. document.getElementById('modal-bgp-peer-password').value = '';
  7927. document.getElementById('modal-bgp-peer-multihop').checked = false;
  7928. if (document.getElementById('modal-bgp-peer-tx-ttl')) document.getElementById('modal-bgp-peer-tx-ttl').value = '';
  7929. if (document.getElementById('modal-bgp-peer-rx-min-ttl')) document.getElementById('modal-bgp-peer-rx-min-ttl').value = '';
  7930. document.getElementById('modal-bgp-peer-connect').checked = true;
  7931. document.getElementById('modal-bgp-peer-listen').checked = true;
  7932. // Extra Tab
  7933. document.getElementById('modal-bgp-peer-holdtime').value = '00:00:30';
  7934. document.getElementById('modal-bgp-peer-keepalive').value = '00:00:10';
  7935. if (document.getElementById('modal-bgp-peer-use-bfd')) document.getElementById('modal-bgp-peer-use-bfd').checked = false;
  7936. if (document.getElementById('modal-bgp-peer-vrf')) document.getElementById('modal-bgp-peer-vrf').value = 'main';
  7937. if (document.getElementById('modal-bgp-peer-no-client-reflect')) document.getElementById('modal-bgp-peer-no-client-reflect').checked = true;
  7938. document.getElementById('modal-bgp-peer-redist-conn').checked = false;
  7939. document.getElementById('modal-bgp-peer-redist-static').checked = true;
  7940. if (document.getElementById('modal-bgp-peer-redist-rip')) document.getElementById('modal-bgp-peer-redist-rip').checked = false;
  7941. document.getElementById('modal-bgp-peer-redist-ospf').checked = false;
  7942. document.getElementById('modal-bgp-peer-redist-bgp').checked = false;
  7943. if (document.getElementById('modal-bgp-peer-redist-vpn')) document.getElementById('modal-bgp-peer-redist-vpn').checked = false;
  7944. if (document.getElementById('modal-bgp-peer-redist-dhcp')) document.getElementById('modal-bgp-peer-redist-dhcp').checked = false;
  7945. if (document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn')) document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn').checked = false;
  7946. if (document.getElementById('modal-bgp-peer-redist-slaac')) document.getElementById('modal-bgp-peer-redist-slaac').checked = false;
  7947. document.getElementById('modal-bgp-peer-default-orig').checked = false;
  7948. if (document.getElementById('modal-bgp-peer-network-blackhole')) document.getElementById('modal-bgp-peer-network-blackhole').checked = false;
  7949. if (document.getElementById('modal-bgp-peer-no-early-cut')) document.getElementById('modal-bgp-peer-no-early-cut').checked = false;
  7950. if (document.getElementById('modal-bgp-peer-keep-sent-attrs')) document.getElementById('modal-bgp-peer-keep-sent-attrs').checked = false;
  7951. if (document.getElementById('modal-bgp-peer-input-affinity')) document.getElementById('modal-bgp-peer-input-affinity').value = '';
  7952. if (document.getElementById('modal-bgp-peer-output-affinity')) document.getElementById('modal-bgp-peer-output-affinity').value = '';
  7953. // Attributes Tab
  7954. document.getElementById('modal-bgp-peer-nexthop-choice').value = 'force-self';
  7955. document.getElementById('modal-bgp-peer-default-prepend').value = 0;
  7956. document.getElementById('modal-bgp-peer-allow-as-in').value = 0;
  7957. if (document.getElementById('modal-bgp-peer-ignore-as-path-len')) document.getElementById('modal-bgp-peer-ignore-as-path-len').checked = false;
  7958. document.getElementById('modal-bgp-peer-remove-priv-as').checked = false;
  7959. document.getElementById('modal-bgp-peer-as-override').checked = false;
  7960. // Filter Tab
  7961. populateFilterChainsDatalist();
  7962. document.getElementById('modal-bgp-peer-in-filter').value = '';
  7963. if (document.getElementById('modal-bgp-peer-in-accept-nlri')) document.getElementById('modal-bgp-peer-in-accept-nlri').value = '';
  7964. if (document.getElementById('modal-bgp-peer-in-accept-comm')) document.getElementById('modal-bgp-peer-in-accept-comm').value = '';
  7965. if (document.getElementById('modal-bgp-peer-in-accept-ext-comm')) document.getElementById('modal-bgp-peer-in-accept-ext-comm').value = '';
  7966. if (document.getElementById('modal-bgp-peer-in-accept-large-comm')) document.getElementById('modal-bgp-peer-in-accept-large-comm').value = '';
  7967. if (document.getElementById('modal-bgp-peer-in-filter-comm')) document.getElementById('modal-bgp-peer-in-filter-comm').value = '';
  7968. if (document.getElementById('modal-bgp-peer-in-filter-ext-comm')) document.getElementById('modal-bgp-peer-in-filter-ext-comm').value = '';
  7969. if (document.getElementById('modal-bgp-peer-in-filter-large-comm')) document.getElementById('modal-bgp-peer-in-filter-large-comm').value = '';
  7970. if (document.getElementById('modal-bgp-peer-in-filter-unknown')) document.getElementById('modal-bgp-peer-in-filter-unknown').checked = false;
  7971. document.getElementById('modal-bgp-peer-out-filter').value = '';
  7972. if (document.getElementById('modal-bgp-peer-out-selection-policy')) document.getElementById('modal-bgp-peer-out-selection-policy').value = 'disabled';
  7973. if (document.getElementById('modal-bgp-peer-out-network-name')) document.getElementById('modal-bgp-peer-out-network-name').value = '';
  7974. populateBgpRoutingTables();
  7975. const container = document.getElementById('modal-bgp-output-networks-container');
  7976. if (container) {
  7977. container.innerHTML = '';
  7978. addOutputNetworkRow('');
  7979. }
  7980. const removeBtn = document.getElementById('modal-btn-remove-peer');
  7981. if (removeBtn) removeBtn.classList.add('hidden');
  7982. switchBgpPeerModalTab('general');
  7983. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  7984. }
  7985. function populateFilterChainsDatalist() {
  7986. const dl = document.getElementById('filter-chains-list');
  7987. if (!dl) return;
  7988. const chains = new Set();
  7989. (state.routingFilters || []).forEach(f => {
  7990. if (f.chain) chains.add(f.chain);
  7991. });
  7992. if (chains.size === 0) {
  7993. chains.add('awmn');
  7994. chains.add('bgp-in');
  7995. chains.add('bgp-out');
  7996. }
  7997. dl.innerHTML = '';
  7998. chains.forEach(c => {
  7999. const opt = document.createElement('option');
  8000. opt.value = c;
  8001. dl.appendChild(opt);
  8002. });
  8003. }
  8004. function openEditBgpPeerModal(id) {
  8005. const p = (state.bgpPeers || []).find(item => item.id === id);
  8006. if (!p) return;
  8007. populateBgpRoutingTables();
  8008. populateFilterChainsDatalist();
  8009. document.getElementById('modal-bgp-peer-id').value = p.id;
  8010. document.getElementById('bgp-peer-modal-title').innerText = p.name || p.id;
  8011. // General Tab
  8012. document.getElementById('modal-bgp-peer-enabled').checked = p.enabled !== false && !p.disabled;
  8013. document.getElementById('modal-bgp-peer-comment').value = p.comment || '';
  8014. document.getElementById('modal-bgp-peer-name').value = p.name || '';
  8015. if (document.getElementById('modal-bgp-peer-instance')) document.getElementById('modal-bgp-peer-instance').value = p.instance || 'bgp-instance-1';
  8016. if (document.getElementById('modal-bgp-peer-template')) document.getElementById('modal-bgp-peer-template').value = p.template || '';
  8017. document.getElementById('modal-bgp-peer-local-as').value = p.local_as || '';
  8018. document.getElementById('modal-bgp-peer-router-id').value = p.router_id || '';
  8019. document.getElementById('modal-bgp-peer-afi-ip').checked = true;
  8020. document.getElementById('modal-bgp-peer-afi-ipv6').checked = p.afi === 'ipv6';
  8021. document.getElementById('modal-bgp-peer-remote-addr').value = p.remote_address || '';
  8022. document.getElementById('modal-bgp-peer-remote-port').value = p.remote_port || '';
  8023. document.getElementById('modal-bgp-peer-remote-as').value = p.remote_as || '';
  8024. if (document.getElementById('modal-bgp-peer-remote-allow-as')) document.getElementById('modal-bgp-peer-remote-allow-as').value = p.remote_allow_as || '';
  8025. document.getElementById('modal-bgp-peer-local-addr').value = p.local_address || '';
  8026. document.getElementById('modal-bgp-peer-local-port').value = p.local_port || '';
  8027. document.getElementById('modal-bgp-peer-local-role').value = p.local_role || 'ebgp';
  8028. document.getElementById('modal-bgp-peer-password').value = p.password || '';
  8029. document.getElementById('modal-bgp-peer-multihop').checked = !!p.multihop;
  8030. if (document.getElementById('modal-bgp-peer-tx-ttl')) document.getElementById('modal-bgp-peer-tx-ttl').value = p.tx_ttl || '';
  8031. if (document.getElementById('modal-bgp-peer-rx-min-ttl')) document.getElementById('modal-bgp-peer-rx-min-ttl').value = p.rx_min_ttl || '';
  8032. document.getElementById('modal-bgp-peer-connect').checked = p.connect !== false;
  8033. document.getElementById('modal-bgp-peer-listen').checked = p.listen !== false;
  8034. // Extra Tab
  8035. document.getElementById('modal-bgp-peer-holdtime').value = p.hold_time ? formatBgpTime(p.hold_time) : '00:00:30';
  8036. document.getElementById('modal-bgp-peer-keepalive').value = p.keepalive_time ? formatBgpTime(p.keepalive_time) : '00:00:10';
  8037. if (document.getElementById('modal-bgp-peer-use-bfd')) document.getElementById('modal-bgp-peer-use-bfd').checked = !!p.use_bfd;
  8038. document.getElementById('modal-bgp-peer-routing-table').value = p.routing_table || 'main';
  8039. if (document.getElementById('modal-bgp-peer-vrf')) document.getElementById('modal-bgp-peer-vrf').value = p.vrf || 'main';
  8040. if (document.getElementById('modal-bgp-peer-no-client-reflect')) document.getElementById('modal-bgp-peer-no-client-reflect').checked = p.no_client_reflect !== false;
  8041. document.getElementById('modal-bgp-peer-redist-conn').checked = !!p.redist_connected;
  8042. document.getElementById('modal-bgp-peer-redist-static').checked = p.redist_static !== false;
  8043. if (document.getElementById('modal-bgp-peer-redist-rip')) document.getElementById('modal-bgp-peer-redist-rip').checked = !!p.redist_rip;
  8044. document.getElementById('modal-bgp-peer-redist-ospf').checked = !!p.redist_ospf;
  8045. document.getElementById('modal-bgp-peer-redist-bgp').checked = !!p.redist_bgp;
  8046. if (document.getElementById('modal-bgp-peer-redist-vpn')) document.getElementById('modal-bgp-peer-redist-vpn').checked = !!p.redist_vpn;
  8047. if (document.getElementById('modal-bgp-peer-redist-dhcp')) document.getElementById('modal-bgp-peer-redist-dhcp').checked = !!p.redist_dhcp;
  8048. if (document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn')) document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn').checked = !!p.redist_bgp_mpls_vpn;
  8049. if (document.getElementById('modal-bgp-peer-redist-slaac')) document.getElementById('modal-bgp-peer-redist-slaac').checked = !!p.redist_slaac;
  8050. document.getElementById('modal-bgp-peer-default-orig').checked = !!p.default_originate;
  8051. if (document.getElementById('modal-bgp-peer-network-blackhole')) document.getElementById('modal-bgp-peer-network-blackhole').checked = !!p.network_blackhole;
  8052. if (document.getElementById('modal-bgp-peer-no-early-cut')) document.getElementById('modal-bgp-peer-no-early-cut').checked = !!p.no_early_cut;
  8053. if (document.getElementById('modal-bgp-peer-keep-sent-attrs')) document.getElementById('modal-bgp-peer-keep-sent-attrs').checked = !!p.keep_sent_attrs;
  8054. if (document.getElementById('modal-bgp-peer-input-affinity')) document.getElementById('modal-bgp-peer-input-affinity').value = p.input_affinity || '';
  8055. if (document.getElementById('modal-bgp-peer-output-affinity')) document.getElementById('modal-bgp-peer-output-affinity').value = p.output_affinity || '';
  8056. // Attributes Tab
  8057. document.getElementById('modal-bgp-peer-nexthop-choice').value = p.nexthop_choice || (p.nexthop_self ? 'force-self' : 'default');
  8058. document.getElementById('modal-bgp-peer-default-prepend').value = p.default_prepend || 0;
  8059. document.getElementById('modal-bgp-peer-allow-as-in').value = p.allow_as_in || 0;
  8060. if (document.getElementById('modal-bgp-peer-ignore-as-path-len')) document.getElementById('modal-bgp-peer-ignore-as-path-len').checked = !!p.ignore_as_path_len;
  8061. document.getElementById('modal-bgp-peer-remove-priv-as').checked = !!p.remove_private_as;
  8062. document.getElementById('modal-bgp-peer-as-override').checked = !!p.as_override;
  8063. // Filter Tab
  8064. document.getElementById('modal-bgp-peer-in-filter').value = p.in_filter || '';
  8065. if (document.getElementById('modal-bgp-peer-in-accept-nlri')) document.getElementById('modal-bgp-peer-in-accept-nlri').value = p.in_accept_nlri || '';
  8066. if (document.getElementById('modal-bgp-peer-in-accept-comm')) document.getElementById('modal-bgp-peer-in-accept-comm').value = p.in_accept_communities || '';
  8067. if (document.getElementById('modal-bgp-peer-in-accept-ext-comm')) document.getElementById('modal-bgp-peer-in-accept-ext-comm').value = p.in_accept_ext_communities || '';
  8068. if (document.getElementById('modal-bgp-peer-in-accept-large-comm')) document.getElementById('modal-bgp-peer-in-accept-large-comm').value = p.in_accept_large_communities || '';
  8069. if (document.getElementById('modal-bgp-peer-in-filter-comm')) document.getElementById('modal-bgp-peer-in-filter-comm').value = p.in_filter_communities || '';
  8070. if (document.getElementById('modal-bgp-peer-in-filter-ext-comm')) document.getElementById('modal-bgp-peer-in-filter-ext-comm').value = p.in_filter_ext_communities || '';
  8071. if (document.getElementById('modal-bgp-peer-in-filter-large-comm')) document.getElementById('modal-bgp-peer-in-filter-large-comm').value = p.in_filter_large_communities || '';
  8072. if (document.getElementById('modal-bgp-peer-in-filter-unknown')) document.getElementById('modal-bgp-peer-in-filter-unknown').checked = !!p.in_filter_unknown;
  8073. document.getElementById('modal-bgp-peer-out-filter').value = p.out_filter || '';
  8074. if (document.getElementById('modal-bgp-peer-out-selection-policy')) document.getElementById('modal-bgp-peer-out-selection-policy').value = p.out_selection_policy || 'disabled';
  8075. if (document.getElementById('modal-bgp-peer-out-network-name')) document.getElementById('modal-bgp-peer-out-network-name').value = p.output_network || '';
  8076. // Output Networks
  8077. const container = document.getElementById('modal-bgp-output-networks-container');
  8078. if (container) {
  8079. container.innerHTML = '';
  8080. if (p.output_networks && p.output_networks.length > 0) {
  8081. p.output_networks.forEach(net => addOutputNetworkRow(net));
  8082. } else {
  8083. addOutputNetworkRow('');
  8084. }
  8085. }
  8086. const removeBtn = document.getElementById('modal-btn-remove-peer');
  8087. if (removeBtn) removeBtn.classList.remove('hidden');
  8088. switchBgpPeerModalTab('general');
  8089. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  8090. }
  8091. function copyCurrentBgpPeer() {
  8092. document.getElementById('modal-bgp-peer-id').value = '';
  8093. const nameEl = document.getElementById('modal-bgp-peer-name');
  8094. if (nameEl) nameEl.value = (nameEl.value || 'peer') + '-copy';
  8095. document.getElementById('bgp-peer-modal-title').innerText = 'New...';
  8096. const removeBtn = document.getElementById('modal-btn-remove-peer');
  8097. if (removeBtn) removeBtn.classList.add('hidden');
  8098. showToast('Cloned', 'BGP connection copied to new draft', 'info');
  8099. }
  8100. function removeCurrentBgpPeer() {
  8101. const id = document.getElementById('modal-bgp-peer-id')?.value;
  8102. if (!id) return;
  8103. deleteBgpPeer(id);
  8104. closeBgpPeerModal();
  8105. }
  8106. function closeBgpPeerModal() {
  8107. document.getElementById('bgp-peer-modal').classList.add('hidden');
  8108. }
  8109. function getBgpPeerFormData() {
  8110. const netInputs = document.querySelectorAll('#modal-bgp-output-networks-container .output-net-row input');
  8111. const outputNetworks = [];
  8112. netInputs.forEach(inp => {
  8113. const v = inp.value.trim();
  8114. if (v) outputNetworks.push(v);
  8115. });
  8116. const enabled = document.getElementById('modal-bgp-peer-enabled').checked;
  8117. return {
  8118. id: document.getElementById('modal-bgp-peer-id').value,
  8119. name: document.getElementById('modal-bgp-peer-name').value.trim(),
  8120. enabled: enabled,
  8121. disabled: !enabled,
  8122. comment: document.getElementById('modal-bgp-peer-comment').value.trim(),
  8123. instance: document.getElementById('modal-bgp-peer-instance')?.value.trim() || 'bgp-instance-1',
  8124. template: document.getElementById('modal-bgp-peer-template')?.value.trim() || '',
  8125. local_as: parseInt(document.getElementById('modal-bgp-peer-local-as')?.value, 10) || 0,
  8126. router_id: document.getElementById('modal-bgp-peer-router-id').value.trim(),
  8127. afi: document.getElementById('modal-bgp-peer-afi-ipv6').checked ? 'ipv6' : 'ip',
  8128. remote_address: document.getElementById('modal-bgp-peer-remote-addr').value.trim(),
  8129. remote_port: parseInt(document.getElementById('modal-bgp-peer-remote-port').value, 10) || 0,
  8130. remote_as: parseInt(document.getElementById('modal-bgp-peer-remote-as').value, 10) || 0,
  8131. remote_allow_as: document.getElementById('modal-bgp-peer-remote-allow-as')?.value.trim() || '',
  8132. local_address: document.getElementById('modal-bgp-peer-local-addr').value.trim(),
  8133. local_port: parseInt(document.getElementById('modal-bgp-peer-local-port').value, 10) || 0,
  8134. local_role: document.getElementById('modal-bgp-peer-local-role').value,
  8135. password: document.getElementById('modal-bgp-peer-password').value,
  8136. multihop: document.getElementById('modal-bgp-peer-multihop').checked,
  8137. tx_ttl: parseInt(document.getElementById('modal-bgp-peer-tx-ttl')?.value, 10) || 0,
  8138. rx_min_ttl: parseInt(document.getElementById('modal-bgp-peer-rx-min-ttl')?.value, 10) || 0,
  8139. connect: document.getElementById('modal-bgp-peer-connect').checked,
  8140. listen: document.getElementById('modal-bgp-peer-listen').checked,
  8141. hold_time: parseBgpTime(document.getElementById('modal-bgp-peer-holdtime').value),
  8142. keepalive_time: parseBgpTime(document.getElementById('modal-bgp-peer-keepalive').value),
  8143. use_bfd: document.getElementById('modal-bgp-peer-use-bfd')?.checked || false,
  8144. routing_table: document.getElementById('modal-bgp-peer-routing-table').value,
  8145. vrf: document.getElementById('modal-bgp-peer-vrf')?.value.trim() || 'main',
  8146. no_client_reflect: document.getElementById('modal-bgp-peer-no-client-reflect')?.checked || false,
  8147. redist_connected: document.getElementById('modal-bgp-peer-redist-conn').checked,
  8148. redist_static: document.getElementById('modal-bgp-peer-redist-static').checked,
  8149. redist_rip: document.getElementById('modal-bgp-peer-redist-rip')?.checked || false,
  8150. redist_ospf: document.getElementById('modal-bgp-peer-redist-ospf').checked,
  8151. redist_bgp: document.getElementById('modal-bgp-peer-redist-bgp').checked,
  8152. redist_vpn: document.getElementById('modal-bgp-peer-redist-vpn')?.checked || false,
  8153. redist_dhcp: document.getElementById('modal-bgp-peer-redist-dhcp')?.checked || false,
  8154. redist_bgp_mpls_vpn: document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn')?.checked || false,
  8155. redist_slaac: document.getElementById('modal-bgp-peer-redist-slaac')?.checked || false,
  8156. default_originate: document.getElementById('modal-bgp-peer-default-orig').checked,
  8157. network_blackhole: document.getElementById('modal-bgp-peer-network-blackhole')?.checked || false,
  8158. no_early_cut: document.getElementById('modal-bgp-peer-no-early-cut')?.checked || false,
  8159. keep_sent_attrs: document.getElementById('modal-bgp-peer-keep-sent-attrs')?.checked || false,
  8160. input_affinity: (document.getElementById('modal-bgp-peer-input-affinity')?.value || '').trim(),
  8161. output_affinity: (document.getElementById('modal-bgp-peer-output-affinity')?.value || '').trim(),
  8162. nexthop_choice: document.getElementById('modal-bgp-peer-nexthop-choice').value,
  8163. nexthop_self: document.getElementById('modal-bgp-peer-nexthop-choice').value === 'force-self',
  8164. default_prepend: parseInt(document.getElementById('modal-bgp-peer-default-prepend').value, 10) || 0,
  8165. allow_as_in: parseInt(document.getElementById('modal-bgp-peer-allow-as-in').value, 10) || 0,
  8166. ignore_as_path_len: document.getElementById('modal-bgp-peer-ignore-as-path-len')?.checked || false,
  8167. remove_private_as: document.getElementById('modal-bgp-peer-remove-priv-as').checked,
  8168. as_override: document.getElementById('modal-bgp-peer-as-override').checked,
  8169. in_filter: (document.getElementById('modal-bgp-peer-in-filter')?.value || '').trim(),
  8170. in_accept_nlri: (document.getElementById('modal-bgp-peer-in-accept-nlri')?.value || '').trim(),
  8171. in_accept_communities: (document.getElementById('modal-bgp-peer-in-accept-comm')?.value || '').trim(),
  8172. in_accept_ext_communities: (document.getElementById('modal-bgp-peer-in-accept-ext-comm')?.value || '').trim(),
  8173. in_accept_large_communities: (document.getElementById('modal-bgp-peer-in-accept-large-comm')?.value || '').trim(),
  8174. in_filter_communities: (document.getElementById('modal-bgp-peer-in-filter-comm')?.value || '').trim(),
  8175. in_filter_ext_communities: (document.getElementById('modal-bgp-peer-in-filter-ext-comm')?.value || '').trim(),
  8176. in_filter_large_communities: (document.getElementById('modal-bgp-peer-in-filter-large-comm')?.value || '').trim(),
  8177. in_filter_unknown: document.getElementById('modal-bgp-peer-in-filter-unknown')?.checked || false,
  8178. out_filter: (document.getElementById('modal-bgp-peer-out-filter')?.value || '').trim(),
  8179. out_selection_policy: document.getElementById('modal-bgp-peer-out-selection-policy')?.value || 'disabled',
  8180. output_network: (document.getElementById('modal-bgp-peer-out-network-name')?.value || '').trim(),
  8181. output_networks: outputNetworks
  8182. };
  8183. }
  8184. async function submitBgpPeer(e) {
  8185. if (e) e.preventDefault();
  8186. const payload = getBgpPeerFormData();
  8187. try {
  8188. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  8189. method: 'POST',
  8190. headers: { 'Content-Type': 'application/json' },
  8191. body: JSON.stringify(payload)
  8192. });
  8193. if (res.ok) {
  8194. closeBgpPeerModal();
  8195. showToast('Success', 'BGP Connection saved', 'success');
  8196. loadDynamicRouting();
  8197. } else {
  8198. const err = await res.json();
  8199. showToast('Error', err.error || 'Failed to save peer', 'error');
  8200. }
  8201. } catch (err) {
  8202. showToast('Error', err.message, 'error');
  8203. }
  8204. }
  8205. async function applyBgpPeerModal(e) {
  8206. if (e) e.preventDefault();
  8207. const payload = getBgpPeerFormData();
  8208. try {
  8209. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  8210. method: 'POST',
  8211. headers: { 'Content-Type': 'application/json' },
  8212. body: JSON.stringify(payload)
  8213. });
  8214. if (res.ok) {
  8215. const data = await res.json();
  8216. if (data.peer && data.peer.id) {
  8217. document.getElementById('modal-bgp-peer-id').value = data.peer.id;
  8218. document.getElementById('bgp-peer-modal-title').innerText = data.peer.name || data.peer.id;
  8219. document.getElementById('modal-btn-remove-peer')?.classList.remove('hidden');
  8220. }
  8221. showToast('Applied', 'BGP Connection applied', 'success');
  8222. loadDynamicRouting();
  8223. } else {
  8224. const err = await res.json();
  8225. showToast('Error', err.error || 'Failed to apply peer', 'error');
  8226. }
  8227. } catch (err) {
  8228. showToast('Error', err.message, 'error');
  8229. }
  8230. }
  8231. async function deleteBgpPeer(id) {
  8232. if (!confirm('Are you sure you want to delete this BGP peer connection?')) return;
  8233. try {
  8234. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8235. if (res.ok) {
  8236. showToast('Deleted', 'BGP peer removed', 'success');
  8237. loadDynamicRouting();
  8238. }
  8239. } catch (err) {
  8240. showToast('Error', err.message, 'error');
  8241. }
  8242. }
  8243. async function toggleBgpPeerState(id, disabled) {
  8244. try {
  8245. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}/state`, {
  8246. method: 'POST',
  8247. headers: { 'Content-Type': 'application/json' },
  8248. body: JSON.stringify({ disabled })
  8249. });
  8250. if (res.ok) {
  8251. showToast('Updated', `Peer ${disabled ? 'disabled' : 'enabled'}`, 'success');
  8252. loadDynamicRouting();
  8253. }
  8254. } catch (err) {
  8255. showToast('Error', err.message, 'error');
  8256. }
  8257. }
  8258. function openAddBgpNetworkModal() {
  8259. document.getElementById('bgp-network-form').reset();
  8260. document.getElementById('modal-bgp-net-id').value = '';
  8261. document.getElementById('bgp-network-modal').classList.remove('hidden');
  8262. }
  8263. function closeBgpNetworkModal() {
  8264. document.getElementById('bgp-network-modal').classList.add('hidden');
  8265. }
  8266. async function submitBgpNetwork(e) {
  8267. e.preventDefault();
  8268. const payload = {
  8269. id: document.getElementById('modal-bgp-net-id').value,
  8270. network: document.getElementById('modal-bgp-net-cidr').value.trim(),
  8271. comment: document.getElementById('modal-bgp-net-comment').value.trim(),
  8272. disabled: document.getElementById('modal-bgp-net-disabled').checked
  8273. };
  8274. try {
  8275. const res = await fetch(`${API_BASE}/routing/bgp/networks`, {
  8276. method: 'POST',
  8277. headers: { 'Content-Type': 'application/json' },
  8278. body: JSON.stringify(payload)
  8279. });
  8280. if (res.ok) {
  8281. closeBgpNetworkModal();
  8282. showToast('Success', 'BGP network advertisement saved', 'success');
  8283. loadDynamicRouting();
  8284. } else {
  8285. const err = await res.json();
  8286. showToast('Error', err.error || 'Failed to save network', 'error');
  8287. }
  8288. } catch (err) {
  8289. showToast('Error', err.message, 'error');
  8290. }
  8291. }
  8292. async function deleteBgpNetwork(id) {
  8293. if (!confirm('Are you sure you want to stop announcing this network?')) return;
  8294. try {
  8295. const res = await fetch(`${API_BASE}/routing/bgp/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8296. if (res.ok) {
  8297. showToast('Deleted', 'Network advertisement removed', 'success');
  8298. loadDynamicRouting();
  8299. }
  8300. } catch (err) {
  8301. showToast('Error', err.message, 'error');
  8302. }
  8303. }
  8304. // =========================================================================
  8305. // ROUTEROS v7 OSPF MODALS & ACTIONS
  8306. // =========================================================================
  8307. // --- 1. OSPF INSTANCE ---
  8308. function openOspfInstanceModal(id = null) {
  8309. const isEdit = !!id;
  8310. const inst = (state.ospfInstances || []).find(i => i.id === id) || {
  8311. id: '',
  8312. name: 'Default',
  8313. version: 2,
  8314. vrf: 'main',
  8315. router_id: '192.168.131.56',
  8316. routing_table: 'main',
  8317. enabled: true,
  8318. redistribute_connected: false,
  8319. redistribute_static: true,
  8320. redistribute_bgp: false,
  8321. comment: ''
  8322. };
  8323. document.getElementById('ospf-instance-modal-title').innerText = isEdit ? inst.name : 'New...';
  8324. document.getElementById('modal-ospf-inst-id').value = isEdit ? inst.id : '';
  8325. document.getElementById('modal-ospf-inst-enabled').checked = !inst.disabled;
  8326. document.getElementById('modal-ospf-inst-comment').value = inst.comment || '';
  8327. document.getElementById('modal-ospf-inst-name').value = inst.name || 'Default';
  8328. document.getElementById('modal-ospf-inst-version').value = inst.version || 2;
  8329. document.getElementById('modal-ospf-inst-vrf').value = inst.vrf || 'main';
  8330. document.getElementById('modal-ospf-inst-router-id').value = inst.router_id || '';
  8331. document.getElementById('modal-ospf-inst-routing-table').value = inst.routing_table || 'main';
  8332. document.getElementById('modal-ospf-inst-redist-conn').checked = !!inst.redistribute_connected;
  8333. document.getElementById('modal-ospf-inst-redist-static').checked = inst.redistribute_static !== false;
  8334. document.getElementById('modal-ospf-inst-redist-bgp').checked = !!inst.redistribute_bgp;
  8335. const btnRem = document.getElementById('btn-ospf-inst-modal-remove');
  8336. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  8337. document.getElementById('ospf-instance-modal').classList.remove('hidden');
  8338. }
  8339. function openEditOspfInstanceModal(id) {
  8340. openOspfInstanceModal(id);
  8341. }
  8342. function closeOspfInstanceModal() {
  8343. document.getElementById('ospf-instance-modal').classList.add('hidden');
  8344. }
  8345. async function submitOspfInstance(e) {
  8346. if (e) e.preventDefault();
  8347. const payload = {
  8348. id: document.getElementById('modal-ospf-inst-id').value,
  8349. name: document.getElementById('modal-ospf-inst-name').value.trim() || 'Default',
  8350. version: parseInt(document.getElementById('modal-ospf-inst-version').value, 10) || 2,
  8351. vrf: document.getElementById('modal-ospf-inst-vrf').value.trim() || 'main',
  8352. router_id: document.getElementById('modal-ospf-inst-router-id').value.trim(),
  8353. routing_table: document.getElementById('modal-ospf-inst-routing-table').value.trim() || 'main',
  8354. enabled: document.getElementById('modal-ospf-inst-enabled').checked,
  8355. disabled: !document.getElementById('modal-ospf-inst-enabled').checked,
  8356. comment: document.getElementById('modal-ospf-inst-comment').value.trim(),
  8357. redistribute_connected: document.getElementById('modal-ospf-inst-redist-conn').checked,
  8358. redistribute_static: document.getElementById('modal-ospf-inst-redist-static').checked,
  8359. redistribute_bgp: document.getElementById('modal-ospf-inst-redist-bgp').checked
  8360. };
  8361. try {
  8362. const res = await fetch(`${API_BASE}/routing/ospf/instances`, {
  8363. method: 'POST',
  8364. headers: { 'Content-Type': 'application/json' },
  8365. body: JSON.stringify(payload)
  8366. });
  8367. if (res.ok) {
  8368. closeOspfInstanceModal();
  8369. showToast('Saved', 'OSPF instance updated', 'success');
  8370. loadDynamicRouting();
  8371. } else {
  8372. const err = await res.json();
  8373. showToast('Error', err.error || 'Failed to save OSPF instance', 'error');
  8374. }
  8375. } catch (err) {
  8376. showToast('Error', err.message, 'error');
  8377. }
  8378. }
  8379. function applyOspfInstanceForm() {
  8380. submitOspfInstance(null);
  8381. }
  8382. function copyOspfInstance() {
  8383. document.getElementById('modal-ospf-inst-id').value = '';
  8384. document.getElementById('modal-ospf-inst-name').value += '-copy';
  8385. document.getElementById('ospf-instance-modal-title').innerText = 'New...';
  8386. showToast('Copied', 'Duplicated as new OSPF instance', 'info');
  8387. }
  8388. async function deleteCurrentOspfInstance() {
  8389. const id = document.getElementById('modal-ospf-inst-id').value;
  8390. if (!id) return;
  8391. if (!confirm('Are you sure you want to remove this OSPF instance?')) return;
  8392. try {
  8393. const res = await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8394. if (res.ok) {
  8395. closeOspfInstanceModal();
  8396. showToast('Removed', 'OSPF instance deleted', 'success');
  8397. loadDynamicRouting();
  8398. }
  8399. } catch (err) {
  8400. showToast('Error', err.message, 'error');
  8401. }
  8402. }
  8403. async function enableSelectedOspfInstance() {
  8404. const id = state.selectedOspfRow?.instances;
  8405. if (!id) return;
  8406. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}/state`, {
  8407. method: 'POST',
  8408. headers: { 'Content-Type': 'application/json' },
  8409. body: JSON.stringify({ disabled: false })
  8410. });
  8411. loadDynamicRouting();
  8412. }
  8413. async function disableSelectedOspfInstance() {
  8414. const id = state.selectedOspfRow?.instances;
  8415. if (!id) return;
  8416. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}/state`, {
  8417. method: 'POST',
  8418. headers: { 'Content-Type': 'application/json' },
  8419. body: JSON.stringify({ disabled: true })
  8420. });
  8421. loadDynamicRouting();
  8422. }
  8423. async function removeSelectedOspfInstance() {
  8424. const id = state.selectedOspfRow?.instances;
  8425. if (!id) return;
  8426. if (!confirm('Delete selected OSPF instance?')) return;
  8427. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8428. loadDynamicRouting();
  8429. }
  8430. async function promptCommentOspfInstance() {
  8431. const id = state.selectedOspfRow?.instances;
  8432. if (!id) return;
  8433. const inst = (state.ospfInstances || []).find(i => i.id === id);
  8434. if (!inst) return;
  8435. const comment = prompt('Enter comment for OSPF instance:', inst.comment || '');
  8436. if (comment === null) return;
  8437. inst.comment = comment;
  8438. await fetch(`${API_BASE}/routing/ospf/instances`, {
  8439. method: 'POST',
  8440. headers: { 'Content-Type': 'application/json' },
  8441. body: JSON.stringify(inst)
  8442. });
  8443. loadDynamicRouting();
  8444. }
  8445. // --- 2. OSPF AREA ---
  8446. function populateOspfAreaDropdowns() {
  8447. const instSelect = document.getElementById('modal-ospf-area-instance');
  8448. if (instSelect) {
  8449. const cur = instSelect.value;
  8450. instSelect.innerHTML = (state.ospfInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)}</option>`).join('');
  8451. if (instSelect.innerHTML === '') instSelect.innerHTML = '<option value="Default">Default</option>';
  8452. if (cur) instSelect.value = cur;
  8453. }
  8454. }
  8455. function openOspfAreaModal(id = null) {
  8456. const isEdit = !!id;
  8457. populateOspfAreaDropdowns();
  8458. const area = (state.ospfAreas || []).find(a => a.id === id) || {
  8459. id: '',
  8460. name: 'Default',
  8461. instance: 'Default',
  8462. area_id: '0.0.0.0',
  8463. area_type: 'default',
  8464. default_cost: 1,
  8465. no_summaries: false,
  8466. disabled: false,
  8467. comment: ''
  8468. };
  8469. document.getElementById('ospf-area-modal-title').innerText = isEdit ? area.name : 'New...';
  8470. document.getElementById('modal-ospf-area-id').value = isEdit ? area.id : '';
  8471. document.getElementById('modal-ospf-area-enabled').checked = !area.disabled;
  8472. document.getElementById('modal-ospf-area-comment').value = area.comment || '';
  8473. document.getElementById('modal-ospf-area-name').value = area.name || 'Default';
  8474. document.getElementById('modal-ospf-area-instance').value = area.instance || 'Default';
  8475. document.getElementById('modal-ospf-area-areaid').value = area.area_id || '0.0.0.0';
  8476. document.getElementById('modal-ospf-area-type').value = area.area_type || 'default';
  8477. document.getElementById('modal-ospf-area-default-cost').value = area.default_cost || 1;
  8478. document.getElementById('modal-ospf-area-no-summaries').checked = !!area.no_summaries;
  8479. const btnRem = document.getElementById('btn-ospf-area-modal-remove');
  8480. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  8481. document.getElementById('ospf-area-modal').classList.remove('hidden');
  8482. }
  8483. function openEditOspfAreaModal(id) {
  8484. openOspfAreaModal(id);
  8485. }
  8486. function closeOspfAreaModal() {
  8487. document.getElementById('ospf-area-modal').classList.add('hidden');
  8488. }
  8489. async function submitOspfArea(e) {
  8490. if (e) e.preventDefault();
  8491. const payload = {
  8492. id: document.getElementById('modal-ospf-area-id').value,
  8493. name: document.getElementById('modal-ospf-area-name').value.trim() || 'Default',
  8494. instance: document.getElementById('modal-ospf-area-instance').value.trim() || 'Default',
  8495. area_id: document.getElementById('modal-ospf-area-areaid').value.trim() || '0.0.0.0',
  8496. area_type: document.getElementById('modal-ospf-area-type').value,
  8497. default_cost: parseInt(document.getElementById('modal-ospf-area-default-cost').value, 10) || 1,
  8498. no_summaries: document.getElementById('modal-ospf-area-no-summaries').checked,
  8499. disabled: !document.getElementById('modal-ospf-area-enabled').checked,
  8500. comment: document.getElementById('modal-ospf-area-comment').value.trim()
  8501. };
  8502. try {
  8503. const res = await fetch(`${API_BASE}/routing/ospf/areas`, {
  8504. method: 'POST',
  8505. headers: { 'Content-Type': 'application/json' },
  8506. body: JSON.stringify(payload)
  8507. });
  8508. if (res.ok) {
  8509. closeOspfAreaModal();
  8510. showToast('Saved', 'OSPF area saved', 'success');
  8511. loadDynamicRouting();
  8512. } else {
  8513. const err = await res.json();
  8514. showToast('Error', err.error || 'Failed to save area', 'error');
  8515. }
  8516. } catch (err) {
  8517. showToast('Error', err.message, 'error');
  8518. }
  8519. }
  8520. function applyOspfAreaForm() {
  8521. submitOspfArea(null);
  8522. }
  8523. function copyOspfArea() {
  8524. document.getElementById('modal-ospf-area-id').value = '';
  8525. document.getElementById('modal-ospf-area-name').value += '-copy';
  8526. document.getElementById('ospf-area-modal-title').innerText = 'New...';
  8527. showToast('Copied', 'Duplicated as new OSPF area', 'info');
  8528. }
  8529. async function deleteCurrentOspfArea() {
  8530. const id = document.getElementById('modal-ospf-area-id').value;
  8531. if (!id) return;
  8532. if (!confirm('Are you sure you want to remove this OSPF area?')) return;
  8533. try {
  8534. const res = await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8535. if (res.ok) {
  8536. closeOspfAreaModal();
  8537. showToast('Removed', 'OSPF area deleted', 'success');
  8538. loadDynamicRouting();
  8539. }
  8540. } catch (err) {
  8541. showToast('Error', err.message, 'error');
  8542. }
  8543. }
  8544. async function enableSelectedOspfArea() {
  8545. const id = state.selectedOspfRow?.areas;
  8546. if (!id) return;
  8547. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}/state`, {
  8548. method: 'POST',
  8549. headers: { 'Content-Type': 'application/json' },
  8550. body: JSON.stringify({ disabled: false })
  8551. });
  8552. loadDynamicRouting();
  8553. }
  8554. async function disableSelectedOspfArea() {
  8555. const id = state.selectedOspfRow?.areas;
  8556. if (!id) return;
  8557. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}/state`, {
  8558. method: 'POST',
  8559. headers: { 'Content-Type': 'application/json' },
  8560. body: JSON.stringify({ disabled: true })
  8561. });
  8562. loadDynamicRouting();
  8563. }
  8564. async function removeSelectedOspfArea() {
  8565. const id = state.selectedOspfRow?.areas;
  8566. if (!id) return;
  8567. if (!confirm('Delete selected OSPF area?')) return;
  8568. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8569. loadDynamicRouting();
  8570. }
  8571. async function promptCommentOspfArea() {
  8572. const id = state.selectedOspfRow?.areas;
  8573. if (!id) return;
  8574. const area = (state.ospfAreas || []).find(a => a.id === id);
  8575. if (!area) return;
  8576. const comment = prompt('Enter comment for OSPF area:', area.comment || '');
  8577. if (comment === null) return;
  8578. area.comment = comment;
  8579. await fetch(`${API_BASE}/routing/ospf/areas`, {
  8580. method: 'POST',
  8581. headers: { 'Content-Type': 'application/json' },
  8582. body: JSON.stringify(area)
  8583. });
  8584. loadDynamicRouting();
  8585. }
  8586. // --- 3. OSPF AREA RANGE ---
  8587. function populateAreaRangeDropdowns() {
  8588. const select = document.getElementById('modal-ospf-range-area');
  8589. if (select) {
  8590. const cur = select.value;
  8591. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  8592. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  8593. if (cur) select.value = cur;
  8594. }
  8595. }
  8596. function openOspfAreaRangeModal(id = null) {
  8597. const isEdit = !!id;
  8598. populateAreaRangeDropdowns();
  8599. const r = (state.ospfAreaRanges || []).find(it => it.id === id) || {
  8600. id: '',
  8601. area: 'Default',
  8602. prefix: '',
  8603. cost: 1,
  8604. advertise: true,
  8605. disabled: false,
  8606. comment: ''
  8607. };
  8608. document.getElementById('ospf-area-range-modal-title').innerText = isEdit ? r.prefix : 'New...';
  8609. document.getElementById('modal-ospf-range-id').value = isEdit ? r.id : '';
  8610. document.getElementById('modal-ospf-range-enabled').checked = !r.disabled;
  8611. document.getElementById('modal-ospf-range-comment').value = r.comment || '';
  8612. document.getElementById('modal-ospf-range-area').value = r.area || 'Default';
  8613. document.getElementById('modal-ospf-range-prefix').value = r.prefix || '';
  8614. document.getElementById('modal-ospf-range-cost').value = r.cost || 1;
  8615. document.getElementById('modal-ospf-range-advertise').checked = r.advertise !== false;
  8616. const btnRem = document.getElementById('btn-ospf-range-modal-remove');
  8617. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  8618. document.getElementById('ospf-area-range-modal').classList.remove('hidden');
  8619. }
  8620. function openEditOspfAreaRangeModal(id) {
  8621. openOspfAreaRangeModal(id);
  8622. }
  8623. function closeOspfAreaRangeModal() {
  8624. document.getElementById('ospf-area-range-modal').classList.add('hidden');
  8625. }
  8626. async function submitOspfAreaRange(e) {
  8627. if (e) e.preventDefault();
  8628. const payload = {
  8629. id: document.getElementById('modal-ospf-range-id').value,
  8630. area: document.getElementById('modal-ospf-range-area').value,
  8631. prefix: document.getElementById('modal-ospf-range-prefix').value.trim(),
  8632. cost: parseInt(document.getElementById('modal-ospf-range-cost').value, 10) || 1,
  8633. advertise: document.getElementById('modal-ospf-range-advertise').checked,
  8634. disabled: !document.getElementById('modal-ospf-range-enabled').checked,
  8635. comment: document.getElementById('modal-ospf-range-comment').value.trim()
  8636. };
  8637. try {
  8638. const res = await fetch(`${API_BASE}/routing/ospf/area-ranges`, {
  8639. method: 'POST',
  8640. headers: { 'Content-Type': 'application/json' },
  8641. body: JSON.stringify(payload)
  8642. });
  8643. if (res.ok) {
  8644. closeOspfAreaRangeModal();
  8645. showToast('Saved', 'Area range saved', 'success');
  8646. loadDynamicRouting();
  8647. } else {
  8648. const err = await res.json();
  8649. showToast('Error', err.error || 'Failed to save area range', 'error');
  8650. }
  8651. } catch (err) {
  8652. showToast('Error', err.message, 'error');
  8653. }
  8654. }
  8655. function applyOspfAreaRangeForm() {
  8656. submitOspfAreaRange(null);
  8657. }
  8658. async function deleteCurrentOspfAreaRange() {
  8659. const id = document.getElementById('modal-ospf-range-id').value;
  8660. if (!id) return;
  8661. if (!confirm('Delete this area range?')) return;
  8662. try {
  8663. await fetch(`${API_BASE}/routing/ospf/area-ranges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8664. closeOspfAreaRangeModal();
  8665. showToast('Removed', 'Area range removed', 'success');
  8666. loadDynamicRouting();
  8667. } catch (err) {
  8668. showToast('Error', err.message, 'error');
  8669. }
  8670. }
  8671. async function enableSelectedOspfAreaRange() {
  8672. const id = state.selectedOspfRow?.['area-ranges'];
  8673. if (!id) return;
  8674. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  8675. if (!r) return;
  8676. r.disabled = false;
  8677. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  8678. loadDynamicRouting();
  8679. }
  8680. async function disableSelectedOspfAreaRange() {
  8681. const id = state.selectedOspfRow?.['area-ranges'];
  8682. if (!id) return;
  8683. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  8684. if (!r) return;
  8685. r.disabled = true;
  8686. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  8687. loadDynamicRouting();
  8688. }
  8689. async function removeSelectedOspfAreaRange() {
  8690. const id = state.selectedOspfRow?.['area-ranges'];
  8691. if (!id) return;
  8692. if (!confirm('Delete selected area range?')) return;
  8693. await fetch(`${API_BASE}/routing/ospf/area-ranges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8694. loadDynamicRouting();
  8695. }
  8696. async function promptCommentOspfAreaRange() {
  8697. const id = state.selectedOspfRow?.['area-ranges'];
  8698. if (!id) return;
  8699. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  8700. if (!r) return;
  8701. const comment = prompt('Enter comment for area range:', r.comment || '');
  8702. if (comment === null) return;
  8703. r.comment = comment;
  8704. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  8705. loadDynamicRouting();
  8706. }
  8707. // --- 4. OSPF INTERFACE TEMPLATE ---
  8708. function switchOspfTemplateTab(tab) {
  8709. const tabGen = document.getElementById('ospf-tmpl-tab-general');
  8710. const tabAuth = document.getElementById('ospf-tmpl-tab-auth');
  8711. const btnGen = document.getElementById('ospf-tmpl-tab-btn-general');
  8712. const btnAuth = document.getElementById('ospf-tmpl-tab-btn-auth');
  8713. if (tab === 'general') {
  8714. if (tabGen) tabGen.classList.remove('hidden');
  8715. if (tabAuth) tabAuth.classList.add('hidden');
  8716. if (btnGen) btnGen.className = 'px-4 py-2 text-xs font-bold border-b-2 border-sky-500 text-white transition';
  8717. if (btnAuth) btnAuth.className = 'px-4 py-2 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition';
  8718. } else {
  8719. if (tabGen) tabGen.classList.add('hidden');
  8720. if (tabAuth) tabAuth.classList.remove('hidden');
  8721. if (btnGen) btnGen.className = 'px-4 py-2 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition';
  8722. if (btnAuth) btnAuth.className = 'px-4 py-2 text-xs font-bold border-b-2 border-sky-500 text-white transition';
  8723. }
  8724. }
  8725. function populateTemplateAreaDropdowns() {
  8726. const select = document.getElementById('modal-ospf-tmpl-area');
  8727. if (select) {
  8728. const cur = select.value;
  8729. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  8730. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  8731. if (cur) select.value = cur;
  8732. }
  8733. }
  8734. function openOspfTemplateModal(id = null) {
  8735. const isEdit = !!id;
  8736. populateTemplateAreaDropdowns();
  8737. switchOspfTemplateTab('general');
  8738. const tmpl = (state.ospfTemplates || []).find(t => t.id === id) || {
  8739. id: '',
  8740. interfaces: '',
  8741. area: 'Default',
  8742. networks: '',
  8743. network_type: 'broadcast',
  8744. cost: 1,
  8745. priority: 128,
  8746. passive: false,
  8747. hello_interval: 10,
  8748. dead_interval: 40,
  8749. auth: 'none',
  8750. auth_key: '',
  8751. disabled: false,
  8752. comment: ''
  8753. };
  8754. document.getElementById('ospf-template-modal-title').innerText = isEdit ? (tmpl.interfaces || tmpl.networks || 'Template') : 'New...';
  8755. document.getElementById('modal-ospf-tmpl-id').value = isEdit ? tmpl.id : '';
  8756. document.getElementById('modal-ospf-tmpl-enabled').checked = !tmpl.disabled;
  8757. document.getElementById('modal-ospf-tmpl-comment').value = tmpl.comment || '';
  8758. document.getElementById('modal-ospf-tmpl-interfaces').value = tmpl.interfaces || tmpl.interface || '';
  8759. document.getElementById('modal-ospf-tmpl-area').value = tmpl.area || 'Default';
  8760. document.getElementById('modal-ospf-tmpl-networks').value = tmpl.networks || tmpl.network || '';
  8761. document.getElementById('modal-ospf-tmpl-net-type').value = tmpl.network_type || 'broadcast';
  8762. document.getElementById('modal-ospf-tmpl-cost').value = tmpl.cost || 1;
  8763. document.getElementById('modal-ospf-tmpl-priority').value = tmpl.priority || 128;
  8764. document.getElementById('modal-ospf-tmpl-passive').checked = !!tmpl.passive;
  8765. document.getElementById('modal-ospf-tmpl-hello').value = tmpl.hello_interval || 10;
  8766. document.getElementById('modal-ospf-tmpl-dead').value = tmpl.dead_interval || 40;
  8767. document.getElementById('modal-ospf-tmpl-auth').value = tmpl.auth || tmpl.auth_type || 'none';
  8768. document.getElementById('modal-ospf-tmpl-auth-key').value = tmpl.auth_key || '';
  8769. const btnRem = document.getElementById('btn-ospf-tmpl-modal-remove');
  8770. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  8771. document.getElementById('ospf-template-modal').classList.remove('hidden');
  8772. }
  8773. function openEditOspfTemplateModal(id) {
  8774. openOspfTemplateModal(id);
  8775. }
  8776. function closeOspfTemplateModal() {
  8777. document.getElementById('ospf-template-modal').classList.add('hidden');
  8778. }
  8779. async function submitOspfTemplate(e) {
  8780. if (e) e.preventDefault();
  8781. const payload = {
  8782. id: document.getElementById('modal-ospf-tmpl-id').value,
  8783. interfaces: document.getElementById('modal-ospf-tmpl-interfaces').value.trim(),
  8784. interface: document.getElementById('modal-ospf-tmpl-interfaces').value.trim(),
  8785. area: document.getElementById('modal-ospf-tmpl-area').value,
  8786. networks: document.getElementById('modal-ospf-tmpl-networks').value.trim(),
  8787. network: document.getElementById('modal-ospf-tmpl-networks').value.trim(),
  8788. network_type: document.getElementById('modal-ospf-tmpl-net-type').value,
  8789. cost: parseInt(document.getElementById('modal-ospf-tmpl-cost').value, 10) || 1,
  8790. priority: parseInt(document.getElementById('modal-ospf-tmpl-priority').value, 10) || 128,
  8791. passive: document.getElementById('modal-ospf-tmpl-passive').checked,
  8792. hello_interval: parseInt(document.getElementById('modal-ospf-tmpl-hello').value, 10) || 10,
  8793. dead_interval: parseInt(document.getElementById('modal-ospf-tmpl-dead').value, 10) || 40,
  8794. auth: document.getElementById('modal-ospf-tmpl-auth').value,
  8795. auth_type: document.getElementById('modal-ospf-tmpl-auth').value,
  8796. auth_key: document.getElementById('modal-ospf-tmpl-auth-key').value,
  8797. disabled: !document.getElementById('modal-ospf-tmpl-enabled').checked,
  8798. comment: document.getElementById('modal-ospf-tmpl-comment').value.trim()
  8799. };
  8800. try {
  8801. const res = await fetch(`${API_BASE}/routing/ospf/templates`, {
  8802. method: 'POST',
  8803. headers: { 'Content-Type': 'application/json' },
  8804. body: JSON.stringify(payload)
  8805. });
  8806. if (res.ok) {
  8807. closeOspfTemplateModal();
  8808. showToast('Saved', 'Interface template saved', 'success');
  8809. loadDynamicRouting();
  8810. } else {
  8811. const err = await res.json();
  8812. showToast('Error', err.error || 'Failed to save interface template', 'error');
  8813. }
  8814. } catch (err) {
  8815. showToast('Error', err.message, 'error');
  8816. }
  8817. }
  8818. function applyOspfTemplateForm() {
  8819. submitOspfTemplate(null);
  8820. }
  8821. function copyOspfTemplate() {
  8822. document.getElementById('modal-ospf-tmpl-id').value = '';
  8823. document.getElementById('ospf-template-modal-title').innerText = 'New...';
  8824. showToast('Copied', 'Duplicated as new template', 'info');
  8825. }
  8826. async function deleteCurrentOspfTemplate() {
  8827. const id = document.getElementById('modal-ospf-tmpl-id').value;
  8828. if (!id) return;
  8829. if (!confirm('Delete this interface template?')) return;
  8830. try {
  8831. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8832. closeOspfTemplateModal();
  8833. showToast('Removed', 'Interface template deleted', 'success');
  8834. loadDynamicRouting();
  8835. } catch (err) {
  8836. showToast('Error', err.message, 'error');
  8837. }
  8838. }
  8839. async function enableSelectedOspfTemplate() {
  8840. const id = state.selectedOspfRow?.templates;
  8841. if (!id) return;
  8842. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  8843. method: 'POST',
  8844. headers: { 'Content-Type': 'application/json' },
  8845. body: JSON.stringify({ disabled: false })
  8846. });
  8847. loadDynamicRouting();
  8848. }
  8849. async function disableSelectedOspfTemplate() {
  8850. const id = state.selectedOspfRow?.templates;
  8851. if (!id) return;
  8852. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  8853. method: 'POST',
  8854. headers: { 'Content-Type': 'application/json' },
  8855. body: JSON.stringify({ disabled: true })
  8856. });
  8857. loadDynamicRouting();
  8858. }
  8859. async function removeSelectedOspfTemplate() {
  8860. const id = state.selectedOspfRow?.templates;
  8861. if (!id) return;
  8862. if (!confirm('Delete selected interface template?')) return;
  8863. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8864. loadDynamicRouting();
  8865. }
  8866. async function promptCommentOspfTemplate() {
  8867. const id = state.selectedOspfRow?.templates;
  8868. if (!id) return;
  8869. const tmpl = (state.ospfTemplates || []).find(t => t.id === id);
  8870. if (!tmpl) return;
  8871. const comment = prompt('Enter comment for template:', tmpl.comment || '');
  8872. if (comment === null) return;
  8873. tmpl.comment = comment;
  8874. await fetch(`${API_BASE}/routing/ospf/templates`, {
  8875. method: 'POST',
  8876. headers: { 'Content-Type': 'application/json' },
  8877. body: JSON.stringify(tmpl)
  8878. });
  8879. loadDynamicRouting();
  8880. }
  8881. // --- 5. OSPF STATIC NEIGHBOR ---
  8882. function populateStaticNbrAreaDropdowns() {
  8883. const select = document.getElementById('modal-ospf-snbr-area');
  8884. if (select) {
  8885. const cur = select.value;
  8886. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  8887. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  8888. if (cur) select.value = cur;
  8889. }
  8890. }
  8891. function openOspfStaticNbrModal(id = null) {
  8892. const isEdit = !!id;
  8893. populateStaticNbrAreaDropdowns();
  8894. const nbr = (state.ospfStaticNbrs || []).find(n => n.id === id) || {
  8895. id: '',
  8896. address: '',
  8897. area: 'Default',
  8898. poll_interval: 120,
  8899. cost: 1,
  8900. disabled: false,
  8901. comment: ''
  8902. };
  8903. document.getElementById('ospf-static-nbr-modal-title').innerText = isEdit ? nbr.address : 'New...';
  8904. document.getElementById('modal-ospf-snbr-id').value = isEdit ? nbr.id : '';
  8905. document.getElementById('modal-ospf-snbr-enabled').checked = !nbr.disabled;
  8906. document.getElementById('modal-ospf-snbr-comment').value = nbr.comment || '';
  8907. document.getElementById('modal-ospf-snbr-address').value = nbr.address || '';
  8908. document.getElementById('modal-ospf-snbr-area').value = nbr.area || 'Default';
  8909. document.getElementById('modal-ospf-snbr-poll').value = nbr.poll_interval || 120;
  8910. document.getElementById('modal-ospf-snbr-cost').value = nbr.cost || 1;
  8911. const btnRem = document.getElementById('btn-ospf-snbr-modal-remove');
  8912. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  8913. document.getElementById('ospf-static-nbr-modal').classList.remove('hidden');
  8914. }
  8915. function openEditOspfStaticNbrModal(id) {
  8916. openOspfStaticNbrModal(id);
  8917. }
  8918. function closeOspfStaticNbrModal() {
  8919. document.getElementById('ospf-static-nbr-modal').classList.add('hidden');
  8920. }
  8921. async function submitOspfStaticNbr(e) {
  8922. if (e) e.preventDefault();
  8923. const payload = {
  8924. id: document.getElementById('modal-ospf-snbr-id').value,
  8925. address: document.getElementById('modal-ospf-snbr-address').value.trim(),
  8926. area: document.getElementById('modal-ospf-snbr-area').value,
  8927. poll_interval: parseInt(document.getElementById('modal-ospf-snbr-poll').value, 10) || 120,
  8928. cost: parseInt(document.getElementById('modal-ospf-snbr-cost').value, 10) || 1,
  8929. disabled: !document.getElementById('modal-ospf-snbr-enabled').checked,
  8930. comment: document.getElementById('modal-ospf-snbr-comment').value.trim()
  8931. };
  8932. try {
  8933. const res = await fetch(`${API_BASE}/routing/ospf/static-neighbors`, {
  8934. method: 'POST',
  8935. headers: { 'Content-Type': 'application/json' },
  8936. body: JSON.stringify(payload)
  8937. });
  8938. if (res.ok) {
  8939. closeOspfStaticNbrModal();
  8940. showToast('Saved', 'Static neighbor saved', 'success');
  8941. loadDynamicRouting();
  8942. } else {
  8943. const err = await res.json();
  8944. showToast('Error', err.error || 'Failed to save static neighbor', 'error');
  8945. }
  8946. } catch (err) {
  8947. showToast('Error', err.message, 'error');
  8948. }
  8949. }
  8950. function applyOspfStaticNbrForm() {
  8951. submitOspfStaticNbr(null);
  8952. }
  8953. async function deleteCurrentOspfStaticNbr() {
  8954. const id = document.getElementById('modal-ospf-snbr-id').value;
  8955. if (!id) return;
  8956. if (!confirm('Delete this static neighbor?')) return;
  8957. try {
  8958. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8959. closeOspfStaticNbrModal();
  8960. showToast('Removed', 'Static neighbor removed', 'success');
  8961. loadDynamicRouting();
  8962. } catch (err) {
  8963. showToast('Error', err.message, 'error');
  8964. }
  8965. }
  8966. async function enableSelectedOspfStaticNbr() {
  8967. const id = state.selectedOspfRow?.['static-nbrs'];
  8968. if (!id) return;
  8969. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  8970. if (!n) return;
  8971. n.disabled = false;
  8972. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  8973. loadDynamicRouting();
  8974. }
  8975. async function disableSelectedOspfStaticNbr() {
  8976. const id = state.selectedOspfRow?.['static-nbrs'];
  8977. if (!id) return;
  8978. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  8979. if (!n) return;
  8980. n.disabled = true;
  8981. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  8982. loadDynamicRouting();
  8983. }
  8984. async function removeSelectedOspfStaticNbr() {
  8985. const id = state.selectedOspfRow?.['static-nbrs'];
  8986. if (!id) return;
  8987. if (!confirm('Delete selected static neighbor?')) return;
  8988. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8989. loadDynamicRouting();
  8990. }
  8991. async function promptCommentOspfStaticNbr() {
  8992. const id = state.selectedOspfRow?.['static-nbrs'];
  8993. if (!id) return;
  8994. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  8995. if (!n) return;
  8996. const comment = prompt('Enter comment for static neighbor:', n.comment || '');
  8997. if (comment === null) return;
  8998. n.comment = comment;
  8999. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  9000. loadDynamicRouting();
  9001. }
  9002. // Backward-compat aliases
  9003. function openAddOspfInterfaceModal() { openOspfTemplateModal(); }
  9004. function openEditOspfInterfaceModal(id) { openEditOspfTemplateModal(id); }
  9005. function closeOspfInterfaceModal() { closeOspfTemplateModal(); }
  9006. function submitOspfInterface(e) { submitOspfTemplate(e); }
  9007. function deleteOspfInterface(id) {
  9008. fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' }).then(() => loadDynamicRouting());
  9009. }
  9010. function toggleOspfInterfaceState(id, disabled) {
  9011. fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  9012. method: 'POST',
  9013. headers: { 'Content-Type': 'application/json' },
  9014. body: JSON.stringify({ disabled })
  9015. }).then(() => loadDynamicRouting());
  9016. }
  9017. function openAddOspfAreaModal() { openOspfAreaModal(); }
  9018. function deleteOspfArea(id) {
  9019. fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' }).then(() => loadDynamicRouting());
  9020. }
  9021. // ============================================================================
  9022. // ==================== MIKROTIK BRIDGE SUBSYSTEM ==============================
  9023. // ============================================================================
  9024. function switchBridgeSubTab(tab) {
  9025. state.bridgeSubTab = tab;
  9026. const tabs = ['bridges', 'ports', 'vlans', 'hosts'];
  9027. tabs.forEach(t => {
  9028. const panel = document.getElementById(`bridge-subtab-${t}`);
  9029. const btn = document.getElementById(`bridge-subtab-btn-${t}`);
  9030. if (panel) {
  9031. if (t === tab) panel.classList.remove('hidden');
  9032. else panel.classList.add('hidden');
  9033. }
  9034. if (btn) {
  9035. if (t === tab) {
  9036. 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';
  9037. } else {
  9038. 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';
  9039. }
  9040. }
  9041. });
  9042. const addBtn = document.getElementById('bridge-top-action-btn');
  9043. if (addBtn) {
  9044. if (tab === 'bridges') addBtn.innerHTML = '<span>+ Add Bridge</span>';
  9045. else if (tab === 'ports') addBtn.innerHTML = '<span>+ Add Port</span>';
  9046. else if (tab === 'vlans') addBtn.innerHTML = '<span>+ Add VLAN Entry</span>';
  9047. else if (tab === 'hosts') addBtn.innerHTML = '<span>🔄 Refresh MACs</span>';
  9048. }
  9049. if (tab === 'hosts') loadBridgeHosts();
  9050. setTimeout(initTableSorting, 50);
  9051. }
  9052. function openCurrentBridgeModal() {
  9053. if (state.bridgeSubTab === 'bridges') openAddBridgeModal();
  9054. else if (state.bridgeSubTab === 'ports') openAddBridgePortModal();
  9055. else if (state.bridgeSubTab === 'vlans') openAddBridgeVLANModal();
  9056. else if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  9057. }
  9058. async function loadBridge() {
  9059. try {
  9060. const [bridgesRes, portsRes, vlansRes, summaryRes, eoipRes, vlanIfacesRes] = await Promise.all([
  9061. fetch(`${API_BASE}/bridge/bridges`),
  9062. fetch(`${API_BASE}/bridge/ports`),
  9063. fetch(`${API_BASE}/bridge/vlans`),
  9064. fetch(`${API_BASE}/bridge/summary`),
  9065. fetch(`${API_BASE}/vpn/eoip`),
  9066. fetch(`${API_BASE}/vlans`)
  9067. ]);
  9068. if (bridgesRes.ok) state.bridges = await bridgesRes.json();
  9069. if (portsRes.ok) state.bridgePorts = await portsRes.json();
  9070. if (vlansRes.ok) state.bridgeVLANs = await vlansRes.json();
  9071. if (summaryRes.ok) state.bridgeSummary = await summaryRes.json();
  9072. if (eoipRes && eoipRes.ok) state.eoipTunnels = await eoipRes.json();
  9073. if (vlanIfacesRes && vlanIfacesRes.ok) state.vlans = await vlanIfacesRes.json();
  9074. // Badges & Stats
  9075. const bBridges = document.getElementById('bridge-badge-bridges');
  9076. if (bBridges) bBridges.innerText = (state.bridges || []).length;
  9077. const bPorts = document.getElementById('bridge-badge-ports');
  9078. if (bPorts) bPorts.innerText = (state.bridgePorts || []).length;
  9079. const bVlans = document.getElementById('bridge-badge-vlans');
  9080. if (bVlans) bVlans.innerText = (state.bridgeVLANs || []).length;
  9081. const bHosts = document.getElementById('bridge-badge-hosts');
  9082. if (bHosts) bHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  9083. const sBr = document.getElementById('bridge-stat-bridges');
  9084. if (sBr) sBr.innerText = (state.bridges || []).length;
  9085. const sPorts = document.getElementById('bridge-stat-ports');
  9086. if (sPorts) sPorts.innerText = (state.bridgePorts || []).length;
  9087. const sHosts = document.getElementById('bridge-stat-hosts');
  9088. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  9089. renderBridges();
  9090. renderBridgePorts();
  9091. renderBridgeVLANs();
  9092. if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  9093. } catch (err) {
  9094. console.error('Failed to load bridge subsystem:', err);
  9095. }
  9096. }
  9097. // ----------------- Bridges -----------------
  9098. function renderBridges() {
  9099. const tbody = document.getElementById('bridge-table-body');
  9100. const empty = document.getElementById('bridge-empty-bridges');
  9101. const countBadge = document.getElementById('bridge-count-badge');
  9102. if (!tbody) return;
  9103. tbody.innerHTML = '';
  9104. const bridges = state.bridges || [];
  9105. if (countBadge) countBadge.innerText = `${bridges.length} Bridges`;
  9106. if (bridges.length === 0) {
  9107. empty?.classList.remove('hidden');
  9108. return;
  9109. }
  9110. empty?.classList.add('hidden');
  9111. bridges.forEach((b, idx) => {
  9112. const tr = document.createElement('tr');
  9113. tr.className = `hover:bg-slate-800/40 transition text-xs ${b.disabled ? 'opacity-50' : ''}`;
  9114. // Format IP addresses pill list
  9115. let ipsHtml = '<span class="text-slate-600 font-sans">None</span>';
  9116. if (b.ip_addresses && b.ip_addresses.length > 0) {
  9117. ipsHtml = b.ip_addresses.map(ip => `
  9118. <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">
  9119. <span>${ip}</span>
  9120. <button onclick="deleteBridgeIP('${b.id}', '${ip}')" class="text-slate-500 hover:text-rose-400 font-bold ml-0.5">×</button>
  9121. </span>
  9122. `).join(' ');
  9123. }
  9124. const runningFlag = b.running ? '<span class="text-emerald-400 font-bold" title="Running (R)">R</span>' : '<span class="text-slate-600">-</span>';
  9125. const disabledFlag = b.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '';
  9126. const flagDisplay = `${runningFlag}${disabledFlag ? ' ' + disabledFlag : ''}`;
  9127. tr.innerHTML = `
  9128. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  9129. <td class="py-2.5 px-3 text-center font-mono">${flagDisplay}</td>
  9130. <td class="py-2.5 px-3 font-bold text-white text-sm">
  9131. <span class="text-sky-400 mr-1.5">🌉</span>${b.name}
  9132. </td>
  9133. <td class="py-2.5 px-3 text-slate-300">${b.mtu}</td>
  9134. <td class="py-2.5 px-3 font-mono text-slate-300 text-[11px]">${b.mac_address || '-'}</td>
  9135. <td class="py-2.5 px-3">
  9136. <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>
  9137. </td>
  9138. <td class="py-2.5 px-3 text-center">
  9139. ${b.vlan_filtering ? '<span class="text-emerald-400 font-bold">yes</span>' : '<span class="text-slate-500">no</span>'}
  9140. </td>
  9141. <td class="py-2.5 px-3 font-mono">${b.pvid || 1}</td>
  9142. <td class="py-2.5 px-3">
  9143. <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>
  9144. </td>
  9145. <td class="py-2.5 px-3">
  9146. <div class="flex items-center gap-1.5 flex-wrap">
  9147. ${ipsHtml}
  9148. <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>
  9149. </div>
  9150. </td>
  9151. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  9152. <span class="text-emerald-400">↓ ${b.rx_human || '0 B'}</span> / <span class="text-cyan-400">↑ ${b.tx_human || '0 B'}</span>
  9153. </td>
  9154. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${b.comment || ''}">${b.comment || '-'}</td>
  9155. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  9156. <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>
  9157. <button onclick="openEditBridgeModal('${b.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  9158. <button onclick="deleteBridge('${b.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  9159. </td>
  9160. `;
  9161. tbody.appendChild(tr);
  9162. });
  9163. }
  9164. function openAddBridgeModal() {
  9165. document.getElementById('bridge-modal-title').innerText = 'Add Bridge Interface';
  9166. document.getElementById('bridge-modal-id').value = '';
  9167. document.getElementById('bridge-modal-name').value = 'bridge1';
  9168. document.getElementById('bridge-modal-name').disabled = false;
  9169. document.getElementById('bridge-modal-mtu').value = '1500';
  9170. document.getElementById('bridge-modal-mac').value = '';
  9171. document.getElementById('bridge-modal-stp').value = 'rstp';
  9172. document.getElementById('bridge-modal-priority').value = '32768';
  9173. document.getElementById('bridge-modal-vlanfiltering').checked = false;
  9174. document.getElementById('bridge-modal-pvid').value = '1';
  9175. document.getElementById('bridge-modal-fastforward').checked = true;
  9176. document.getElementById('bridge-modal-comment').value = '';
  9177. document.getElementById('bridge-modal-disabled').checked = false;
  9178. toggleBridgeModalVlanFiltering();
  9179. document.getElementById('bridge-modal').classList.remove('hidden');
  9180. }
  9181. function openEditBridgeModal(id) {
  9182. const b = (state.bridges || []).find(x => x.id === id);
  9183. if (!b) return;
  9184. document.getElementById('bridge-modal-title').innerText = `Edit Bridge (${b.name})`;
  9185. document.getElementById('bridge-modal-id').value = b.id;
  9186. document.getElementById('bridge-modal-name').value = b.name;
  9187. document.getElementById('bridge-modal-name').disabled = true;
  9188. document.getElementById('bridge-modal-mtu').value = b.mtu || 1500;
  9189. document.getElementById('bridge-modal-mac').value = b.mac_address || '';
  9190. document.getElementById('bridge-modal-stp').value = b.stp || 'rstp';
  9191. document.getElementById('bridge-modal-priority').value = b.priority || 32768;
  9192. document.getElementById('bridge-modal-vlanfiltering').checked = !!b.vlan_filtering;
  9193. document.getElementById('bridge-modal-pvid').value = b.pvid || 1;
  9194. document.getElementById('bridge-modal-fastforward').checked = b.fast_forward !== false;
  9195. document.getElementById('bridge-modal-comment').value = b.comment || '';
  9196. document.getElementById('bridge-modal-disabled').checked = !!b.disabled;
  9197. toggleBridgeModalVlanFiltering();
  9198. document.getElementById('bridge-modal').classList.remove('hidden');
  9199. }
  9200. function closeBridgeModal() {
  9201. document.getElementById('bridge-modal').classList.add('hidden');
  9202. }
  9203. function toggleBridgeModalVlanFiltering() {
  9204. const chk = document.getElementById('bridge-modal-vlanfiltering').checked;
  9205. const pvidBox = document.getElementById('bridge-modal-pvid-box');
  9206. if (pvidBox) {
  9207. if (chk) pvidBox.classList.remove('opacity-40');
  9208. else pvidBox.classList.add('opacity-40');
  9209. }
  9210. }
  9211. async function submitSaveBridge(e) {
  9212. e.preventDefault();
  9213. const id = document.getElementById('bridge-modal-id').value;
  9214. const name = document.getElementById('bridge-modal-name').value.trim();
  9215. const mtu = parseInt(document.getElementById('bridge-modal-mtu').value, 10) || 1500;
  9216. const mac = document.getElementById('bridge-modal-mac').value.trim();
  9217. const stp = document.getElementById('bridge-modal-stp').value;
  9218. const priority = parseInt(document.getElementById('bridge-modal-priority').value, 10) || 32768;
  9219. const vlanFiltering = document.getElementById('bridge-modal-vlanfiltering').checked;
  9220. const pvid = parseInt(document.getElementById('bridge-modal-pvid').value, 10) || 1;
  9221. const fastForward = document.getElementById('bridge-modal-fastforward').checked;
  9222. const comment = document.getElementById('bridge-modal-comment').value.trim();
  9223. const disabled = document.getElementById('bridge-modal-disabled').checked;
  9224. try {
  9225. const res = await fetch(`${API_BASE}/bridge/bridges`, {
  9226. method: 'POST',
  9227. headers: { 'Content-Type': 'application/json' },
  9228. body: JSON.stringify({
  9229. id,
  9230. name,
  9231. mtu,
  9232. mac_address: mac,
  9233. stp,
  9234. priority,
  9235. vlan_filtering: vlanFiltering,
  9236. pvid,
  9237. fast_forward: fastForward,
  9238. comment,
  9239. disabled
  9240. })
  9241. });
  9242. if (res.ok) {
  9243. showToast('Bridge Saved', `Bridge ${name} configured`, 'success');
  9244. closeBridgeModal();
  9245. loadBridge();
  9246. fetchData(false);
  9247. } else {
  9248. const err = await res.json();
  9249. showToast('Error', err.error || err.message || 'Failed to save bridge', 'error');
  9250. }
  9251. } catch (err) {
  9252. showToast('Error', err.message, 'error');
  9253. }
  9254. }
  9255. async function toggleBridgeState(id, disabled) {
  9256. try {
  9257. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/state`, {
  9258. method: 'POST',
  9259. headers: { 'Content-Type': 'application/json' },
  9260. body: JSON.stringify({ disabled })
  9261. });
  9262. if (res.ok) {
  9263. loadBridge();
  9264. fetchData(false);
  9265. }
  9266. } catch (err) {
  9267. showToast('Error', err.message, 'error');
  9268. }
  9269. }
  9270. async function deleteBridge(id) {
  9271. const b = (state.bridges || []).find(x => x.id === id);
  9272. const name = b ? b.name : id;
  9273. if (!confirm(`Are you sure you want to delete bridge '${name}'? All member ports will be detached.`)) return;
  9274. try {
  9275. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9276. if (res.ok) {
  9277. showToast('Deleted', `Bridge ${name} deleted`, 'success');
  9278. loadBridge();
  9279. fetchData(false);
  9280. } else {
  9281. const err = await res.json();
  9282. showToast('Error', err.error || err.message || 'Failed to delete bridge', 'error');
  9283. }
  9284. } catch (err) {
  9285. showToast('Error', err.message, 'error');
  9286. }
  9287. }
  9288. // ----------------- Bridge IP Assignments -----------------
  9289. function openAddBridgeIPModal(id, name) {
  9290. document.getElementById('bridge-ip-modal-id').value = id;
  9291. document.getElementById('bridge-ip-modal-sub').innerText = name;
  9292. document.getElementById('bridge-ip-modal-cidr').value = '';
  9293. document.getElementById('bridge-ip-modal').classList.remove('hidden');
  9294. }
  9295. function closeBridgeIPModal() {
  9296. document.getElementById('bridge-ip-modal').classList.add('hidden');
  9297. }
  9298. async function submitAddBridgeIP(e) {
  9299. e.preventDefault();
  9300. const id = document.getElementById('bridge-ip-modal-id').value;
  9301. const ip = document.getElementById('bridge-ip-modal-cidr').value.trim();
  9302. try {
  9303. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  9304. method: 'POST',
  9305. headers: { 'Content-Type': 'application/json' },
  9306. body: JSON.stringify({ ip })
  9307. });
  9308. if (res.ok) {
  9309. showToast('IP Assigned', `${ip} assigned to bridge`, 'success');
  9310. closeBridgeIPModal();
  9311. loadBridge();
  9312. fetchData(false);
  9313. } else {
  9314. const err = await res.json();
  9315. showToast('Error', err.error || err.message || 'Failed to add IP', 'error');
  9316. }
  9317. } catch (err) {
  9318. showToast('Error', err.message, 'error');
  9319. }
  9320. }
  9321. async function deleteBridgeIP(id, ip) {
  9322. if (!confirm(`Remove IP address ${ip} from bridge?`)) return;
  9323. try {
  9324. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  9325. method: 'DELETE',
  9326. headers: { 'Content-Type': 'application/json' },
  9327. body: JSON.stringify({ ip })
  9328. });
  9329. if (res.ok) {
  9330. showToast('IP Removed', `${ip} removed from bridge`, 'success');
  9331. loadBridge();
  9332. fetchData(false);
  9333. }
  9334. } catch (err) {
  9335. showToast('Error', err.message, 'error');
  9336. }
  9337. }
  9338. // ----------------- Bridge Ports -----------------
  9339. function renderBridgePorts() {
  9340. const tbody = document.getElementById('bridge-ports-table-body');
  9341. const empty = document.getElementById('bridge-empty-ports');
  9342. const countBadge = document.getElementById('bridge-ports-count-badge');
  9343. const filterBridge = document.getElementById('bridge-ports-filter-bridge')?.value || '';
  9344. if (!tbody) return;
  9345. tbody.innerHTML = '';
  9346. // Update filter select
  9347. populateBridgeSelect('bridge-ports-filter-bridge', filterBridge, true);
  9348. const ports = (state.bridgePorts || []).filter(p => !filterBridge || p.bridge === filterBridge);
  9349. if (countBadge) countBadge.innerText = `${ports.length} Ports`;
  9350. if (ports.length === 0) {
  9351. empty?.classList.remove('hidden');
  9352. return;
  9353. }
  9354. empty?.classList.add('hidden');
  9355. ports.forEach((p, idx) => {
  9356. const tr = document.createElement('tr');
  9357. tr.className = `hover:bg-slate-800/40 transition text-xs ${p.disabled ? 'opacity-50' : ''}`;
  9358. const disabledFlag = p.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  9359. tr.innerHTML = `
  9360. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  9361. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  9362. <td class="py-2.5 px-3 font-bold text-white text-sm">
  9363. <span class="text-emerald-400 mr-1.5">🔌</span>${p.interface}
  9364. </td>
  9365. <td class="py-2.5 px-3 font-semibold text-sky-400">${p.bridge}</td>
  9366. <td class="py-2.5 px-3 font-mono">${p.pvid || 1}</td>
  9367. <td class="py-2.5 px-3 text-slate-300">${p.frame_types}</td>
  9368. <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>
  9369. <td class="py-2.5 px-3">
  9370. ${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>'}
  9371. </td>
  9372. <td class="py-2.5 px-3">
  9373. <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>
  9374. </td>
  9375. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${p.comment || ''}">${p.comment || '-'}</td>
  9376. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  9377. <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>
  9378. <button onclick="openEditBridgePortModal('${p.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  9379. <button onclick="deleteBridgePort('${p.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  9380. </td>
  9381. `;
  9382. tbody.appendChild(tr);
  9383. });
  9384. }
  9385. function openAddBridgePortModal() {
  9386. document.getElementById('bridge-port-modal-title').innerText = 'Add Port to Bridge';
  9387. document.getElementById('bridge-port-modal-id').value = '';
  9388. populateBridgeSelect('bridge-port-modal-bridge');
  9389. populateBridgePortCandidateSelect('bridge-port-modal-interface');
  9390. document.getElementById('bridge-port-modal-pvid').value = '1';
  9391. document.getElementById('bridge-port-modal-frametypes').value = 'admit-all';
  9392. document.getElementById('bridge-port-modal-ingressfiltering').checked = false;
  9393. document.getElementById('bridge-port-modal-horizon').value = '0';
  9394. document.getElementById('bridge-port-modal-pathcost').value = '10';
  9395. document.getElementById('bridge-port-modal-priority').value = '128';
  9396. document.getElementById('bridge-port-modal-learn').checked = true;
  9397. document.getElementById('bridge-port-modal-comment').value = '';
  9398. document.getElementById('bridge-port-modal-disabled').checked = false;
  9399. document.getElementById('bridge-port-modal').classList.remove('hidden');
  9400. }
  9401. function openEditBridgePortModal(id) {
  9402. const p = (state.bridgePorts || []).find(x => x.id === id);
  9403. if (!p) return;
  9404. document.getElementById('bridge-port-modal-title').innerText = `Edit Bridge Port (${p.interface})`;
  9405. document.getElementById('bridge-port-modal-id').value = p.id;
  9406. populateBridgeSelect('bridge-port-modal-bridge', p.bridge);
  9407. populateBridgePortCandidateSelect('bridge-port-modal-interface', p.interface);
  9408. document.getElementById('bridge-port-modal-pvid').value = p.pvid || 1;
  9409. document.getElementById('bridge-port-modal-frametypes').value = p.frame_types || 'admit-all';
  9410. document.getElementById('bridge-port-modal-ingressfiltering').checked = !!p.ingress_filtering;
  9411. document.getElementById('bridge-port-modal-horizon').value = p.horizon || 0;
  9412. document.getElementById('bridge-port-modal-pathcost').value = p.path_cost || 10;
  9413. document.getElementById('bridge-port-modal-priority').value = p.priority || 128;
  9414. document.getElementById('bridge-port-modal-learn').checked = p.learn !== false;
  9415. document.getElementById('bridge-port-modal-comment').value = p.comment || '';
  9416. document.getElementById('bridge-port-modal-disabled').checked = !!p.disabled;
  9417. document.getElementById('bridge-port-modal').classList.remove('hidden');
  9418. }
  9419. function closeBridgePortModal() {
  9420. document.getElementById('bridge-port-modal').classList.add('hidden');
  9421. }
  9422. async function submitSaveBridgePort(e) {
  9423. e.preventDefault();
  9424. const id = document.getElementById('bridge-port-modal-id').value;
  9425. const bridge = document.getElementById('bridge-port-modal-bridge').value;
  9426. const iface = document.getElementById('bridge-port-modal-interface').value;
  9427. const pvid = parseInt(document.getElementById('bridge-port-modal-pvid').value, 10) || 1;
  9428. const frameTypes = document.getElementById('bridge-port-modal-frametypes').value;
  9429. const ingressFiltering = document.getElementById('bridge-port-modal-ingressfiltering').checked;
  9430. const horizon = parseInt(document.getElementById('bridge-port-modal-horizon').value, 10) || 0;
  9431. const pathCost = parseInt(document.getElementById('bridge-port-modal-pathcost').value, 10) || 10;
  9432. const priority = parseInt(document.getElementById('bridge-port-modal-priority').value, 10) || 128;
  9433. const learn = document.getElementById('bridge-port-modal-learn').checked;
  9434. const comment = document.getElementById('bridge-port-modal-comment').value.trim();
  9435. const disabled = document.getElementById('bridge-port-modal-disabled').checked;
  9436. try {
  9437. const res = await fetch(`${API_BASE}/bridge/ports`, {
  9438. method: 'POST',
  9439. headers: { 'Content-Type': 'application/json' },
  9440. body: JSON.stringify({
  9441. id,
  9442. bridge,
  9443. interface: iface,
  9444. pvid,
  9445. frame_types: frameTypes,
  9446. ingress_filtering: ingressFiltering,
  9447. horizon,
  9448. path_cost: pathCost,
  9449. priority,
  9450. learn,
  9451. comment,
  9452. disabled
  9453. })
  9454. });
  9455. if (res.ok) {
  9456. showToast('Port Attached', `${iface} added to ${bridge}`, 'success');
  9457. closeBridgePortModal();
  9458. loadBridge();
  9459. fetchData(false);
  9460. } else {
  9461. const err = await res.json();
  9462. showToast('Error', err.error || err.message || 'Failed to save port', 'error');
  9463. }
  9464. } catch (err) {
  9465. showToast('Error', err.message, 'error');
  9466. }
  9467. }
  9468. async function toggleBridgePortState(id, disabled) {
  9469. try {
  9470. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}/state`, {
  9471. method: 'POST',
  9472. headers: { 'Content-Type': 'application/json' },
  9473. body: JSON.stringify({ disabled })
  9474. });
  9475. if (res.ok) {
  9476. loadBridge();
  9477. fetchData(false);
  9478. }
  9479. } catch (err) {
  9480. showToast('Error', err.message, 'error');
  9481. }
  9482. }
  9483. async function deleteBridgePort(id) {
  9484. const p = (state.bridgePorts || []).find(x => x.id === id);
  9485. const iface = p ? p.interface : id;
  9486. if (!confirm(`Detach interface '${iface}' from bridge?`)) return;
  9487. try {
  9488. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9489. if (res.ok) {
  9490. showToast('Port Detached', `${iface} removed from bridge`, 'success');
  9491. loadBridge();
  9492. fetchData(false);
  9493. }
  9494. } catch (err) {
  9495. showToast('Error', err.message, 'error');
  9496. }
  9497. }
  9498. // ----------------- Bridge VLANs -----------------
  9499. function renderBridgeVLANs() {
  9500. const tbody = document.getElementById('bridge-vlans-table-body');
  9501. const empty = document.getElementById('bridge-empty-vlans');
  9502. const countBadge = document.getElementById('bridge-vlans-count-badge');
  9503. const filterBridge = document.getElementById('bridge-vlans-filter-bridge')?.value || '';
  9504. if (!tbody) return;
  9505. tbody.innerHTML = '';
  9506. populateBridgeSelect('bridge-vlans-filter-bridge', filterBridge, true);
  9507. const vlans = (state.bridgeVLANs || []).filter(v => !filterBridge || v.bridge === filterBridge);
  9508. if (countBadge) countBadge.innerText = `${vlans.length} Entries`;
  9509. if (vlans.length === 0) {
  9510. empty?.classList.remove('hidden');
  9511. return;
  9512. }
  9513. empty?.classList.add('hidden');
  9514. vlans.forEach((v, idx) => {
  9515. const tr = document.createElement('tr');
  9516. tr.className = `hover:bg-slate-800/40 transition text-xs ${v.disabled ? 'opacity-50' : ''}`;
  9517. const taggedHtml = (v.tagged && v.tagged.length > 0)
  9518. ? 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(' ')
  9519. : '<span class="text-slate-600">none</span>';
  9520. const untaggedHtml = (v.untagged && v.untagged.length > 0)
  9521. ? 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(' ')
  9522. : '<span class="text-slate-600">none</span>';
  9523. const disabledFlag = v.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  9524. tr.innerHTML = `
  9525. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  9526. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  9527. <td class="py-2.5 px-3 font-semibold text-sky-400">${v.bridge}</td>
  9528. <td class="py-2.5 px-3 font-bold text-white font-mono text-sm">${v.vlan_ids}</td>
  9529. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${taggedHtml}</div></td>
  9530. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${untaggedHtml}</div></td>
  9531. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${v.comment || ''}">${v.comment || '-'}</td>
  9532. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  9533. <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>
  9534. <button onclick="openEditBridgeVLANModal('${v.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  9535. <button onclick="deleteBridgeVLAN('${v.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  9536. </td>
  9537. `;
  9538. tbody.appendChild(tr);
  9539. });
  9540. }
  9541. function openAddBridgeVLANModal() {
  9542. document.getElementById('bridge-vlan-modal-title').innerText = 'Add Bridge VLAN Entry';
  9543. document.getElementById('bridge-vlan-modal-id').value = '';
  9544. populateBridgeSelect('bridge-vlan-modal-bridge');
  9545. document.getElementById('bridge-vlan-modal-vlanids').value = '';
  9546. document.getElementById('bridge-vlan-modal-comment').value = '';
  9547. document.getElementById('bridge-vlan-modal-disabled').checked = false;
  9548. updateBridgeVlanPortCheckboxes();
  9549. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  9550. }
  9551. function openEditBridgeVLANModal(id) {
  9552. const v = (state.bridgeVLANs || []).find(x => x.id === id);
  9553. if (!v) return;
  9554. document.getElementById('bridge-vlan-modal-title').innerText = `Edit Bridge VLAN (${v.vlan_ids})`;
  9555. document.getElementById('bridge-vlan-modal-id').value = v.id;
  9556. populateBridgeSelect('bridge-vlan-modal-bridge', v.bridge);
  9557. document.getElementById('bridge-vlan-modal-vlanids').value = v.vlan_ids;
  9558. document.getElementById('bridge-vlan-modal-comment').value = v.comment || '';
  9559. document.getElementById('bridge-vlan-modal-disabled').checked = !!v.disabled;
  9560. updateBridgeVlanPortCheckboxes(v.tagged || [], v.untagged || []);
  9561. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  9562. }
  9563. function closeBridgeVlanModal() {
  9564. document.getElementById('bridge-vlan-modal').classList.add('hidden');
  9565. }
  9566. function updateBridgeVlanPortCheckboxes(taggedSelected = [], untaggedSelected = []) {
  9567. const selBridge = document.getElementById('bridge-vlan-modal-bridge')?.value || '';
  9568. const taggedBox = document.getElementById('bridge-vlan-tagged-ports');
  9569. const untaggedBox = document.getElementById('bridge-vlan-untagged-ports');
  9570. if (!taggedBox || !untaggedBox) return;
  9571. // Ports belonging to the selected bridge
  9572. const memberPorts = (state.bridgePorts || []).filter(p => !selBridge || p.bridge === selBridge);
  9573. if (memberPorts.length === 0) {
  9574. taggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  9575. untaggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  9576. return;
  9577. }
  9578. taggedBox.innerHTML = memberPorts.map(p => `
  9579. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  9580. <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">
  9581. <span>${p.interface}</span>
  9582. </label>
  9583. `).join('');
  9584. untaggedBox.innerHTML = memberPorts.map(p => `
  9585. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  9586. <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">
  9587. <span>${p.interface}</span>
  9588. </label>
  9589. `).join('');
  9590. }
  9591. async function submitSaveBridgeVLAN(e) {
  9592. e.preventDefault();
  9593. const id = document.getElementById('bridge-vlan-modal-id').value;
  9594. const bridge = document.getElementById('bridge-vlan-modal-bridge').value;
  9595. const vlanIDs = document.getElementById('bridge-vlan-modal-vlanids').value.trim();
  9596. const comment = document.getElementById('bridge-vlan-modal-comment').value.trim();
  9597. const disabled = document.getElementById('bridge-vlan-modal-disabled').checked;
  9598. const tagged = Array.from(document.querySelectorAll('input[name="bvlan-tagged"]:checked')).map(x => x.value);
  9599. const untagged = Array.from(document.querySelectorAll('input[name="bvlan-untagged"]:checked')).map(x => x.value);
  9600. try {
  9601. const res = await fetch(`${API_BASE}/bridge/vlans`, {
  9602. method: 'POST',
  9603. headers: { 'Content-Type': 'application/json' },
  9604. body: JSON.stringify({
  9605. id,
  9606. bridge,
  9607. vlan_ids: vlanIDs,
  9608. tagged,
  9609. untagged,
  9610. comment,
  9611. disabled
  9612. })
  9613. });
  9614. if (res.ok) {
  9615. showToast('VLAN Entry Saved', `VLAN ${vlanIDs} configured on ${bridge}`, 'success');
  9616. closeBridgeVlanModal();
  9617. loadBridge();
  9618. } else {
  9619. const err = await res.json();
  9620. showToast('Error', err.error || err.message || 'Failed to save VLAN entry', 'error');
  9621. }
  9622. } catch (err) {
  9623. showToast('Error', err.message, 'error');
  9624. }
  9625. }
  9626. async function toggleBridgeVLANState(id, disabled) {
  9627. try {
  9628. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}/state`, {
  9629. method: 'POST',
  9630. headers: { 'Content-Type': 'application/json' },
  9631. body: JSON.stringify({ disabled })
  9632. });
  9633. if (res.ok) loadBridge();
  9634. } catch (err) {
  9635. showToast('Error', err.message, 'error');
  9636. }
  9637. }
  9638. async function deleteBridgeVLAN(id) {
  9639. if (!confirm('Delete this bridge VLAN entry?')) return;
  9640. try {
  9641. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9642. if (res.ok) {
  9643. showToast('Deleted', 'VLAN entry removed from bridge', 'success');
  9644. loadBridge();
  9645. }
  9646. } catch (err) {
  9647. showToast('Error', err.message, 'error');
  9648. }
  9649. }
  9650. // ----------------- Hosts / MAC Table -----------------
  9651. async function loadBridgeHosts() {
  9652. const filterBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || '';
  9653. populateBridgeSelect('bridge-hosts-filter-bridge', filterBridge, true);
  9654. try {
  9655. const url = filterBridge ? `${API_BASE}/bridge/hosts?bridge=${encodeURIComponent(filterBridge)}` : `${API_BASE}/bridge/hosts`;
  9656. const res = await fetch(url);
  9657. if (res.ok) {
  9658. state.bridgeHosts = await res.json();
  9659. renderBridgeHosts();
  9660. }
  9661. } catch (err) {
  9662. console.error('Failed to load bridge hosts:', err);
  9663. }
  9664. }
  9665. function renderBridgeHosts() {
  9666. const tbody = document.getElementById('bridge-hosts-table-body');
  9667. const empty = document.getElementById('bridge-empty-hosts');
  9668. const countBadge = document.getElementById('bridge-hosts-count-badge');
  9669. const search = (document.getElementById('bridge-hosts-search')?.value || '').toLowerCase().trim();
  9670. if (!tbody) return;
  9671. tbody.innerHTML = '';
  9672. const hosts = (state.bridgeHosts || []).filter(h => {
  9673. if (!search) return true;
  9674. return (h.mac || '').toLowerCase().includes(search) || (h.interface || '').toLowerCase().includes(search) || (h.bridge || '').toLowerCase().includes(search);
  9675. });
  9676. if (countBadge) countBadge.innerText = `${hosts.length} Hosts`;
  9677. if (hosts.length === 0) {
  9678. empty?.classList.remove('hidden');
  9679. return;
  9680. }
  9681. empty?.classList.add('hidden');
  9682. hosts.forEach(h => {
  9683. const tr = document.createElement('tr');
  9684. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  9685. let flagBadges = '';
  9686. 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>';
  9687. 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>';
  9688. 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>';
  9689. tr.innerHTML = `
  9690. <td class="py-2.5 px-3 font-mono font-bold text-white text-sm">${h.mac}</td>
  9691. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${h.interface || '-'}</td>
  9692. <td class="py-2.5 px-3 font-mono text-sky-400">${h.bridge || '-'}</td>
  9693. <td class="py-2.5 px-3 font-mono">${h.vlan_id || 1}</td>
  9694. <td class="py-2.5 px-3 font-mono text-slate-400">${h.age ? h.age.toFixed(1) + 's' : '-'}</td>
  9695. <td class="py-2.5 px-3">${flagBadges}</td>
  9696. `;
  9697. tbody.appendChild(tr);
  9698. });
  9699. }
  9700. async function flushBridgeHosts() {
  9701. const selBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || (state.bridges[0] ? state.bridges[0].name : '');
  9702. if (!selBridge) {
  9703. showToast('Notice', 'Please select a bridge to flush dynamic MACs', 'info');
  9704. return;
  9705. }
  9706. if (!confirm(`Flush all dynamic learned MAC addresses on bridge '${selBridge}'?`)) return;
  9707. try {
  9708. const res = await fetch(`${API_BASE}/bridge/hosts/flush`, {
  9709. method: 'POST',
  9710. headers: { 'Content-Type': 'application/json' },
  9711. body: JSON.stringify({ bridge: selBridge })
  9712. });
  9713. if (res.ok) {
  9714. showToast('FDB Flushed', `Dynamic MACs flushed on ${selBridge}`, 'success');
  9715. loadBridgeHosts();
  9716. }
  9717. } catch (err) {
  9718. showToast('Error', err.message, 'error');
  9719. }
  9720. }
  9721. // ----------------- Helpers -----------------
  9722. function populateBridgeSelect(selectId, currentVal = '', includeAll = false) {
  9723. const sel = document.getElementById(selectId);
  9724. if (!sel) return;
  9725. const prevVal = currentVal || sel.value;
  9726. sel.innerHTML = includeAll ? '<option value="">All Bridges</option>' : '';
  9727. (state.bridges || []).forEach(b => {
  9728. const opt = document.createElement('option');
  9729. opt.value = b.name;
  9730. opt.innerText = `${b.name} (${b.ports_count} ports)`;
  9731. if (b.name === prevVal) opt.selected = true;
  9732. sel.appendChild(opt);
  9733. });
  9734. }
  9735. function populateBridgePortCandidateSelect(selectId, currentVal = '') {
  9736. const sel = document.getElementById(selectId);
  9737. if (!sel) return;
  9738. sel.innerHTML = '<option value="">(Select Interface...)</option>';
  9739. // 1. Physical Interfaces
  9740. const grpPhys = document.createElement('optgroup');
  9741. grpPhys.label = 'Physical Interfaces';
  9742. (state.interfaces || []).filter(i => i.type !== 'bridge' && i.type !== 'vlan' && i.type !== 'loopback').forEach(i => {
  9743. const opt = document.createElement('option');
  9744. opt.value = i.name;
  9745. opt.innerText = `${i.name} (${i.role || i.type})`;
  9746. if (i.name === currentVal) opt.selected = true;
  9747. grpPhys.appendChild(opt);
  9748. });
  9749. if (grpPhys.children.length > 0) sel.appendChild(grpPhys);
  9750. // 2. VLAN Sub-interfaces
  9751. const grpVlans = document.createElement('optgroup');
  9752. grpVlans.label = 'VLAN Sub-interfaces (802.1Q)';
  9753. (state.vlans || []).forEach(v => {
  9754. const opt = document.createElement('option');
  9755. opt.value = v.name;
  9756. opt.innerText = `${v.name} (VLAN ${v.vlan_id})`;
  9757. if (v.name === currentVal) opt.selected = true;
  9758. grpVlans.appendChild(opt);
  9759. });
  9760. if (grpVlans.children.length > 0) sel.appendChild(grpVlans);
  9761. // 3. EoIP Tunnels (MikroTik EoIP bridging!)
  9762. const grpEoip = document.createElement('optgroup');
  9763. grpEoip.label = 'EoIP Tunnels (Layer 2 VPN)';
  9764. (state.eoipTunnels || []).forEach(t => {
  9765. const opt = document.createElement('option');
  9766. opt.value = t.name;
  9767. opt.innerText = `${t.name} (Tunnel ID: ${t.tunnel_id} -> ${t.remote_address})`;
  9768. if (t.name === currentVal) opt.selected = true;
  9769. grpEoip.appendChild(opt);
  9770. });
  9771. if (grpEoip.children.length > 0) sel.appendChild(grpEoip);
  9772. }
  9773. // -------------------------------------------------------------
  9774. // RouterOS v7 Routing Filters Management (/routing filter)
  9775. // -------------------------------------------------------------
  9776. if (!state.activeRoutingFilterTab) state.activeRoutingFilterTab = 'rules';
  9777. if (!state.selectedFilterRow) state.selectedFilterRow = {};
  9778. if (!state.rfSort) state.rfSort = {};
  9779. function switchRoutingFilterTab(tab) {
  9780. state.activeRoutingFilterTab = tab;
  9781. const tabs = ['rules', 'select-rules', 'community-lists', 'as-lists'];
  9782. tabs.forEach(t => {
  9783. const btn = document.getElementById(`tab-rf-${t}`);
  9784. const content = document.getElementById(`tab-content-rf-${t}`);
  9785. if (btn) {
  9786. if (t === tab) {
  9787. btn.className = 'px-3 py-1 text-xs font-semibold rounded bg-emerald-600/20 text-emerald-300 border border-emerald-500/30 transition shadow-sm';
  9788. } else {
  9789. btn.className = 'px-3 py-1 text-xs font-semibold rounded text-slate-400 hover:text-white hover:bg-slate-800 transition';
  9790. }
  9791. }
  9792. if (content) {
  9793. if (t === tab) content.classList.remove('hidden');
  9794. else content.classList.add('hidden');
  9795. }
  9796. });
  9797. const chainContainer = document.getElementById('rf-chain-filter-container');
  9798. if (chainContainer) {
  9799. if (tab === 'rules' || tab === 'select-rules') chainContainer.classList.remove('hidden');
  9800. else chainContainer.classList.add('hidden');
  9801. }
  9802. renderRoutingFilters();
  9803. }
  9804. function selectFilterRow(tab, id) {
  9805. if (state.selectedFilterRow[tab] === id) {
  9806. delete state.selectedFilterRow[tab];
  9807. } else {
  9808. state.selectedFilterRow[tab] = id;
  9809. }
  9810. if (tab === 'rules') renderRoutingFilterRules();
  9811. else if (tab === 'select-rules') renderRoutingFilterSelectRules();
  9812. else if (tab === 'community-lists') renderRoutingFilterCommunityLists();
  9813. else if (tab === 'as-lists') renderRoutingFilterASLists();
  9814. }
  9815. function openRoutingFilterNewModal() {
  9816. const tab = state.activeRoutingFilterTab || 'rules';
  9817. if (tab === 'rules') openAddRoutingFilterModal();
  9818. else if (tab === 'select-rules') openAddSelectRuleModal();
  9819. else if (tab === 'community-lists') openAddCommunityListModal();
  9820. else if (tab === 'as-lists') openAddASListModal();
  9821. }
  9822. function toggleSelectedRoutingFilter(disabled) {
  9823. const tab = state.activeRoutingFilterTab || 'rules';
  9824. const id = state.selectedFilterRow[tab];
  9825. if (!id) {
  9826. showToast('Select Row', 'Please click on a row to select it first', 'info');
  9827. return;
  9828. }
  9829. if (tab === 'rules') toggleRoutingFilterState(id, disabled);
  9830. else if (tab === 'select-rules') toggleSelectRuleState(id, disabled);
  9831. else if (tab === 'community-lists') toggleCommunityListState(id, disabled);
  9832. else if (tab === 'as-lists') toggleASListState(id, disabled);
  9833. }
  9834. function removeSelectedRoutingFilter() {
  9835. const tab = state.activeRoutingFilterTab || 'rules';
  9836. const id = state.selectedFilterRow[tab];
  9837. if (!id) {
  9838. showToast('Select Row', 'Please click on a row to select it first', 'info');
  9839. return;
  9840. }
  9841. if (tab === 'rules') deleteRoutingFilter(id);
  9842. else if (tab === 'select-rules') deleteSelectRule(id);
  9843. else if (tab === 'community-lists') deleteCommunityList(id);
  9844. else if (tab === 'as-lists') deleteASList(id);
  9845. }
  9846. function searchRoutingFilters(q) {
  9847. state.rfSearchQuery = (q || '').trim().toLowerCase();
  9848. renderRoutingFilters();
  9849. }
  9850. function sortFilterTable(tab, col) {
  9851. if (!state.rfSort) state.rfSort = {};
  9852. if (!state.rfSort[tab]) state.rfSort[tab] = { col: col, asc: true };
  9853. if (state.rfSort[tab].col === col) {
  9854. state.rfSort[tab].asc = !state.rfSort[tab].asc;
  9855. } else {
  9856. state.rfSort[tab].col = col;
  9857. state.rfSort[tab].asc = true;
  9858. }
  9859. const asc = state.rfSort[tab].asc;
  9860. let list = [];
  9861. if (tab === 'rules') list = state.routingFilters || [];
  9862. else if (tab === 'select-rules') list = state.routingSelectRules || [];
  9863. else if (tab === 'community-lists') list = state.routingCommunityLists || [];
  9864. else if (tab === 'as-lists') list = state.routingASLists || [];
  9865. list.sort((a, b) => {
  9866. let valA = a[col] ?? '';
  9867. let valB = b[col] ?? '';
  9868. if (col === 'flags') {
  9869. valA = a.disabled ? 'X' : 'A';
  9870. valB = b.disabled ? 'X' : 'A';
  9871. }
  9872. if (typeof valA === 'number' && typeof valB === 'number') {
  9873. return asc ? valA - valB : valB - valA;
  9874. }
  9875. return asc ? String(valA).localeCompare(String(valB)) : String(valB).localeCompare(String(valA));
  9876. });
  9877. const allCols = ['flags', 'rule_order', 'chain', 'rule', 'name', 'communities', 'range', 'regexp', 'comment'];
  9878. allCols.forEach(c => {
  9879. const el = document.getElementById(`sort-icon-${tab}-${c}`);
  9880. if (el) el.innerText = (c === col) ? (asc ? '▲' : '▼') : '';
  9881. });
  9882. if (tab === 'rules') renderRoutingFilterRules();
  9883. else if (tab === 'select-rules') renderRoutingFilterSelectRules();
  9884. else if (tab === 'community-lists') renderRoutingFilterCommunityLists();
  9885. else if (tab === 'as-lists') renderRoutingFilterASLists();
  9886. }
  9887. function renderRoutingFilters() {
  9888. const navBadge = document.getElementById('badge-filters-count');
  9889. const allRules = state.routingFilters || [];
  9890. if (navBadge) navBadge.innerText = allRules.length;
  9891. // Populate chain filter select options and datalist
  9892. const chainSelect = document.getElementById('routing-filter-chain-select');
  9893. const chainDatalist = document.getElementById('dl-routing-chains');
  9894. const uniqueChains = Array.from(new Set(allRules.map(r => r.chain).filter(Boolean))).sort();
  9895. if (chainSelect) {
  9896. const currentVal = state.filterChainSelected || 'all';
  9897. chainSelect.innerHTML = `<option value="all">All Chains (${allRules.length})</option>` +
  9898. uniqueChains.map(ch => {
  9899. const count = allRules.filter(r => r.chain === ch).length;
  9900. return `<option value="${escapeHtml(ch)}"${currentVal === ch ? ' selected' : ''}>${escapeHtml(ch)} (${count})</option>`;
  9901. }).join('');
  9902. chainSelect.value = currentVal;
  9903. }
  9904. if (chainDatalist) {
  9905. chainDatalist.innerHTML = uniqueChains.map(ch => `<option value="${escapeHtml(ch)}">`).join('');
  9906. }
  9907. renderRoutingFilterRules();
  9908. renderRoutingFilterSelectRules();
  9909. renderRoutingFilterCommunityLists();
  9910. renderRoutingFilterASLists();
  9911. }
  9912. function filterRoutingFiltersByChain(chain) {
  9913. state.filterChainSelected = chain;
  9914. renderRoutingFilters();
  9915. }
  9916. // -------------------------------------------------------------
  9917. // TAB 1: RULES (/routing filter rule)
  9918. // -------------------------------------------------------------
  9919. function renderRoutingFilterRules() {
  9920. const tbody = document.getElementById('routing-filter-rules-tbody');
  9921. if (!tbody) return;
  9922. const empty = document.getElementById('rf-rules-empty');
  9923. const statusCount = document.getElementById('rf-status-count');
  9924. let list = (state.routingFilters || []).slice();
  9925. if (state.filterChainSelected && state.filterChainSelected !== 'all') {
  9926. list = list.filter(r => r.chain === state.filterChainSelected);
  9927. }
  9928. const q = state.rfSearchQuery;
  9929. if (q) {
  9930. list = list.filter(r =>
  9931. (r.chain && r.chain.toLowerCase().includes(q)) ||
  9932. (r.rule && r.rule.toLowerCase().includes(q)) ||
  9933. (r.prefix && r.prefix.toLowerCase().includes(q)) ||
  9934. (r.comment && r.comment.toLowerCase().includes(q))
  9935. );
  9936. }
  9937. if (!state.rfSort?.['rules']) {
  9938. list.sort((a, b) => {
  9939. if (a.chain !== b.chain) return (a.chain || '').localeCompare(b.chain || '');
  9940. return (a.rule_order || 0) - (b.rule_order || 0);
  9941. });
  9942. }
  9943. if (statusCount && (state.activeRoutingFilterTab === 'rules' || !state.activeRoutingFilterTab)) {
  9944. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  9945. }
  9946. if (list.length === 0) {
  9947. tbody.innerHTML = '';
  9948. if (empty) empty.classList.remove('hidden');
  9949. return;
  9950. }
  9951. if (empty) empty.classList.add('hidden');
  9952. tbody.innerHTML = list.map(r => {
  9953. const isSelected = state.selectedFilterRow?.['rules'] === r.id;
  9954. const flagA = !r.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  9955. const flagX = r.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  9956. const flagC = r.comment ? '<span class="text-amber-400 font-bold ml-1" title="Comment">C</span>' : '';
  9957. let ruleDisplay = '';
  9958. if (r.rule && r.rule.trim() !== '') {
  9959. ruleDisplay = `<span class="text-emerald-400 font-mono font-medium">${escapeHtml(r.rule)}</span>`;
  9960. } else {
  9961. let conds = [];
  9962. if (r.prefix) conds.push(`dst in ${escapeHtml(r.prefix)}`);
  9963. if (r.match_protocol && r.match_protocol !== 'any') conds.push(`protocol ${escapeHtml(r.match_protocol)}`);
  9964. let act = r.action || 'accept';
  9965. ruleDisplay = `<span class="text-slate-300 font-mono">if (${conds.length ? conds.join(' && ') : 'true'}) { ${escapeHtml(act)}; }</span>`;
  9966. }
  9967. return `
  9968. <tr onclick="selectFilterRow('rules', '${r.id}')" class="cursor-pointer transition select-none ${isSelected ? 'bg-emerald-950/40 ring-1 ring-emerald-500/40' : 'hover:bg-slate-800/40'}">
  9969. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}${flagC}</td>
  9970. <td class="py-2 px-2 font-mono text-slate-400 font-bold">${r.rule_order || 10}</td>
  9971. <td class="py-2 px-3">
  9972. <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>
  9973. </td>
  9974. <td class="py-2 px-3 break-all max-w-xl">${ruleDisplay}</td>
  9975. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(r.comment || '')}</td>
  9976. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  9977. <button onclick="moveRoutingFilterOrder('${r.id}', -1)" title="Move Up" class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 hover:bg-slate-700 text-slate-300 border border-slate-700">▲</button>
  9978. <button onclick="moveRoutingFilterOrder('${r.id}', 1)" title="Move Down" class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 hover:bg-slate-700 text-slate-300 border border-slate-700">▼</button>
  9979. <button onclick="toggleRoutingFilterState('${r.id}', ${!r.disabled})" class="px-2 py-0.5 rounded text-[10px] ${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'}">
  9980. ${r.disabled ? 'Enable' : 'Disable'}
  9981. </button>
  9982. <button onclick="openEditRoutingFilterModal('${r.id}')" class="px-2 py-0.5 rounded text-[10px] bg-slate-800 hover:bg-slate-700 text-emerald-300 border border-slate-700">
  9983. Edit
  9984. </button>
  9985. <button onclick="deleteRoutingFilter('${r.id}')" class="px-2 py-0.5 rounded text-[10px] bg-rose-950/60 hover:bg-rose-900 text-rose-300 border border-rose-900/50">
  9986. ✕
  9987. </button>
  9988. </td>
  9989. </tr>
  9990. `;
  9991. }).join('');
  9992. }
  9993. // -------------------------------------------------------------
  9994. // TAB 2: SELECT RULES (/routing filter select-rule)
  9995. // -------------------------------------------------------------
  9996. function renderRoutingFilterSelectRules() {
  9997. const tbody = document.getElementById('routing-filter-select-rules-tbody');
  9998. if (!tbody) return;
  9999. const empty = document.getElementById('rf-select-rules-empty');
  10000. const statusCount = document.getElementById('rf-status-count');
  10001. let list = (state.routingSelectRules || []).slice();
  10002. if (state.filterChainSelected && state.filterChainSelected !== 'all') {
  10003. list = list.filter(r => r.chain === state.filterChainSelected);
  10004. }
  10005. const q = state.rfSearchQuery;
  10006. if (q) {
  10007. list = list.filter(r =>
  10008. (r.chain && r.chain.toLowerCase().includes(q)) ||
  10009. (r.rule && r.rule.toLowerCase().includes(q)) ||
  10010. (r.comment && r.comment.toLowerCase().includes(q))
  10011. );
  10012. }
  10013. if (statusCount && state.activeRoutingFilterTab === 'select-rules') {
  10014. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  10015. }
  10016. if (list.length === 0) {
  10017. tbody.innerHTML = '';
  10018. if (empty) empty.classList.remove('hidden');
  10019. return;
  10020. }
  10021. if (empty) empty.classList.add('hidden');
  10022. tbody.innerHTML = list.map(r => {
  10023. const isSelected = state.selectedFilterRow?.['select-rules'] === r.id;
  10024. const flagA = !r.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  10025. const flagX = r.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  10026. return `
  10027. <tr onclick="selectFilterRow('select-rules', '${r.id}')" class="cursor-pointer transition select-none ${isSelected ? 'bg-emerald-950/40 ring-1 ring-emerald-500/40' : 'hover:bg-slate-800/40'}">
  10028. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  10029. <td class="py-2 px-2 font-mono text-slate-400 font-bold">${r.rule_order || 10}</td>
  10030. <td class="py-2 px-3">
  10031. <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>
  10032. </td>
  10033. <td class="py-2 px-3 break-all max-w-xl font-mono text-emerald-400">${escapeHtml(r.rule || '')}</td>
  10034. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(r.comment || '')}</td>
  10035. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  10036. <button onclick="toggleSelectRuleState('${r.id}', ${!r.disabled})" class="px-2 py-0.5 rounded text-[10px] ${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'}">
  10037. ${r.disabled ? 'Enable' : 'Disable'}
  10038. </button>
  10039. <button onclick="openEditSelectRuleModal('${r.id}')" class="px-2 py-0.5 rounded text-[10px] bg-slate-800 hover:bg-slate-700 text-emerald-300 border border-slate-700">
  10040. Edit
  10041. </button>
  10042. <button onclick="deleteSelectRule('${r.id}')" class="px-2 py-0.5 rounded text-[10px] bg-rose-950/60 hover:bg-rose-900 text-rose-300 border border-rose-900/50">
  10043. ✕
  10044. </button>
  10045. </td>
  10046. </tr>
  10047. `;
  10048. }).join('');
  10049. }
  10050. // -------------------------------------------------------------
  10051. // TAB 3: COMMUNITY LISTS (/routing filter community-list)
  10052. // -------------------------------------------------------------
  10053. function renderRoutingFilterCommunityLists() {
  10054. const tbody = document.getElementById('routing-filter-comm-lists-tbody');
  10055. if (!tbody) return;
  10056. const empty = document.getElementById('rf-comm-lists-empty');
  10057. const statusCount = document.getElementById('rf-status-count');
  10058. let list = (state.routingCommunityLists || []).slice();
  10059. const q = state.rfSearchQuery;
  10060. if (q) {
  10061. list = list.filter(cl =>
  10062. (cl.name && cl.name.toLowerCase().includes(q)) ||
  10063. (cl.comment && cl.comment.toLowerCase().includes(q)) ||
  10064. (cl.communities && cl.communities.some(c => c.toLowerCase().includes(q)))
  10065. );
  10066. }
  10067. if (statusCount && state.activeRoutingFilterTab === 'community-lists') {
  10068. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  10069. }
  10070. if (list.length === 0) {
  10071. tbody.innerHTML = '';
  10072. if (empty) empty.classList.remove('hidden');
  10073. return;
  10074. }
  10075. if (empty) empty.classList.add('hidden');
  10076. tbody.innerHTML = list.map(cl => {
  10077. const isSelected = state.selectedFilterRow?.['community-lists'] === cl.id;
  10078. const flagA = !cl.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  10079. const flagX = cl.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  10080. const commBadges = (cl.communities || []).map(c =>
  10081. `<span class="px-1.5 py-0.5 rounded text-[10px] bg-indigo-950 text-indigo-300 border border-indigo-800/40 font-mono">${escapeHtml(c)}</span>`
  10082. ).join(' ');
  10083. return `
  10084. <tr onclick="selectFilterRow('community-lists', '${cl.id}')" class="cursor-pointer transition select-none ${isSelected ? 'bg-emerald-950/40 ring-1 ring-emerald-500/40' : 'hover:bg-slate-800/40'}">
  10085. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  10086. <td class="py-2 px-3 font-mono font-bold text-white">${escapeHtml(cl.name)}</td>
  10087. <td class="py-2 px-3 space-x-1">${commBadges || '<span class="text-slate-600">-</span>'}</td>
  10088. <td class="py-2 px-3 font-mono text-slate-400">${escapeHtml(cl.regexp || '-')}</td>
  10089. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(cl.comment || '')}</td>
  10090. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  10091. <button onclick="toggleCommunityListState('${cl.id}', ${!cl.disabled})" class="px-2 py-0.5 rounded text-[10px] ${cl.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'}">
  10092. ${cl.disabled ? 'Enable' : 'Disable'}
  10093. </button>
  10094. <button onclick="openEditCommunityListModal('${cl.id}')" class="px-2 py-0.5 rounded text-[10px] bg-slate-800 hover:bg-slate-700 text-emerald-300 border border-slate-700">
  10095. Edit
  10096. </button>
  10097. <button onclick="deleteCommunityList('${cl.id}')" class="px-2 py-0.5 rounded text-[10px] bg-rose-950/60 hover:bg-rose-900 text-rose-300 border border-rose-900/50">
  10098. ✕
  10099. </button>
  10100. </td>
  10101. </tr>
  10102. `;
  10103. }).join('');
  10104. }
  10105. // -------------------------------------------------------------
  10106. // TAB 4: AS LISTS (/routing filter num-list)
  10107. // -------------------------------------------------------------
  10108. function renderRoutingFilterASLists() {
  10109. const tbody = document.getElementById('routing-filter-as-lists-tbody');
  10110. if (!tbody) return;
  10111. const empty = document.getElementById('rf-as-lists-empty');
  10112. const statusCount = document.getElementById('rf-status-count');
  10113. let list = (state.routingASLists || []).slice();
  10114. const q = state.rfSearchQuery;
  10115. if (q) {
  10116. list = list.filter(al =>
  10117. (al.name && al.name.toLowerCase().includes(q)) ||
  10118. (al.range && al.range.toLowerCase().includes(q)) ||
  10119. (al.comment && al.comment.toLowerCase().includes(q))
  10120. );
  10121. }
  10122. if (statusCount && state.activeRoutingFilterTab === 'as-lists') {
  10123. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  10124. }
  10125. if (list.length === 0) {
  10126. tbody.innerHTML = '';
  10127. if (empty) empty.classList.remove('hidden');
  10128. return;
  10129. }
  10130. if (empty) empty.classList.add('hidden');
  10131. tbody.innerHTML = list.map(al => {
  10132. const isSelected = state.selectedFilterRow?.['as-lists'] === al.id;
  10133. const flagA = !al.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  10134. const flagX = al.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  10135. return `
  10136. <tr onclick="selectFilterRow('as-lists', '${al.id}')" class="cursor-pointer transition select-none ${isSelected ? 'bg-emerald-950/40 ring-1 ring-emerald-500/40' : 'hover:bg-slate-800/40'}">
  10137. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  10138. <td class="py-2 px-3 font-mono font-bold text-white">${escapeHtml(al.name)}</td>
  10139. <td class="py-2 px-3 font-mono text-purple-300">${escapeHtml(al.range)}</td>
  10140. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(al.comment || '')}</td>
  10141. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  10142. <button onclick="toggleASListState('${al.id}', ${!al.disabled})" class="px-2 py-0.5 rounded text-[10px] ${al.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'}">
  10143. ${al.disabled ? 'Enable' : 'Disable'}
  10144. </button>
  10145. <button onclick="openEditASListModal('${al.id}')" class="px-2 py-0.5 rounded text-[10px] bg-slate-800 hover:bg-slate-700 text-emerald-300 border border-slate-700">
  10146. Edit
  10147. </button>
  10148. <button onclick="deleteASList('${al.id}')" class="px-2 py-0.5 rounded text-[10px] bg-rose-950/60 hover:bg-rose-900 text-rose-300 border border-rose-900/50">
  10149. ✕
  10150. </button>
  10151. </td>
  10152. </tr>
  10153. `;
  10154. }).join('');
  10155. }
  10156. // -------------------------------------------------------------
  10157. // SNIPPETS & WIZARD HELPERS
  10158. // -------------------------------------------------------------
  10159. function insertRuleSnippet(type) {
  10160. const textarea = document.getElementById('modal-rf-rule');
  10161. if (!textarea) return;
  10162. let snippet = '';
  10163. switch (type) {
  10164. case 'accept-default':
  10165. snippet = 'if (dst in 0.0.0.0/0) { accept; }';
  10166. break;
  10167. case 'drop-rfc1918':
  10168. snippet = 'if (dst in 10.0.0.0/8 || dst in 172.16.0.0/12 || dst in 192.168.0.0/16) { reject; }';
  10169. break;
  10170. case 'len-24':
  10171. snippet = 'if (dst-len > 24) { reject; }';
  10172. break;
  10173. case 'local-pref-150':
  10174. snippet = 'if (dst in 10.0.0.0/8) { set bgp-local-pref 150; accept; }';
  10175. break;
  10176. case 'as-prepend-2':
  10177. snippet = 'set bgp-path-prepend 2; accept;';
  10178. break;
  10179. case 'set-comm':
  10180. snippet = 'set bgp-communities.add 65000:100; accept;';
  10181. break;
  10182. case 'match-comm':
  10183. snippet = 'if (bgp-communities includes 65000:100) { accept; }';
  10184. break;
  10185. case 'reject-all':
  10186. snippet = 'reject;';
  10187. break;
  10188. }
  10189. if (!snippet) return;
  10190. if (!textarea.value.trim()) {
  10191. textarea.value = snippet;
  10192. } else {
  10193. textarea.value = textarea.value.trim() + '\n' + snippet;
  10194. }
  10195. }
  10196. function generateScriptFromWizard() {
  10197. const pfx = (document.getElementById('modal-rf-prefix')?.value || '').trim();
  10198. const pfxLen = (document.getElementById('modal-rf-prefix-len')?.value || '').trim();
  10199. const proto = document.getElementById('modal-rf-protocol')?.value || 'any';
  10200. const asp = (document.getElementById('modal-rf-as-path')?.value || '').trim();
  10201. const comm = (document.getElementById('modal-rf-community')?.value || '').trim();
  10202. const act = document.getElementById('modal-rf-action')?.value || 'accept';
  10203. const lp = parseInt(document.getElementById('modal-rf-set-local-pref')?.value, 10) || 0;
  10204. const prep = parseInt(document.getElementById('modal-rf-set-as-prepend')?.value, 10) || 0;
  10205. const conds = [];
  10206. if (pfx) {
  10207. if (pfxLen) {
  10208. if (pfxLen.includes('-')) {
  10209. const parts = pfxLen.split('-');
  10210. conds.push(`dst in ${pfx}{${parts[0].trim()},${parts[1].trim()}}`);
  10211. } else {
  10212. conds.push(`dst in ${pfx} && dst-len >= ${pfxLen}`);
  10213. }
  10214. } else {
  10215. conds.push(`dst in ${pfx}`);
  10216. }
  10217. }
  10218. if (proto && proto !== 'any') {
  10219. conds.push(`protocol ${proto}`);
  10220. }
  10221. if (asp) {
  10222. conds.push(`bgp-as-path "${asp}"`);
  10223. }
  10224. if (comm) {
  10225. conds.push(`bgp-communities includes ${comm}`);
  10226. }
  10227. const actions = [];
  10228. if (lp > 0) actions.push(`set bgp-local-pref ${lp};`);
  10229. if (prep > 0) actions.push(`set bgp-path-prepend ${prep};`);
  10230. actions.push(`${act};`);
  10231. let code = '';
  10232. if (conds.length > 0) {
  10233. code = `if (${conds.join(' && ')}) {\n ${actions.join(' ')}\n}`;
  10234. } else {
  10235. code = actions.join(' ');
  10236. }
  10237. const textarea = document.getElementById('modal-rf-rule');
  10238. if (textarea) textarea.value = code;
  10239. }
  10240. // -------------------------------------------------------------
  10241. // MODAL CRUD: RULES (/routing filter rule)
  10242. // -------------------------------------------------------------
  10243. function openAddRoutingFilterModal(defaultChain = '') {
  10244. const form = document.getElementById('routing-filter-form');
  10245. if (form) form.reset();
  10246. const idEl = document.getElementById('modal-rf-id');
  10247. if (idEl) idEl.value = '';
  10248. const titleEl = document.getElementById('modal-rf-title');
  10249. if (titleEl) titleEl.innerText = 'Add Routing Filter Rule';
  10250. const chainEl = document.getElementById('modal-rf-chain');
  10251. if (chainEl) chainEl.value = defaultChain || (state.filterChainSelected && state.filterChainSelected !== 'all' ? state.filterChainSelected : 'bgp-in');
  10252. const orderEl = document.getElementById('modal-rf-order');
  10253. if (orderEl) orderEl.value = ((state.routingFilters || []).length + 1) * 10;
  10254. const ruleEl = document.getElementById('modal-rf-rule');
  10255. if (ruleEl) ruleEl.value = 'if (dst in 10.0.0.0/8) { set bgp-local-pref 150; accept; }';
  10256. const disEl = document.getElementById('modal-rf-disabled');
  10257. if (disEl) disEl.checked = false;
  10258. const modal = document.getElementById('modal-routing-filter');
  10259. if (modal) modal.classList.remove('hidden');
  10260. }
  10261. function openEditRoutingFilterModal(id) {
  10262. const r = (state.routingFilters || []).find(item => item.id === id);
  10263. if (!r) return;
  10264. const idEl = document.getElementById('modal-rf-id');
  10265. if (idEl) idEl.value = r.id;
  10266. const titleEl = document.getElementById('modal-rf-title');
  10267. if (titleEl) titleEl.innerText = 'Edit Routing Filter Rule';
  10268. const chainEl = document.getElementById('modal-rf-chain');
  10269. if (chainEl) chainEl.value = r.chain || '';
  10270. const orderEl = document.getElementById('modal-rf-order');
  10271. if (orderEl) orderEl.value = r.rule_order || 10;
  10272. const ruleEl = document.getElementById('modal-rf-rule');
  10273. if (ruleEl) {
  10274. if (r.rule) {
  10275. ruleEl.value = r.rule;
  10276. } else {
  10277. let conds = [];
  10278. if (r.prefix) conds.push(`dst in ${r.prefix}`);
  10279. if (r.match_protocol && r.match_protocol !== 'any') conds.push(`protocol ${r.match_protocol}`);
  10280. let act = r.action || 'accept';
  10281. ruleEl.value = `if (${conds.length ? conds.join(' && ') : 'true'}) { ${act}; }`;
  10282. }
  10283. }
  10284. const comEl = document.getElementById('modal-rf-comment');
  10285. if (comEl) comEl.value = r.comment || '';
  10286. const disEl = document.getElementById('modal-rf-disabled');
  10287. if (disEl) disEl.checked = !!r.disabled;
  10288. const modal = document.getElementById('modal-routing-filter');
  10289. if (modal) modal.classList.remove('hidden');
  10290. }
  10291. function closeRoutingFilterModal() {
  10292. const modal = document.getElementById('modal-routing-filter');
  10293. if (modal) modal.classList.add('hidden');
  10294. }
  10295. async function submitRoutingFilter(e) {
  10296. if (e) e.preventDefault();
  10297. const payload = {
  10298. id: document.getElementById('modal-rf-id').value,
  10299. chain: document.getElementById('modal-rf-chain').value.trim(),
  10300. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  10301. rule: document.getElementById('modal-rf-rule').value.trim(),
  10302. comment: document.getElementById('modal-rf-comment').value.trim(),
  10303. disabled: document.getElementById('modal-rf-disabled').checked
  10304. };
  10305. try {
  10306. const res = await fetch(`${API_BASE}/routing/filters`, {
  10307. method: 'POST',
  10308. headers: { 'Content-Type': 'application/json' },
  10309. body: JSON.stringify(payload)
  10310. });
  10311. if (res.ok) {
  10312. closeRoutingFilterModal();
  10313. showToast('Success', 'Routing filter rule saved', 'success');
  10314. loadDynamicRouting();
  10315. } else {
  10316. const err = await res.json();
  10317. showToast('Error', err.error || 'Failed to save filter rule', 'error');
  10318. }
  10319. } catch (err) {
  10320. showToast('Error', err.message, 'error');
  10321. }
  10322. }
  10323. async function applyRoutingFilterForm() {
  10324. const payload = {
  10325. id: document.getElementById('modal-rf-id').value,
  10326. chain: document.getElementById('modal-rf-chain').value.trim(),
  10327. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  10328. rule: document.getElementById('modal-rf-rule').value.trim(),
  10329. comment: document.getElementById('modal-rf-comment').value.trim(),
  10330. disabled: document.getElementById('modal-rf-disabled').checked
  10331. };
  10332. try {
  10333. const res = await fetch(`${API_BASE}/routing/filters`, {
  10334. method: 'POST',
  10335. headers: { 'Content-Type': 'application/json' },
  10336. body: JSON.stringify(payload)
  10337. });
  10338. if (res.ok) {
  10339. const data = await res.json();
  10340. if (data.id) document.getElementById('modal-rf-id').value = data.id;
  10341. showToast('Applied', 'Routing filter configuration applied', 'success');
  10342. loadDynamicRouting();
  10343. } else {
  10344. const err = await res.json();
  10345. showToast('Error', err.error || 'Failed to apply filter rule', 'error');
  10346. }
  10347. } catch (err) {
  10348. showToast('Error', err.message, 'error');
  10349. }
  10350. }
  10351. async function moveRoutingFilterOrder(id, delta) {
  10352. const list = state.routingFilters || [];
  10353. const idx = list.findIndex(r => r.id === id);
  10354. if (idx < 0) return;
  10355. const targetIdx = idx + delta;
  10356. if (targetIdx < 0 || targetIdx >= list.length) return;
  10357. const currentOrder = list[idx].rule_order || 10;
  10358. const targetOrder = list[targetIdx].rule_order || 20;
  10359. list[idx].rule_order = targetOrder;
  10360. list[targetIdx].rule_order = currentOrder;
  10361. try {
  10362. await fetch(`${API_BASE}/routing/filters`, {
  10363. method: 'POST',
  10364. headers: { 'Content-Type': 'application/json' },
  10365. body: JSON.stringify(list[idx])
  10366. });
  10367. await fetch(`${API_BASE}/routing/filters`, {
  10368. method: 'POST',
  10369. headers: { 'Content-Type': 'application/json' },
  10370. body: JSON.stringify(list[targetIdx])
  10371. });
  10372. loadDynamicRouting();
  10373. } catch (e) {
  10374. console.error('Reorder error:', e);
  10375. }
  10376. }
  10377. async function deleteRoutingFilter(id) {
  10378. if (!confirm('Are you sure you want to delete this routing filter rule?')) return;
  10379. try {
  10380. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10381. if (res.ok) {
  10382. showToast('Deleted', 'Routing filter rule removed', 'info');
  10383. loadDynamicRouting();
  10384. } else {
  10385. const err = await res.json();
  10386. showToast('Error', err.error || 'Failed to delete rule', 'error');
  10387. }
  10388. } catch (err) {
  10389. showToast('Error', err.message, 'error');
  10390. }
  10391. }
  10392. async function toggleRoutingFilterState(id, disabled) {
  10393. try {
  10394. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}/state`, {
  10395. method: 'POST',
  10396. headers: { 'Content-Type': 'application/json' },
  10397. body: JSON.stringify({ disabled })
  10398. });
  10399. if (res.ok) {
  10400. showToast('Status Updated', `Rule ${disabled ? 'disabled' : 'enabled'}`, 'info');
  10401. loadDynamicRouting();
  10402. } else {
  10403. const err = await res.json();
  10404. showToast('Error', err.error || 'Failed to toggle rule state', 'error');
  10405. }
  10406. } catch (err) {
  10407. showToast('Error', err.message, 'error');
  10408. }
  10409. }
  10410. // -------------------------------------------------------------
  10411. // MODAL CRUD: SELECT RULES (/routing filter select-rule)
  10412. // -------------------------------------------------------------
  10413. function openAddSelectRuleModal() {
  10414. document.getElementById('modal-rf-sr-id').value = '';
  10415. document.getElementById('modal-rf-sr-title').innerText = 'Add Routing Select Rule';
  10416. document.getElementById('modal-rf-sr-chain').value = state.filterChainSelected && state.filterChainSelected !== 'all' ? state.filterChainSelected : 'bgp-out';
  10417. document.getElementById('modal-rf-sr-order').value = ((state.routingSelectRules || []).length + 1) * 10;
  10418. document.getElementById('modal-rf-sr-rule').value = 'if (protocol bgp && dst in 10.0.0.0/8) { accept; }';
  10419. document.getElementById('modal-rf-sr-comment').value = '';
  10420. document.getElementById('modal-rf-sr-disabled').checked = false;
  10421. document.getElementById('modal-rf-select-rule').classList.remove('hidden');
  10422. }
  10423. function openEditSelectRuleModal(id) {
  10424. const r = (state.routingSelectRules || []).find(item => item.id === id);
  10425. if (!r) return;
  10426. document.getElementById('modal-rf-sr-id').value = r.id;
  10427. document.getElementById('modal-rf-sr-title').innerText = 'Edit Routing Select Rule';
  10428. document.getElementById('modal-rf-sr-chain').value = r.chain || '';
  10429. document.getElementById('modal-rf-sr-order').value = r.rule_order || 10;
  10430. document.getElementById('modal-rf-sr-rule').value = r.rule || '';
  10431. document.getElementById('modal-rf-sr-comment').value = r.comment || '';
  10432. document.getElementById('modal-rf-sr-disabled').checked = !!r.disabled;
  10433. document.getElementById('modal-rf-select-rule').classList.remove('hidden');
  10434. }
  10435. function closeSelectRuleModal() {
  10436. document.getElementById('modal-rf-select-rule').classList.add('hidden');
  10437. }
  10438. async function submitSelectRule(e) {
  10439. e.preventDefault();
  10440. const payload = {
  10441. id: document.getElementById('modal-rf-sr-id').value,
  10442. chain: document.getElementById('modal-rf-sr-chain').value.trim(),
  10443. rule_order: parseInt(document.getElementById('modal-rf-sr-order').value, 10) || 10,
  10444. rule: document.getElementById('modal-rf-sr-rule').value.trim(),
  10445. comment: document.getElementById('modal-rf-sr-comment').value.trim(),
  10446. disabled: document.getElementById('modal-rf-sr-disabled').checked
  10447. };
  10448. try {
  10449. const res = await fetch(`${API_BASE}/routing/filters/select-rules`, {
  10450. method: 'POST',
  10451. headers: { 'Content-Type': 'application/json' },
  10452. body: JSON.stringify(payload)
  10453. });
  10454. if (res.ok) {
  10455. closeSelectRuleModal();
  10456. showToast('Success', 'Select rule saved', 'success');
  10457. loadDynamicRouting();
  10458. } else {
  10459. const err = await res.json();
  10460. showToast('Error', err.error || 'Failed to save select rule', 'error');
  10461. }
  10462. } catch (err) {
  10463. showToast('Error', err.message, 'error');
  10464. }
  10465. }
  10466. async function deleteSelectRule(id) {
  10467. if (!confirm('Are you sure you want to delete this select rule?')) return;
  10468. try {
  10469. const res = await fetch(`${API_BASE}/routing/filters/select-rules/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10470. if (res.ok) {
  10471. showToast('Deleted', 'Select rule removed', 'info');
  10472. loadDynamicRouting();
  10473. } else {
  10474. const err = await res.json();
  10475. showToast('Error', err.error || 'Failed to delete select rule', 'error');
  10476. }
  10477. } catch (err) {
  10478. showToast('Error', err.message, 'error');
  10479. }
  10480. }
  10481. async function toggleSelectRuleState(id, disabled) {
  10482. try {
  10483. const res = await fetch(`${API_BASE}/routing/filters/select-rules/${encodeURIComponent(id)}/state`, {
  10484. method: 'POST',
  10485. headers: { 'Content-Type': 'application/json' },
  10486. body: JSON.stringify({ disabled })
  10487. });
  10488. if (res.ok) {
  10489. showToast('Status Updated', `Select rule ${disabled ? 'disabled' : 'enabled'}`, 'info');
  10490. loadDynamicRouting();
  10491. } else {
  10492. const err = await res.json();
  10493. showToast('Error', err.error || 'Failed to update select rule state', 'error');
  10494. }
  10495. } catch (err) {
  10496. showToast('Error', err.message, 'error');
  10497. }
  10498. }
  10499. // -------------------------------------------------------------
  10500. // MODAL CRUD: COMMUNITY LISTS (/routing filter community-list)
  10501. // -------------------------------------------------------------
  10502. function openAddCommunityListModal() {
  10503. document.getElementById('modal-rf-cl-id').value = '';
  10504. document.getElementById('modal-rf-cl-title').innerText = 'Add BGP Community List';
  10505. document.getElementById('modal-rf-cl-name').value = '';
  10506. document.getElementById('modal-rf-cl-communities').value = '';
  10507. document.getElementById('modal-rf-cl-regexp').value = '';
  10508. document.getElementById('modal-rf-cl-comment').value = '';
  10509. document.getElementById('modal-rf-cl-disabled').checked = false;
  10510. document.getElementById('modal-rf-community-list').classList.remove('hidden');
  10511. }
  10512. function openEditCommunityListModal(id) {
  10513. const cl = (state.routingCommunityLists || []).find(item => item.id === id);
  10514. if (!cl) return;
  10515. document.getElementById('modal-rf-cl-id').value = cl.id;
  10516. document.getElementById('modal-rf-cl-title').innerText = 'Edit BGP Community List';
  10517. document.getElementById('modal-rf-cl-name').value = cl.name || '';
  10518. document.getElementById('modal-rf-cl-communities').value = (cl.communities || []).join(', ');
  10519. document.getElementById('modal-rf-cl-regexp').value = cl.regexp || '';
  10520. document.getElementById('modal-rf-cl-comment').value = cl.comment || '';
  10521. document.getElementById('modal-rf-cl-disabled').checked = !!cl.disabled;
  10522. document.getElementById('modal-rf-community-list').classList.remove('hidden');
  10523. }
  10524. function closeCommunityListModal() {
  10525. document.getElementById('modal-rf-community-list').classList.add('hidden');
  10526. }
  10527. async function submitCommunityList(e) {
  10528. e.preventDefault();
  10529. const rawComms = document.getElementById('modal-rf-cl-communities').value;
  10530. const comms = rawComms.split(',').map(c => c.trim()).filter(Boolean);
  10531. const payload = {
  10532. id: document.getElementById('modal-rf-cl-id').value,
  10533. name: document.getElementById('modal-rf-cl-name').value.trim(),
  10534. communities: comms,
  10535. regexp: document.getElementById('modal-rf-cl-regexp').value.trim(),
  10536. comment: document.getElementById('modal-rf-cl-comment').value.trim(),
  10537. disabled: document.getElementById('modal-rf-cl-disabled').checked
  10538. };
  10539. try {
  10540. const res = await fetch(`${API_BASE}/routing/filters/community-lists`, {
  10541. method: 'POST',
  10542. headers: { 'Content-Type': 'application/json' },
  10543. body: JSON.stringify(payload)
  10544. });
  10545. if (res.ok) {
  10546. closeCommunityListModal();
  10547. showToast('Success', 'Community list saved', 'success');
  10548. loadDynamicRouting();
  10549. } else {
  10550. const err = await res.json();
  10551. showToast('Error', err.error || 'Failed to save community list', 'error');
  10552. }
  10553. } catch (err) {
  10554. showToast('Error', err.message, 'error');
  10555. }
  10556. }
  10557. async function deleteCommunityList(id) {
  10558. if (!confirm('Are you sure you want to delete this community list?')) return;
  10559. try {
  10560. const res = await fetch(`${API_BASE}/routing/filters/community-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10561. if (res.ok) {
  10562. showToast('Deleted', 'Community list removed', 'info');
  10563. loadDynamicRouting();
  10564. } else {
  10565. const err = await res.json();
  10566. showToast('Error', err.error || 'Failed to delete community list', 'error');
  10567. }
  10568. } catch (err) {
  10569. showToast('Error', err.message, 'error');
  10570. }
  10571. }
  10572. async function toggleCommunityListState(id, disabled) {
  10573. try {
  10574. const res = await fetch(`${API_BASE}/routing/filters/community-lists/${encodeURIComponent(id)}/state`, {
  10575. method: 'POST',
  10576. headers: { 'Content-Type': 'application/json' },
  10577. body: JSON.stringify({ disabled })
  10578. });
  10579. if (res.ok) {
  10580. showToast('Status Updated', `Community list ${disabled ? 'disabled' : 'enabled'}`, 'info');
  10581. loadDynamicRouting();
  10582. } else {
  10583. const err = await res.json();
  10584. showToast('Error', err.error || 'Failed to update community list state', 'error');
  10585. }
  10586. } catch (err) {
  10587. showToast('Error', err.message, 'error');
  10588. }
  10589. }
  10590. // -------------------------------------------------------------
  10591. // MODAL CRUD: AS LISTS (/routing filter num-list)
  10592. // -------------------------------------------------------------
  10593. function openAddASListModal() {
  10594. document.getElementById('modal-rf-al-id').value = '';
  10595. document.getElementById('modal-rf-al-title').innerText = 'Add AS Number List';
  10596. document.getElementById('modal-rf-al-name').value = '';
  10597. document.getElementById('modal-rf-al-range').value = '';
  10598. document.getElementById('modal-rf-al-comment').value = '';
  10599. document.getElementById('modal-rf-al-disabled').checked = false;
  10600. document.getElementById('modal-rf-as-list').classList.remove('hidden');
  10601. }
  10602. function openEditASListModal(id) {
  10603. const al = (state.routingASLists || []).find(item => item.id === id);
  10604. if (!al) return;
  10605. document.getElementById('modal-rf-al-id').value = al.id;
  10606. document.getElementById('modal-rf-al-title').innerText = 'Edit AS Number List';
  10607. document.getElementById('modal-rf-al-name').value = al.name || '';
  10608. document.getElementById('modal-rf-al-range').value = al.range || '';
  10609. document.getElementById('modal-rf-al-comment').value = al.comment || '';
  10610. document.getElementById('modal-rf-al-disabled').checked = !!al.disabled;
  10611. document.getElementById('modal-rf-as-list').classList.remove('hidden');
  10612. }
  10613. function closeASListModal() {
  10614. document.getElementById('modal-rf-as-list').classList.add('hidden');
  10615. }
  10616. async function submitASList(e) {
  10617. e.preventDefault();
  10618. const payload = {
  10619. id: document.getElementById('modal-rf-al-id').value,
  10620. name: document.getElementById('modal-rf-al-name').value.trim(),
  10621. range: document.getElementById('modal-rf-al-range').value.trim(),
  10622. comment: document.getElementById('modal-rf-al-comment').value.trim(),
  10623. disabled: document.getElementById('modal-rf-al-disabled').checked
  10624. };
  10625. try {
  10626. const res = await fetch(`${API_BASE}/routing/filters/as-lists`, {
  10627. method: 'POST',
  10628. headers: { 'Content-Type': 'application/json' },
  10629. body: JSON.stringify(payload)
  10630. });
  10631. if (res.ok) {
  10632. closeASListModal();
  10633. showToast('Success', 'AS number list saved', 'success');
  10634. loadDynamicRouting();
  10635. } else {
  10636. const err = await res.json();
  10637. showToast('Error', err.error || 'Failed to save AS list', 'error');
  10638. }
  10639. } catch (err) {
  10640. showToast('Error', err.message, 'error');
  10641. }
  10642. }
  10643. async function deleteASList(id) {
  10644. if (!confirm('Are you sure you want to delete this AS list?')) return;
  10645. try {
  10646. const res = await fetch(`${API_BASE}/routing/filters/as-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10647. if (res.ok) {
  10648. showToast('Deleted', 'AS list removed', 'info');
  10649. loadDynamicRouting();
  10650. } else {
  10651. const err = await res.json();
  10652. showToast('Error', err.error || 'Failed to delete AS list', 'error');
  10653. }
  10654. } catch (err) {
  10655. showToast('Error', err.message, 'error');
  10656. }
  10657. }
  10658. async function toggleASListState(id, disabled) {
  10659. try {
  10660. const res = await fetch(`${API_BASE}/routing/filters/as-lists/${encodeURIComponent(id)}/state`, {
  10661. method: 'POST',
  10662. headers: { 'Content-Type': 'application/json' },
  10663. body: JSON.stringify({ disabled })
  10664. });
  10665. if (res.ok) {
  10666. showToast('Status Updated', `AS list ${disabled ? 'disabled' : 'enabled'}`, 'info');
  10667. loadDynamicRouting();
  10668. } else {
  10669. const err = await res.json();
  10670. showToast('Error', err.error || 'Failed to update AS list state', 'error');
  10671. }
  10672. } catch (err) {
  10673. showToast('Error', err.message, 'error');
  10674. }
  10675. }
  10676. // ==========================================
  10677. // TROUBLESHOOT & DIAGNOSTIC TOOLS (/tool)
  10678. // ==========================================
  10679. function loadToolsView() {
  10680. populateToolsInterfaces();
  10681. switchToolsSubTab(state.activeToolsSubTab || 'ping');
  10682. }
  10683. function populateToolsInterfaces() {
  10684. const pingSel = document.getElementById('tools-ping-iface');
  10685. const traceSel = document.getElementById('tools-tr-iface');
  10686. let opts = '<option value="">Auto (Default Route)</option>';
  10687. if (Array.isArray(state.interfaces)) {
  10688. state.interfaces.forEach(iface => {
  10689. if (iface.name) {
  10690. opts += `<option value="${escapeHtml(iface.name)}">${escapeHtml(iface.name)}${iface.ip_address ? ' (' + escapeHtml(iface.ip_address) + ')' : ''}</option>`;
  10691. }
  10692. });
  10693. }
  10694. if (pingSel) {
  10695. const cur = pingSel.value;
  10696. pingSel.innerHTML = opts;
  10697. if (cur) pingSel.value = cur;
  10698. }
  10699. if (traceSel) {
  10700. const cur = traceSel.value;
  10701. traceSel.innerHTML = opts;
  10702. if (cur) traceSel.value = cur;
  10703. }
  10704. }
  10705. function switchToolsSubTab(subTab) {
  10706. state.activeToolsSubTab = subTab;
  10707. const tabs = ['ping', 'traceroute', 'mtr', 'dns', 'port'];
  10708. tabs.forEach(t => {
  10709. const btn = document.getElementById(`tools-subtab-btn-${t}`);
  10710. const view = document.getElementById(`tools-view-${t}`);
  10711. if (btn) {
  10712. if (t === subTab) {
  10713. 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';
  10714. } else {
  10715. 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';
  10716. }
  10717. }
  10718. if (view) {
  10719. if (t === subTab) {
  10720. view.classList.remove('hidden');
  10721. } else {
  10722. view.classList.add('hidden');
  10723. }
  10724. }
  10725. });
  10726. }
  10727. function setPortPreset(port) {
  10728. const input = document.getElementById('tools-port-num');
  10729. if (input) input.value = port;
  10730. }
  10731. let pingAbortController = null;
  10732. let tracerouteAbortController = null;
  10733. function clearPingTable() {
  10734. const tbody = document.getElementById('tools-ping-tbody');
  10735. if (tbody) tbody.innerHTML = '';
  10736. const rawEl = document.getElementById('tools-ping-raw');
  10737. if (rawEl) rawEl.innerText = '';
  10738. const sentEl = document.getElementById('tools-ping-stat-sent');
  10739. if (sentEl) sentEl.innerText = '0';
  10740. const recvEl = document.getElementById('tools-ping-stat-recv');
  10741. if (recvEl) recvEl.innerText = '0';
  10742. const lossEl = document.getElementById('tools-ping-stat-loss');
  10743. if (lossEl) lossEl.innerText = '0%';
  10744. const avgEl = document.getElementById('tools-ping-stat-avg');
  10745. if (avgEl) avgEl.innerText = '0 ms';
  10746. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  10747. if (minMaxEl) minMaxEl.innerText = '-';
  10748. const badge = document.getElementById('tools-ping-status-badge');
  10749. if (badge) {
  10750. badge.className = '';
  10751. badge.innerText = '';
  10752. }
  10753. }
  10754. function clearTracerouteTable() {
  10755. const tbody = document.getElementById('tools-tr-tbody');
  10756. if (tbody) tbody.innerHTML = '';
  10757. const rawEl = document.getElementById('tools-tr-raw');
  10758. if (rawEl) rawEl.innerText = '';
  10759. const statHops = document.getElementById('tools-tr-hops-count');
  10760. if (statHops) statHops.innerText = '0 Hops';
  10761. }
  10762. function resetPingButton() {
  10763. const btn = document.getElementById('tools-ping-btn');
  10764. const btnText = document.getElementById('tools-ping-btn-text');
  10765. const spinner = document.getElementById('tools-ping-spinner');
  10766. if (btn) {
  10767. btn.disabled = false;
  10768. 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';
  10769. }
  10770. if (btnText) btnText.innerText = 'Start Ping';
  10771. if (spinner) spinner.classList.add('hidden');
  10772. }
  10773. function setPingRunningButton() {
  10774. const btn = document.getElementById('tools-ping-btn');
  10775. const btnText = document.getElementById('tools-ping-btn-text');
  10776. const spinner = document.getElementById('tools-ping-spinner');
  10777. if (btn) {
  10778. btn.disabled = false;
  10779. 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';
  10780. }
  10781. if (btnText) btnText.innerText = 'Stop Ping';
  10782. if (spinner) spinner.classList.remove('hidden');
  10783. }
  10784. function resetTracerouteButton() {
  10785. const btn = document.getElementById('tools-tr-btn');
  10786. const btnText = document.getElementById('tools-tr-btn-text');
  10787. const spinner = document.getElementById('tools-tr-spinner');
  10788. if (btn) {
  10789. btn.disabled = false;
  10790. 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';
  10791. }
  10792. if (btnText) btnText.innerText = 'Start Traceroute';
  10793. if (spinner) spinner.classList.add('hidden');
  10794. }
  10795. function setTracerouteRunningButton() {
  10796. const btn = document.getElementById('tools-tr-btn');
  10797. const btnText = document.getElementById('tools-tr-btn-text');
  10798. const spinner = document.getElementById('tools-tr-spinner');
  10799. if (btn) {
  10800. btn.disabled = false;
  10801. 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';
  10802. }
  10803. if (btnText) btnText.innerText = 'Stop Traceroute';
  10804. if (spinner) spinner.classList.remove('hidden');
  10805. }
  10806. async function executePing(e) {
  10807. if (e) e.preventDefault();
  10808. // If already running, clicking the button stops the stream!
  10809. if (pingAbortController) {
  10810. pingAbortController.abort();
  10811. pingAbortController = null;
  10812. resetPingButton();
  10813. showToast('Ping Stopped', 'Live ping stopped by user', 'info');
  10814. return;
  10815. }
  10816. const target = document.getElementById('tools-ping-target')?.value?.trim();
  10817. const count = parseInt(document.getElementById('tools-ping-count')?.value || '4', 10);
  10818. const size = parseInt(document.getElementById('tools-ping-size')?.value || '56', 10);
  10819. const timeout = parseInt(document.getElementById('tools-ping-timeout')?.value || '3', 10);
  10820. const iface = document.getElementById('tools-ping-iface')?.value || '';
  10821. const dontFrag = document.getElementById('tools-ping-df')?.checked || false;
  10822. if (!target) {
  10823. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  10824. return;
  10825. }
  10826. clearPingTable();
  10827. const resCard = document.getElementById('tools-ping-results');
  10828. if (resCard) resCard.classList.remove('hidden');
  10829. pingAbortController = new AbortController();
  10830. setPingRunningButton();
  10831. try {
  10832. const res = await fetch(`${API_BASE}/tools/ping/stream`, {
  10833. method: 'POST',
  10834. headers: { 'Content-Type': 'application/json' },
  10835. body: JSON.stringify({
  10836. target,
  10837. count,
  10838. size,
  10839. timeout,
  10840. interface: iface,
  10841. dont_frag: dontFrag
  10842. }),
  10843. signal: pingAbortController.signal
  10844. });
  10845. if (!res.ok) {
  10846. const errText = await res.text();
  10847. showToast('Ping Error', errText || 'Failed to start live ping', 'error');
  10848. resetPingButton();
  10849. pingAbortController = null;
  10850. return;
  10851. }
  10852. const reader = res.body.getReader();
  10853. const decoder = new TextDecoder('utf-8');
  10854. let buffer = '';
  10855. while (true) {
  10856. const { done, value } = await reader.read();
  10857. if (done) break;
  10858. buffer += decoder.decode(value, { stream: true });
  10859. const blocks = buffer.split('\n\n');
  10860. buffer = blocks.pop() || '';
  10861. for (const block of blocks) {
  10862. const trimmed = block.trim();
  10863. if (!trimmed) continue;
  10864. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  10865. try {
  10866. const evt = JSON.parse(line);
  10867. handleLivePingEvent(evt);
  10868. } catch (parseErr) {
  10869. console.warn('Ping SSE parse error:', parseErr, line);
  10870. }
  10871. }
  10872. }
  10873. } catch (err) {
  10874. if (err.name === 'AbortError') {
  10875. // User aborted normally
  10876. } else {
  10877. showToast('Ping Error', err.message, 'error');
  10878. }
  10879. } finally {
  10880. pingAbortController = null;
  10881. resetPingButton();
  10882. }
  10883. }
  10884. function handleLivePingEvent(evt) {
  10885. const sentEl = document.getElementById('tools-ping-stat-sent');
  10886. const recvEl = document.getElementById('tools-ping-stat-recv');
  10887. const lossEl = document.getElementById('tools-ping-stat-loss');
  10888. const avgEl = document.getElementById('tools-ping-stat-avg');
  10889. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  10890. const badge = document.getElementById('tools-ping-status-badge');
  10891. const tbody = document.getElementById('tools-ping-tbody');
  10892. const rawEl = document.getElementById('tools-ping-raw');
  10893. if (evt.raw && rawEl) {
  10894. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  10895. rawEl.scrollTop = rawEl.scrollHeight;
  10896. }
  10897. if (evt.type === 'reply') {
  10898. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  10899. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  10900. if (lossEl && evt.packet_loss_pct !== undefined) {
  10901. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  10902. lossEl.className = evt.packet_loss_pct === 0
  10903. ? 'text-base font-bold font-mono text-emerald-400 mt-1'
  10904. : (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');
  10905. }
  10906. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  10907. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  10908. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  10909. }
  10910. if (badge) {
  10911. if (evt.packet_loss_pct === 0) {
  10912. 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';
  10913. badge.innerText = '100% OK';
  10914. } else {
  10915. 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';
  10916. badge.innerText = `${evt.packet_loss_pct.toFixed(0)}% LOSS`;
  10917. }
  10918. }
  10919. if (tbody) {
  10920. const tr = document.createElement('tr');
  10921. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  10922. tr.innerHTML = `
  10923. <td class="py-2 px-3 text-slate-300">#${evt.seq}</td>
  10924. <td class="py-2 px-3 font-semibold text-white">${escapeHtml(evt.from)}</td>
  10925. <td class="py-2 px-3 text-slate-400">${evt.bytes} bytes</td>
  10926. <td class="py-2 px-3 text-slate-300">${evt.ttl}</td>
  10927. <td class="py-2 px-3 font-bold text-amber-300">${evt.time_ms.toFixed(2)} ms</td>
  10928. <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>
  10929. `;
  10930. tbody.appendChild(tr);
  10931. }
  10932. } else if (evt.type === 'timeout') {
  10933. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  10934. if (lossEl && evt.packet_loss_pct !== undefined) {
  10935. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  10936. 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';
  10937. }
  10938. if (badge) {
  10939. 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';
  10940. badge.innerText = `${evt.packet_loss_pct?.toFixed(0) || 100}% LOSS`;
  10941. }
  10942. if (tbody) {
  10943. const tr = document.createElement('tr');
  10944. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs opacity-75';
  10945. tr.innerHTML = `
  10946. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  10947. <td class="py-2 px-3 font-semibold text-slate-500 italic">Request timed out</td>
  10948. <td class="py-2 px-3 text-slate-600">--</td>
  10949. <td class="py-2 px-3 text-slate-600">--</td>
  10950. <td class="py-2 px-3 font-bold text-slate-500">* * *</td>
  10951. <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>
  10952. `;
  10953. tbody.appendChild(tr);
  10954. }
  10955. } else if (evt.type === 'unreach') {
  10956. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  10957. if (lossEl && evt.packet_loss_pct !== undefined) {
  10958. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  10959. lossEl.className = 'text-base font-bold font-mono text-rose-400 mt-1';
  10960. }
  10961. if (badge) {
  10962. 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';
  10963. badge.innerText = 'UNREACHABLE';
  10964. }
  10965. if (tbody) {
  10966. const tr = document.createElement('tr');
  10967. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  10968. tr.innerHTML = `
  10969. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  10970. <td class="py-2 px-3 font-semibold text-rose-400">${escapeHtml(evt.from || 'Gateway')}</td>
  10971. <td class="py-2 px-3 text-slate-600">--</td>
  10972. <td class="py-2 px-3 text-slate-600">--</td>
  10973. <td class="py-2 px-3 font-bold text-rose-400 text-xs">${escapeHtml(evt.message || 'Unreachable')}</td>
  10974. <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>
  10975. `;
  10976. tbody.appendChild(tr);
  10977. }
  10978. } else if (evt.type === 'stats') {
  10979. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  10980. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  10981. if (lossEl && evt.packet_loss_pct !== undefined) lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  10982. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  10983. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  10984. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  10985. }
  10986. } else if (evt.type === 'done') {
  10987. 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');
  10988. }
  10989. }
  10990. async function executeTraceroute(e) {
  10991. if (e) e.preventDefault();
  10992. if (tracerouteAbortController) {
  10993. tracerouteAbortController.abort();
  10994. tracerouteAbortController = null;
  10995. resetTracerouteButton();
  10996. showToast('Traceroute Stopped', 'Traceroute stopped by user', 'info');
  10997. return;
  10998. }
  10999. const target = document.getElementById('tools-tr-target')?.value?.trim();
  11000. const maxHops = parseInt(document.getElementById('tools-tr-maxhops')?.value || '15', 10);
  11001. const protocol = document.getElementById('tools-tr-proto')?.value || 'icmp';
  11002. const iface = document.getElementById('tools-tr-iface')?.value || '';
  11003. const resolve = document.getElementById('tools-tr-resolve')?.checked || false;
  11004. if (!target) {
  11005. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  11006. return;
  11007. }
  11008. clearTracerouteTable();
  11009. const resCard = document.getElementById('tools-tr-results');
  11010. if (resCard) resCard.classList.remove('hidden');
  11011. tracerouteAbortController = new AbortController();
  11012. setTracerouteRunningButton();
  11013. try {
  11014. const res = await fetch(`${API_BASE}/tools/traceroute/stream`, {
  11015. method: 'POST',
  11016. headers: { 'Content-Type': 'application/json' },
  11017. body: JSON.stringify({
  11018. target,
  11019. max_hops: maxHops,
  11020. protocol,
  11021. interface: iface,
  11022. resolve
  11023. }),
  11024. signal: tracerouteAbortController.signal
  11025. });
  11026. if (!res.ok) {
  11027. const errText = await res.text();
  11028. showToast('Traceroute Error', errText || 'Failed to start traceroute', 'error');
  11029. resetTracerouteButton();
  11030. tracerouteAbortController = null;
  11031. return;
  11032. }
  11033. const reader = res.body.getReader();
  11034. const decoder = new TextDecoder('utf-8');
  11035. let buffer = '';
  11036. while (true) {
  11037. const { done, value } = await reader.read();
  11038. if (done) break;
  11039. buffer += decoder.decode(value, { stream: true });
  11040. const blocks = buffer.split('\n\n');
  11041. buffer = blocks.pop() || '';
  11042. for (const block of blocks) {
  11043. const trimmed = block.trim();
  11044. if (!trimmed) continue;
  11045. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  11046. try {
  11047. const evt = JSON.parse(line);
  11048. handleLiveTracerouteEvent(evt);
  11049. } catch (parseErr) {
  11050. console.warn('Traceroute SSE parse error:', parseErr, line);
  11051. }
  11052. }
  11053. }
  11054. } catch (err) {
  11055. if (err.name === 'AbortError') {
  11056. // User aborted normally
  11057. } else {
  11058. showToast('Traceroute Error', err.message, 'error');
  11059. }
  11060. } finally {
  11061. tracerouteAbortController = null;
  11062. resetTracerouteButton();
  11063. }
  11064. }
  11065. function handleLiveTracerouteEvent(evt) {
  11066. const statHops = document.getElementById('tools-tr-hops-count');
  11067. const tbody = document.getElementById('tools-tr-tbody');
  11068. const rawEl = document.getElementById('tools-tr-raw');
  11069. if (evt.raw && rawEl) {
  11070. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  11071. rawEl.scrollTop = rawEl.scrollHeight;
  11072. }
  11073. if (evt.hops_count !== undefined && statHops) {
  11074. statHops.innerText = `${evt.hops_count} Hops`;
  11075. }
  11076. if (evt.type === 'hop' && evt.hop && tbody) {
  11077. const h = evt.hop;
  11078. const isTimeout = h.status === 'timeout' || (!h.ip && !h.host);
  11079. const rtt1 = Array.isArray(h.times_ms) && h.times_ms[0] ? `${h.times_ms[0]} ms` : (isTimeout ? '*' : '--');
  11080. const rtt2 = Array.isArray(h.times_ms) && h.times_ms[1] ? `${h.times_ms[1]} ms` : (isTimeout ? '*' : '--');
  11081. const displayHost = h.host && h.host !== h.ip ? `${escapeHtml(h.host)} (${escapeHtml(h.ip || '')})` : escapeHtml(h.ip || (isTimeout ? 'Request timed out' : '--'));
  11082. const tr = document.createElement('tr');
  11083. tr.className = `hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs ${isTimeout ? 'opacity-60' : ''}`;
  11084. tr.innerHTML = `
  11085. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  11086. <td class="py-2.5 px-3 font-semibold ${isTimeout ? 'text-slate-500 italic' : 'text-cyan-300'}">${displayHost}</td>
  11087. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt1)}</td>
  11088. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt2)}</td>
  11089. <td class="py-2.5 px-3 text-right">
  11090. ${isTimeout
  11091. ? '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-slate-800 text-slate-400 border border-slate-700">TIMEOUT</span>'
  11092. : '<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>'}
  11093. </td>
  11094. `;
  11095. tbody.appendChild(tr);
  11096. } else if (evt.type === 'done') {
  11097. showToast('Traceroute Finished', `Traced ${evt.hops_count || 0} hops`, 'info');
  11098. }
  11099. }
  11100. async function executeMTR(e) {
  11101. if (e) e.preventDefault();
  11102. const target = document.getElementById('tools-mtr-target')?.value?.trim();
  11103. const cycles = parseInt(document.getElementById('tools-mtr-count')?.value || '3', 10);
  11104. if (!target) {
  11105. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  11106. return;
  11107. }
  11108. const btn = document.getElementById('tools-mtr-btn');
  11109. const spinner = document.getElementById('tools-mtr-spinner');
  11110. if (btn) btn.disabled = true;
  11111. if (spinner) spinner.classList.remove('hidden');
  11112. try {
  11113. const res = await fetch(`${API_BASE}/tools/mtr`, {
  11114. method: 'POST',
  11115. headers: { 'Content-Type': 'application/json' },
  11116. body: JSON.stringify({ target, count: cycles })
  11117. });
  11118. const data = await res.json();
  11119. if (!res.ok) {
  11120. showToast('MTR Error', data.error || 'Failed to execute MTR', 'error');
  11121. return;
  11122. }
  11123. const resCard = document.getElementById('tools-mtr-results');
  11124. if (resCard) resCard.classList.remove('hidden');
  11125. const hopsCount = Array.isArray(data.hops) ? data.hops.length : 0;
  11126. const statHops = document.getElementById('tools-mtr-hops-count');
  11127. if (statHops) statHops.innerText = `${hopsCount} Hops`;
  11128. const tbody = document.getElementById('tools-mtr-tbody');
  11129. if (tbody) {
  11130. if (hopsCount > 0) {
  11131. tbody.innerHTML = data.hops.map(h => {
  11132. 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');
  11133. return `
  11134. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  11135. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  11136. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(h.host || '--')}</td>
  11137. <td class="py-2.5 px-3 ${lossClass}">${h.loss_pct.toFixed(1)}%</td>
  11138. <td class="py-2.5 px-3 text-slate-300">${h.sent}</td>
  11139. <td class="py-2.5 px-3 text-slate-300">${h.last_ms.toFixed(1)}</td>
  11140. <td class="py-2.5 px-3 font-bold text-amber-300">${h.avg_ms.toFixed(1)}</td>
  11141. <td class="py-2.5 px-3 text-emerald-400">${h.best_ms.toFixed(1)}</td>
  11142. <td class="py-2.5 px-3 text-rose-400">${h.wrst_ms.toFixed(1)}</td>
  11143. <td class="py-2.5 px-3 text-slate-400">${h.stdev_ms.toFixed(1)}</td>
  11144. </tr>
  11145. `;
  11146. }).join('');
  11147. } else {
  11148. tbody.innerHTML = `<tr><td colspan="9" class="p-4 text-center text-xs text-rose-400 font-mono">No MTR data collected</td></tr>`;
  11149. }
  11150. }
  11151. const rawEl = document.getElementById('tools-mtr-raw');
  11152. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  11153. showToast('MTR Finished', `Report completed (${hopsCount} hops discovered)`, 'info');
  11154. } catch (err) {
  11155. showToast('MTR Error', err.message, 'error');
  11156. } finally {
  11157. if (btn) btn.disabled = false;
  11158. if (spinner) spinner.classList.add('hidden');
  11159. }
  11160. }
  11161. async function executeDNS(e) {
  11162. if (e) e.preventDefault();
  11163. const domain = document.getElementById('tools-dns-domain')?.value?.trim();
  11164. const type = document.getElementById('tools-dns-type')?.value || 'A';
  11165. const server = document.getElementById('tools-dns-server')?.value?.trim() || '';
  11166. if (!domain) {
  11167. showToast('Input Required', 'Please enter a hostname or domain', 'warning');
  11168. return;
  11169. }
  11170. const btn = document.getElementById('tools-dns-btn');
  11171. const spinner = document.getElementById('tools-dns-spinner');
  11172. if (btn) btn.disabled = true;
  11173. if (spinner) spinner.classList.remove('hidden');
  11174. try {
  11175. const res = await fetch(`${API_BASE}/tools/dns`, {
  11176. method: 'POST',
  11177. headers: { 'Content-Type': 'application/json' },
  11178. body: JSON.stringify({ domain, type, server })
  11179. });
  11180. const data = await res.json();
  11181. if (!res.ok) {
  11182. showToast('DNS Error', data.error || 'Failed to resolve DNS query', 'error');
  11183. return;
  11184. }
  11185. const resCard = document.getElementById('tools-dns-results');
  11186. if (resCard) resCard.classList.remove('hidden');
  11187. const metaEl = document.getElementById('tools-dns-meta');
  11188. if (metaEl) metaEl.innerText = `Resolved in ${data.query_time_ms ?? 0} ms via ${escapeHtml(data.server || 'System DNS')}`;
  11189. const tbody = document.getElementById('tools-dns-tbody');
  11190. if (tbody) {
  11191. if (Array.isArray(data.records) && data.records.length > 0) {
  11192. tbody.innerHTML = data.records.map(r => `
  11193. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  11194. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.name)}</td>
  11195. <td class="py-2.5 px-3 text-slate-400">${r.ttl}s</td>
  11196. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.class || 'IN')}</td>
  11197. <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>
  11198. <td class="py-2.5 px-3 font-bold text-amber-300 break-all">${escapeHtml(r.value)}</td>
  11199. </tr>
  11200. `).join('');
  11201. } else {
  11202. 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>`;
  11203. }
  11204. }
  11205. const rawEl = document.getElementById('tools-dns-raw');
  11206. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  11207. showToast('DNS Lookup Done', `Resolved ${domain} in ${data.query_time_ms} ms`, 'success');
  11208. } catch (err) {
  11209. showToast('DNS Error', err.message, 'error');
  11210. } finally {
  11211. if (btn) btn.disabled = false;
  11212. if (spinner) spinner.classList.add('hidden');
  11213. }
  11214. }
  11215. async function executePortProbe(e) {
  11216. if (e) e.preventDefault();
  11217. const target = document.getElementById('tools-port-target')?.value?.trim();
  11218. const port = parseInt(document.getElementById('tools-port-num')?.value || '80', 10);
  11219. const timeout = parseInt(document.getElementById('tools-port-timeout')?.value || '3', 10);
  11220. if (!target || !port) {
  11221. showToast('Input Required', 'Please enter a target host and TCP port', 'warning');
  11222. return;
  11223. }
  11224. const btn = document.getElementById('tools-port-btn');
  11225. const spinner = document.getElementById('tools-port-spinner');
  11226. if (btn) btn.disabled = true;
  11227. if (spinner) spinner.classList.remove('hidden');
  11228. try {
  11229. const res = await fetch(`${API_BASE}/tools/port-probe`, {
  11230. method: 'POST',
  11231. headers: { 'Content-Type': 'application/json' },
  11232. body: JSON.stringify({ target, port, timeout })
  11233. });
  11234. const data = await res.json();
  11235. if (!res.ok) {
  11236. showToast('Probe Error', data.error || 'Failed to probe TCP port', 'error');
  11237. return;
  11238. }
  11239. const resCard = document.getElementById('tools-port-results');
  11240. if (resCard) resCard.classList.remove('hidden');
  11241. const banner = document.getElementById('tools-port-banner');
  11242. const icon = document.getElementById('tools-port-icon');
  11243. const title = document.getElementById('tools-port-title');
  11244. const sub = document.getElementById('tools-port-sub');
  11245. const latency = document.getElementById('tools-port-latency');
  11246. if (data.open) {
  11247. if (banner) banner.className = 'rounded-xl p-5 border bg-emerald-950/30 border-emerald-800/50 flex items-center justify-between';
  11248. if (icon) {
  11249. 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';
  11250. icon.innerText = '✓';
  11251. }
  11252. if (title) {
  11253. title.className = 'text-sm font-bold text-emerald-300';
  11254. title.innerText = `PORT ${port} OPEN / LISTENING`;
  11255. }
  11256. if (sub) {
  11257. sub.className = 'text-xs mt-0.5 font-mono text-emerald-400/80';
  11258. sub.innerText = `TCP 3-way handshake established with ${escapeHtml(target)}:${port}${data.service ? ' (' + escapeHtml(data.service) + ')' : ''}`;
  11259. }
  11260. if (latency) {
  11261. latency.className = 'text-base font-bold font-mono text-emerald-300';
  11262. latency.innerText = `${data.latency_ms.toFixed(2)} ms`;
  11263. }
  11264. } else {
  11265. if (banner) banner.className = 'rounded-xl p-5 border bg-rose-950/30 border-rose-800/50 flex items-center justify-between';
  11266. if (icon) {
  11267. 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';
  11268. icon.innerText = '✕';
  11269. }
  11270. if (title) {
  11271. title.className = 'text-sm font-bold text-rose-300';
  11272. title.innerText = `PORT ${port} CLOSED / FILTERED`;
  11273. }
  11274. if (sub) {
  11275. sub.className = 'text-xs mt-0.5 font-mono text-rose-400/80';
  11276. sub.innerText = `Connection failed or timed out to ${escapeHtml(target)}:${port}`;
  11277. }
  11278. if (latency) {
  11279. latency.className = 'text-base font-bold font-mono text-slate-500';
  11280. latency.innerText = '--';
  11281. }
  11282. }
  11283. const rawEl = document.getElementById('tools-port-raw');
  11284. 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'}`);
  11285. showToast('Probe Complete', `Port ${port} is ${data.open ? 'OPEN' : 'CLOSED'}`, data.open ? 'success' : 'warning');
  11286. } catch (err) {
  11287. showToast('Probe Error', err.message, 'error');
  11288. } finally {
  11289. if (btn) btn.disabled = false;
  11290. if (spinner) spinner.classList.add('hidden');
  11291. }
  11292. }
  11293. // ==========================================
  11294. // DHCP CLIENT (/ip dhcp-client) CONTROLLER
  11295. // ==========================================
  11296. async function loadDHCPClients(showToastMsg = false) {
  11297. try {
  11298. const [clientsRes, sumRes] = await Promise.all([
  11299. fetch(`${API_BASE}/dhcp/clients`),
  11300. fetch(`${API_BASE}/dhcp/clients/summary`)
  11301. ]);
  11302. if (clientsRes.ok) {
  11303. state.dhcpClients = await clientsRes.json();
  11304. }
  11305. if (sumRes.ok) {
  11306. state.dhcpSummary = await sumRes.json();
  11307. }
  11308. renderDHCPClients();
  11309. updateDHCPSummaryCards();
  11310. const bDhcp = document.getElementById('badge-dhcp-client-count');
  11311. if (bDhcp && state.dhcpSummary) {
  11312. bDhcp.innerText = state.dhcpSummary.total_clients || 0;
  11313. }
  11314. if (showToastMsg) {
  11315. showToast('Refreshed', 'DHCP Client telemetry updated', 'info');
  11316. }
  11317. } catch (err) {
  11318. console.error('Failed to load DHCP clients:', err);
  11319. if (showToastMsg) {
  11320. showToast('Notice', 'Unable to fetch DHCP client status', 'warning');
  11321. }
  11322. }
  11323. }
  11324. function updateDHCPSummaryCards() {
  11325. const sum = state.dhcpSummary || {
  11326. total_clients: (state.dhcpClients || []).length,
  11327. bound_clients: (state.dhcpClients || []).filter(c => c.status === 'bound').length,
  11328. searching_clients: (state.dhcpClients || []).filter(c => c.status === 'searching').length,
  11329. disabled_clients: (state.dhcpClients || []).filter(c => !c.enabled).length
  11330. };
  11331. const totalEl = document.getElementById('dhcp-stat-total');
  11332. const boundEl = document.getElementById('dhcp-stat-bound');
  11333. const searchEl = document.getElementById('dhcp-stat-searching');
  11334. const disEl = document.getElementById('dhcp-stat-disabled');
  11335. if (totalEl) totalEl.innerText = sum.total_clients ?? 0;
  11336. if (boundEl) boundEl.innerText = sum.bound_clients ?? 0;
  11337. if (searchEl) searchEl.innerText = sum.searching_clients ?? 0;
  11338. if (disEl) disEl.innerText = sum.disabled_clients ?? 0;
  11339. }
  11340. function renderDHCPClients() {
  11341. const tbody = document.getElementById('dhcp-clients-tbody');
  11342. const emptyState = document.getElementById('dhcp-clients-empty');
  11343. if (!tbody) return;
  11344. const clients = Array.isArray(state.dhcpClients) ? state.dhcpClients : [];
  11345. if (clients.length === 0) {
  11346. tbody.innerHTML = '';
  11347. if (emptyState) emptyState.classList.remove('hidden');
  11348. return;
  11349. }
  11350. if (emptyState) emptyState.classList.add('hidden');
  11351. tbody.innerHTML = clients.map(c => {
  11352. let statusBadge = '';
  11353. if (!c.enabled) {
  11354. 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>';
  11355. } else if (c.status === 'bound') {
  11356. 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>';
  11357. } else if (c.status === 'searching') {
  11358. 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>';
  11359. } else if (c.status === 'stopped') {
  11360. 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>';
  11361. } else {
  11362. 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>`;
  11363. }
  11364. 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>';
  11365. const gwDisplay = c.gateway ? `<span class="text-slate-300">${escapeHtml(c.gateway)}</span>` : '<span class="text-slate-600">--</span>';
  11366. const srvDisplay = c.dhcp_server ? `<span class="text-slate-300">${escapeHtml(c.dhcp_server)}</span>` : '<span class="text-slate-600">--</span>';
  11367. 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>';
  11368. const expDisplay = c.expires_in ? `<span class="text-purple-300">${escapeHtml(c.expires_in)}</span>` : '<span class="text-slate-600">--</span>';
  11369. // Option flags
  11370. const flags = [];
  11371. 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>');
  11372. 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>');
  11373. 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>');
  11374. 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>`);
  11375. return `
  11376. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 text-xs transition">
  11377. <td class="py-3 px-4">
  11378. <div class="flex items-center gap-2">
  11379. <span class="font-bold text-white text-sm">${escapeHtml(c.interface)}</span>
  11380. ${c.comment ? `<span class="text-[11px] text-slate-400 font-sans italic">(${escapeHtml(c.comment)})</span>` : ''}
  11381. </div>
  11382. </td>
  11383. <td class="py-3 px-4">${statusBadge}</td>
  11384. <td class="py-3 px-4 font-mono">${ipDisplay}</td>
  11385. <td class="py-3 px-4 font-mono">${gwDisplay}</td>
  11386. <td class="py-3 px-4 font-mono">${srvDisplay}</td>
  11387. <td class="py-3 px-4 font-mono text-[11px]">${dnsDisplay}</td>
  11388. <td class="py-3 px-4 font-mono text-[11px]">${expDisplay}</td>
  11389. <td class="py-3 px-4">
  11390. <div class="flex flex-wrap gap-1 font-mono">${flags.join('')}</div>
  11391. </td>
  11392. <td class="py-3 px-4 text-right space-x-1.5 font-sans whitespace-nowrap">
  11393. ${c.enabled ? `
  11394. <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>
  11395. <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>
  11396. <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>
  11397. ` : `
  11398. <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>
  11399. `}
  11400. <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>
  11401. <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>
  11402. </td>
  11403. </tr>
  11404. `;
  11405. }).join('');
  11406. }
  11407. function openDHCPClientModal(clientId = null) {
  11408. const modal = document.getElementById('modal-dhcp-client');
  11409. if (!modal) return;
  11410. const title = document.getElementById('modal-dhcp-title');
  11411. const idInput = document.getElementById('modal-dhcp-id');
  11412. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  11413. const distInput = document.getElementById('modal-dhcp-distance');
  11414. const commentInput = document.getElementById('modal-dhcp-comment');
  11415. const defRouteCheck = document.getElementById('modal-dhcp-def-route');
  11416. const peerDnsCheck = document.getElementById('modal-dhcp-peer-dns');
  11417. const peerNtpCheck = document.getElementById('modal-dhcp-peer-ntp');
  11418. const enabledCheck = document.getElementById('modal-dhcp-enabled');
  11419. // Populate interfaces
  11420. if (ifaceSelect) {
  11421. let opts = '<option value="">Select interface...</option>';
  11422. const allIfaces = state.interfaces || [];
  11423. const allVlans = state.vlans || [];
  11424. const usedIfaces = new Set((state.dhcpClients || []).map(c => c.interface));
  11425. // Group 1: Physical & Bridge Interfaces
  11426. opts += '<optgroup label="Physical & Bridge Interfaces">';
  11427. allIfaces.forEach(i => {
  11428. const isConfigured = usedIfaces.has(i.name) ? ' (Configured)' : '';
  11429. opts += `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)} [${escapeHtml(i.role || i.type)}]${isConfigured}</option>`;
  11430. });
  11431. opts += '</optgroup>';
  11432. // Group 2: VLAN Interfaces
  11433. if (allVlans.length > 0) {
  11434. opts += '<optgroup label="802.1Q VLAN Sub-interfaces">';
  11435. allVlans.forEach(v => {
  11436. const isConfigured = usedIfaces.has(v.name) ? ' (Configured)' : '';
  11437. opts += `<option value="${escapeHtml(v.name)}">${escapeHtml(v.name)} (VLAN ${v.vlan_id})${isConfigured}</option>`;
  11438. });
  11439. opts += '</optgroup>';
  11440. }
  11441. ifaceSelect.innerHTML = opts;
  11442. }
  11443. if (clientId) {
  11444. const client = (state.dhcpClients || []).find(c => c.id === clientId);
  11445. if (client) {
  11446. if (title) title.innerText = `Edit DHCP Client: ${client.interface}`;
  11447. if (idInput) idInput.value = client.id;
  11448. if (ifaceSelect) {
  11449. ifaceSelect.value = client.interface;
  11450. ifaceSelect.disabled = true; // interface cannot be changed on edit
  11451. }
  11452. if (distInput) distInput.value = client.default_route_distance || 1;
  11453. if (commentInput) commentInput.value = client.comment || '';
  11454. if (defRouteCheck) defRouteCheck.checked = client.add_default_route !== false;
  11455. if (peerDnsCheck) peerDnsCheck.checked = client.use_peer_dns !== false;
  11456. if (peerNtpCheck) peerNtpCheck.checked = client.use_peer_ntp !== false;
  11457. if (enabledCheck) enabledCheck.checked = client.enabled !== false;
  11458. }
  11459. } else {
  11460. if (title) title.innerText = 'Add DHCP Client';
  11461. if (idInput) idInput.value = '';
  11462. if (ifaceSelect) {
  11463. ifaceSelect.value = '';
  11464. ifaceSelect.disabled = false;
  11465. }
  11466. if (distInput) distInput.value = 1;
  11467. if (commentInput) commentInput.value = '';
  11468. if (defRouteCheck) defRouteCheck.checked = true;
  11469. if (peerDnsCheck) peerDnsCheck.checked = true;
  11470. if (peerNtpCheck) peerNtpCheck.checked = true;
  11471. if (enabledCheck) enabledCheck.checked = true;
  11472. }
  11473. modal.classList.remove('hidden');
  11474. }
  11475. function openDHCPClientModalForIface(ifaceName) {
  11476. openDHCPClientModal();
  11477. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  11478. if (ifaceSelect && ifaceName) {
  11479. ifaceSelect.value = ifaceName;
  11480. }
  11481. }
  11482. function closeDHCPClientModal() {
  11483. const modal = document.getElementById('modal-dhcp-client');
  11484. if (modal) modal.classList.add('hidden');
  11485. }
  11486. async function submitSaveDHCPClient(e) {
  11487. if (e) e.preventDefault();
  11488. const id = document.getElementById('modal-dhcp-id')?.value;
  11489. const iface = document.getElementById('modal-dhcp-iface')?.value?.trim();
  11490. const distance = parseInt(document.getElementById('modal-dhcp-distance')?.value || '1', 10);
  11491. const comment = document.getElementById('modal-dhcp-comment')?.value?.trim() || '';
  11492. const defRoute = document.getElementById('modal-dhcp-def-route')?.checked ?? true;
  11493. const peerDns = document.getElementById('modal-dhcp-peer-dns')?.checked ?? true;
  11494. const peerNtp = document.getElementById('modal-dhcp-peer-ntp')?.checked ?? true;
  11495. const enabled = document.getElementById('modal-dhcp-enabled')?.checked ?? true;
  11496. if (!id && !iface) {
  11497. showToast('Input Required', 'Please select an interface for the DHCP client', 'warning');
  11498. return;
  11499. }
  11500. try {
  11501. let res;
  11502. if (id) {
  11503. // PUT update
  11504. res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  11505. method: 'PUT',
  11506. headers: { 'Content-Type': 'application/json' },
  11507. body: JSON.stringify({
  11508. enabled,
  11509. add_default_route: defRoute,
  11510. default_route_distance: distance,
  11511. use_peer_dns: peerDns,
  11512. use_peer_ntp: peerNtp,
  11513. comment
  11514. })
  11515. });
  11516. } else {
  11517. // POST create
  11518. res = await fetch(`${API_BASE}/dhcp/clients`, {
  11519. method: 'POST',
  11520. headers: { 'Content-Type': 'application/json' },
  11521. body: JSON.stringify({
  11522. interface: iface,
  11523. enabled,
  11524. add_default_route: defRoute,
  11525. default_route_distance: distance,
  11526. use_peer_dns: peerDns,
  11527. use_peer_ntp: peerNtp,
  11528. comment
  11529. })
  11530. });
  11531. }
  11532. const data = await res.json();
  11533. if (!res.ok) {
  11534. showToast('Error', data.error || 'Failed to save DHCP client', 'error');
  11535. return;
  11536. }
  11537. closeDHCPClientModal();
  11538. showToast('Success', id ? 'DHCP Client updated successfully' : `DHCP Client activated on ${iface}`, 'success');
  11539. await loadDHCPClients();
  11540. fetchData(); // refresh interfaces list with new lease/status
  11541. } catch (err) {
  11542. showToast('Error', err.message, 'error');
  11543. }
  11544. }
  11545. async function toggleDHCPClientState(id, enabled) {
  11546. try {
  11547. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/state`, {
  11548. method: 'POST',
  11549. headers: { 'Content-Type': 'application/json' },
  11550. body: JSON.stringify({ enabled })
  11551. });
  11552. const data = await res.json();
  11553. if (!res.ok) {
  11554. showToast('Error', data.error || 'Failed to toggle client state', 'error');
  11555. return;
  11556. }
  11557. showToast('Updated', `DHCP client ${enabled ? 'enabled' : 'disabled'}`, 'info');
  11558. await loadDHCPClients();
  11559. fetchData();
  11560. } catch (err) {
  11561. showToast('Error', err.message, 'error');
  11562. }
  11563. }
  11564. async function renewDHCPClient(id) {
  11565. try {
  11566. showToast('Renewing...', 'Requesting DHCP lease renewal from upstream server', 'info');
  11567. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/renew`, {
  11568. method: 'POST'
  11569. });
  11570. const data = await res.json();
  11571. if (!res.ok) {
  11572. showToast('Error', data.error || 'Failed to renew lease', 'error');
  11573. return;
  11574. }
  11575. showToast('Lease Renewed', 'DHCP renewal signal sent successfully', 'success');
  11576. setTimeout(() => {
  11577. loadDHCPClients();
  11578. fetchData();
  11579. }, 1500);
  11580. } catch (err) {
  11581. showToast('Error', err.message, 'error');
  11582. }
  11583. }
  11584. async function releaseDHCPClient(id) {
  11585. try {
  11586. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/release`, {
  11587. method: 'POST'
  11588. });
  11589. const data = await res.json();
  11590. if (!res.ok) {
  11591. showToast('Error', data.error || 'Failed to release lease', 'error');
  11592. return;
  11593. }
  11594. showToast('Lease Released', 'DHCP lease released from upstream server', 'info');
  11595. await loadDHCPClients();
  11596. fetchData();
  11597. } catch (err) {
  11598. showToast('Error', err.message, 'error');
  11599. }
  11600. }
  11601. async function deleteDHCPClient(id, ifaceName) {
  11602. if (!confirm(`Are you sure you want to remove the DHCP Client on ${ifaceName}? The interface will release its dynamic IP.`)) {
  11603. return;
  11604. }
  11605. try {
  11606. const res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  11607. method: 'DELETE'
  11608. });
  11609. const data = await res.json();
  11610. if (!res.ok) {
  11611. showToast('Error', data.error || 'Failed to delete DHCP client', 'error');
  11612. return;
  11613. }
  11614. showToast('Deleted', `DHCP client removed from ${ifaceName}`, 'info');
  11615. await loadDHCPClients();
  11616. fetchData();
  11617. } catch (err) {
  11618. showToast('Error', err.message, 'error');
  11619. }
  11620. }
  11621. // ==================== DHCP SERVER (/ip dhcp-server) ====================
  11622. async function loadDHCPServer(populate = true) {
  11623. try {
  11624. const [sumRes, srvRes, netRes, leaseRes, optRes] = await Promise.all([
  11625. fetch(`${API_BASE}/dhcp-server/summary`),
  11626. fetch(`${API_BASE}/dhcp-server/servers`),
  11627. fetch(`${API_BASE}/dhcp-server/networks`),
  11628. fetch(`${API_BASE}/dhcp-server/leases`),
  11629. fetch(`${API_BASE}/dhcp-server/options`)
  11630. ]);
  11631. if (sumRes.ok) state.dhcpServerSummary = await sumRes.json();
  11632. if (srvRes.ok) state.dhcpServers = await srvRes.json();
  11633. if (netRes.ok) state.dhcpNetworks = await netRes.json();
  11634. if (leaseRes.ok) state.dhcpLeases = await leaseRes.json();
  11635. if (optRes.ok) state.dhcpOptions = await optRes.json();
  11636. const sum = state.dhcpServerSummary || {};
  11637. const srvs = state.dhcpServers || [];
  11638. const nets = state.dhcpNetworks || [];
  11639. const leases = state.dhcpLeases || [];
  11640. const opts = state.dhcpOptions || [];
  11641. // KPI Cards
  11642. const statActive = document.getElementById('dhcp-server-stat-active');
  11643. if (statActive) {
  11644. const activeCount = srvs.filter(s => s.running).length;
  11645. statActive.innerText = `${activeCount} / ${srvs.length}`;
  11646. }
  11647. const statLeases = document.getElementById('dhcp-server-stat-leases');
  11648. if (statLeases) {
  11649. statLeases.innerText = leases.length;
  11650. }
  11651. const statLeasesSub = document.getElementById('dhcp-server-stat-leases-sub');
  11652. if (statLeasesSub) {
  11653. const dyn = leases.filter(l => l.dynamic).length;
  11654. const st = leases.filter(l => !l.dynamic).length;
  11655. statLeasesSub.innerText = `${dyn} dynamic, ${st} static`;
  11656. }
  11657. const statNetworks = document.getElementById('dhcp-server-stat-networks');
  11658. if (statNetworks) {
  11659. statNetworks.innerText = nets.length;
  11660. }
  11661. // Subtab Badges
  11662. const bSrv = document.getElementById('dhcp-server-tab-badge-servers');
  11663. if (bSrv) bSrv.innerText = srvs.length;
  11664. const bNet = document.getElementById('dhcp-server-tab-badge-networks');
  11665. if (bNet) bNet.innerText = nets.length;
  11666. const bLease = document.getElementById('dhcp-server-tab-badge-leases');
  11667. if (bLease) bLease.innerText = leases.length;
  11668. const bOpt = document.getElementById('dhcp-server-tab-badge-options');
  11669. if (bOpt) bOpt.innerText = opts.length;
  11670. // Sidebar Badge
  11671. const sideBadge = document.getElementById('badge-dhcp-server-count');
  11672. if (sideBadge) sideBadge.innerText = leases.length || srvs.length;
  11673. renderCurrentDHCPServerTab();
  11674. } catch (err) {
  11675. console.error('Failed to load DHCP Server:', err);
  11676. }
  11677. }
  11678. function switchDHCPServerTab(tab) {
  11679. state.dhcpServerTab = tab;
  11680. const tabs = ['servers', 'networks', 'leases', 'options'];
  11681. tabs.forEach(t => {
  11682. const panel = document.getElementById(`dhcp-server-subtab-${t}`);
  11683. const btn = document.getElementById(`dhcp-server-tab-btn-${t}`);
  11684. if (panel) {
  11685. if (t === tab) panel.classList.remove('hidden');
  11686. else panel.classList.add('hidden');
  11687. }
  11688. if (btn) {
  11689. if (t === tab) {
  11690. 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';
  11691. } else {
  11692. 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';
  11693. }
  11694. }
  11695. });
  11696. const addBtn = document.getElementById('dhcp-server-primary-add-btn');
  11697. if (addBtn) {
  11698. if (tab === 'servers') addBtn.innerHTML = '<span>+ Add Server</span>';
  11699. else if (tab === 'networks') addBtn.innerHTML = '<span>+ Add Network</span>';
  11700. else if (tab === 'leases') addBtn.innerHTML = '<span>+ Add Static Lease</span>';
  11701. else if (tab === 'options') addBtn.innerHTML = '<span>+ Add Option</span>';
  11702. }
  11703. renderCurrentDHCPServerTab();
  11704. }
  11705. function handleDHCPServerPrimaryAdd() {
  11706. const tab = state.dhcpServerTab || 'servers';
  11707. if (tab === 'servers') openAddDHCPServerModal();
  11708. else if (tab === 'networks') openAddDHCPNetworkModal();
  11709. else if (tab === 'leases') openAddDHCPStaticLeaseModal();
  11710. else if (tab === 'options') openAddDHCPOptionModal();
  11711. }
  11712. function renderCurrentDHCPServerTab() {
  11713. const tab = state.dhcpServerTab || 'servers';
  11714. if (tab === 'servers') renderDHCPServers();
  11715. else if (tab === 'networks') renderDHCPNetworks();
  11716. else if (tab === 'leases') renderDHCPLeases();
  11717. else if (tab === 'options') renderDHCPOptions();
  11718. }
  11719. function renderDHCPServers() {
  11720. const tbody = document.getElementById('dhcp-server-tbody');
  11721. const empty = document.getElementById('dhcp-server-empty');
  11722. if (!tbody) return;
  11723. tbody.innerHTML = '';
  11724. const servers = state.dhcpServers || [];
  11725. if (servers.length === 0) {
  11726. empty?.classList.remove('hidden');
  11727. return;
  11728. }
  11729. empty?.classList.add('hidden');
  11730. servers.forEach(s => {
  11731. const tr = document.createElement('tr');
  11732. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  11733. tr.innerHTML = `
  11734. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(s.running, s.disabled)}</td>
  11735. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(s.name)}</td>
  11736. <td class="py-2.5 px-3 font-mono text-cyan-400 font-semibold">${escapeHtml(s.interface)}</td>
  11737. <td class="py-2.5 px-3 font-mono font-semibold">${s.network ? `<span class="px-2 py-0.5 rounded text-[11px] bg-emerald-500/10 text-emerald-300 border border-emerald-500/20 font-bold">${escapeHtml(s.network)}</span>` : '<span class="text-slate-500 italic text-[11px]">Unassigned</span>'}</td>
  11738. <td class="py-2.5 px-3 font-mono text-emerald-400">${escapeHtml(s.address_pool)}</td>
  11739. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(s.lease_time || '12h')}</td>
  11740. <td class="py-2.5 px-3 font-mono text-slate-300">${s.authoritative ? '<span class="text-emerald-400 font-bold">yes</span>' : '<span class="text-slate-500">no</span>'}</td>
  11741. <td class="py-2.5 px-3 font-mono text-cyan-300"><span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 border border-slate-700">${s.active_leases || 0}</span></td>
  11742. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]" title="${escapeHtml(s.comment || '')}">${escapeHtml(s.comment || '-')}</td>
  11743. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  11744. <button onclick="toggleDHCPServerState('${s.id}', ${!s.disabled})" class="text-xs ${s.disabled ? 'text-emerald-400' : 'text-slate-400'} hover:underline">${s.disabled ? 'Enable' : 'Disable'}</button>
  11745. <button onclick="openEditDHCPServerModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  11746. <button onclick="deleteDHCPServer('${s.id}', '${escapeHtml(s.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  11747. </td>
  11748. `;
  11749. tbody.appendChild(tr);
  11750. });
  11751. }
  11752. function renderDHCPNetworks() {
  11753. const tbody = document.getElementById('dhcp-networks-tbody');
  11754. const empty = document.getElementById('dhcp-networks-empty');
  11755. if (!tbody) return;
  11756. tbody.innerHTML = '';
  11757. const networks = state.dhcpNetworks || [];
  11758. if (networks.length === 0) {
  11759. empty?.classList.remove('hidden');
  11760. return;
  11761. }
  11762. empty?.classList.add('hidden');
  11763. networks.forEach(n => {
  11764. const tr = document.createElement('tr');
  11765. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  11766. const dnsStr = (n.dns_servers || []).join(', ') || '-';
  11767. const ntpStr = (n.ntp_servers || []).join(', ') || '-';
  11768. tr.innerHTML = `
  11769. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${escapeHtml(n.address)}</td>
  11770. <td class="py-2.5 px-3 font-mono text-cyan-300 font-semibold">${escapeHtml(n.gateway || '-')}</td>
  11771. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(n.netmask || '-')}</td>
  11772. <td class="py-2.5 px-3 font-mono text-slate-300 truncate max-w-[120px]" title="${escapeHtml(dnsStr)}">${escapeHtml(dnsStr)}</td>
  11773. <td class="py-2.5 px-3 font-mono text-slate-400">${escapeHtml(n.domain || '-')}</td>
  11774. <td class="py-2.5 px-3 font-mono text-purple-300 truncate max-w-[120px]" title="${escapeHtml(ntpStr)}">${escapeHtml(ntpStr)}</td>
  11775. <td class="py-2.5 px-3 font-mono text-amber-300">${escapeHtml(n.next_server || '-')}</td>
  11776. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(n.boot_file_name || '-')}</td>
  11777. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(n.comment || '')}">${escapeHtml(n.comment || '-')}</td>
  11778. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  11779. <button onclick="openEditDHCPNetworkModal('${n.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  11780. <button onclick="deleteDHCPNetwork('${n.id}', '${escapeHtml(n.address)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  11781. </td>
  11782. `;
  11783. tbody.appendChild(tr);
  11784. });
  11785. }
  11786. function renderDHCPLeases() {
  11787. const tbody = document.getElementById('dhcp-leases-tbody');
  11788. const empty = document.getElementById('dhcp-leases-empty');
  11789. if (!tbody) return;
  11790. tbody.innerHTML = '';
  11791. const leases = state.dhcpLeases || [];
  11792. if (leases.length === 0) {
  11793. empty?.classList.remove('hidden');
  11794. return;
  11795. }
  11796. empty?.classList.add('hidden');
  11797. leases.forEach(l => {
  11798. const tr = document.createElement('tr');
  11799. tr.className = `hover:bg-slate-800/40 transition text-xs ${l.disabled ? 'opacity-50' : ''}`;
  11800. const flag = l.dynamic ? '<span class="text-sky-400 font-bold" title="Dynamic">D</span>' : '<span class="text-purple-400 font-bold" title="Static Reservation">S</span>';
  11801. const statusBadge = l.status === 'bound'
  11802. ? '<span class="px-1.5 py-0.5 rounded text-[10px] bg-emerald-500/20 text-emerald-300 border border-emerald-500/30 font-semibold font-mono">bound</span>'
  11803. : l.status === 'static'
  11804. ? '<span class="px-1.5 py-0.5 rounded text-[10px] bg-purple-500/20 text-purple-300 border border-purple-500/30 font-semibold font-mono">static</span>'
  11805. : '<span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 text-slate-400 border border-slate-700 font-mono">waiting</span>';
  11806. const makeStaticBtn = l.dynamic
  11807. ? `<button onclick="makeDHCPLeaseStatic('${escapeHtml(l.mac_address)}', '${escapeHtml(l.address)}', '${escapeHtml(l.hostname || '')}', '${escapeHtml(l.comment || '')}')" class="text-xs px-2 py-0.5 rounded bg-purple-500/20 text-purple-300 border border-purple-500/30 hover:bg-purple-500/30 font-medium">Make Static</button>`
  11808. : `<button onclick="deleteDHCPStaticLease('${l.id}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Remove</button>`;
  11809. tr.innerHTML = `
  11810. <td class="py-2.5 px-3 text-center">${flag}</td>
  11811. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(l.address)}</td>
  11812. <td class="py-2.5 px-3 font-mono text-cyan-300">${escapeHtml(l.mac_address)}</td>
  11813. <td class="py-2.5 px-3 font-sans text-slate-200 font-medium">${escapeHtml(l.hostname || '*')}</td>
  11814. <td class="py-2.5 px-3 font-mono text-slate-400">${escapeHtml(l.server || 'all')}</td>
  11815. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(l.expires_in || 'never')}</td>
  11816. <td class="py-2.5 px-3">${statusBadge}</td>
  11817. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(l.comment || '')}">${escapeHtml(l.comment || '-')}</td>
  11818. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  11819. ${makeStaticBtn}
  11820. </td>
  11821. `;
  11822. tbody.appendChild(tr);
  11823. });
  11824. }
  11825. function renderDHCPOptions() {
  11826. const tbody = document.getElementById('dhcp-options-tbody');
  11827. const empty = document.getElementById('dhcp-options-empty');
  11828. if (!tbody) return;
  11829. tbody.innerHTML = '';
  11830. const options = state.dhcpOptions || [];
  11831. if (options.length === 0) {
  11832. empty?.classList.remove('hidden');
  11833. return;
  11834. }
  11835. empty?.classList.add('hidden');
  11836. options.forEach(o => {
  11837. const tr = document.createElement('tr');
  11838. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  11839. tr.innerHTML = `
  11840. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(o.name)}</td>
  11841. <td class="py-2.5 px-3 font-bold text-cyan-400 font-mono">${o.code}</td>
  11842. <td class="py-2.5 px-3 font-mono text-emerald-400 break-all max-w-xs">${escapeHtml(o.value)}</td>
  11843. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-xs" title="${escapeHtml(o.comment || '')}">${escapeHtml(o.comment || '-')}</td>
  11844. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  11845. <button onclick="openEditDHCPOptionModal('${o.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  11846. <button onclick="deleteDHCPOption('${o.id}', '${escapeHtml(o.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  11847. </td>
  11848. `;
  11849. tbody.appendChild(tr);
  11850. });
  11851. }
  11852. // ==================== MODALS & ACTIONS: SERVER ====================
  11853. function populateDHCPNetworkSelect(elemId, selectedVal) {
  11854. const sel = document.getElementById(elemId);
  11855. if (!sel) return;
  11856. sel.innerHTML = '<option value="">Select network subnet...</option>';
  11857. const networks = state.dhcpNetworks || [];
  11858. networks.forEach(n => {
  11859. const opt = document.createElement('option');
  11860. opt.value = n.address;
  11861. opt.innerText = `${n.address} (Gateway: ${n.gateway || 'None'}${n.comment ? ' - ' + n.comment : ''})`;
  11862. if (selectedVal && (selectedVal === n.address || selectedVal === n.id)) {
  11863. opt.selected = true;
  11864. }
  11865. sel.appendChild(opt);
  11866. });
  11867. }
  11868. function onDHCPServerNetworkChange() {
  11869. const netSel = document.getElementById('dhcp-server-modal-network');
  11870. if (!netSel) return;
  11871. const netVal = netSel.value;
  11872. if (!netVal) return;
  11873. const poolInput = document.getElementById('dhcp-server-modal-pool');
  11874. if (!poolInput) return;
  11875. // Auto-calculate suggested address pool based on subnet CIDR
  11876. const parts = netVal.split('/');
  11877. const ip = parts[0];
  11878. const cidr = parseInt(parts[1] || '24', 10);
  11879. if (cidr === 24) {
  11880. const octets = ip.split('.');
  11881. if (octets.length === 4) {
  11882. const base = `${octets[0]}.${octets[1]}.${octets[2]}`;
  11883. poolInput.value = `${base}.10-${base}.254`;
  11884. }
  11885. }
  11886. }
  11887. function openAddDHCPServerModal() {
  11888. document.getElementById('dhcp-server-modal-title').innerText = 'Add DHCP Server';
  11889. document.getElementById('dhcp-server-modal-id').value = '';
  11890. document.getElementById('dhcp-server-modal-name').value = `dhcp${(state.dhcpServers || []).length + 1}`;
  11891. document.getElementById('dhcp-server-modal-pool').value = '192.168.88.10-192.168.88.254';
  11892. document.getElementById('dhcp-server-modal-leasetime').value = '12h';
  11893. document.getElementById('dhcp-server-modal-comment').value = '';
  11894. document.getElementById('dhcp-server-modal-authoritative').checked = true;
  11895. document.getElementById('dhcp-server-modal-disabled').checked = false;
  11896. populateDHCPIfaceSelect('dhcp-server-modal-iface', '');
  11897. const networks = state.dhcpNetworks || [];
  11898. const defaultNet = networks.length > 0 ? networks[0].address : '';
  11899. populateDHCPNetworkSelect('dhcp-server-modal-network', defaultNet);
  11900. if (defaultNet) {
  11901. onDHCPServerNetworkChange();
  11902. }
  11903. document.getElementById('dhcp-server-instance-modal').classList.remove('hidden');
  11904. }
  11905. function openEditDHCPServerModal(id) {
  11906. const s = (state.dhcpServers || []).find(item => item.id === id);
  11907. if (!s) return;
  11908. document.getElementById('dhcp-server-modal-title').innerText = `Edit DHCP Server (${s.name})`;
  11909. document.getElementById('dhcp-server-modal-id').value = s.id;
  11910. document.getElementById('dhcp-server-modal-name').value = s.name;
  11911. document.getElementById('dhcp-server-modal-pool').value = s.address_pool;
  11912. document.getElementById('dhcp-server-modal-leasetime').value = s.lease_time || '12h';
  11913. document.getElementById('dhcp-server-modal-comment').value = s.comment || '';
  11914. document.getElementById('dhcp-server-modal-authoritative').checked = s.authoritative !== false;
  11915. document.getElementById('dhcp-server-modal-disabled').checked = !!s.disabled;
  11916. populateDHCPIfaceSelect('dhcp-server-modal-iface', s.interface);
  11917. populateDHCPNetworkSelect('dhcp-server-modal-network', s.network || '');
  11918. document.getElementById('dhcp-server-instance-modal').classList.remove('hidden');
  11919. }
  11920. function closeDHCPServerModal() {
  11921. document.getElementById('dhcp-server-instance-modal').classList.add('hidden');
  11922. }
  11923. async function submitSaveDHCPServer(e) {
  11924. e.preventDefault();
  11925. const id = document.getElementById('dhcp-server-modal-id').value;
  11926. const name = document.getElementById('dhcp-server-modal-name').value.trim();
  11927. const iface = document.getElementById('dhcp-server-modal-iface').value;
  11928. const network = document.getElementById('dhcp-server-modal-network').value.trim();
  11929. const pool = document.getElementById('dhcp-server-modal-pool').value.trim();
  11930. const leaseTime = document.getElementById('dhcp-server-modal-leasetime').value.trim() || '12h';
  11931. const comment = document.getElementById('dhcp-server-modal-comment').value.trim();
  11932. const authoritative = document.getElementById('dhcp-server-modal-authoritative').checked;
  11933. const disabled = document.getElementById('dhcp-server-modal-disabled').checked;
  11934. try {
  11935. const res = await fetch(`${API_BASE}/dhcp-server/servers`, {
  11936. method: 'POST',
  11937. headers: { 'Content-Type': 'application/json' },
  11938. body: JSON.stringify({
  11939. id,
  11940. name,
  11941. interface: iface,
  11942. network,
  11943. address_pool: pool,
  11944. lease_time: leaseTime,
  11945. authoritative,
  11946. disabled,
  11947. comment
  11948. })
  11949. });
  11950. if (res.ok) {
  11951. showToast('DHCP Server Saved', `Server ${name} configured successfully`, 'success');
  11952. closeDHCPServerModal();
  11953. loadDHCPServer(false);
  11954. fetchData(false);
  11955. } else {
  11956. const err = await res.text();
  11957. showToast('Error', err, 'error');
  11958. }
  11959. } catch (err) {
  11960. showToast('Error', err.message, 'error');
  11961. }
  11962. }
  11963. async function toggleDHCPServerState(id, disabled) {
  11964. try {
  11965. const res = await fetch(`${API_BASE}/dhcp-server/servers/${encodeURIComponent(id)}/state`, {
  11966. method: 'POST',
  11967. headers: { 'Content-Type': 'application/json' },
  11968. body: JSON.stringify({ disabled })
  11969. });
  11970. if (res.ok) {
  11971. showToast('State Updated', disabled ? 'Server disabled' : 'Server enabled', 'info');
  11972. loadDHCPServer(false);
  11973. fetchData(false);
  11974. }
  11975. } catch (err) {
  11976. showToast('Error', err.message, 'error');
  11977. }
  11978. }
  11979. async function deleteDHCPServer(id, name) {
  11980. if (!confirm(`Are you sure you want to delete DHCP Server "${name}"?`)) return;
  11981. try {
  11982. const res = await fetch(`${API_BASE}/dhcp-server/servers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11983. if (res.ok) {
  11984. showToast('Deleted', `DHCP Server ${name} removed`, 'success');
  11985. loadDHCPServer(false);
  11986. fetchData(false);
  11987. }
  11988. } catch (err) {
  11989. showToast('Error', err.message, 'error');
  11990. }
  11991. }
  11992. // ==================== MODALS & ACTIONS: NETWORKS ====================
  11993. function openAddDHCPNetworkModal() {
  11994. document.getElementById('dhcp-network-modal-title').innerText = 'Add DHCP Network';
  11995. document.getElementById('dhcp-network-modal-id').value = '';
  11996. document.getElementById('dhcp-network-modal-address').value = '192.168.88.0/24';
  11997. document.getElementById('dhcp-network-modal-gateway').value = '192.168.88.1';
  11998. document.getElementById('dhcp-network-modal-dns').value = '192.168.88.1, 1.1.1.1, 8.8.8.8';
  11999. document.getElementById('dhcp-network-modal-domain').value = 'lan';
  12000. document.getElementById('dhcp-network-modal-ntp').value = '192.168.88.1, time.cloudflare.com';
  12001. document.getElementById('dhcp-network-modal-tftp').value = '';
  12002. document.getElementById('dhcp-network-modal-bootfile').value = '';
  12003. document.getElementById('dhcp-network-modal-wins').value = '';
  12004. document.getElementById('dhcp-network-modal-netmask').value = '';
  12005. document.getElementById('dhcp-network-modal-comment').value = '';
  12006. renderDHCPNetworkOptionsCheckboxes([]);
  12007. document.getElementById('dhcp-network-modal').classList.remove('hidden');
  12008. }
  12009. function openEditDHCPNetworkModal(id) {
  12010. const n = (state.dhcpNetworks || []).find(item => item.id === id);
  12011. if (!n) return;
  12012. document.getElementById('dhcp-network-modal-title').innerText = `Edit DHCP Network (${n.address})`;
  12013. document.getElementById('dhcp-network-modal-id').value = n.id;
  12014. document.getElementById('dhcp-network-modal-address').value = n.address;
  12015. document.getElementById('dhcp-network-modal-gateway').value = n.gateway || '';
  12016. document.getElementById('dhcp-network-modal-dns').value = (n.dns_servers || []).join(', ');
  12017. document.getElementById('dhcp-network-modal-domain').value = n.domain || '';
  12018. document.getElementById('dhcp-network-modal-ntp').value = (n.ntp_servers || []).join(', ');
  12019. document.getElementById('dhcp-network-modal-tftp').value = n.next_server || '';
  12020. document.getElementById('dhcp-network-modal-bootfile').value = n.boot_file_name || '';
  12021. document.getElementById('dhcp-network-modal-wins').value = (n.wins_servers || []).join(', ');
  12022. document.getElementById('dhcp-network-modal-netmask').value = n.netmask || '';
  12023. document.getElementById('dhcp-network-modal-comment').value = n.comment || '';
  12024. renderDHCPNetworkOptionsCheckboxes(n.dhcp_options || []);
  12025. document.getElementById('dhcp-network-modal').classList.remove('hidden');
  12026. }
  12027. function renderDHCPNetworkOptionsCheckboxes(selectedIds) {
  12028. const container = document.getElementById('dhcp-network-modal-options-list');
  12029. if (!container) return;
  12030. container.innerHTML = '';
  12031. const opts = state.dhcpOptions || [];
  12032. if (opts.length === 0) {
  12033. container.innerHTML = '<span class="text-slate-500 text-[11px] col-span-2">No custom options configured. Add some in the "Options" tab.</span>';
  12034. return;
  12035. }
  12036. opts.forEach(o => {
  12037. const isChecked = selectedIds.includes(o.id);
  12038. const label = document.createElement('label');
  12039. label.className = 'flex items-center space-x-2 text-slate-300 hover:text-white cursor-pointer';
  12040. label.innerHTML = `
  12041. <input type="checkbox" name="dhcp-net-opt" value="${o.id}" ${isChecked ? 'checked' : ''} class="rounded bg-slate-800 border-slate-700 text-emerald-600">
  12042. <span class="truncate" title="${escapeHtml(o.name)} (Code ${o.code})">${escapeHtml(o.name)} <span class="text-cyan-400">#${o.code}</span></span>
  12043. `;
  12044. container.appendChild(label);
  12045. });
  12046. }
  12047. function closeDHCPNetworkModal() {
  12048. document.getElementById('dhcp-network-modal').classList.add('hidden');
  12049. }
  12050. async function submitSaveDHCPNetwork(e) {
  12051. e.preventDefault();
  12052. const id = document.getElementById('dhcp-network-modal-id').value;
  12053. const address = document.getElementById('dhcp-network-modal-address').value.trim();
  12054. const gateway = document.getElementById('dhcp-network-modal-gateway').value.trim();
  12055. const dnsStr = document.getElementById('dhcp-network-modal-dns').value.trim();
  12056. const domain = document.getElementById('dhcp-network-modal-domain').value.trim();
  12057. const ntpStr = document.getElementById('dhcp-network-modal-ntp').value.trim();
  12058. const tftp = document.getElementById('dhcp-network-modal-tftp').value.trim();
  12059. const bootfile = document.getElementById('dhcp-network-modal-bootfile').value.trim();
  12060. const winsStr = document.getElementById('dhcp-network-modal-wins').value.trim();
  12061. const netmask = document.getElementById('dhcp-network-modal-netmask').value.trim();
  12062. const comment = document.getElementById('dhcp-network-modal-comment').value.trim();
  12063. const selectedOpts = [];
  12064. document.querySelectorAll('input[name="dhcp-net-opt"]:checked').forEach(cb => selectedOpts.push(cb.value));
  12065. const dnsServers = dnsStr ? dnsStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  12066. const ntpServers = ntpStr ? ntpStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  12067. const winsServers = winsStr ? winsStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  12068. try {
  12069. const res = await fetch(`${API_BASE}/dhcp-server/networks`, {
  12070. method: 'POST',
  12071. headers: { 'Content-Type': 'application/json' },
  12072. body: JSON.stringify({
  12073. id,
  12074. address,
  12075. gateway,
  12076. netmask,
  12077. dns_servers: dnsServers,
  12078. domain,
  12079. ntp_servers: ntpServers,
  12080. next_server: tftp,
  12081. boot_file_name: bootfile,
  12082. wins_servers: winsServers,
  12083. dhcp_options: selectedOpts,
  12084. comment
  12085. })
  12086. });
  12087. if (res.ok) {
  12088. showToast('Network Saved', `Subnet ${address} configured successfully`, 'success');
  12089. closeDHCPNetworkModal();
  12090. loadDHCPServer(false);
  12091. fetchData(false);
  12092. } else {
  12093. const err = await res.text();
  12094. showToast('Error', err, 'error');
  12095. }
  12096. } catch (err) {
  12097. showToast('Error', err.message, 'error');
  12098. }
  12099. }
  12100. async function deleteDHCPNetwork(id, addr) {
  12101. if (!confirm(`Are you sure you want to delete DHCP Network "${addr}"?`)) return;
  12102. try {
  12103. const res = await fetch(`${API_BASE}/dhcp-server/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12104. if (res.ok) {
  12105. showToast('Deleted', `Network ${addr} removed`, 'success');
  12106. loadDHCPServer(false);
  12107. fetchData(false);
  12108. }
  12109. } catch (err) {
  12110. showToast('Error', err.message, 'error');
  12111. }
  12112. }
  12113. // ==================== MODALS & ACTIONS: LEASES ====================
  12114. function openAddDHCPStaticLeaseModal() {
  12115. document.getElementById('dhcp-static-lease-modal-title').innerText = 'Add Static Lease Reservation';
  12116. document.getElementById('dhcp-static-lease-modal-id').value = '';
  12117. document.getElementById('dhcp-static-lease-modal-mac').value = '';
  12118. document.getElementById('dhcp-static-lease-modal-ip').value = '';
  12119. document.getElementById('dhcp-static-lease-modal-hostname').value = '';
  12120. document.getElementById('dhcp-static-lease-modal-server').value = 'all';
  12121. document.getElementById('dhcp-static-lease-modal-comment').value = '';
  12122. document.getElementById('dhcp-static-lease-modal-disabled').checked = false;
  12123. document.getElementById('dhcp-static-lease-modal').classList.remove('hidden');
  12124. }
  12125. function closeDHCPStaticLeaseModal() {
  12126. document.getElementById('dhcp-static-lease-modal').classList.add('hidden');
  12127. }
  12128. async function submitSaveDHCPStaticLease(e) {
  12129. e.preventDefault();
  12130. const id = document.getElementById('dhcp-static-lease-modal-id').value;
  12131. const mac = document.getElementById('dhcp-static-lease-modal-mac').value.trim();
  12132. const ip = document.getElementById('dhcp-static-lease-modal-ip').value.trim();
  12133. const hostname = document.getElementById('dhcp-static-lease-modal-hostname').value.trim();
  12134. const server = document.getElementById('dhcp-static-lease-modal-server').value.trim() || 'all';
  12135. const comment = document.getElementById('dhcp-static-lease-modal-comment').value.trim();
  12136. const disabled = document.getElementById('dhcp-static-lease-modal-disabled').checked;
  12137. try {
  12138. const res = await fetch(`${API_BASE}/dhcp-server/leases/static`, {
  12139. method: 'POST',
  12140. headers: { 'Content-Type': 'application/json' },
  12141. body: JSON.stringify({
  12142. id,
  12143. mac_address: mac,
  12144. address: ip,
  12145. hostname,
  12146. server,
  12147. comment,
  12148. disabled
  12149. })
  12150. });
  12151. if (res.ok) {
  12152. showToast('Static Lease Saved', `IP ${ip} reserved for ${mac}`, 'success');
  12153. closeDHCPStaticLeaseModal();
  12154. loadDHCPServer(false);
  12155. fetchData(false);
  12156. } else {
  12157. const err = await res.text();
  12158. showToast('Error', err, 'error');
  12159. }
  12160. } catch (err) {
  12161. showToast('Error', err.message, 'error');
  12162. }
  12163. }
  12164. async function deleteDHCPStaticLease(id) {
  12165. if (!confirm('Are you sure you want to remove this static reservation?')) return;
  12166. try {
  12167. const res = await fetch(`${API_BASE}/dhcp-server/leases/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12168. if (res.ok) {
  12169. showToast('Deleted', 'Static lease removed', 'success');
  12170. loadDHCPServer(false);
  12171. fetchData(false);
  12172. }
  12173. } catch (err) {
  12174. showToast('Error', err.message, 'error');
  12175. }
  12176. }
  12177. async function makeDHCPLeaseStatic(mac, ip, hostname, comment) {
  12178. try {
  12179. const res = await fetch(`${API_BASE}/dhcp-server/leases/make-static`, {
  12180. method: 'POST',
  12181. headers: { 'Content-Type': 'application/json' },
  12182. body: JSON.stringify({
  12183. mac_address: mac,
  12184. address: ip,
  12185. hostname,
  12186. comment: comment || 'Converted to static'
  12187. })
  12188. });
  12189. if (res.ok) {
  12190. showToast('Lease Made Static', `IP ${ip} permanently reserved for ${mac}`, 'success');
  12191. loadDHCPServer(false);
  12192. fetchData(false);
  12193. } else {
  12194. const err = await res.text();
  12195. showToast('Error', err, 'error');
  12196. }
  12197. } catch (err) {
  12198. showToast('Error', err.message, 'error');
  12199. }
  12200. }
  12201. // ==================== MODALS & ACTIONS: OPTIONS ====================
  12202. function openAddDHCPOptionModal() {
  12203. document.getElementById('dhcp-option-modal-title').innerText = 'Add DHCP Option';
  12204. document.getElementById('dhcp-option-modal-id').value = '';
  12205. document.getElementById('dhcp-option-modal-name').value = '';
  12206. document.getElementById('dhcp-option-modal-code').value = '';
  12207. document.getElementById('dhcp-option-modal-value').value = '';
  12208. document.getElementById('dhcp-option-modal-comment').value = '';
  12209. document.getElementById('dhcp-option-modal').classList.remove('hidden');
  12210. }
  12211. function openEditDHCPOptionModal(id) {
  12212. const o = (state.dhcpOptions || []).find(item => item.id === id);
  12213. if (!o) return;
  12214. document.getElementById('dhcp-option-modal-title').innerText = `Edit DHCP Option (${o.name})`;
  12215. document.getElementById('dhcp-option-modal-id').value = o.id;
  12216. document.getElementById('dhcp-option-modal-name').value = o.name;
  12217. document.getElementById('dhcp-option-modal-code').value = o.code;
  12218. document.getElementById('dhcp-option-modal-value').value = o.value;
  12219. document.getElementById('dhcp-option-modal-comment').value = o.comment || '';
  12220. document.getElementById('dhcp-option-modal').classList.remove('hidden');
  12221. }
  12222. function closeDHCPOptionModal() {
  12223. document.getElementById('dhcp-option-modal').classList.add('hidden');
  12224. }
  12225. async function submitSaveDHCPOption(e) {
  12226. e.preventDefault();
  12227. const id = document.getElementById('dhcp-option-modal-id').value;
  12228. const name = document.getElementById('dhcp-option-modal-name').value.trim();
  12229. const code = parseInt(document.getElementById('dhcp-option-modal-code').value);
  12230. const value = document.getElementById('dhcp-option-modal-value').value.trim();
  12231. const comment = document.getElementById('dhcp-option-modal-comment').value.trim();
  12232. try {
  12233. const res = await fetch(`${API_BASE}/dhcp-server/options`, {
  12234. method: 'POST',
  12235. headers: { 'Content-Type': 'application/json' },
  12236. body: JSON.stringify({ id, name, code, value, comment })
  12237. });
  12238. if (res.ok) {
  12239. showToast('Option Saved', `DHCP option ${name} (#${code}) configured`, 'success');
  12240. closeDHCPOptionModal();
  12241. loadDHCPServer(false);
  12242. fetchData(false);
  12243. } else {
  12244. const err = await res.text();
  12245. showToast('Error', err, 'error');
  12246. }
  12247. } catch (err) {
  12248. showToast('Error', err.message, 'error');
  12249. }
  12250. }
  12251. async function deleteDHCPOption(id, name) {
  12252. if (!confirm(`Are you sure you want to delete DHCP Option "${name}"?`)) return;
  12253. try {
  12254. const res = await fetch(`${API_BASE}/dhcp-server/options/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12255. if (res.ok) {
  12256. showToast('Deleted', `Option ${name} removed`, 'success');
  12257. loadDHCPServer(false);
  12258. fetchData(false);
  12259. }
  12260. } catch (err) {
  12261. showToast('Error', err.message, 'error');
  12262. }
  12263. }
  12264. // ==================== WIZARD: DHCP SETUP (MikroTik style) ====================
  12265. function openDHCPServerSetupModal() {
  12266. populateDHCPIfaceSelect('dhcp-wizard-iface', '');
  12267. onDHCPWizardIfaceChange();
  12268. document.getElementById('dhcp-setup-wizard-modal').classList.remove('hidden');
  12269. }
  12270. function closeDHCPServerSetupModal() {
  12271. document.getElementById('dhcp-setup-wizard-modal').classList.add('hidden');
  12272. }
  12273. function onDHCPWizardIfaceChange() {
  12274. const ifaceName = document.getElementById('dhcp-wizard-iface').value;
  12275. const iface = (state.interfaces || []).find(i => i.name === ifaceName);
  12276. let ip = '192.168.88.1';
  12277. let prefix = '24';
  12278. if (iface && iface.ip_address) {
  12279. const parts = iface.ip_address.split('/');
  12280. ip = parts[0];
  12281. if (parts.length > 1) prefix = parts[1];
  12282. }
  12283. // Calculate subnet base (e.g. 192.168.88.0/24)
  12284. const ipParts = ip.split('.');
  12285. if (ipParts.length === 4) {
  12286. const baseSpace = `${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.0/${prefix}`;
  12287. const pool = `${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.10-${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.254`;
  12288. document.getElementById('dhcp-wizard-space').value = baseSpace;
  12289. document.getElementById('dhcp-wizard-gateway').value = ip;
  12290. document.getElementById('dhcp-wizard-pool').value = pool;
  12291. document.getElementById('dhcp-wizard-dns').value = `${ip}, 1.1.1.1, 8.8.8.8`;
  12292. document.getElementById('dhcp-wizard-ntp').value = `${ip}`;
  12293. }
  12294. }
  12295. async function submitDHCPServerSetupWizard(e) {
  12296. e.preventDefault();
  12297. const iface = document.getElementById('dhcp-wizard-iface').value;
  12298. const space = document.getElementById('dhcp-wizard-space').value.trim();
  12299. const gw = document.getElementById('dhcp-wizard-gateway').value.trim();
  12300. const pool = document.getElementById('dhcp-wizard-pool').value.trim();
  12301. const dnsStr = document.getElementById('dhcp-wizard-dns').value.trim();
  12302. const leaseTime = document.getElementById('dhcp-wizard-leasetime').value.trim() || '12h';
  12303. const ntpStr = document.getElementById('dhcp-wizard-ntp').value.trim();
  12304. const tftp = document.getElementById('dhcp-wizard-tftp').value.trim();
  12305. const dnsServers = dnsStr ? dnsStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  12306. const ntpServers = ntpStr ? ntpStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  12307. try {
  12308. const res = await fetch(`${API_BASE}/dhcp-server/setup`, {
  12309. method: 'POST',
  12310. headers: { 'Content-Type': 'application/json' },
  12311. body: JSON.stringify({
  12312. interface: iface,
  12313. address_space: space,
  12314. gateway: gw,
  12315. address_pool: pool,
  12316. dns_servers: dnsServers,
  12317. lease_time: leaseTime,
  12318. ntp_servers: ntpServers,
  12319. next_server: tftp
  12320. })
  12321. });
  12322. if (res.ok) {
  12323. showToast('DHCP Setup Complete', `DHCP Server setup finished on ${iface}`, 'success');
  12324. closeDHCPServerSetupModal();
  12325. loadDHCPServer(false);
  12326. fetchData(false);
  12327. } else {
  12328. const err = await res.text();
  12329. showToast('Error', err, 'error');
  12330. }
  12331. } catch (err) {
  12332. showToast('Error', err.message, 'error');
  12333. }
  12334. }
  12335. function populateDHCPIfaceSelect(elemId, selectedVal) {
  12336. const sel = document.getElementById(elemId);
  12337. if (!sel) return;
  12338. sel.innerHTML = '<option value="">Select interface...</option>';
  12339. const ifaces = state.interfaces || [];
  12340. ifaces.forEach(i => {
  12341. if (i.name === 'lo') return;
  12342. const opt = document.createElement('option');
  12343. opt.value = i.name;
  12344. const ipStr = i.ip_address ? ` (${i.ip_address})` : '';
  12345. opt.textContent = `${i.name}${ipStr} [${i.role || i.type || 'interface'}]`;
  12346. if (i.name === selectedVal) opt.selected = true;
  12347. sel.appendChild(opt);
  12348. });
  12349. }
  12350. // ==================== UNIVERSAL TABLE ORDERING / SORTING (WINBOX / WEBFIG STYLE) ====================
  12351. function initTableSorting() {
  12352. document.querySelectorAll('table').forEach(setupSortableTable);
  12353. }
  12354. function setupSortableTable(table) {
  12355. const thead = table.querySelector('thead');
  12356. const tbody = table.querySelector('tbody');
  12357. if (!thead || !tbody) return;
  12358. const headerRows = thead.querySelectorAll('tr');
  12359. if (headerRows.length === 0) return;
  12360. const ths = headerRows[headerRows.length - 1].querySelectorAll('th');
  12361. ths.forEach((th, colIdx) => {
  12362. if (th._sortBound) return;
  12363. th._sortBound = true;
  12364. const rawText = th.innerText.trim().toLowerCase();
  12365. const isActionsCol = rawText === 'actions' || (rawText === 'action' && th.classList.contains('text-right'));
  12366. const isCheckboxCol = !!th.querySelector('input[type="checkbox"]');
  12367. const isExpandCol = (th.classList.contains('w-8') || th.classList.contains('w-6')) && !rawText;
  12368. const isExplicitNoSort = th.classList.contains('no-sort') || th.getAttribute('data-sortable') === 'false';
  12369. if (isActionsCol || isCheckboxCol || isExpandCol || isExplicitNoSort) {
  12370. return;
  12371. }
  12372. th.classList.add('table-sortable', 'group');
  12373. if (!th.title) th.title = 'Click to sort (Ascending / Descending / Default)';
  12374. let icon = th.querySelector('.table-sort-icon');
  12375. if (!icon) {
  12376. icon = document.createElement('span');
  12377. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  12378. icon.innerHTML = '⇅';
  12379. th.appendChild(icon);
  12380. }
  12381. th.addEventListener('click', (e) => {
  12382. if (e.target.tagName === 'INPUT' || e.target.tagName === 'BUTTON' || e.target.closest('button, input')) return;
  12383. handleHeaderClick(table, th, colIdx);
  12384. });
  12385. });
  12386. if (!tbody._sortObserved) {
  12387. tbody._sortObserved = true;
  12388. let sortDebounceTimer = null;
  12389. const observer = new MutationObserver((mutations) => {
  12390. if (tbody._isSorting) return;
  12391. const hasChildChanges = mutations.some(m => m.type === 'childList' && m.addedNodes.length > 0);
  12392. if (!hasChildChanges) return;
  12393. clearTimeout(sortDebounceTimer);
  12394. sortDebounceTimer = setTimeout(() => {
  12395. if (tbody._isSorting) return;
  12396. if (table._activeSort && table._activeSort.dir !== 'none') {
  12397. applyTableSort(table, table._activeSort.colIdx, table._activeSort.dir, false);
  12398. } else {
  12399. tagOriginalRowOrder(tbody);
  12400. }
  12401. }, 10);
  12402. });
  12403. observer.observe(tbody, { childList: true });
  12404. }
  12405. tagOriginalRowOrder(tbody);
  12406. }
  12407. function tagOriginalRowOrder(tbody) {
  12408. let idx = 0;
  12409. Array.from(tbody.children).forEach(tr => {
  12410. if (!tr.querySelector('td[colspan]')) {
  12411. if (!tr.hasAttribute('data-orig-idx')) {
  12412. tr.setAttribute('data-orig-idx', idx++);
  12413. }
  12414. }
  12415. });
  12416. }
  12417. function handleHeaderClick(table, th, colIdx) {
  12418. const currentSort = table._activeSort || { colIdx: -1, dir: 'none' };
  12419. let newDir = 'asc';
  12420. if (currentSort.colIdx === colIdx) {
  12421. if (currentSort.dir === 'asc') newDir = 'desc';
  12422. else if (currentSort.dir === 'desc') newDir = 'none';
  12423. else newDir = 'asc';
  12424. } else {
  12425. newDir = 'asc';
  12426. }
  12427. table._activeSort = { colIdx, dir: newDir };
  12428. updateHeaderIcons(table, colIdx, newDir);
  12429. applyTableSort(table, colIdx, newDir, true);
  12430. }
  12431. function updateHeaderIcons(table, activeColIdx, dir) {
  12432. const thead = table.querySelector('thead');
  12433. if (!thead) return;
  12434. const ths = thead.querySelectorAll('th');
  12435. ths.forEach((th, idx) => {
  12436. const icon = th.querySelector('.table-sort-icon');
  12437. if (!icon) return;
  12438. if (idx === activeColIdx && dir !== 'none') {
  12439. icon.innerHTML = dir === 'asc' ? '▲' : '▼';
  12440. icon.className = 'table-sort-icon text-cyan-400 font-bold opacity-100';
  12441. th.classList.add('table-sorted-active');
  12442. } else {
  12443. icon.innerHTML = '⇅';
  12444. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  12445. th.classList.remove('table-sorted-active');
  12446. }
  12447. });
  12448. }
  12449. function applyTableSort(table, colIdx, dir, userInitiated) {
  12450. const tbody = table.querySelector('tbody');
  12451. if (!tbody || tbody.children.length <= 1) return;
  12452. tbody._isSorting = true;
  12453. tagOriginalRowOrder(tbody);
  12454. // Group parent rows and any attached drawer/sub-rows
  12455. const groups = [];
  12456. let currentGroup = null;
  12457. Array.from(tbody.children).forEach(tr => {
  12458. if (tr.querySelector('td[colspan]')) {
  12459. if (currentGroup) {
  12460. currentGroup.subRows.push(tr);
  12461. } else {
  12462. groups.push({ mainRow: tr, subRows: [] });
  12463. }
  12464. } else {
  12465. currentGroup = { mainRow: tr, subRows: [] };
  12466. groups.push(currentGroup);
  12467. }
  12468. });
  12469. if (dir === 'none') {
  12470. groups.sort((a, b) => {
  12471. const idxA = parseInt(a.mainRow.getAttribute('data-orig-idx') || '0', 10);
  12472. const idxB = parseInt(b.mainRow.getAttribute('data-orig-idx') || '0', 10);
  12473. return idxA - idxB;
  12474. });
  12475. } else {
  12476. groups.sort((a, b) => {
  12477. const cellA = a.mainRow.children[colIdx];
  12478. const cellB = b.mainRow.children[colIdx];
  12479. const res = compareTableCells(cellA, cellB);
  12480. return dir === 'asc' ? res : -res;
  12481. });
  12482. }
  12483. // Re-append rows in sorted order
  12484. groups.forEach(g => {
  12485. tbody.appendChild(g.mainRow);
  12486. g.subRows.forEach(sub => tbody.appendChild(sub));
  12487. });
  12488. tbody._isSorting = false;
  12489. }
  12490. function getCellRawText(cell) {
  12491. if (!cell) return '';
  12492. if (cell.hasAttribute('data-sort-value')) return cell.getAttribute('data-sort-value');
  12493. const input = cell.querySelector('input, select');
  12494. if (input) {
  12495. if (input.type === 'checkbox') return input.checked ? '1' : '0';
  12496. return input.value;
  12497. }
  12498. return cell.innerText.trim();
  12499. }
  12500. function parseTrafficToNumber(str) {
  12501. const m = str.match(/^([\d.,]+)\s*([KMGTkmgt]?[iI]?[Bb](?:ps|\/s)?)/);
  12502. if (!m) return null;
  12503. const num = parseFloat(m[1].replace(/,/g, ''));
  12504. if (isNaN(num)) return null;
  12505. const unit = m[2].toUpperCase();
  12506. let mult = 1;
  12507. if (unit.startsWith('K')) mult = 1024;
  12508. else if (unit.startsWith('M')) mult = 1024 * 1024;
  12509. else if (unit.startsWith('G')) mult = 1024 * 1024 * 1024;
  12510. else if (unit.startsWith('T')) mult = 1024 * 1024 * 1024 * 1024;
  12511. return num * mult;
  12512. }
  12513. function parseIpToNumber(str) {
  12514. const clean = str.replace(/^[!~]/, '').trim();
  12515. const m = clean.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(?:\/(\d{1,2}))?/);
  12516. if (!m) return null;
  12517. const o1 = parseInt(m[1], 10);
  12518. const o2 = parseInt(m[2], 10);
  12519. const o3 = parseInt(m[3], 10);
  12520. const o4 = parseInt(m[4], 10);
  12521. if (o1 > 255 || o2 > 255 || o3 > 255 || o4 > 255) return null;
  12522. return ((o1 * 256 + o2) * 256 + o3) * 256 + o4;
  12523. }
  12524. function parseCompoundPackets(str) {
  12525. const m = str.match(/^([\d,]+)p/);
  12526. if (!m) return null;
  12527. return parseInt(m[1].replace(/,/g, ''), 10);
  12528. }
  12529. function compareTableCells(cellA, cellB) {
  12530. const a = getCellRawText(cellA);
  12531. const b = getCellRawText(cellB);
  12532. if (a === '' && b !== '') return 1;
  12533. if (b === '' && a !== '') return -1;
  12534. if (a === b) return 0;
  12535. // 1. IP Addresses / CIDR
  12536. const ipA = parseIpToNumber(a);
  12537. const ipB = parseIpToNumber(b);
  12538. if (ipA !== null && ipB !== null) return ipA - ipB;
  12539. // 2. Packet counts (e.g. "1,250p / 45 KB")
  12540. const pktA = parseCompoundPackets(a);
  12541. const pktB = parseCompoundPackets(b);
  12542. if (pktA !== null && pktB !== null) return pktA - pktB;
  12543. // 3. Traffic / Throughput / Bytes (e.g. "1.2 MB", "500 KiB", "10 Gbps")
  12544. const trafA = parseTrafficToNumber(a);
  12545. const trafB = parseTrafficToNumber(b);
  12546. if (trafA !== null && trafB !== null) return trafA - trafB;
  12547. // 4. Numbers with '#' or formatted with commas (e.g. "#1", "24", "1,200")
  12548. const cleanNumA = a.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  12549. const cleanNumB = b.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  12550. const numA = Number(cleanNumA);
  12551. const numB = Number(cleanNumB);
  12552. if (!isNaN(numA) && !isNaN(numB) && cleanNumA !== '' && cleanNumB !== '') {
  12553. return numA - numB;
  12554. }
  12555. // 5. Natural case-insensitive string compare
  12556. return a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' });
  12557. }
  12558. // ==================== VRRP HIGH AVAILABILITY CONTROLLER ====================
  12559. async function loadVRRP(showToastNotification = false) {
  12560. try {
  12561. const [instRes, sumRes] = await Promise.all([
  12562. fetch(`${API_BASE}/vrrp/instances`),
  12563. fetch(`${API_BASE}/vrrp/summary`)
  12564. ]);
  12565. if (instRes.ok) {
  12566. state.vrrpInstances = await instRes.json();
  12567. renderVRRP();
  12568. }
  12569. if (sumRes.ok) {
  12570. state.vrrpSummary = await sumRes.json();
  12571. renderVRRPSummary();
  12572. }
  12573. if (showToastNotification) {
  12574. showToast('Refreshed', 'VRRP telemetry refreshed', 'info');
  12575. }
  12576. } catch (err) {
  12577. console.error('Failed to load VRRP:', err);
  12578. }
  12579. }
  12580. function renderVRRPSummary() {
  12581. const s = state.vrrpSummary || { total_instances: 0, master_instances: 0, backup_instances: 0 };
  12582. const elTotal = document.getElementById('vrrp-stat-total');
  12583. if (elTotal) elTotal.innerText = s.total_instances || 0;
  12584. const elMaster = document.getElementById('vrrp-stat-master');
  12585. if (elMaster) elMaster.innerText = s.master_instances || 0;
  12586. const elBackup = document.getElementById('vrrp-stat-backup');
  12587. if (elBackup) elBackup.innerText = s.backup_instances || 0;
  12588. const bCount = document.getElementById('badge-vrrp-count');
  12589. if (bCount) bCount.innerText = s.total_instances || 0;
  12590. const dot = document.getElementById('badge-vrrp-dot');
  12591. if (dot) {
  12592. if (s.master_instances > 0) {
  12593. dot.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  12594. } else if (s.backup_instances > 0) {
  12595. dot.className = 'w-2 h-2 rounded-full bg-sky-400';
  12596. } else {
  12597. dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  12598. }
  12599. }
  12600. }
  12601. function renderVRRP() {
  12602. const tbody = document.getElementById('vrrp-table-tbody');
  12603. const empty = document.getElementById('vrrp-table-empty');
  12604. if (!tbody) return;
  12605. tbody.innerHTML = '';
  12606. const instances = state.vrrpInstances || [];
  12607. if (instances.length === 0) {
  12608. empty?.classList.remove('hidden');
  12609. return;
  12610. }
  12611. empty?.classList.add('hidden');
  12612. instances.forEach(inst => {
  12613. const tr = document.createElement('tr');
  12614. tr.className = `hover:bg-slate-800/40 transition text-xs ${inst.disabled ? 'opacity-50' : ''}`;
  12615. // Render Flag: M (Master), B (Backup), F (Fault), X (Disabled)
  12616. let flagHtml = `<span class="inline-flex items-center justify-center w-5 h-5 rounded-md font-mono font-bold text-[11px] bg-slate-800 text-slate-500 border border-slate-700">-</span>`;
  12617. if (inst.disabled) {
  12618. flagHtml = `<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>`;
  12619. } else if (inst.state === 'MASTER') {
  12620. flagHtml = `<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="Master (Holding VIP)">M</span>`;
  12621. } else if (inst.state === 'BACKUP') {
  12622. flagHtml = `<span class="inline-flex items-center justify-center w-5 h-5 rounded-md font-mono font-bold text-[11px] bg-sky-500/20 text-sky-400 border border-sky-500/40 shadow-sm" title="Backup (Standby)">B</span>`;
  12623. } else if (inst.state === 'FAULT') {
  12624. flagHtml = `<span class="inline-flex items-center justify-center w-5 h-5 rounded-md font-mono font-bold text-[11px] bg-amber-500/20 text-amber-400 border border-amber-500/40 shadow-sm" title="Fault (Interface Down)">F</span>`;
  12625. }
  12626. // Render State Badge
  12627. let stateBadge = `<span class="px-2 py-0.5 rounded text-[10px] bg-slate-800 text-slate-400 border border-slate-700">DISABLED</span>`;
  12628. if (!inst.disabled) {
  12629. if (inst.state === 'MASTER') {
  12630. stateBadge = `<span class="px-2 py-0.5 rounded text-[10px] bg-emerald-500/20 text-emerald-300 border border-emerald-500/40 font-bold inline-flex items-center gap-1.5"><span class="w-1.5 h-1.5 rounded-full bg-emerald-400 animate-pulse"></span>MASTER</span>`;
  12631. } else if (inst.state === 'BACKUP') {
  12632. stateBadge = `<span class="px-2 py-0.5 rounded text-[10px] bg-sky-500/20 text-sky-300 border border-sky-500/40 font-bold inline-flex items-center gap-1.5"><span class="w-1.5 h-1.5 rounded-full bg-sky-400"></span>BACKUP</span>`;
  12633. } else if (inst.state === 'FAULT') {
  12634. stateBadge = `<span class="px-2 py-0.5 rounded text-[10px] bg-amber-500/20 text-amber-300 border border-amber-500/40 font-bold inline-flex items-center gap-1.5"><span class="w-1.5 h-1.5 rounded-full bg-amber-400"></span>FAULT</span>`;
  12635. }
  12636. }
  12637. const vipsStr = (inst.virtual_ips || []).join(', ') || '-';
  12638. tr.innerHTML = `
  12639. <td class="py-2.5 px-3 text-center">${flagHtml}</td>
  12640. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(inst.name)}</td>
  12641. <td class="py-2.5 px-3 font-mono text-cyan-400 font-semibold">${escapeHtml(inst.interface)}</td>
  12642. <td class="py-2.5 px-3 font-mono font-bold text-center text-white">${inst.vrid}</td>
  12643. <td class="py-2.5 px-3 font-mono text-center text-slate-300 font-semibold">${inst.priority}</td>
  12644. <td class="py-2.5 px-3 font-mono text-emerald-400 font-bold"><span class="px-2 py-0.5 rounded bg-emerald-500/10 border border-emerald-500/20">${escapeHtml(vipsStr)}</span></td>
  12645. <td class="py-2.5 px-3 font-mono text-center text-slate-300">${inst.preempt ? '<span class="text-emerald-400 font-semibold">yes</span>' : '<span class="text-slate-500">no</span>'}</td>
  12646. <td class="py-2.5 px-3 font-mono text-slate-400 text-[11px]">${escapeHtml(inst.virtual_mac || '-')}</td>
  12647. <td class="py-2.5 px-3 text-center">${stateBadge}</td>
  12648. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]" title="${escapeHtml(inst.comment || '')}">${escapeHtml(inst.comment || '-')}</td>
  12649. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  12650. <button onclick="toggleVRRPState('${inst.id}', ${!inst.disabled})" class="text-xs ${inst.disabled ? 'text-emerald-400' : 'text-slate-400'} hover:underline">${inst.disabled ? 'Enable' : 'Disable'}</button>
  12651. <button onclick="openEditVRRPModal('${inst.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  12652. <button onclick="deleteVRRP('${inst.id}', '${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  12653. </td>
  12654. `;
  12655. tbody.appendChild(tr);
  12656. });
  12657. }
  12658. function populateVRRPIfaceSelect(elemId, selectedIface) {
  12659. const sel = document.getElementById(elemId);
  12660. if (!sel) return;
  12661. sel.innerHTML = '<option value="">Select interface...</option>';
  12662. const ifaces = state.interfaces || [];
  12663. ifaces.forEach(i => {
  12664. const opt = document.createElement('option');
  12665. opt.value = i.name;
  12666. opt.innerText = `${i.name} (${i.type || 'net'}${i.ip ? ' - ' + i.ip : ''})`;
  12667. if (selectedIface && selectedIface === i.name) opt.selected = true;
  12668. sel.appendChild(opt);
  12669. });
  12670. }
  12671. function openAddVRRPModal() {
  12672. document.getElementById('modal-vrrp-title').innerText = 'Add VRRP Instance';
  12673. document.getElementById('modal-vrrp-id').value = '';
  12674. document.getElementById('modal-vrrp-name').value = `vrrp${(state.vrrpInstances || []).length + 1}`;
  12675. document.getElementById('modal-vrrp-vrid').value = 10 + (state.vrrpInstances || []).length;
  12676. document.getElementById('modal-vrrp-priority').value = 100;
  12677. document.getElementById('modal-vrrp-vip').value = '192.168.88.254/24';
  12678. document.getElementById('modal-vrrp-version').value = '3';
  12679. document.getElementById('modal-vrrp-interval').value = 1;
  12680. document.getElementById('modal-vrrp-authtype').value = 'none';
  12681. document.getElementById('modal-vrrp-authpass').value = '';
  12682. document.getElementById('modal-vrrp-comment').value = '';
  12683. document.getElementById('modal-vrrp-preempt').checked = true;
  12684. document.getElementById('modal-vrrp-disabled').checked = false;
  12685. populateVRRPIfaceSelect('modal-vrrp-iface', '');
  12686. document.getElementById('modal-vrrp-instance').classList.remove('hidden');
  12687. }
  12688. function openEditVRRPModal(id) {
  12689. const inst = (state.vrrpInstances || []).find(item => item.id === id);
  12690. if (!inst) return;
  12691. document.getElementById('modal-vrrp-title').innerText = `Edit VRRP Instance (${inst.name})`;
  12692. document.getElementById('modal-vrrp-id').value = inst.id;
  12693. document.getElementById('modal-vrrp-name').value = inst.name;
  12694. document.getElementById('modal-vrrp-vrid').value = inst.vrid;
  12695. document.getElementById('modal-vrrp-priority').value = inst.priority;
  12696. document.getElementById('modal-vrrp-vip').value = (inst.virtual_ips || []).join(', ');
  12697. document.getElementById('modal-vrrp-version').value = String(inst.version || 3);
  12698. document.getElementById('modal-vrrp-interval').value = inst.interval || 1;
  12699. document.getElementById('modal-vrrp-authtype').value = inst.auth_type || 'none';
  12700. document.getElementById('modal-vrrp-authpass').value = inst.auth_password || '';
  12701. document.getElementById('modal-vrrp-comment').value = inst.comment || '';
  12702. document.getElementById('modal-vrrp-preempt').checked = inst.preempt !== false;
  12703. document.getElementById('modal-vrrp-disabled').checked = !!inst.disabled;
  12704. populateVRRPIfaceSelect('modal-vrrp-iface', inst.interface);
  12705. document.getElementById('modal-vrrp-instance').classList.remove('hidden');
  12706. }
  12707. function closeVRRPModal() {
  12708. document.getElementById('modal-vrrp-instance').classList.add('hidden');
  12709. }
  12710. async function submitSaveVRRP(e) {
  12711. e.preventDefault();
  12712. const id = document.getElementById('modal-vrrp-id').value;
  12713. const name = document.getElementById('modal-vrrp-name').value.trim();
  12714. const iface = document.getElementById('modal-vrrp-iface').value;
  12715. const vrid = parseInt(document.getElementById('modal-vrrp-vrid').value, 10) || 1;
  12716. const priority = parseInt(document.getElementById('modal-vrrp-priority').value, 10) || 100;
  12717. const vipRaw = document.getElementById('modal-vrrp-vip').value.trim();
  12718. const version = parseInt(document.getElementById('modal-vrrp-version').value, 10) || 3;
  12719. const interval = parseInt(document.getElementById('modal-vrrp-interval').value, 10) || 1;
  12720. const authType = document.getElementById('modal-vrrp-authtype').value;
  12721. const authPass = document.getElementById('modal-vrrp-authpass').value.trim();
  12722. const comment = document.getElementById('modal-vrrp-comment').value.trim();
  12723. const preempt = document.getElementById('modal-vrrp-preempt').checked;
  12724. const disabled = document.getElementById('modal-vrrp-disabled').checked;
  12725. const vips = vipRaw.split(',').map(s => s.trim()).filter(Boolean);
  12726. try {
  12727. const res = await fetch(`${API_BASE}/vrrp/instances`, {
  12728. method: 'POST',
  12729. headers: { 'Content-Type': 'application/json' },
  12730. body: JSON.stringify({
  12731. id,
  12732. name,
  12733. interface: iface,
  12734. vrid,
  12735. priority,
  12736. virtual_ips: vips,
  12737. version,
  12738. interval,
  12739. auth_type: authType,
  12740. auth_password: authPass,
  12741. comment,
  12742. preempt,
  12743. disabled
  12744. })
  12745. });
  12746. if (res.ok) {
  12747. showToast('VRRP Saved', `VRRP instance ${name} configured`, 'success');
  12748. closeVRRPModal();
  12749. loadVRRP(false);
  12750. fetchData(false);
  12751. } else {
  12752. const err = await res.text();
  12753. showToast('Error', err, 'error');
  12754. }
  12755. } catch (err) {
  12756. showToast('Error', err.message, 'error');
  12757. }
  12758. }
  12759. async function deleteVRRP(id, name) {
  12760. if (!confirm(`Delete VRRP instance "${name}"?`)) return;
  12761. try {
  12762. const res = await fetch(`${API_BASE}/vrrp/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12763. if (res.ok) {
  12764. showToast('Deleted', `VRRP instance ${name} removed`, 'info');
  12765. loadVRRP(false);
  12766. fetchData(false);
  12767. } else {
  12768. const err = await res.text();
  12769. showToast('Error', err, 'error');
  12770. }
  12771. } catch (err) {
  12772. showToast('Error', err.message, 'error');
  12773. }
  12774. }
  12775. async function toggleVRRPState(id, disabled) {
  12776. try {
  12777. const res = await fetch(`${API_BASE}/vrrp/instances/${encodeURIComponent(id)}/state`, {
  12778. method: 'POST',
  12779. headers: { 'Content-Type': 'application/json' },
  12780. body: JSON.stringify({ disabled })
  12781. });
  12782. if (res.ok) {
  12783. showToast('State Updated', disabled ? 'VRRP disabled' : 'VRRP enabled', 'info');
  12784. loadVRRP(false);
  12785. fetchData(false);
  12786. } else {
  12787. const err = await res.text();
  12788. showToast('Error', err, 'error');
  12789. }
  12790. } catch (err) {
  12791. showToast('Error', err.message, 'error');
  12792. }
  12793. }
  12794. // Global observer for dynamically injected tables (e.g. inside modals or drawers)
  12795. if (typeof MutationObserver !== 'undefined' && typeof document !== 'undefined') {
  12796. const docTableObserver = new MutationObserver((mutations) => {
  12797. let needsInit = false;
  12798. for (const m of mutations) {
  12799. for (const node of m.addedNodes) {
  12800. if (node.nodeType === 1) {
  12801. if (node.tagName === 'TABLE' || (node.querySelector && node.querySelector('table'))) {
  12802. needsInit = true;
  12803. break;
  12804. }
  12805. }
  12806. }
  12807. if (needsInit) break;
  12808. }
  12809. if (needsInit) {
  12810. initTableSorting();
  12811. }
  12812. });
  12813. docTableObserver.observe(document.body || document.documentElement, { childList: true, subtree: true });
  12814. }
  12815. // =========================================================================
  12816. // BANDWIDTH TEST (BwTest) BENCHMARK ENGINE
  12817. // =========================================================================
  12818. const bwtestState = {
  12819. running: false,
  12820. pollTimer: null,
  12821. eventSource: null,
  12822. chartPoints: [],
  12823. maxChartPoints: 60,
  12824. serverConfig: null,
  12825. peakTx: 0,
  12826. peakRx: 0,
  12827. targetDuration: 10,
  12828. lastSampleIndex: 0
  12829. };
  12830. async function loadBwTestView() {
  12831. fetchBwTestServerStatus();
  12832. loadBwTestHistory();
  12833. resizeBwTestCanvas();
  12834. checkActiveBwTest();
  12835. }
  12836. async function fetchBwTestServerStatus() {
  12837. try {
  12838. const res = await fetch(`${API_BASE}/tools/bwtest/server`);
  12839. if (!res.ok) return;
  12840. const s = await res.json();
  12841. bwtestState.serverConfig = s;
  12842. // Update indicator and badges
  12843. const indicator = document.getElementById('bwtest-server-indicator');
  12844. const badge = document.getElementById('bwtest-server-badge');
  12845. const sideBadge = document.getElementById('badge-bwtest-server');
  12846. if (s.enabled && s.running) {
  12847. if (indicator) indicator.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  12848. if (badge) {
  12849. badge.innerText = `Port ${s.port} (Active)`;
  12850. badge.className = 'text-emerald-400 font-bold';
  12851. }
  12852. if (sideBadge) {
  12853. sideBadge.innerText = s.port;
  12854. sideBadge.className = 'text-[10px] bg-emerald-950 text-emerald-300 border border-emerald-800/40 px-1.5 py-0.2 rounded-full font-mono';
  12855. }
  12856. } else {
  12857. if (indicator) indicator.className = 'w-2 h-2 rounded-full bg-slate-600';
  12858. if (badge) {
  12859. badge.innerText = `Disabled`;
  12860. badge.className = 'text-slate-500 font-bold';
  12861. }
  12862. if (sideBadge) {
  12863. sideBadge.innerText = 'Off';
  12864. sideBadge.className = 'text-[10px] bg-slate-800 text-slate-500 border border-slate-700 px-1.5 py-0.2 rounded-full font-mono';
  12865. }
  12866. }
  12867. // Modal fields
  12868. const toggle = document.getElementById('bwtest-server-enable-toggle');
  12869. if (toggle) toggle.checked = !!s.enabled;
  12870. const portInp = document.getElementById('bwtest-server-port-input');
  12871. if (portInp) portInp.value = s.port || 2000;
  12872. const actSess = document.getElementById('bwtest-modal-active-sessions');
  12873. if (actSess) actSess.innerText = s.active_sessions || 0;
  12874. const totServ = document.getElementById('bwtest-modal-total-served');
  12875. if (totServ) totServ.innerText = s.total_sessions_served || 0;
  12876. const totBytes = document.getElementById('bwtest-modal-total-bytes');
  12877. if (totBytes) totBytes.innerText = formatBytes(s.total_bytes_processed || 0);
  12878. } catch (err) {
  12879. console.error('Failed to fetch BwTest server status:', err);
  12880. }
  12881. }
  12882. function openBwTestServerModal() {
  12883. fetchBwTestServerStatus();
  12884. document.getElementById('modal-bwtest-server')?.classList.remove('hidden');
  12885. }
  12886. function closeBwTestServerModal() {
  12887. document.getElementById('modal-bwtest-server')?.classList.add('hidden');
  12888. }
  12889. async function submitBwTestServerSettings(e) {
  12890. e.preventDefault();
  12891. const enabled = document.getElementById('bwtest-server-enable-toggle').checked;
  12892. const port = parseInt(document.getElementById('bwtest-server-port-input').value, 10) || 2000;
  12893. try {
  12894. const res = await fetch(`${API_BASE}/tools/bwtest/server`, {
  12895. method: 'POST',
  12896. headers: { 'Content-Type': 'application/json' },
  12897. body: JSON.stringify({ enabled, port, listen_addr: '0.0.0.0', allow_anonymous: true })
  12898. });
  12899. if (!res.ok) {
  12900. const err = await res.json();
  12901. throw new Error(err.error || 'Failed to update server configuration');
  12902. }
  12903. showToast('BwTest Server', `Bandwidth Test server updated (Port ${port})`, 'success');
  12904. closeBwTestServerModal();
  12905. fetchBwTestServerStatus();
  12906. } catch (err) {
  12907. showToast('Server Configuration Error', err.message, 'error');
  12908. }
  12909. }
  12910. function setBwTestTarget(target) {
  12911. const inp = document.getElementById('bwtest-input-target');
  12912. if (inp) inp.value = target;
  12913. }
  12914. function setBwTestProtocol(proto) {
  12915. const hiddenInp = document.getElementById('bwtest-input-protocol');
  12916. if (hiddenInp) hiddenInp.value = proto;
  12917. const btnUdp = document.getElementById('bwtest-proto-udp');
  12918. const btnTcp = document.getElementById('bwtest-proto-tcp');
  12919. const badge = document.getElementById('bwtest-proto-badge');
  12920. const pktField = document.getElementById('bwtest-field-pktsize');
  12921. const activeUdpCls = 'py-2.5 px-3 rounded-lg text-xs font-bold border transition text-center bg-emerald-600/20 border-emerald-500/50 text-emerald-300 shadow-sm flex items-center justify-center gap-2';
  12922. const activeTcpCls = 'py-2.5 px-3 rounded-lg text-xs font-bold border transition text-center bg-blue-600/20 border-blue-500/50 text-blue-300 shadow-sm flex items-center justify-center gap-2';
  12923. const inactiveCls = 'py-2.5 px-3 rounded-lg text-xs font-medium border border-slate-800 bg-slate-950 text-slate-400 hover:text-white transition text-center flex items-center justify-center gap-2';
  12924. if (proto === 'udp') {
  12925. if (btnUdp) {
  12926. btnUdp.className = activeUdpCls;
  12927. const dot = btnUdp.querySelector('span');
  12928. if (dot) dot.className = 'w-2 h-2 rounded-full bg-emerald-400';
  12929. }
  12930. if (btnTcp) {
  12931. btnTcp.className = inactiveCls;
  12932. const dot = btnTcp.querySelector('span');
  12933. if (dot) dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  12934. }
  12935. if (badge) {
  12936. badge.innerText = 'UDP Mode (RFC 3550 Jitter + Loss %)';
  12937. badge.className = 'text-[10px] font-mono text-emerald-400 bg-emerald-500/10 px-2 py-0.5 rounded border border-emerald-500/20';
  12938. }
  12939. if (pktField) pktField.classList.remove('opacity-40');
  12940. } else {
  12941. if (btnUdp) {
  12942. btnUdp.className = inactiveCls;
  12943. const dot = btnUdp.querySelector('span');
  12944. if (dot) dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  12945. }
  12946. if (btnTcp) {
  12947. btnTcp.className = activeTcpCls;
  12948. const dot = btnTcp.querySelector('span');
  12949. if (dot) dot.className = 'w-2 h-2 rounded-full bg-blue-400';
  12950. }
  12951. if (badge) {
  12952. badge.innerText = 'TCP Mode (Sliding Window Throughput)';
  12953. badge.className = 'text-[10px] font-mono text-blue-400 bg-blue-500/10 px-2 py-0.5 rounded border border-blue-500/20';
  12954. }
  12955. if (pktField) pktField.classList.add('opacity-40');
  12956. }
  12957. }
  12958. function setBwTestDirection(dir) {
  12959. const hiddenInp = document.getElementById('bwtest-input-direction');
  12960. if (hiddenInp) hiddenInp.value = dir;
  12961. const btnBoth = document.getElementById('bwtest-dir-both');
  12962. const btnTx = document.getElementById('bwtest-dir-tx');
  12963. const btnRx = document.getElementById('bwtest-dir-rx');
  12964. const activeCls = 'py-2 px-2 rounded-lg text-xs font-bold border transition text-center bg-emerald-600/20 border-emerald-500/50 text-emerald-300 shadow-sm';
  12965. const inactiveCls = 'py-2 px-2 rounded-lg text-xs font-medium border border-slate-800 bg-slate-950 text-slate-400 hover:text-white transition text-center';
  12966. if (btnBoth) btnBoth.className = dir === 'both' ? activeCls : inactiveCls;
  12967. if (btnTx) btnTx.className = dir === 'tx' ? activeCls : inactiveCls;
  12968. if (btnRx) btnRx.className = dir === 'rx' ? activeCls : inactiveCls;
  12969. }
  12970. function setBwTestLimit(bps) {
  12971. const sel = document.getElementById('bwtest-input-limit');
  12972. if (sel) sel.value = String(bps);
  12973. }
  12974. async function checkActiveBwTest() {
  12975. try {
  12976. const res = await fetch(`${API_BASE}/tools/bwtest/status`);
  12977. if (!res.ok) return;
  12978. const st = await res.json();
  12979. if (st.running) {
  12980. setBwTestRunningUI(true);
  12981. if (st.current_sample) handleBwTestSample(st.current_sample);
  12982. startBwTestTelemetry();
  12983. }
  12984. } catch (err) {
  12985. console.error('Failed to check active BwTest:', err);
  12986. }
  12987. }
  12988. async function startBwTest(e) {
  12989. if (e && e.preventDefault) e.preventDefault();
  12990. const target = document.getElementById('bwtest-input-target').value.trim() || '127.0.0.1';
  12991. const port = parseInt(document.getElementById('bwtest-input-port').value, 10) || 2000;
  12992. const direction = document.getElementById('bwtest-input-direction').value || 'both';
  12993. const protocol = document.getElementById('bwtest-input-protocol').value || 'udp';
  12994. const bandwidth_limit = parseInt(document.getElementById('bwtest-input-limit').value, 10) || 0;
  12995. const packet_size = parseInt(document.getElementById('bwtest-input-pktsize').value, 10) || 1472;
  12996. const streams = parseInt(document.getElementById('bwtest-input-streams').value, 10) || 1;
  12997. const duration = parseInt(document.getElementById('bwtest-input-duration').value, 10);
  12998. bwtestState.targetDuration = duration;
  12999. bwtestState.chartPoints = [];
  13000. bwtestState.peakTx = 0;
  13001. bwtestState.peakRx = 0;
  13002. bwtestState.lastSampleIndex = 0;
  13003. // Clear UI elements
  13004. document.getElementById('bwtest-stat-tx-mbps').innerText = '0.00';
  13005. document.getElementById('bwtest-stat-tx-peak').innerText = '0.00 Mbps';
  13006. document.getElementById('bwtest-stat-tx-pkts').innerText = '0';
  13007. document.getElementById('bwtest-stat-rx-mbps').innerText = '0.00';
  13008. document.getElementById('bwtest-stat-rx-peak').innerText = '0.00 Mbps';
  13009. document.getElementById('bwtest-stat-rx-pkts').innerText = '0';
  13010. document.getElementById('bwtest-stat-loss').innerText = '0.0%';
  13011. document.getElementById('bwtest-stat-jitter').innerText = '0.00 ms';
  13012. document.getElementById('bwtest-stat-time').innerText = '0.0s';
  13013. document.getElementById('bwtest-stat-data').innerText = '0.0 MB';
  13014. document.getElementById('bwtest-stat-target-dur').innerText = duration > 0 ? `/ ${duration}s` : '/ ∞';
  13015. const tbody = document.getElementById('bwtest-samples-tbody');
  13016. if (tbody) tbody.innerHTML = '';
  13017. document.getElementById('bwtest-sample-count').innerText = '0 samples';
  13018. setBwTestRunningUI(true);
  13019. try {
  13020. const res = await fetch(`${API_BASE}/tools/bwtest/start`, {
  13021. method: 'POST',
  13022. headers: { 'Content-Type': 'application/json' },
  13023. body: JSON.stringify({
  13024. target,
  13025. port,
  13026. direction,
  13027. protocol,
  13028. bandwidth_limit,
  13029. packet_size,
  13030. streams,
  13031. duration
  13032. })
  13033. });
  13034. if (!res.ok) {
  13035. const err = await res.json();
  13036. throw new Error(err.error || 'Failed to start bandwidth test');
  13037. }
  13038. showToast('Benchmark Started', `Target: ${target}:${port} (${direction.toUpperCase()}, ${protocol.toUpperCase()})`, 'info');
  13039. startBwTestTelemetry();
  13040. } catch (err) {
  13041. setBwTestRunningUI(false);
  13042. showToast('Start Failed', err.message, 'error');
  13043. }
  13044. }
  13045. function setBwTestRunningUI(running) {
  13046. bwtestState.running = running;
  13047. const startBtn = document.getElementById('bwtest-btn-start');
  13048. const stopBtn = document.getElementById('bwtest-btn-stop');
  13049. const badge = document.getElementById('bwtest-run-status-badge');
  13050. const ph = document.getElementById('bwtest-chart-placeholder');
  13051. if (running) {
  13052. if (startBtn) {
  13053. startBtn.disabled = true;
  13054. startBtn.classList.add('opacity-50', 'cursor-not-allowed');
  13055. }
  13056. if (stopBtn) {
  13057. stopBtn.disabled = false;
  13058. stopBtn.classList.remove('opacity-40');
  13059. }
  13060. if (badge) {
  13061. badge.innerText = 'TESTING...';
  13062. badge.className = 'px-2 py-0.5 rounded text-[10px] font-mono bg-emerald-500/20 text-emerald-300 border border-emerald-500/40 font-bold animate-pulse';
  13063. }
  13064. if (ph) ph.style.display = 'none';
  13065. } else {
  13066. if (startBtn) {
  13067. startBtn.disabled = false;
  13068. startBtn.classList.remove('opacity-50', 'cursor-not-allowed');
  13069. }
  13070. if (stopBtn) {
  13071. stopBtn.disabled = true;
  13072. stopBtn.classList.add('opacity-40');
  13073. }
  13074. if (badge) {
  13075. badge.innerText = 'IDLE';
  13076. badge.className = 'px-2 py-0.5 rounded text-[10px] font-mono bg-slate-800 text-slate-400 border border-slate-700 font-semibold';
  13077. }
  13078. }
  13079. }
  13080. async function stopBwTest() {
  13081. try {
  13082. await fetch(`${API_BASE}/tools/bwtest/stop`, { method: 'POST' });
  13083. showToast('Test Stopped', 'Bandwidth test terminated by user', 'info');
  13084. } catch (err) {
  13085. console.error('Failed to stop test:', err);
  13086. }
  13087. }
  13088. function startBwTestTelemetry() {
  13089. if (bwtestState.pollTimer) clearInterval(bwtestState.pollTimer);
  13090. bwtestState.pollTimer = setInterval(async () => {
  13091. try {
  13092. const res = await fetch(`${API_BASE}/tools/bwtest/status`);
  13093. if (!res.ok) return;
  13094. const st = await res.json();
  13095. if (st.recent_samples && st.recent_samples.length > 0) {
  13096. // Process new samples
  13097. const newSamples = st.recent_samples.slice(bwtestState.lastSampleIndex);
  13098. newSamples.forEach(s => handleBwTestSample(s));
  13099. bwtestState.lastSampleIndex = st.recent_samples.length;
  13100. }
  13101. if (!st.running) {
  13102. clearInterval(bwtestState.pollTimer);
  13103. bwtestState.pollTimer = null;
  13104. setBwTestRunningUI(false);
  13105. handleBwTestFinish(st.summary, st.error);
  13106. }
  13107. } catch (err) {
  13108. console.error('BwTest polling error:', err);
  13109. }
  13110. }, 400);
  13111. }
  13112. function handleBwTestSample(s) {
  13113. if (!s) return;
  13114. const txMbps = s.tx_mbps || 0;
  13115. const rxMbps = s.rx_mbps || 0;
  13116. if (txMbps > bwtestState.peakTx) bwtestState.peakTx = txMbps;
  13117. if (rxMbps > bwtestState.peakRx) bwtestState.peakRx = rxMbps;
  13118. // KPI updates
  13119. const elTx = document.getElementById('bwtest-stat-tx-mbps');
  13120. if (elTx) elTx.innerText = txMbps.toFixed(2);
  13121. const elTxPeak = document.getElementById('bwtest-stat-tx-peak');
  13122. if (elTxPeak) elTxPeak.innerText = `${bwtestState.peakTx.toFixed(2)} Mbps`;
  13123. const elTxPkts = document.getElementById('bwtest-stat-tx-pkts');
  13124. if (elTxPkts) elTxPkts.innerText = s.tx_packets || 0;
  13125. const elRx = document.getElementById('bwtest-stat-rx-mbps');
  13126. if (elRx) elRx.innerText = rxMbps.toFixed(2);
  13127. const elRxPeak = document.getElementById('bwtest-stat-rx-peak');
  13128. if (elRxPeak) elRxPeak.innerText = `${bwtestState.peakRx.toFixed(2)} Mbps`;
  13129. const elRxPkts = document.getElementById('bwtest-stat-rx-pkts');
  13130. if (elRxPkts) elRxPkts.innerText = s.rx_packets || 0;
  13131. const elLoss = document.getElementById('bwtest-stat-loss');
  13132. if (elLoss) {
  13133. elLoss.innerText = `${(s.loss_pct || 0).toFixed(1)}%`;
  13134. elLoss.className = (s.loss_pct > 1.0) ? 'text-2xl font-bold text-rose-400' : 'text-2xl font-bold text-emerald-400';
  13135. }
  13136. const elLostPkts = document.getElementById('bwtest-stat-lost-pkts');
  13137. if (elLostPkts) elLostPkts.innerText = s.lost_packets || 0;
  13138. const elJitter = document.getElementById('bwtest-stat-jitter');
  13139. if (elJitter) elJitter.innerText = `${(s.jitter_ms || 0).toFixed(2)} ms`;
  13140. const elTime = document.getElementById('bwtest-stat-time');
  13141. if (elTime) elTime.innerText = `${(s.elapsed_sec || 0).toFixed(1)}s`;
  13142. const elData = document.getElementById('bwtest-stat-data');
  13143. if (elData) elData.innerText = formatBytes((s.tx_bytes || 0) + (s.rx_bytes || 0));
  13144. const elGraphRate = document.getElementById('bwtest-graph-rate');
  13145. if (elGraphRate) elGraphRate.innerText = `TX: ${txMbps.toFixed(1)} Mbps • RX: ${rxMbps.toFixed(1)} Mbps`;
  13146. // Append point to chart buffer
  13147. bwtestState.chartPoints.push({
  13148. elapsed: s.elapsed_sec || 0,
  13149. tx: txMbps,
  13150. rx: rxMbps
  13151. });
  13152. if (bwtestState.chartPoints.length > bwtestState.maxChartPoints) {
  13153. bwtestState.chartPoints.shift();
  13154. }
  13155. drawBwTestChart();
  13156. // Add row to breakdown table
  13157. const tbody = document.getElementById('bwtest-samples-tbody');
  13158. if (tbody) {
  13159. const tr = document.createElement('tr');
  13160. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  13161. tr.innerHTML = `
  13162. <td class="py-1.5 px-3 font-semibold text-white">${(s.elapsed_sec || 0).toFixed(1)}s</td>
  13163. <td class="py-1.5 px-3 font-bold text-cyan-400">${txMbps.toFixed(2)} Mbps</td>
  13164. <td class="py-1.5 px-3 font-bold text-purple-400">${rxMbps.toFixed(2)} Mbps</td>
  13165. <td class="py-1.5 px-3 ${(s.loss_pct > 1.0) ? 'text-rose-400 font-bold' : 'text-emerald-400'}">${(s.loss_pct || 0).toFixed(1)}%</td>
  13166. <td class="py-1.5 px-3 text-slate-300">${(s.jitter_ms || 0).toFixed(2)} ms</td>
  13167. <td class="py-1.5 px-3 text-slate-400">${formatBytes((s.tx_bytes || 0) + (s.rx_bytes || 0))}</td>
  13168. `;
  13169. tbody.insertBefore(tr, tbody.firstChild);
  13170. const countEl = document.getElementById('bwtest-sample-count');
  13171. if (countEl) countEl.innerText = `${tbody.children.length} samples`;
  13172. }
  13173. }
  13174. function handleBwTestFinish(summary, error) {
  13175. const badge = document.getElementById('bwtest-run-status-badge');
  13176. if (error) {
  13177. showToast('Benchmark Error', error, 'error');
  13178. if (badge) {
  13179. badge.innerText = 'ERROR';
  13180. badge.className = 'px-2 py-0.5 rounded text-[10px] font-mono bg-rose-500/20 text-rose-300 border border-rose-500/40 font-bold';
  13181. }
  13182. } else if (summary) {
  13183. const avgTx = summary.avg_tx_mbps.toFixed(1);
  13184. const avgRx = summary.avg_rx_mbps.toFixed(1);
  13185. showToast('Benchmark Complete', `Average TX: ${avgTx} Mbps | RX: ${avgRx} Mbps (Loss: ${summary.avg_loss_pct.toFixed(1)}%)`, 'success');
  13186. if (badge) {
  13187. badge.innerText = 'COMPLETED';
  13188. badge.className = 'px-2 py-0.5 rounded text-[10px] font-mono bg-emerald-500/20 text-emerald-300 border border-emerald-500/40 font-bold';
  13189. }
  13190. }
  13191. loadBwTestHistory();
  13192. fetchBwTestServerStatus();
  13193. }
  13194. function resizeBwTestCanvas() {
  13195. const canvas = document.getElementById('bwtest-chart');
  13196. if (!canvas || !canvas.parentElement) return;
  13197. const rect = canvas.parentElement.getBoundingClientRect();
  13198. const dpr = window.devicePixelRatio || 1;
  13199. canvas.width = rect.width * dpr;
  13200. canvas.height = rect.height * dpr;
  13201. const ctx = canvas.getContext('2d');
  13202. ctx.scale(dpr, dpr);
  13203. drawBwTestChart();
  13204. }
  13205. window.addEventListener('resize', () => {
  13206. if (state.activeTab === 'bwtest') resizeBwTestCanvas();
  13207. });
  13208. function drawBwTestChart() {
  13209. const canvas = document.getElementById('bwtest-chart');
  13210. if (!canvas) return;
  13211. const ctx = canvas.getContext('2d');
  13212. const dpr = window.devicePixelRatio || 1;
  13213. const width = canvas.width / dpr;
  13214. const height = canvas.height / dpr;
  13215. ctx.clearRect(0, 0, width, height);
  13216. const points = bwtestState.chartPoints;
  13217. if (!points || points.length === 0) return;
  13218. // Determine scale ceiling
  13219. let maxRate = 10;
  13220. for (const p of points) {
  13221. if (p.tx > maxRate) maxRate = p.tx;
  13222. if (p.rx > maxRate) maxRate = p.rx;
  13223. }
  13224. maxRate = Math.ceil(maxRate * 1.25); // 25% headroom
  13225. const paddingLeft = 55;
  13226. const paddingBottom = 24;
  13227. const paddingTop = 12;
  13228. const paddingRight = 16;
  13229. const chartW = width - paddingLeft - paddingRight;
  13230. const chartH = height - paddingTop - paddingBottom;
  13231. // Grid Lines and Y-Axis labels
  13232. ctx.strokeStyle = 'rgba(51, 65, 85, 0.4)';
  13233. ctx.lineWidth = 1;
  13234. ctx.fillStyle = '#94a3b8';
  13235. ctx.font = '10px monospace';
  13236. ctx.textAlign = 'right';
  13237. const gridSteps = 4;
  13238. for (let i = 0; i <= gridSteps; i++) {
  13239. const val = (maxRate / gridSteps) * i;
  13240. const y = paddingTop + chartH - (i / gridSteps) * chartH;
  13241. ctx.beginPath();
  13242. ctx.moveTo(paddingLeft, y);
  13243. ctx.lineTo(width - paddingRight, y);
  13244. ctx.stroke();
  13245. ctx.fillText(`${Math.round(val)}M`, paddingLeft - 8, y + 3);
  13246. }
  13247. // Draw TX Line (Cyan #22d3ee)
  13248. drawSeries(ctx, points, p => p.tx, maxRate, paddingLeft, paddingTop, chartW, chartH, '#22d3ee', 'rgba(34, 211, 238, 0.15)');
  13249. // Draw RX Line (Purple #a855f7)
  13250. drawSeries(ctx, points, p => p.rx, maxRate, paddingLeft, paddingTop, chartW, chartH, '#a855f7', 'rgba(168, 85, 247, 0.15)');
  13251. }
  13252. function drawSeries(ctx, points, valFn, maxVal, left, top, w, h, strokeColor, fillColor) {
  13253. if (points.length < 2) return;
  13254. const stepX = w / Math.max(points.length - 1, 1);
  13255. // Gradient area fill
  13256. const grad = ctx.createLinearGradient(0, top, 0, top + h);
  13257. grad.addColorStop(0, fillColor);
  13258. grad.addColorStop(1, 'rgba(0, 0, 0, 0)');
  13259. ctx.beginPath();
  13260. points.forEach((p, idx) => {
  13261. const x = left + idx * stepX;
  13262. const val = valFn(p);
  13263. const y = top + h - (val / maxVal) * h;
  13264. if (idx === 0) {
  13265. ctx.moveTo(x, y);
  13266. } else {
  13267. ctx.lineTo(x, y);
  13268. }
  13269. });
  13270. // Complete path for fill
  13271. ctx.lineTo(left + (points.length - 1) * stepX, top + h);
  13272. ctx.lineTo(left, top + h);
  13273. ctx.closePath();
  13274. ctx.fillStyle = grad;
  13275. ctx.fill();
  13276. // Draw line stroke
  13277. ctx.beginPath();
  13278. ctx.lineWidth = 2.5;
  13279. ctx.strokeStyle = strokeColor;
  13280. points.forEach((p, idx) => {
  13281. const x = left + idx * stepX;
  13282. const val = valFn(p);
  13283. const y = top + h - (val / maxVal) * h;
  13284. if (idx === 0) {
  13285. ctx.moveTo(x, y);
  13286. } else {
  13287. ctx.lineTo(x, y);
  13288. }
  13289. });
  13290. ctx.stroke();
  13291. // Draw end point halo
  13292. const lastP = points[points.length - 1];
  13293. const lastX = left + (points.length - 1) * stepX;
  13294. const lastY = top + h - (valFn(lastP) / maxVal) * h;
  13295. ctx.fillStyle = strokeColor;
  13296. ctx.beginPath();
  13297. ctx.arc(lastX, lastY, 4, 0, 2 * Math.PI);
  13298. ctx.fill();
  13299. }
  13300. async function loadBwTestHistory() {
  13301. try {
  13302. const res = await fetch(`${API_BASE}/tools/bwtest/history`);
  13303. if (!res.ok) return;
  13304. const list = await res.json();
  13305. renderBwTestHistory(Array.isArray(list) ? list : []);
  13306. } catch (err) {
  13307. console.error('Failed to load BwTest history:', err);
  13308. }
  13309. }
  13310. function renderBwTestHistory(list) {
  13311. const tbody = document.getElementById('bwtest-history-tbody');
  13312. if (!tbody) return;
  13313. if (list.length === 0) {
  13314. tbody.innerHTML = `<tr><td colspan="10" class="p-6 text-center text-slate-500 text-xs font-sans">No past benchmark runs recorded yet.</td></tr>`;
  13315. return;
  13316. }
  13317. tbody.innerHTML = '';
  13318. list.forEach(item => {
  13319. const s = item.summary || {};
  13320. const tr = document.createElement('tr');
  13321. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  13322. const dirBadge = item.direction === 'both'
  13323. ? `<span class="px-1.5 py-0.5 rounded text-[10px] bg-emerald-500/20 text-emerald-300 border border-emerald-500/30 uppercase font-semibold">Both</span>`
  13324. : item.direction === 'tx'
  13325. ? `<span class="px-1.5 py-0.5 rounded text-[10px] bg-cyan-500/20 text-cyan-300 border border-cyan-500/30 uppercase font-semibold">TX Only</span>`
  13326. : `<span class="px-1.5 py-0.5 rounded text-[10px] bg-purple-500/20 text-purple-300 border border-purple-500/30 uppercase font-semibold">RX Only</span>`;
  13327. const protoBadge = item.protocol === 'tcp'
  13328. ? `<span class="px-1.5 py-0.5 rounded text-[10px] bg-blue-500/20 text-blue-300 border border-blue-500/30 font-semibold uppercase">TCP</span>`
  13329. : `<span class="px-1.5 py-0.5 rounded text-[10px] bg-amber-500/20 text-amber-300 border border-amber-500/30 font-semibold uppercase">UDP</span>`;
  13330. const dateStr = item.timestamp ? new Date(item.timestamp).toLocaleString() : '-';
  13331. tr.innerHTML = `
  13332. <td class="py-2.5 px-4 font-bold text-white font-mono text-[11px]">${escapeHtml(item.id || '-')}</td>
  13333. <td class="py-2.5 px-4 text-emerald-400 font-mono font-medium">${escapeHtml(item.target || '-')}</td>
  13334. <td class="py-2.5 px-4">${protoBadge}</td>
  13335. <td class="py-2.5 px-4">${dirBadge}</td>
  13336. <td class="py-2.5 px-4 text-slate-300">${(s.duration_sec || 0).toFixed(1)}s</td>
  13337. <td class="py-2.5 px-4 font-bold text-cyan-400 font-mono">${(s.avg_tx_mbps || 0).toFixed(1)} / ${(s.peak_tx_mbps || 0).toFixed(1)} <span class="text-[10px] text-slate-400 font-normal">Mbps</span></td>
  13338. <td class="py-2.5 px-4 font-bold text-purple-400 font-mono">${(s.avg_rx_mbps || 0).toFixed(1)} / ${(s.peak_rx_mbps || 0).toFixed(1)} <span class="text-[10px] text-slate-400 font-normal">Mbps</span></td>
  13339. <td class="py-2.5 px-4 ${(s.avg_loss_pct > 1.0) ? 'text-rose-400 font-bold' : 'text-emerald-400'} font-mono">${(s.avg_loss_pct || 0).toFixed(1)}% <span class="text-[10px] text-slate-400 font-normal">(${s.total_lost_packets || 0})</span></td>
  13340. <td class="py-2.5 px-4 text-slate-300 font-mono">${(s.avg_jitter_ms || 0).toFixed(2)} ms</td>
  13341. <td class="py-2.5 px-4 text-slate-400 text-[11px] font-sans">${escapeHtml(dateStr)}</td>
  13342. `;
  13343. tbody.appendChild(tr);
  13344. });
  13345. }
  13346. // ======================== SETTINGS & ROUTER DNS ========================
  13347. state.settingsSubTab = 'dns';
  13348. state.dnsSettings = null;
  13349. state.dnsStaticRecords = [];
  13350. state.dnsStatus = null;
  13351. function switchSettingsSubTab(sub) {
  13352. state.settingsSubTab = sub;
  13353. const btnDns = document.getElementById('btn-settings-subtab-dns');
  13354. const btnSys = document.getElementById('btn-settings-subtab-system');
  13355. const tabDns = document.getElementById('settings-subtab-dns');
  13356. const tabSys = document.getElementById('settings-subtab-system');
  13357. if (sub === 'dns') {
  13358. if (btnDns) {
  13359. btnDns.className = 'px-3.5 py-1.5 rounded-lg text-xs font-semibold bg-cyan-600 text-white transition flex items-center gap-1.5';
  13360. }
  13361. if (btnSys) {
  13362. btnSys.className = 'px-3.5 py-1.5 rounded-lg text-xs font-semibold bg-slate-800 text-slate-300 hover:text-white transition flex items-center gap-1.5';
  13363. }
  13364. tabDns?.classList.remove('hidden');
  13365. tabSys?.classList.add('hidden');
  13366. loadDNSSettings();
  13367. } else {
  13368. if (btnSys) {
  13369. btnSys.className = 'px-3.5 py-1.5 rounded-lg text-xs font-semibold bg-cyan-600 text-white transition flex items-center gap-1.5';
  13370. }
  13371. if (btnDns) {
  13372. btnDns.className = 'px-3.5 py-1.5 rounded-lg text-xs font-semibold bg-slate-800 text-slate-300 hover:text-white transition flex items-center gap-1.5';
  13373. }
  13374. tabSys?.classList.remove('hidden');
  13375. tabDns?.classList.add('hidden');
  13376. loadSystemSettings();
  13377. }
  13378. }
  13379. async function loadSettingsData(showLoading = false) {
  13380. if (state.settingsSubTab === 'system') {
  13381. await loadSystemSettings();
  13382. } else {
  13383. await loadDNSSettings();
  13384. }
  13385. }
  13386. async function loadDNSSettings() {
  13387. try {
  13388. const [settingsRes, staticRes, statusRes] = await Promise.all([
  13389. fetch(`${API_BASE}/dns/settings`),
  13390. fetch(`${API_BASE}/dns/static`),
  13391. fetch(`${API_BASE}/dns/status`)
  13392. ]);
  13393. if (settingsRes.ok) {
  13394. state.dnsSettings = await settingsRes.json();
  13395. populateDNSSettingsForm(state.dnsSettings);
  13396. }
  13397. if (staticRes.ok) {
  13398. state.dnsStaticRecords = await staticRes.json();
  13399. renderStaticDNSList();
  13400. }
  13401. if (statusRes.ok) {
  13402. state.dnsStatus = await statusRes.json();
  13403. updateDNSStatusView(state.dnsStatus);
  13404. }
  13405. } catch (err) {
  13406. console.error('Failed to load DNS settings:', err);
  13407. }
  13408. }
  13409. function populateDNSSettingsForm(s) {
  13410. if (!s) return;
  13411. const dnsForm = document.getElementById('form-dns-settings');
  13412. const isEditing = dnsForm && (dnsForm.contains(document.activeElement) || dnsForm.dataset.dirty === 'true');
  13413. const dynamicEl = document.getElementById('dns-dynamic-servers-list');
  13414. if (dynamicEl) {
  13415. if (Array.isArray(s.dynamic_servers) && s.dynamic_servers.length > 0) {
  13416. dynamicEl.innerHTML = s.dynamic_servers.map(d => `<span class="px-2 py-0.5 rounded bg-cyan-950 text-cyan-300 border border-cyan-800 font-mono">${escapeHtml(d)}</span>`).join(' ');
  13417. } else {
  13418. dynamicEl.innerText = 'None';
  13419. }
  13420. }
  13421. // If user is actively typing or editing in the form, do not overwrite their inputs!
  13422. if (isEditing) return;
  13423. const serversInput = document.getElementById('dns-servers-input');
  13424. if (serversInput) serversInput.value = (s.servers || []).join(', ');
  13425. const cacheSizeInput = document.getElementById('dns-cache-size-input');
  13426. if (cacheSizeInput) cacheSizeInput.value = s.cache_size || 2048;
  13427. const domainInput = document.getElementById('dns-domain-input');
  13428. if (domainInput) domainInput.value = s.domain || '';
  13429. const allowRemoteInput = document.getElementById('dns-allow-remote-input');
  13430. if (allowRemoteInput) allowRemoteInput.checked = s.allow_remote_requests !== false;
  13431. }
  13432. function updateDNSStatusView(st) {
  13433. if (!st) return;
  13434. const preview = document.getElementById('dns-resolv-preview');
  13435. if (preview) preview.innerText = st.resolv_conf_content || '(empty)';
  13436. const pillText = document.getElementById('dns-live-status-text');
  13437. const pill = document.getElementById('dns-live-status-pill');
  13438. if (pill && pillText) {
  13439. if (st.service_running) {
  13440. pill.className = 'px-2.5 py-1 rounded-full text-[11px] font-mono bg-emerald-500/10 text-emerald-400 border border-emerald-500/30 flex items-center gap-1.5';
  13441. pillText.innerText = 'DNS Service Active';
  13442. } else {
  13443. pill.className = 'px-2.5 py-1 rounded-full text-[11px] font-mono bg-rose-500/10 text-rose-400 border border-rose-500/30 flex items-center gap-1.5';
  13444. pillText.innerText = 'DNS Service Inactive';
  13445. }
  13446. }
  13447. }
  13448. function appendDNSPreset(preset) {
  13449. const input = document.getElementById('dns-servers-input');
  13450. if (!input) return;
  13451. const dnsForm = document.getElementById('form-dns-settings');
  13452. if (dnsForm) dnsForm.dataset.dirty = 'true';
  13453. const current = input.value.trim();
  13454. if (!current) {
  13455. input.value = preset;
  13456. } else {
  13457. const existing = current.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  13458. const toAdd = preset.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  13459. toAdd.forEach(ip => {
  13460. if (!existing.includes(ip)) existing.push(ip);
  13461. });
  13462. input.value = existing.join(', ');
  13463. }
  13464. }
  13465. async function saveDNSSettings(e) {
  13466. e.preventDefault();
  13467. const rawServers = document.getElementById('dns-servers-input')?.value || '';
  13468. const servers = rawServers.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  13469. if (servers.length === 0) {
  13470. showToast('Validation Error', 'Please enter at least one upstream DNS server IP', 'error');
  13471. return;
  13472. }
  13473. const cacheSize = parseInt(document.getElementById('dns-cache-size-input')?.value || '2048', 10);
  13474. const domain = (document.getElementById('dns-domain-input')?.value || '').trim();
  13475. const allowRemote = document.getElementById('dns-allow-remote-input')?.checked ?? true;
  13476. try {
  13477. const res = await fetch(`${API_BASE}/dns/settings`, {
  13478. method: 'POST',
  13479. headers: { 'Content-Type': 'application/json' },
  13480. body: JSON.stringify({
  13481. servers: servers,
  13482. cache_size: cacheSize,
  13483. domain: domain,
  13484. allow_remote_requests: allowRemote
  13485. })
  13486. });
  13487. const data = await res.json();
  13488. if (res.ok) {
  13489. const dnsForm = document.getElementById('form-dns-settings');
  13490. if (dnsForm) dnsForm.dataset.dirty = 'false';
  13491. showToast('DNS Applied', 'Router DNS forwarders and resolver settings updated successfully', 'success');
  13492. loadDNSSettings();
  13493. } else {
  13494. showToast('Error', data.error || data.message || 'Failed to save DNS settings', 'error');
  13495. }
  13496. } catch (err) {
  13497. showToast('Error', err.message, 'error');
  13498. }
  13499. }
  13500. async function flushDNSCache() {
  13501. try {
  13502. const res = await fetch(`${API_BASE}/dns/flush`, { method: 'POST' });
  13503. if (res.ok) {
  13504. showToast('Cache Flushed', 'Router DNS cache cleared and static hosts reloaded', 'success');
  13505. loadDNSSettings();
  13506. } else {
  13507. const err = await res.json();
  13508. showToast('Error', err.error || 'Failed to flush cache', 'error');
  13509. }
  13510. } catch (err) {
  13511. showToast('Error', err.message, 'error');
  13512. }
  13513. }
  13514. function renderStaticDNSList() {
  13515. const tbody = document.getElementById('dns-static-tbody');
  13516. const empty = document.getElementById('dns-static-empty');
  13517. const badge = document.getElementById('dns-static-count-badge');
  13518. if (!tbody) return;
  13519. tbody.innerHTML = '';
  13520. const records = state.dnsStaticRecords || [];
  13521. if (badge) badge.innerText = `${records.length} Records`;
  13522. if (records.length === 0) {
  13523. empty?.classList.remove('hidden');
  13524. return;
  13525. }
  13526. empty?.classList.add('hidden');
  13527. records.forEach(rec => {
  13528. const tr = document.createElement('tr');
  13529. tr.className = `hover:bg-slate-800/40 transition text-xs ${rec.disabled ? 'opacity-50' : ''}`;
  13530. tr.innerHTML = `
  13531. <td class="py-2.5 px-4 font-bold text-white">${escapeHtml(rec.name)}</td>
  13532. <td class="py-2.5 px-4">
  13533. <span class="px-2 py-0.5 rounded text-[10px] font-bold ${
  13534. rec.type === 'CNAME' ? 'bg-purple-950 text-purple-300 border border-purple-800' :
  13535. (rec.type === 'AAAA' ? 'bg-blue-950 text-blue-300 border border-blue-800' : 'bg-cyan-950 text-cyan-300 border border-cyan-800')
  13536. }">
  13537. ${rec.type || 'A'}
  13538. </span>
  13539. </td>
  13540. <td class="py-2.5 px-4 text-emerald-400 font-mono">${escapeHtml(rec.address)}</td>
  13541. <td class="py-2.5 px-4 text-slate-400 font-mono">${rec.ttl || 3600}s</td>
  13542. <td class="py-2.5 px-4 text-slate-400 italic truncate max-w-[140px]">${escapeHtml(rec.comment || '-')}</td>
  13543. <td class="py-2.5 px-4">
  13544. <span class="px-1.5 py-0.5 rounded text-[10px] font-semibold ${rec.disabled ? 'bg-slate-800 text-slate-500' : 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/30'}">
  13545. ${rec.disabled ? 'Disabled' : 'Active'}
  13546. </span>
  13547. </td>
  13548. <td class="py-2.5 px-4 text-right space-x-2 font-sans whitespace-nowrap">
  13549. <button onclick="toggleStaticDNS('${rec.id}', ${!rec.disabled})" class="text-xs ${rec.disabled ? 'text-emerald-400' : 'text-slate-400'} hover:underline">${rec.disabled ? 'Enable' : 'Disable'}</button>
  13550. <button onclick="openStaticDNSModal('${rec.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold">Edit</button>
  13551. <button onclick="deleteStaticDNS('${rec.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  13552. </td>
  13553. `;
  13554. tbody.appendChild(tr);
  13555. });
  13556. }
  13557. function openStaticDNSModal(id = null) {
  13558. const modal = document.getElementById('modal-static-dns');
  13559. const title = document.getElementById('modal-static-dns-title');
  13560. const form = document.getElementById('form-static-dns');
  13561. if (!modal || !form) return;
  13562. form.reset();
  13563. document.getElementById('modal-static-dns-id').value = '';
  13564. if (id) {
  13565. const rec = (state.dnsStaticRecords || []).find(r => r.id === id);
  13566. if (rec) {
  13567. if (title) title.innerText = 'Edit Static DNS Record';
  13568. document.getElementById('modal-static-dns-id').value = rec.id;
  13569. document.getElementById('modal-static-dns-name').value = rec.name;
  13570. document.getElementById('modal-static-dns-type').value = rec.type || 'A';
  13571. document.getElementById('modal-static-dns-addr').value = rec.address;
  13572. document.getElementById('modal-static-dns-ttl').value = rec.ttl || 3600;
  13573. document.getElementById('modal-static-dns-comment').value = rec.comment || '';
  13574. document.getElementById('modal-static-dns-disabled').checked = !!rec.disabled;
  13575. }
  13576. } else {
  13577. if (title) title.innerText = 'Add Static DNS Record';
  13578. }
  13579. modal.classList.remove('hidden');
  13580. }
  13581. function closeStaticDNSModal() {
  13582. document.getElementById('modal-static-dns')?.classList.add('hidden');
  13583. }
  13584. async function submitSaveStaticDNS(e) {
  13585. e.preventDefault();
  13586. const id = document.getElementById('modal-static-dns-id')?.value || '';
  13587. const name = (document.getElementById('modal-static-dns-name')?.value || '').trim();
  13588. const type = document.getElementById('modal-static-dns-type')?.value || 'A';
  13589. const address = (document.getElementById('modal-static-dns-addr')?.value || '').trim();
  13590. const ttl = parseInt(document.getElementById('modal-static-dns-ttl')?.value || '3600', 10);
  13591. const comment = (document.getElementById('modal-static-dns-comment')?.value || '').trim();
  13592. const disabled = document.getElementById('modal-static-dns-disabled')?.checked ?? false;
  13593. if (!name || !address) {
  13594. showToast('Validation Error', 'Name and Target Address are required', 'error');
  13595. return;
  13596. }
  13597. try {
  13598. const res = await fetch(`${API_BASE}/dns/static`, {
  13599. method: 'POST',
  13600. headers: { 'Content-Type': 'application/json' },
  13601. body: JSON.stringify({ id, name, type, address, ttl, comment, disabled })
  13602. });
  13603. const data = await res.json();
  13604. if (res.ok) {
  13605. showToast('Static DNS Saved', `Saved record ${name} -> ${address}`, 'success');
  13606. closeStaticDNSModal();
  13607. loadDNSSettings();
  13608. } else {
  13609. showToast('Error', data.error || data.message || 'Failed to save record', 'error');
  13610. }
  13611. } catch (err) {
  13612. showToast('Error', err.message, 'error');
  13613. }
  13614. }
  13615. async function deleteStaticDNS(id) {
  13616. if (!confirm('Are you sure you want to delete this static DNS entry?')) return;
  13617. try {
  13618. const res = await fetch(`${API_BASE}/dns/static/${encodeURIComponent(id)}`, { method: 'DELETE' });
  13619. if (res.ok) {
  13620. showToast('Deleted', 'Static DNS record deleted', 'success');
  13621. loadDNSSettings();
  13622. }
  13623. } catch (err) {
  13624. showToast('Error', err.message, 'error');
  13625. }
  13626. }
  13627. async function toggleStaticDNS(id, disabled) {
  13628. try {
  13629. const res = await fetch(`${API_BASE}/dns/static/${encodeURIComponent(id)}/state`, {
  13630. method: 'POST',
  13631. headers: { 'Content-Type': 'application/json' },
  13632. body: JSON.stringify({ disabled })
  13633. });
  13634. if (res.ok) {
  13635. showToast('Updated', `Record ${disabled ? 'disabled' : 'enabled'}`, 'success');
  13636. loadDNSSettings();
  13637. }
  13638. } catch (err) {
  13639. showToast('Error', err.message, 'error');
  13640. }
  13641. }
  13642. async function loadSystemSettings() {
  13643. try {
  13644. const sysForm = document.getElementById('form-system-settings');
  13645. const isEditing = sysForm && (sysForm.contains(document.activeElement) || sysForm.dataset.dirty === 'true');
  13646. const res = await fetch(`${API_BASE}/system/settings`);
  13647. if (res.ok) {
  13648. const data = await res.json();
  13649. if (!isEditing) {
  13650. const hostInput = document.getElementById('system-hostname-input');
  13651. if (hostInput) hostInput.value = data.hostname || '';
  13652. const tzInput = document.getElementById('system-timezone-input');
  13653. if (tzInput && data.timezone) tzInput.value = data.timezone;
  13654. }
  13655. }
  13656. } catch (err) {
  13657. console.error('Failed to load system settings:', err);
  13658. }
  13659. }
  13660. async function saveSystemSettings(e) {
  13661. e.preventDefault();
  13662. const hostname = (document.getElementById('system-hostname-input')?.value || '').trim();
  13663. const timezone = document.getElementById('system-timezone-input')?.value || 'UTC';
  13664. try {
  13665. const res = await fetch(`${API_BASE}/system/settings`, {
  13666. method: 'POST',
  13667. headers: { 'Content-Type': 'application/json' },
  13668. body: JSON.stringify({ hostname, timezone })
  13669. });
  13670. const data = await res.json();
  13671. if (res.ok) {
  13672. const sysForm = document.getElementById('form-system-settings');
  13673. if (sysForm) sysForm.dataset.dirty = 'false';
  13674. showToast('System Updated', 'Hostname and timezone saved successfully', 'success');
  13675. const sideH = document.getElementById('side-hostname');
  13676. if (sideH) sideH.innerText = data.hostname;
  13677. } else {
  13678. showToast('Error', data.error || 'Failed to save system settings', 'error');
  13679. }
  13680. } catch (err) {
  13681. showToast('Error', err.message, 'error');
  13682. }
  13683. }