app.js 687 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436
  1. // DebTik - Debian Linux Router Frontend Application Logic
  2. // ================= Interceptor: Automatic Auth Bearer & 401 Handling =================
  3. const originalFetch = window.fetch;
  4. window.fetch = async function(...args) {
  5. let [resource, config] = args;
  6. config = config || {};
  7. // Clone or init headers
  8. let headers = config.headers;
  9. if (!headers) {
  10. headers = {};
  11. config.headers = headers;
  12. }
  13. const token = localStorage.getItem('debtik_token');
  14. if (token) {
  15. if (headers instanceof Headers) {
  16. if (!headers.has('Authorization')) headers.set('Authorization', `Bearer ${token}`);
  17. } else if (Array.isArray(headers)) {
  18. if (!headers.some(([k]) => k.toLowerCase() === 'authorization')) headers.push(['Authorization', `Bearer ${token}`]);
  19. } else {
  20. if (!headers['Authorization']) headers['Authorization'] = `Bearer ${token}`;
  21. }
  22. }
  23. const response = await originalFetch(resource, config);
  24. // If 401 Unauthorized on protected API endpoint, prompt login immediately
  25. if (response.status === 401 && typeof resource === 'string' && resource.includes('/api/') && !resource.includes('/api/auth/login')) {
  26. if (state.currentUser) {
  27. if (window._telemetryInterval) {
  28. clearInterval(window._telemetryInterval);
  29. window._telemetryInterval = null;
  30. }
  31. if (trafficEventSource) {
  32. try { trafficEventSource.close(); } catch(e) {}
  33. trafficEventSource = null;
  34. }
  35. if (trafficPollFallback) {
  36. clearInterval(trafficPollFallback);
  37. trafficPollFallback = null;
  38. }
  39. state.isPolling = false;
  40. state.currentUser = null;
  41. localStorage.removeItem('debtik_token');
  42. showLoginScreen(true);
  43. }
  44. }
  45. return response;
  46. };
  47. let state = {
  48. currentUser: null,
  49. users: [],
  50. interfaces: [],
  51. vlans: [],
  52. systemStatus: null,
  53. vpnStatus: null,
  54. routes: [],
  55. activeTab: 'dashboard',
  56. fwSubTab: 'filter',
  57. bridgeSubTab: 'bridges',
  58. bridges: [],
  59. bridgePorts: [],
  60. bridgeVLANs: [],
  61. bridgeHosts: [],
  62. bridgeSummary: null,
  63. routesSubTab: 'routes',
  64. pppSubTab: 'secrets',
  65. eoipTunnels: [],
  66. pppSecrets: [],
  67. pppProfiles: [],
  68. pppActiveSessions: [],
  69. pppoeServer: null,
  70. pptpServer: null,
  71. l2tpServer: null,
  72. ipsecServer: null,
  73. ifaceFilter: 'all',
  74. currentModalIface: null,
  75. isPolling: false,
  76. expandedParents: new Set(['eth0']),
  77. pppoeData: null,
  78. wgData: null,
  79. ipsecData: null,
  80. l2tpData: null,
  81. pptpData: null,
  82. fwSummary: null,
  83. filterRules: [],
  84. natRules: [],
  85. mangleRules: [],
  86. addressLists: [],
  87. connections: [],
  88. policyRules: [],
  89. routingTables: [],
  90. routingFilters: [],
  91. filterChainSelected: 'all',
  92. activeToolsSubTab: 'ping',
  93. dhcpClients: [],
  94. dhcpSummary: null,
  95. dhcpServerTab: 'servers',
  96. dhcpServers: [],
  97. dhcpNetworks: [],
  98. dhcpLeases: [],
  99. dhcpOptions: [],
  100. dhcpServerSummary: null
  101. };
  102. const API_BASE = '/api';
  103. function escapeHtml(str) {
  104. if (str === null || str === undefined) return '';
  105. return String(str)
  106. .replace(/&/g, '&')
  107. .replace(/</g, '&lt;')
  108. .replace(/>/g, '&gt;')
  109. .replace(/"/g, '&quot;')
  110. .replace(/'/g, '&#039;');
  111. }
  112. function formatBytes(bytes) {
  113. if (bytes === undefined || bytes === null || isNaN(bytes) || bytes === 0) return '0 B';
  114. const k = 1024;
  115. const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
  116. const i = Math.floor(Math.log(bytes) / Math.log(k));
  117. if (i < 0 || i >= sizes.length) return `${bytes} B`;
  118. return `${parseFloat((bytes / Math.pow(k, i)).toFixed(2))} ${sizes[i]}`;
  119. }
  120. // Initialize on page load
  121. document.addEventListener('DOMContentLoaded', async () => {
  122. initTableSorting();
  123. // Verify authentication before bootstrapping telemetry and views
  124. const isAuthenticated = await checkAuthStatus();
  125. if (isAuthenticated) {
  126. const hash = window.location.hash.replace('#', '') || 'dashboard';
  127. navigate(hash);
  128. // Full state telemetry polling every 5 seconds (smooth & flicker-free)
  129. if (!window._telemetryInterval) {
  130. window._telemetryInterval = setInterval(() => {
  131. if (state.isPolling && state.currentUser) {
  132. fetchData(false);
  133. }
  134. }, 5000);
  135. }
  136. }
  137. });
  138. let trafficEventSource = null;
  139. let trafficPollFallback = null;
  140. function initLiveTrafficStream() {
  141. if (trafficEventSource) {
  142. try { trafficEventSource.close(); } catch(e) {}
  143. trafficEventSource = null;
  144. }
  145. if (trafficPollFallback) {
  146. clearInterval(trafficPollFallback);
  147. trafficPollFallback = null;
  148. }
  149. if (window.EventSource) {
  150. try {
  151. trafficEventSource = new EventSource(`${API_BASE}/interfaces/traffic/stream`);
  152. trafficEventSource.onmessage = (event) => {
  153. try {
  154. const data = JSON.parse(event.data);
  155. updateLiveInterfaceTraffic(data);
  156. } catch (e) {
  157. console.error('Error parsing live traffic event:', e);
  158. }
  159. };
  160. trafficEventSource.onerror = () => {
  161. // Fallback polling if SSE disconnects
  162. if (!trafficPollFallback) {
  163. trafficPollFallback = setInterval(pollLiveTrafficSnapshot, 1000);
  164. }
  165. };
  166. trafficEventSource.onopen = () => {
  167. if (trafficPollFallback) {
  168. clearInterval(trafficPollFallback);
  169. trafficPollFallback = null;
  170. }
  171. };
  172. return;
  173. } catch (e) {
  174. console.warn('EventSource failed, using 1s polling fallback:', e);
  175. }
  176. }
  177. // Fallback if EventSource is unavailable
  178. trafficPollFallback = setInterval(pollLiveTrafficSnapshot, 1000);
  179. }
  180. async function pollLiveTrafficSnapshot() {
  181. try {
  182. const res = await fetch(`${API_BASE}/interfaces/traffic/rates`);
  183. if (res.ok) {
  184. const data = await res.json();
  185. updateLiveInterfaceTraffic(data);
  186. }
  187. } catch (e) {}
  188. }
  189. function updateLiveInterfaceTraffic(data) {
  190. if (!data || !data.interfaces) return;
  191. state.latestTraffic = data;
  192. // 1. Update Top & Dashboard Total Bandwidth Indicators
  193. const rxHuman = data.total_rx_human || '0 B/s';
  194. const txHuman = data.total_tx_human || '0 B/s';
  195. const statRx = document.getElementById('stat-traffic-rx');
  196. if (statRx && statRx.innerText !== rxHuman) statRx.innerText = rxHuman;
  197. const statTx = document.getElementById('stat-traffic-tx');
  198. if (statTx && statTx.innerText !== txHuman) statTx.innerText = txHuman;
  199. // 2. Update state.interfaces rates in-memory
  200. if (Array.isArray(state.interfaces)) {
  201. state.interfaces.forEach(i => {
  202. const live = data.interfaces[i.name];
  203. if (live) {
  204. i.rate = {
  205. rx_bytes_sec: live.rx_bytes_sec,
  206. tx_bytes_sec: live.tx_bytes_sec,
  207. rx_human: live.rx_human,
  208. tx_human: live.tx_human
  209. };
  210. i.stats = {
  211. rx_bytes: live.rx_bytes,
  212. tx_bytes: live.tx_bytes,
  213. rx_packets: live.rx_packets,
  214. tx_packets: live.tx_packets,
  215. rx_errors: live.rx_errors,
  216. tx_errors: live.tx_errors,
  217. rx_dropped: live.rx_dropped,
  218. tx_dropped: live.tx_dropped
  219. };
  220. }
  221. });
  222. }
  223. // 3. Update all live UI rate spans in-place (ZERO flicker)
  224. Object.keys(data.interfaces).forEach(name => {
  225. const live = data.interfaces[name];
  226. // Dashboard Port Matrix Card
  227. const cardRate = document.getElementById(`port-card-rate-${name}`);
  228. if (cardRate && cardRate.innerText !== live.rx_human) {
  229. cardRate.innerText = live.rx_human;
  230. }
  231. // Dashboard Quick Interfaces Table
  232. const quickRx = document.getElementById(`quick-rx-${name}`);
  233. if (quickRx) quickRx.innerText = `↓ ${live.rx_human}`;
  234. const quickTx = document.getElementById(`quick-tx-${name}`);
  235. if (quickTx) quickTx.innerText = `↑ ${live.tx_human}`;
  236. // Main Interfaces Tree Table
  237. const ifaceRx = document.getElementById(`iface-rate-rx-${name}`);
  238. if (ifaceRx) ifaceRx.innerText = `↓ ${live.rx_human}`;
  239. const ifaceTx = document.getElementById(`iface-rate-tx-${name}`);
  240. if (ifaceTx) ifaceTx.innerText = `↑ ${live.tx_human}`;
  241. // VLAN Sub-interfaces Table
  242. const vlanRx = document.getElementById(`vlan-rate-rx-${name}`);
  243. if (vlanRx) vlanRx.innerText = `↓ ${live.rx_human}`;
  244. const vlanTx = document.getElementById(`vlan-rate-tx-${name}`);
  245. if (vlanTx) vlanTx.innerText = `↑ ${live.tx_human}`;
  246. // VLAN Page Table
  247. const vlanPageRx = document.getElementById(`vlan-page-rate-rx-${name}`);
  248. if (vlanPageRx) vlanPageRx.innerText = `↓ ${live.rx_human}`;
  249. const vlanPageTx = document.getElementById(`vlan-page-rate-tx-${name}`);
  250. if (vlanPageTx) vlanPageTx.innerText = `↑ ${live.tx_human}`;
  251. });
  252. }
  253. // Navigation Handler
  254. function navigate(tabName) {
  255. if (tabName === 'dynamic-routing' || tabName === 'routing') {
  256. navigate('bgp');
  257. return;
  258. }
  259. if (tabName === 'vlans') {
  260. navigate('interfaces');
  261. return;
  262. }
  263. state.activeTab = tabName;
  264. window.location.hash = tabName;
  265. // Update nav links styling
  266. document.querySelectorAll('.nav-link').forEach(link => {
  267. 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';
  268. });
  269. const activeNav = document.getElementById(`nav-${tabName}`);
  270. if (activeNav) {
  271. 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';
  272. }
  273. // Update page headers
  274. const titles = {
  275. dashboard: { title: 'Dashboard Overview', sub: 'Live router performance and network telemetry' },
  276. interfaces: { title: 'Network Interfaces', sub: 'Interface Table View' },
  277. 'dhcp-client': { title: 'DHCP Client', sub: 'DHCP Client List' },
  278. 'dhcp-server': { title: 'DHCP Server & Subnets', sub: 'DHCP Server instances, subnet networks (NTP, TFTP, DNS), dynamic leases & static reservations' },
  279. bridge: { title: 'Bridge Interfaces', sub: 'IEEE 802.1D / 802.1Q VLAN-aware Layer 2 switching, RSTP & hardware forwarding (FDB)' },
  280. vlans: { title: 'VLAN Virtual Networks', sub: 'IEEE 802.1Q sub-interface segmentation and routing' },
  281. firewall: { title: 'Network Firewall', sub: 'Stateful packet inspection, NAT, traffic mangle, address lists & connection tracking' },
  282. routes: { title: 'Routing & Policy', sub: 'Routing tables, static routes (DAS/DAC), and policy routing rules' },
  283. bgp: { title: 'BGP Dynamic Routing', sub: 'BGP multi-instance peering sessions, advertised networks, and routing table (RIB)' },
  284. ospf: { title: 'OSPF Dynamic Routing', sub: 'OSPFv2 link-state routing, dynamic neighbor adjacencies, and multi-area topology' },
  285. 'routing-filters': { title: 'Routing Policy Filters', sub: 'Route filter chains, prefix matching, BGP community maps & policy-based path control' },
  286. 'dynamic-routing': { title: 'BGP Dynamic Routing', sub: 'Dynamic routing engine and peering sessions' },
  287. ppp: { title: 'PPP Servers & Secrets', sub: 'Subscriber authentication, dynamic IP pools and VPN access concentrators' },
  288. eoip: { title: 'EoIP Tunnels', sub: 'Ethernet over IP (EoIP / GRETAP) Layer 2 encapsulation & transparent network bridging' },
  289. aerotun: { title: 'AeroTUN High-Speed VPN', sub: 'Ultra-fast Layer 3 encrypted tunnel with ChaCha20-Poly1305 and live Adaptive LZ4 compression' },
  290. pppoe: { title: 'PPPoE Client WAN', sub: 'Point-to-Point Protocol over Ethernet WAN access' },
  291. wireguard: { title: 'WireGuard VPN', sub: 'High-performance cryptographic Layer 3 tunnels with ChaCha20-Poly1305 key exchange' },
  292. ipsec: { title: 'IPSec (IKEv2) strongSwan', sub: 'Enterprise Site-to-Site & Roadwarrior IPSec controller' },
  293. l2tp: { title: 'L2TP VPN Client', sub: 'Layer 2 Tunneling Protocol via xl2tpd' },
  294. pptp: { title: 'PPTP VPN Client', sub: 'Point-to-Point Tunneling Protocol with MPPE-128 encryption' },
  295. vrrp: { title: 'VRRP High Availability', sub: 'Virtual Router Redundancy Protocol, active-backup gateway failover & Virtual IP (VIP) routing' },
  296. bwtest: { title: 'Bandwidth Test Benchmark', sub: 'High-speed line-rate throughput benchmark, token-bucket rate limiting, loss & jitter telemetry' },
  297. tools: { title: 'Diagnostic & Troubleshooting Tools', sub: 'Network latency analysis, ICMP/MTR telemetry, path tracing, DNS resolution and TCP probing' },
  298. persistence: { title: 'Debian Configuration', sub: 'Native /etc/network/interfaces.d/ persistence manager' },
  299. settings: { title: 'Router Settings & DNS', sub: 'System DNS forwarder, upstream resolvers, static host mappings, and appliance identity' },
  300. users: { title: 'Local User Manager', sub: 'Manage local system administrator credentials and access permissions' }
  301. };
  302. const header = titles[tabName] || titles.dashboard;
  303. const pTitle = document.getElementById('page-title');
  304. if (pTitle) pTitle.innerText = header.title;
  305. const pSub = document.getElementById('page-subtitle');
  306. if (pSub) pSub.innerText = header.sub;
  307. // Toggle sections dynamically for all section elements
  308. document.querySelectorAll('main section[id^="section-"]').forEach(el => {
  309. if (el.id === `section-${tabName}`) {
  310. el.classList.remove('hidden');
  311. } else {
  312. el.classList.add('hidden');
  313. }
  314. });
  315. if (tabName === 'interfaces') {
  316. loadRoles();
  317. if (state.activeIfaceSubTab === 'roles') switchIfaceSubTab('roles');
  318. else switchIfaceSubTab('tree');
  319. }
  320. if (tabName === 'bridge') loadBridge();
  321. if (tabName === 'firewall') loadFirewall();
  322. if (tabName === 'routes') loadRoutes();
  323. if (tabName === 'bgp') {
  324. loadDynamicRouting();
  325. switchBgpSubTab(state.activeBgpSubTab || 'bgp-peers');
  326. }
  327. if (tabName === 'ospf') {
  328. loadDynamicRouting();
  329. switchOspfTab(state.activeOspfTab || 'instances');
  330. }
  331. if (tabName === 'routing-filters') loadDynamicRouting();
  332. if (tabName === 'dynamic-routing') loadDynamicRouting();
  333. if (tabName === 'ppp') loadPPP();
  334. if (tabName === 'eoip') loadEoIP();
  335. if (tabName === 'aerotun') loadAeroTUN();
  336. if (tabName === 'persistence') loadDebianConfig();
  337. if (tabName === 'pppoe') loadPPPoE();
  338. if (tabName === 'wireguard') loadWireGuard();
  339. if (tabName === 'ipsec') loadIPSec();
  340. if (tabName === 'l2tp') loadL2TP();
  341. if (tabName === 'pptp') loadPPTP();
  342. if (tabName === 'tools') loadToolsView();
  343. if (tabName === 'dhcp-client') loadDHCPClients();
  344. if (tabName === 'dhcp-server') loadDHCPServer();
  345. if (tabName === 'vrrp') loadVRRP();
  346. if (tabName === 'bwtest') loadBwTestView();
  347. if (tabName === 'settings') loadSettingsData();
  348. if (tabName === 'users') loadUsers();
  349. setTimeout(initTableSorting, 50);
  350. }
  351. // Fetch all core system, network and VPN telemetry
  352. async function fetchData(isManual = false) {
  353. const spinner = document.getElementById('refresh-spinner');
  354. if (isManual && spinner) spinner.classList.add('animate-spin');
  355. try {
  356. const [statusRes, ifacesRes, vlansRes, vpnRes, fwRes, dynRes, brSummaryRes, dhcpSumRes, dhcpClientsRes, vrrpSumRes, rolesRes] = await Promise.all([
  357. fetch(`${API_BASE}/system/status`),
  358. fetch(`${API_BASE}/interfaces`),
  359. fetch(`${API_BASE}/vlans`),
  360. fetch(`${API_BASE}/vpn/status`),
  361. fetch(`${API_BASE}/firewall/summary`),
  362. fetch(`${API_BASE}/routing/dynamic/summary`),
  363. fetch(`${API_BASE}/bridge/summary`),
  364. fetch(`${API_BASE}/dhcp/clients/summary`),
  365. fetch(`${API_BASE}/dhcp/clients`),
  366. fetch(`${API_BASE}/vrrp/summary`).catch(() => null),
  367. fetch(`${API_BASE}/roles`).catch(() => null)
  368. ]);
  369. if (rolesRes && rolesRes.ok) {
  370. state.roles = await rolesRes.json();
  371. const countEl = document.getElementById('badge-roles-count');
  372. if (countEl) countEl.innerText = (state.roles || []).length;
  373. }
  374. if (vrrpSumRes && vrrpSumRes.ok) {
  375. state.vrrpSummary = await vrrpSumRes.json();
  376. renderVRRPSummary();
  377. }
  378. if (dhcpSumRes && dhcpSumRes.ok) {
  379. state.dhcpSummary = await dhcpSumRes.json();
  380. const bDhcp = document.getElementById('badge-dhcp-client-count');
  381. if (bDhcp) bDhcp.innerText = state.dhcpSummary?.total_clients || 0;
  382. }
  383. if (dhcpClientsRes && dhcpClientsRes.ok) {
  384. state.dhcpClients = await dhcpClientsRes.json();
  385. }
  386. if (brSummaryRes.ok) {
  387. state.bridgeSummary = await brSummaryRes.json();
  388. const bBridge = document.getElementById('badge-bridge-count');
  389. if (bBridge) bBridge.innerText = state.bridgeSummary?.bridges_count || 0;
  390. const sBr = document.getElementById('bridge-stat-bridges');
  391. if (sBr) sBr.innerText = state.bridgeSummary?.bridges_count || 0;
  392. const sPorts = document.getElementById('bridge-stat-ports');
  393. if (sPorts) sPorts.innerText = state.bridgeSummary?.ports_count || 0;
  394. const sHosts = document.getElementById('bridge-stat-hosts');
  395. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  396. }
  397. if (statusRes.ok) state.systemStatus = await statusRes.json();
  398. if (ifacesRes.ok) {
  399. const ifacesData = await ifacesRes.json();
  400. const rawIfaces = Array.isArray(ifacesData) ? ifacesData : [];
  401. state.interfaces = rawIfaces.filter(i => {
  402. if (!i.name) return false;
  403. if (i.name.startsWith('ep_')) return false;
  404. return !['gre0', 'gretap0', 'erspan0', 'sit0', 'tunl0', 'ip6tnl0', 'ip6gre0', 'ip6erspan0'].includes(i.name);
  405. });
  406. try { populateToolsInterfaces(); } catch (e) {}
  407. }
  408. if (vlansRes.ok) {
  409. const vlansData = await vlansRes.json();
  410. state.vlans = Array.isArray(vlansData) ? vlansData : [];
  411. }
  412. if (vpnRes.ok) state.vpnStatus = await vpnRes.json();
  413. if (fwRes && fwRes.ok) state.fwSummary = await fwRes.json();
  414. if (dynRes && dynRes.ok) state.dynSummary = await dynRes.json();
  415. updateSystemMetrics();
  416. updateBadges();
  417. if (state.activeTab === 'dashboard') renderDashboard();
  418. if (state.activeTab === 'interfaces') {
  419. if (state.activeIfaceSubTab === 'roles') renderRolesTable();
  420. else renderInterfacesList();
  421. }
  422. if (state.activeTab === 'vlans') renderVlansList();
  423. if (state.activeTab === 'firewall') loadFirewall(false);
  424. if (state.activeTab === 'routes') loadRoutes(false);
  425. if (state.activeTab === 'dynamic-routing' || state.activeTab === 'bgp' || state.activeTab === 'ospf') loadDynamicRouting(false);
  426. if (state.activeTab === 'ppp') loadPPP(false);
  427. if (state.activeTab === 'eoip') loadEoIP(false);
  428. if (state.activeTab === 'aerotun') loadAeroTUN(false);
  429. if (state.activeTab === 'pppoe') loadPPPoE(false);
  430. if (state.activeTab === 'wireguard') loadWireGuard(false);
  431. if (state.activeTab === 'ipsec') loadIPSec(false);
  432. if (state.activeTab === 'l2tp') loadL2TP(false);
  433. if (state.activeTab === 'pptp') loadPPTP(false);
  434. if (state.activeTab === 'dhcp-client') loadDHCPClients(false);
  435. if (state.activeTab === 'dhcp-server') loadDHCPServer(false);
  436. if (state.activeTab === 'vrrp') loadVRRP(false);
  437. if (state.activeTab === 'settings') loadSettingsData(false);
  438. if (state.activeTab === 'users') loadUsers(false);
  439. fetchBwTestServerStatus();
  440. } catch (err) {
  441. console.error('Failed to fetch router state:', err);
  442. } finally {
  443. if (isManual && spinner) {
  444. setTimeout(() => spinner.classList.remove('animate-spin'), 300);
  445. }
  446. }
  447. }
  448. // Update Top KPI and Sidebar Telemetry
  449. function updateSystemMetrics() {
  450. const s = state.systemStatus;
  451. const v = state.vpnStatus;
  452. if (!s) return;
  453. // Sidebar Host & Uptime
  454. const sideHost = document.getElementById('side-hostname');
  455. if (sideHost) sideHost.innerText = s.hostname || 'debian-lxc';
  456. const sideUp = document.getElementById('side-uptime');
  457. if (sideUp) sideUp.innerText = s.uptime_human || '0m';
  458. const sideGw = document.getElementById('side-gateway-ip');
  459. if (sideGw) sideGw.innerText = s.default_gateway ? `GW: ${s.default_gateway}` : 'GW: Isolated';
  460. // Compute CPU Metrics
  461. let cpuPct = 0;
  462. if (s.cpu_pct !== undefined) {
  463. cpuPct = s.cpu_pct;
  464. } else if (s.cpu_load && s.cpu_load.length > 0) {
  465. const cores = s.cpu_cores || 1;
  466. cpuPct = Math.min(100, Math.round((parseFloat(s.cpu_load[0]) / cores) * 100));
  467. }
  468. const cpuPctStr = `${cpuPct.toFixed(1)}%`;
  469. const cpuWidth = `${Math.max(3, Math.min(100, cpuPct))}%`;
  470. const loadStr = s.cpu_load ? s.cpu_load.join(', ') : '-';
  471. // Sidebar CPU
  472. const sideCpuVal = document.getElementById('side-cpu-val');
  473. if (sideCpuVal) sideCpuVal.innerText = cpuPctStr;
  474. const sideCpuBar = document.getElementById('side-cpu-bar');
  475. if (sideCpuBar) {
  476. sideCpuBar.style.width = cpuWidth;
  477. sideCpuBar.title = `Container: ${cpuPctStr} | Host Loadavg: ${loadStr} (${s.cpu_cores || 1} cores)`;
  478. }
  479. // Dashboard CPU Card
  480. const dashCpuVal = document.getElementById('dash-cpu-val');
  481. if (dashCpuVal) dashCpuVal.innerText = cpuPctStr;
  482. const dashCpuBar = document.getElementById('dash-cpu-bar');
  483. if (dashCpuBar) {
  484. dashCpuBar.style.width = cpuWidth;
  485. if (cpuPct > 85) {
  486. dashCpuBar.className = 'h-full rounded-full bg-rose-500 transition-all duration-500';
  487. } else if (cpuPct > 65) {
  488. dashCpuBar.className = 'h-full rounded-full bg-amber-500 transition-all duration-500';
  489. } else {
  490. dashCpuBar.className = 'h-full rounded-full bg-emerald-500 transition-all duration-500';
  491. }
  492. }
  493. const dashCpuCores = document.getElementById('dash-cpu-cores');
  494. if (dashCpuCores) dashCpuCores.innerText = `${s.cpu_cores || 1} Cores`;
  495. const dashCpuLoad = document.getElementById('dash-cpu-load');
  496. if (dashCpuLoad) dashCpuLoad.innerText = loadStr;
  497. const dashCpuStatus = document.getElementById('dash-cpu-status');
  498. if (dashCpuStatus) {
  499. if (cpuPct > 85) {
  500. dashCpuStatus.innerText = 'High';
  501. dashCpuStatus.className = 'text-[11px] font-semibold text-rose-400 uppercase px-2 py-0.5 rounded bg-rose-500/10';
  502. } else if (cpuPct > 65) {
  503. dashCpuStatus.innerText = 'Heavy';
  504. dashCpuStatus.className = 'text-[11px] font-semibold text-amber-400 uppercase px-2 py-0.5 rounded bg-amber-500/10';
  505. } else {
  506. dashCpuStatus.innerText = 'Normal';
  507. dashCpuStatus.className = 'text-[11px] font-semibold text-emerald-400 uppercase px-2 py-0.5 rounded bg-emerald-500/10';
  508. }
  509. }
  510. // Compute RAM Metrics
  511. const memPct = Math.round(s.mem_usage_pct || 0);
  512. const memPctStr = `${memPct}%`;
  513. const memWidth = `${Math.max(3, Math.min(100, memPct))}%`;
  514. const usedMB = s.mem_used_mb || 0;
  515. const totalMB = s.mem_total_mb || 0;
  516. const freeMB = totalMB > usedMB ? totalMB - usedMB : 0;
  517. function fmtMemMB(mb) {
  518. if (mb >= 1024) {
  519. return `${(mb / 1024).toFixed(1)} GB`;
  520. }
  521. return `${mb} MB`;
  522. }
  523. // Sidebar RAM
  524. const sideRamVal = document.getElementById('side-ram-val');
  525. if (sideRamVal) sideRamVal.innerText = memPctStr;
  526. const sideRamBar = document.getElementById('side-ram-bar');
  527. if (sideRamBar) sideRamBar.style.width = memWidth;
  528. // Dashboard RAM Card
  529. const dashRamVal = document.getElementById('dash-ram-val');
  530. if (dashRamVal) dashRamVal.innerText = memPctStr;
  531. const dashRamBar = document.getElementById('dash-ram-bar');
  532. if (dashRamBar) {
  533. dashRamBar.style.width = memWidth;
  534. if (memPct > 85) {
  535. dashRamBar.className = 'h-full rounded-full bg-rose-500 transition-all duration-500';
  536. } else if (memPct > 70) {
  537. dashRamBar.className = 'h-full rounded-full bg-amber-500 transition-all duration-500';
  538. } else {
  539. dashRamBar.className = 'h-full rounded-full bg-indigo-500 transition-all duration-500';
  540. }
  541. }
  542. const dashRamUsedTotal = document.getElementById('dash-ram-used-total');
  543. if (dashRamUsedTotal) {
  544. dashRamUsedTotal.innerText = `${fmtMemMB(usedMB)} / ${fmtMemMB(totalMB)}`;
  545. }
  546. const dashRamFree = document.getElementById('dash-ram-free');
  547. if (dashRamFree) {
  548. dashRamFree.innerText = fmtMemMB(freeMB);
  549. }
  550. const dashRamStatus = document.getElementById('dash-ram-status');
  551. if (dashRamStatus) {
  552. if (memPct > 85) {
  553. dashRamStatus.innerText = 'High';
  554. dashRamStatus.className = 'text-[11px] font-semibold text-rose-400 uppercase px-2 py-0.5 rounded bg-rose-500/10';
  555. } else {
  556. dashRamStatus.innerText = 'Active';
  557. dashRamStatus.className = 'text-[11px] font-semibold text-indigo-400 uppercase px-2 py-0.5 rounded bg-indigo-500/10';
  558. }
  559. }
  560. // Legacy Dashboard Stats (Safe checks)
  561. const elIfacesUp = document.getElementById('stat-ifaces-up');
  562. if (elIfacesUp) elIfacesUp.innerText = s.up_ifaces || 0;
  563. const elIfacesTot = document.getElementById('stat-ifaces-total');
  564. if (elIfacesTot) elIfacesTot.innerText = `${s.total_ifaces || 0} Total`;
  565. const elIfacesDown = document.getElementById('stat-ifaces-down');
  566. if (elIfacesDown) elIfacesDown.innerText = `${s.down_ifaces || 0} DOWN`;
  567. const elVlans = document.getElementById('stat-vlans-count');
  568. if (elVlans) elVlans.innerText = s.vlan_ifaces || 0;
  569. // VPN Status Indicators
  570. if (v) {
  571. const totalActive = v.total_active_tunnels || 0;
  572. const statVpnActive = document.getElementById('stat-vpn-active');
  573. if (statVpnActive) statVpnActive.innerText = totalActive;
  574. const tunnelsDot = document.getElementById('tunnels-dot');
  575. const tunnelsLabel = document.getElementById('tunnels-label');
  576. if (tunnelsDot && tunnelsLabel) {
  577. if (totalActive > 0) {
  578. tunnelsDot.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  579. tunnelsLabel.innerText = `${totalActive} Active VPN Tunnel${totalActive > 1 ? 's' : ''}`;
  580. } else {
  581. tunnelsDot.className = 'w-2 h-2 rounded-full bg-slate-500';
  582. tunnelsLabel.innerText = '0 Active VPN Tunnels';
  583. }
  584. }
  585. setDotBadge('badge-pppoe-status', (v.active_pppoe || 0) > 0 || v.pppoe_connected);
  586. setDotBadge('badge-wg-status', (v.active_wireguard || 0) > 0 || v.wireguard_active);
  587. setDotBadge('badge-ipsec-status', (v.active_ipsec || 0) > 0 || v.ipsec_active);
  588. setDotBadge('badge-l2tp-status', (v.active_l2tp || 0) > 0 || v.l2tp_connected);
  589. setDotBadge('badge-pptp-status', (v.active_pptp || 0) > 0 || v.pptp_connected);
  590. }
  591. // Total Live Bandwidth Rate
  592. let totalRx = 0;
  593. let totalTx = 0;
  594. (state.interfaces || []).forEach(i => {
  595. if (i.rate) {
  596. totalRx += i.rate.rx_bytes_sec || 0;
  597. totalTx += i.rate.tx_bytes_sec || 0;
  598. }
  599. });
  600. document.getElementById('stat-traffic-rx').innerText = formatTraffic(totalRx);
  601. document.getElementById('stat-traffic-tx').innerText = formatTraffic(totalTx);
  602. }
  603. function setDotBadge(id, active) {
  604. const el = document.getElementById(id);
  605. if (!el) return;
  606. if (active) {
  607. el.className = 'w-2 h-2 rounded-full bg-emerald-400 shadow-sm shadow-emerald-400/80';
  608. } else {
  609. el.className = 'w-2 h-2 rounded-full bg-slate-600';
  610. }
  611. }
  612. function updateBadges() {
  613. const bIfaces = document.getElementById('badge-ifaces-count');
  614. if (bIfaces) bIfaces.innerText = (state.interfaces || []).length;
  615. const bVlans = document.getElementById('badge-vlans-count');
  616. if (bVlans) bVlans.innerText = (state.vlans || []).length;
  617. if (state.fwSummary) {
  618. const totalFwRules = (state.fwSummary.filter_rules_count || 0) + (state.fwSummary.nat_rules_count || 0) + (state.fwSummary.mangle_rules_count || 0);
  619. const badgeFw = document.getElementById('badge-firewall-count');
  620. if (badgeFw) badgeFw.innerText = totalFwRules;
  621. }
  622. if (state.vpnStatus) {
  623. const v = state.vpnStatus;
  624. const bEoIP = document.getElementById('badge-eoip-count');
  625. if (bEoIP) bEoIP.innerText = v.total_eoip || 0;
  626. const bAero = document.getElementById('badge-aerotun-count');
  627. if (bAero) bAero.innerText = v.total_aerotun || 0;
  628. const bPPPSess = document.getElementById('badge-ppp-sessions');
  629. if (bPPPSess) bPPPSess.innerText = v.total_ppp_sessions || 0;
  630. setDotBadge('badge-pppoe-status', v.active_pppoe > 0 || v.pppoe_server_running);
  631. setDotBadge('badge-wg-status', v.active_wireguard > 0);
  632. setDotBadge('badge-ipsec-status', v.active_ipsec > 0 || v.ipsec_server_running);
  633. setDotBadge('badge-l2tp-status', v.active_l2tp > 0 || v.l2tp_server_running);
  634. setDotBadge('badge-pptp-status', v.active_pptp > 0 || v.pptp_server_running);
  635. }
  636. if (state.dynSummary) {
  637. const d = state.dynSummary;
  638. setDotBadge('badge-bgp-dot', d.bgp_running);
  639. setDotBadge('badge-ospf-dot', d.ospf_running);
  640. const bBgp = document.getElementById('badge-bgp-count');
  641. if (bBgp) bBgp.innerText = (state.bgpPeers || []).length;
  642. const bOspf = document.getElementById('badge-ospf-count');
  643. if (bOspf) bOspf.innerText = (state.ospfInterfaces || []).length;
  644. const bFilters = document.getElementById('badge-filters-count');
  645. if (bFilters) bFilters.innerText = (state.routingFilters || []).length;
  646. }
  647. const bDhcpServer = document.getElementById('badge-dhcp-server-count');
  648. if (bDhcpServer) {
  649. bDhcpServer.innerText = state.dhcpServerSummary ? (state.dhcpServerSummary.active_leases || state.dhcpServerSummary.total_servers || 0) : (state.dhcpServers || []).length;
  650. }
  651. }
  652. // Render Dashboard View
  653. function renderDashboard() {
  654. const matrix = document.getElementById('port-matrix');
  655. if (!matrix) return;
  656. const ifaces = state.interfaces || [];
  657. const sig = ifaces.map(i => `${i.name}:${i.state}:${(i.ipv4 || []).join(',')}:${i.type}:${i.is_vlan}`).join(';');
  658. if (matrix.dataset.sig === sig) {
  659. return; // Structure & link states haven't changed! Do not rebuild or flicker!
  660. }
  661. matrix.dataset.sig = sig;
  662. matrix.innerHTML = '';
  663. (state.interfaces || []).forEach(iface => {
  664. const isUp = iface.state === 'UP';
  665. const isVlan = iface.is_vlan;
  666. const portCard = document.createElement('div');
  667. portCard.className = `p-3 rounded-xl border transition-all cursor-pointer select-none group ${
  668. isUp
  669. ? (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')
  670. : 'bg-slate-900/40 border-slate-800/60 opacity-60 hover:opacity-100 hover:border-slate-700'
  671. }`;
  672. portCard.onclick = () => openIfaceModal(iface.name);
  673. let statusPillClass = isUp ? 'bg-emerald-500 shadow-sm shadow-emerald-500/50' : 'bg-rose-500';
  674. if (isVlan) statusPillClass = isUp ? 'bg-cyan-400 shadow-sm shadow-cyan-400/50' : 'bg-rose-500';
  675. portCard.innerHTML = `
  676. <div class="flex items-center justify-between mb-2">
  677. <span class="font-bold text-xs font-mono text-white group-hover:text-brand-400 transition truncate">${iface.name}</span>
  678. <span class="w-2 h-2 rounded-full ${statusPillClass}"></span>
  679. </div>
  680. <div class="text-[11px] font-mono text-slate-300 truncate">${iface.ipv4 && iface.ipv4.length > 0 ? iface.ipv4[0] : (iface.mac || 'No IP')}</div>
  681. <div class="mt-2 flex items-center justify-between text-[10px] text-slate-400">
  682. <span class="uppercase tracking-wider font-semibold">${isVlan ? `VLAN ${iface.vlan_id}` : iface.type}</span>
  683. <span id="port-card-rate-${iface.name}">${iface.rate?.rx_human || '0 B/s'}</span>
  684. </div>
  685. `;
  686. matrix.appendChild(portCard);
  687. });
  688. const ifaceTbody = document.getElementById('quick-interfaces-table');
  689. if (ifaceTbody) {
  690. ifaceTbody.innerHTML = '';
  691. (state.interfaces || []).forEach(i => {
  692. const isUp = i.state === 'UP';
  693. const tr = document.createElement('tr');
  694. tr.className = 'hover:bg-slate-800/40 transition cursor-pointer';
  695. tr.onclick = () => openIfaceModal(i.name);
  696. const rxStr = i.rate?.rx_human || '0 B/s';
  697. const txStr = i.rate?.tx_human || '0 B/s';
  698. tr.innerHTML = `
  699. <td class="py-2.5 font-bold text-white flex items-center gap-2">
  700. <span class="w-2 h-2 rounded-full ${isUp ? 'bg-emerald-400 shadow-sm shadow-emerald-400/50' : 'bg-rose-400'}"></span>
  701. <span>${i.name}</span>
  702. </td>
  703. <td class="py-2.5 text-slate-300 font-sans">
  704. ${getRoleBadge(i.role || 'LAN')}
  705. </td>
  706. <td class="py-2.5 text-slate-400 text-[11px] font-mono">${i.mac || '-'}</td>
  707. <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>
  708. <td class="py-2.5 text-slate-300 text-[11px] font-mono">
  709. <span id="quick-rx-${i.name}" class="text-emerald-400">↓ ${rxStr}</span> <span class="text-slate-600">•</span> <span id="quick-tx-${i.name}" class="text-cyan-400">↑ ${txStr}</span>
  710. </td>
  711. <td class="py-2.5 text-right font-sans font-semibold">
  712. <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>
  713. </td>
  714. `;
  715. ifaceTbody.appendChild(tr);
  716. });
  717. }
  718. const vlanTbody = document.getElementById('quick-vlans-table');
  719. if (vlanTbody) {
  720. vlanTbody.innerHTML = '';
  721. }
  722. }
  723. // Expand / Collapse Handlers
  724. function toggleExpand(parentName) {
  725. if (state.expandedParents.has(parentName)) {
  726. state.expandedParents.delete(parentName);
  727. } else {
  728. state.expandedParents.add(parentName);
  729. }
  730. renderInterfacesList();
  731. }
  732. // VLAN Support Checker: 802.1Q sub-interfaces are only supported on physical ethernet, veth, bridge, bond
  733. function supportsVLAN(iface) {
  734. if (!iface) return false;
  735. if (iface.is_vlan) return false;
  736. const name = (iface.name || '').toLowerCase();
  737. const type = (iface.type || '').toLowerCase();
  738. const role = (iface.role || '').toLowerCase();
  739. // Exclude loopback
  740. if (name === 'lo' || type === 'loopback' || role === 'loopback') return false;
  741. // Exclude WireGuard (Layer 3 tunnel, no 802.1Q support)
  742. if (type === 'wireguard' || name.startsWith('wg')) return false;
  743. // Exclude PPP / PPPoE
  744. if (type === 'ppp' || name.startsWith('ppp')) return false;
  745. // Exclude other Layer 3 tunnels and dummy devices
  746. if (type === 'dummy' || type === 'gre' || type === 'sit' || type === 'tun' || type === 'tap' ||
  747. name.startsWith('gre') || name.startsWith('sit') || name.startsWith('ipsec') || name.startsWith('xfrm') || name.startsWith('dummy')) {
  748. return false;
  749. }
  750. // If name already contains a dot, it's already a sub-interface
  751. if (name.includes('.')) return false;
  752. return true;
  753. }
  754. // DHCP Client Support Checker: Only broadcast-capable layer-2 interfaces (Ethernet, veth, VLAN, bridge, bond)
  755. function supportsDHCPClient(iface) {
  756. if (!iface) return false;
  757. const name = (iface.name || '').toLowerCase();
  758. const type = (iface.type || '').toLowerCase();
  759. const role = (iface.role || '').toLowerCase();
  760. // Exclude loopback
  761. if (name === 'lo' || type === 'loopback' || role === 'loopback') return false;
  762. // Exclude WireGuard (Layer 3 point-to-point tunnel, no broadcast/DHCP)
  763. if (type === 'wireguard' || name.startsWith('wg')) return false;
  764. // Exclude PPP / PPPoE / L2TP / PPTP tunnels
  765. if (type === 'ppp' || name.startsWith('ppp') || name.startsWith('l2tp') || name.startsWith('pptp')) return false;
  766. // Exclude other Layer 3 tunnels and dummy devices
  767. if (type === 'dummy' || type === 'gre' || type === 'sit' || type === 'tun' || type === 'tap' ||
  768. name.startsWith('gre') || name.startsWith('sit') || name.startsWith('ipsec') || name.startsWith('xfrm') || name.startsWith('dummy')) {
  769. return false;
  770. }
  771. // Exclude bridge member/slave ports (bridge itself handles IP / DHCP)
  772. const isBridgePort = (state.bridgePorts || []).some(bp => bp.interface === iface.name);
  773. if (isBridgePort) return false;
  774. return true;
  775. }
  776. // Expand / Collapse Handlers
  777. function toggleExpand(parentName) {
  778. const childVlans = (state.vlans || []).filter(v => v.parent_name === parentName || v.name.startsWith(parentName + '.'));
  779. if (childVlans.length === 0) {
  780. // Cannot expand an interface with no VLANs
  781. state.expandedParents.delete(parentName);
  782. return;
  783. }
  784. if (state.expandedParents.has(parentName)) {
  785. state.expandedParents.delete(parentName);
  786. } else {
  787. state.expandedParents.add(parentName);
  788. }
  789. renderInterfacesList();
  790. }
  791. function expandAllIfaces(expand) {
  792. if (expand) {
  793. (state.interfaces || []).forEach(i => {
  794. const hasVlans = (state.vlans || []).some(v => v.parent_name === i.name || v.name.startsWith(i.name + '.'));
  795. if (!i.is_vlan && hasVlans) state.expandedParents.add(i.name);
  796. });
  797. } else {
  798. state.expandedParents.clear();
  799. }
  800. renderInterfacesList();
  801. }
  802. // =========================================================================
  803. // INTERFACE ROLE TAGS MANAGEMENT
  804. // =========================================================================
  805. const ROLE_COLORS = {
  806. amber: { bg: 'bg-amber-500/20', text: 'text-amber-300', border: 'border-amber-500/30' },
  807. blue: { bg: 'bg-blue-500/20', text: 'text-blue-300', border: 'border-blue-500/30' },
  808. cyan: { bg: 'bg-cyan-500/20', text: 'text-cyan-300', border: 'border-cyan-500/30' },
  809. emerald: { bg: 'bg-emerald-500/20', text: 'text-emerald-300', border: 'border-emerald-500/30' },
  810. purple: { bg: 'bg-purple-500/20', text: 'text-purple-300', border: 'border-purple-500/30' },
  811. rose: { bg: 'bg-rose-500/20', text: 'text-rose-300', border: 'border-rose-500/30' },
  812. indigo: { bg: 'bg-indigo-500/20', text: 'text-indigo-300', border: 'border-indigo-500/30' },
  813. sky: { bg: 'bg-sky-500/20', text: 'text-sky-300', border: 'border-sky-500/30' },
  814. slate: { bg: 'bg-slate-800', text: 'text-slate-300', border: 'border-slate-700' }
  815. };
  816. function getRoleBadge(roleName) {
  817. const name = roleName || 'LAN';
  818. const role = (state.roles || []).find(r => r.name.toLowerCase() === name.toLowerCase() || r.id.toLowerCase() === name.toLowerCase());
  819. const colorKey = (role?.color || 'blue').toLowerCase();
  820. const theme = ROLE_COLORS[colorKey] || ROLE_COLORS.blue;
  821. return `<span class="px-2 py-0.5 rounded text-[10px] font-semibold ${theme.bg} ${theme.text} border ${theme.border}" title="Role Tag: ${escapeHtml(name)}">${escapeHtml(name)}</span>`;
  822. }
  823. function switchIfaceSubTab(subTab) {
  824. state.activeIfaceSubTab = subTab;
  825. const treeTab = document.getElementById('ifaces-subtab-tree');
  826. const rolesTab = document.getElementById('ifaces-subtab-roles');
  827. const btnTree = document.getElementById('ifaces-subtab-btn-tree');
  828. const btnRoles = document.getElementById('ifaces-subtab-btn-roles');
  829. if (subTab === 'roles') {
  830. treeTab?.classList.add('hidden');
  831. rolesTab?.classList.remove('hidden');
  832. if (btnRoles) {
  833. btnRoles.className = 'px-3.5 py-1.5 rounded-lg text-xs font-semibold bg-brand-500/10 text-brand-400 border border-brand-500/20 transition flex items-center gap-1.5';
  834. }
  835. if (btnTree) {
  836. btnTree.className = 'px-3.5 py-1.5 rounded-lg text-xs font-medium text-slate-400 hover:text-white hover:bg-slate-800 transition flex items-center gap-1.5';
  837. }
  838. loadRoles();
  839. } else {
  840. rolesTab?.classList.add('hidden');
  841. treeTab?.classList.remove('hidden');
  842. if (btnTree) {
  843. btnTree.className = 'px-3.5 py-1.5 rounded-lg text-xs font-semibold bg-brand-500/10 text-brand-400 border border-brand-500/20 transition flex items-center gap-1.5';
  844. }
  845. if (btnRoles) {
  846. btnRoles.className = 'px-3.5 py-1.5 rounded-lg text-xs font-medium text-slate-400 hover:text-white hover:bg-slate-800 transition flex items-center gap-1.5';
  847. }
  848. renderInterfacesList();
  849. }
  850. }
  851. async function loadRoles() {
  852. try {
  853. const res = await fetch(`${API_BASE}/roles`);
  854. if (res.ok) {
  855. state.roles = await res.json();
  856. const countEl = document.getElementById('badge-roles-count');
  857. if (countEl) countEl.innerText = (state.roles || []).length;
  858. renderRolesTable();
  859. populateRoleSelects();
  860. }
  861. } catch (err) {
  862. console.error('Failed to load role tags:', err);
  863. }
  864. }
  865. function renderRolesTable() {
  866. const tbody = document.getElementById('roles-table-body');
  867. const empty = document.getElementById('roles-empty-state');
  868. if (!tbody) return;
  869. const roles = state.roles || [];
  870. if (roles.length === 0) {
  871. tbody.innerHTML = '';
  872. empty?.classList.remove('hidden');
  873. return;
  874. }
  875. empty?.classList.add('hidden');
  876. const sig = roles.map(r => `${r.id}:${r.name}:${r.color}:${r.description}:${(r.interfaces||[]).join(',')}`).join(';');
  877. if (tbody.dataset.sig === sig) return;
  878. tbody.dataset.sig = sig;
  879. tbody.innerHTML = roles.map(r => {
  880. const colorKey = (r.color || 'blue').toLowerCase();
  881. const theme = ROLE_COLORS[colorKey] || ROLE_COLORS.blue;
  882. const ifaces = Array.isArray(r.interfaces) ? r.interfaces : [];
  883. const ifacesChips = ifaces.length > 0
  884. ? ifaces.map(name => `<span onclick="openIfaceModal('${escapeHtml(name)}')" class="cursor-pointer px-2 py-0.5 rounded text-[10px] font-mono bg-slate-800 text-slate-200 border border-slate-700 hover:border-cyan-500 transition mr-1 mb-1 inline-block" title="Click to view/edit ${escapeHtml(name)}">${escapeHtml(name)}</span>`).join('')
  885. : '<span class="text-slate-600 font-sans text-xs italic">Unassigned (0)</span>';
  886. return `
  887. <tr class="hover:bg-slate-800/40 transition">
  888. <td class="py-3 px-4">
  889. <span class="px-2.5 py-1 rounded text-xs font-semibold ${theme.bg} ${theme.text} border ${theme.border}">
  890. ${escapeHtml(r.name)}
  891. </span>
  892. </td>
  893. <td class="py-3 px-4 font-bold text-white font-mono flex items-center gap-2">
  894. <span>${escapeHtml(r.name)}</span>
  895. ${r.builtin ? '<span class="text-[9px] px-1.5 py-0.2 rounded bg-slate-800 text-slate-400 border border-slate-700 uppercase font-sans">Builtin</span>' : ''}
  896. </td>
  897. <td class="py-3 px-4 font-sans capitalize text-slate-300">
  898. <span class="inline-flex items-center gap-1.5">
  899. <span class="w-2 h-2 rounded-full ${theme.bg.replace('/20', '')}"></span>
  900. <span>${escapeHtml(r.color || 'blue')}</span>
  901. </span>
  902. </td>
  903. <td class="py-3 px-4 font-sans text-slate-400 text-xs">${escapeHtml(r.description || '-')}</td>
  904. <td class="py-3 px-4 font-sans">
  905. <div class="flex flex-wrap items-center">
  906. ${ifacesChips}
  907. </div>
  908. </td>
  909. <td class="py-3 px-4 text-right space-x-2 font-sans whitespace-nowrap">
  910. <button onclick="openRoleModal('${escapeHtml(r.id)}')"
  911. class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold px-2 py-1 rounded hover:bg-slate-800 transition">
  912. Edit
  913. </button>
  914. <button onclick="deleteRoleTag('${escapeHtml(r.id)}', '${escapeHtml(r.name)}')"
  915. class="text-xs text-rose-400 hover:text-rose-300 font-semibold px-2 py-1 rounded hover:bg-slate-800 transition">
  916. Delete
  917. </button>
  918. </td>
  919. </tr>
  920. `;
  921. }).join('');
  922. }
  923. function openRoleModal(id = null) {
  924. const modal = document.getElementById('role-modal');
  925. if (!modal) return;
  926. const idInput = document.getElementById('role-modal-id');
  927. const nameInput = document.getElementById('role-modal-name');
  928. const colorSelect = document.getElementById('role-modal-color');
  929. const descInput = document.getElementById('role-modal-desc');
  930. const title = document.getElementById('role-modal-title');
  931. if (id) {
  932. const role = (state.roles || []).find(r => r.id === id);
  933. if (role) {
  934. if (title) title.innerText = `Edit Role Tag: ${role.name}`;
  935. if (idInput) idInput.value = role.id;
  936. if (nameInput) nameInput.value = role.name;
  937. if (colorSelect) colorSelect.value = role.color || 'blue';
  938. if (descInput) descInput.value = role.description || '';
  939. }
  940. } else {
  941. if (title) title.innerText = 'Add Role Tag';
  942. if (idInput) idInput.value = '';
  943. if (nameInput) nameInput.value = '';
  944. if (colorSelect) colorSelect.value = 'blue';
  945. if (descInput) descInput.value = '';
  946. }
  947. updateRoleModalPreview();
  948. modal.classList.remove('hidden');
  949. }
  950. function closeRoleModal() {
  951. const modal = document.getElementById('role-modal');
  952. if (modal) modal.classList.add('hidden');
  953. }
  954. function updateRoleModalPreview() {
  955. const name = document.getElementById('role-modal-name')?.value.trim() || 'Preview';
  956. const colorKey = (document.getElementById('role-modal-color')?.value || 'blue').toLowerCase();
  957. const theme = ROLE_COLORS[colorKey] || ROLE_COLORS.blue;
  958. const preview = document.getElementById('role-modal-preview');
  959. if (preview) {
  960. preview.innerText = name;
  961. preview.className = `px-2.5 py-1 rounded text-xs font-semibold ${theme.bg} ${theme.text} border ${theme.border}`;
  962. }
  963. }
  964. async function submitSaveRole(e) {
  965. e.preventDefault();
  966. const id = document.getElementById('role-modal-id')?.value;
  967. const name = document.getElementById('role-modal-name')?.value.trim();
  968. const color = document.getElementById('role-modal-color')?.value;
  969. const desc = document.getElementById('role-modal-desc')?.value.trim();
  970. if (!name) return;
  971. try {
  972. const payload = { id, name, color, description: desc };
  973. const method = id ? 'PUT' : 'POST';
  974. const url = id ? `${API_BASE}/roles/${encodeURIComponent(id)}` : `${API_BASE}/roles`;
  975. const res = await fetch(url, {
  976. method,
  977. headers: { 'Content-Type': 'application/json' },
  978. body: JSON.stringify(payload)
  979. });
  980. if (res.ok) {
  981. showToast('Role Tag Saved', `Role tag "${name}" saved successfully`, 'success');
  982. closeRoleModal();
  983. await loadRoles();
  984. fetchData(false);
  985. } else {
  986. const err = await res.json();
  987. showToast('Error', err.error || err.message || 'Failed to save role tag', 'error');
  988. }
  989. } catch (err) {
  990. showToast('Error', err.message, 'error');
  991. }
  992. }
  993. async function deleteRoleTag(id, name) {
  994. if (!confirm(`Are you sure you want to delete role tag "${name}"?\nInterfaces assigned to this role will default to LAN.`)) return;
  995. try {
  996. const res = await fetch(`${API_BASE}/roles/${encodeURIComponent(id)}`, {
  997. method: 'DELETE'
  998. });
  999. if (res.ok) {
  1000. showToast('Role Tag Deleted', `Role tag "${name}" removed`, 'success');
  1001. await loadRoles();
  1002. fetchData(false);
  1003. } else {
  1004. const err = await res.json();
  1005. showToast('Error', err.error || err.message || 'Failed to delete role tag', 'error');
  1006. }
  1007. } catch (err) {
  1008. showToast('Error', err.message, 'error');
  1009. }
  1010. }
  1011. function populateRoleSelects(selectedRole = '') {
  1012. const ifaceSelect = document.getElementById('modal-iface-role');
  1013. const vlanSelect = document.getElementById('vlan-role');
  1014. const roles = state.roles || [];
  1015. const optionsHtml = roles.map(r => `<option value="${escapeHtml(r.name)}">${escapeHtml(r.name)}${r.description ? ` (${escapeHtml(r.description)})` : ''}</option>`).join('');
  1016. if (ifaceSelect) {
  1017. const currentVal = selectedRole || ifaceSelect.value || 'LAN';
  1018. if (ifaceSelect.dataset.optionsSig !== optionsHtml) {
  1019. ifaceSelect.innerHTML = optionsHtml;
  1020. ifaceSelect.dataset.optionsSig = optionsHtml;
  1021. }
  1022. if (currentVal) ifaceSelect.value = currentVal;
  1023. }
  1024. if (vlanSelect) {
  1025. const currentVal = selectedRole || vlanSelect.value || 'LAN';
  1026. if (vlanSelect.dataset.optionsSig !== optionsHtml) {
  1027. vlanSelect.innerHTML = optionsHtml;
  1028. vlanSelect.dataset.optionsSig = optionsHtml;
  1029. }
  1030. if (currentVal) vlanSelect.value = currentVal;
  1031. }
  1032. }
  1033. // Filter and Render Hierarchical Interfaces List
  1034. function filterIfaces(filter) {
  1035. state.ifaceFilter = filter || 'all';
  1036. renderInterfacesList();
  1037. }
  1038. function renderInterfacesList() {
  1039. const tbody = document.getElementById('interfaces-tree-tbody');
  1040. const emptyState = document.getElementById('interfaces-empty-state');
  1041. const summary = document.getElementById('ifaces-list-summary');
  1042. const query = (document.getElementById('iface-search')?.value || '').trim().toLowerCase();
  1043. const allIfaces = state.interfaces || [];
  1044. const allVlans = state.vlans || [];
  1045. const parentIfaces = allIfaces.filter(i => !i.is_vlan);
  1046. const filteredParents = parentIfaces.filter(parent => {
  1047. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  1048. if (query) {
  1049. const matchName = parent.name.toLowerCase().includes(query);
  1050. const matchIp = (parent.ipv4 || []).some(ip => ip.toLowerCase().includes(query));
  1051. const matchRole = (parent.role || '').toLowerCase().includes(query);
  1052. const matchType = (parent.type || '').toLowerCase().includes(query);
  1053. const matchVlan = childVlans.some(v =>
  1054. v.name.toLowerCase().includes(query) ||
  1055. String(v.vlan_id).includes(query) ||
  1056. (v.ipv4 || []).some(ip => ip.toLowerCase().includes(query)) ||
  1057. (v.description || '').toLowerCase().includes(query)
  1058. );
  1059. if (!matchName && !matchIp && !matchRole && !matchType && !matchVlan) return false;
  1060. }
  1061. if (state.ifaceFilter === 'has_vlans') return childVlans.length > 0;
  1062. if (state.ifaceFilter === 'physical') return parent.type !== 'loopback';
  1063. if (state.ifaceFilter === 'up') return parent.state === 'UP';
  1064. return true;
  1065. });
  1066. if (summary) {
  1067. summary.innerText = `${parentIfaces.length} Interfaces • ${allVlans.length} Active VLANs`;
  1068. }
  1069. if (filteredParents.length === 0) {
  1070. emptyState?.classList.remove('hidden');
  1071. tbody.innerHTML = '';
  1072. return;
  1073. }
  1074. emptyState?.classList.add('hidden');
  1075. const sig = `${state.ifaceFilter}|${query}|` + filteredParents.map(p => {
  1076. const cVlans = allVlans.filter(v => v.parent_name === p.name || v.name.startsWith(p.name + '.'));
  1077. const dhcp = (state.dhcpClients || []).find(dc => dc.interface === p.name);
  1078. return `${p.name}:${p.state}:${p.role||'LAN'}:${(p.ipv4||[]).join(',')}:${p.mtu}:${cVlans.length}:${state.expandedParents.has(p.name)}:${dhcp?.status || ''}`;
  1079. }).join(';');
  1080. if (tbody.dataset.sig === sig) {
  1081. return; // ZERO changes to structure, links, IPs or VLANs! Do not rebuild DOM!
  1082. }
  1083. tbody.dataset.sig = sig;
  1084. tbody.innerHTML = '';
  1085. filteredParents.forEach(parent => {
  1086. const isUp = parent.state === 'UP';
  1087. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  1088. const hasVlans = childVlans.length > 0;
  1089. const isExpanded = hasVlans && state.expandedParents.has(parent.name);
  1090. const canHaveVlan = supportsVLAN(parent);
  1091. const parentRow = document.createElement('tr');
  1092. parentRow.className = `hover:bg-slate-800/50 transition border-b border-slate-800/80 ${isExpanded ? 'bg-slate-900/80' : ''}`;
  1093. parentRow.innerHTML = `
  1094. <td class="py-3 px-3 text-center">
  1095. ${hasVlans ? `
  1096. <button onclick="toggleExpand('${parent.name}')" title="${isExpanded ? 'Collapse VLANs' : 'Expand VLANs'}"
  1097. class="w-6 h-6 rounded flex items-center justify-center hover:bg-slate-800 text-slate-400 hover:text-white transition">
  1098. <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">
  1099. <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M9 5l7 7-7 7" />
  1100. </svg>
  1101. </button>
  1102. ` : `
  1103. <div class="w-6 h-6 flex items-center justify-center text-slate-700 select-none">
  1104. <span class="w-1.5 h-1.5 rounded-full bg-slate-800"></span>
  1105. </div>
  1106. `}
  1107. </td>
  1108. <td class="py-3 px-4">
  1109. <div class="flex items-center space-x-2.5">
  1110. <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">
  1111. ${parent.type === 'loopback' ? 'LO' : (parent.type === 'wireguard' ? 'WG' : (parent.type === 'bridge' ? 'BR' : 'NIC'))}
  1112. </div>
  1113. <div>
  1114. <div class="flex items-center gap-2">
  1115. <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'}">
  1116. <span>${parent.name}</span>
  1117. <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>
  1118. </span>
  1119. ${hasVlans ? `
  1120. <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>
  1121. ` : `
  1122. <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>
  1123. `}
  1124. </div>
  1125. <div class="text-[10px] text-slate-500 font-sans mt-0.5">${parent.type}</div>
  1126. </div>
  1127. </div>
  1128. </td>
  1129. <td class="py-3 px-4 font-sans">
  1130. <div class="flex items-center gap-1.5">
  1131. ${getRoleBadge(parent.role || 'LAN')}
  1132. <span class="text-xs text-slate-400 truncate max-w-[120px]">${parent.description || '-'}</span>
  1133. </div>
  1134. </td>
  1135. <td class="py-3 px-4">
  1136. ${parent.ipv4 && parent.ipv4.length > 0
  1137. ? `<div class="text-white font-medium">${parent.ipv4[0]}</div>`
  1138. : '<span class="text-slate-600 font-sans">Unassigned</span>'
  1139. }
  1140. ${(() => {
  1141. const c = (state.dhcpClients || []).find(dc => dc.interface === parent.name);
  1142. if (!c) return '';
  1143. 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');
  1144. 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>`;
  1145. })()}
  1146. </td>
  1147. <td class="py-3 px-4 text-slate-400 text-[11px]">
  1148. <div>${parent.mac || 'N/A'}</div>
  1149. <div class="text-[10px] text-slate-500">MTU ${parent.mtu}</div>
  1150. </td>
  1151. <td class="py-3 px-4 text-[11px]">
  1152. <div class="flex items-center space-x-2">
  1153. <span id="iface-rate-rx-${parent.name}" class="text-emerald-400">↓ ${parent.rate?.rx_human || '0 B/s'}</span>
  1154. <span id="iface-rate-tx-${parent.name}" class="text-cyan-400">↑ ${parent.rate?.tx_human || '0 B/s'}</span>
  1155. </div>
  1156. </td>
  1157. <td class="py-3 px-4 font-sans">
  1158. <button onclick="toggleInterfaceState('${parent.name}', '${isUp ? 'down' : 'up'}')"
  1159. class="flex items-center gap-1.5 text-xs font-semibold px-2.5 py-1 rounded-full transition ${
  1160. 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'
  1161. }" title="Click to toggle link status">
  1162. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  1163. <span>${parent.state}</span>
  1164. </button>
  1165. </td>
  1166. <td class="py-3 px-4 text-right space-x-2 font-sans">
  1167. ${(() => {
  1168. const c = (state.dhcpClients || []).find(dc => dc.interface === parent.name);
  1169. if (c) {
  1170. 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>`;
  1171. }
  1172. if (!supportsDHCPClient(parent)) {
  1173. return '';
  1174. }
  1175. 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>`;
  1176. })()}
  1177. ${canHaveVlan ? `
  1178. <button onclick="openVlanModal('${parent.name}')"
  1179. 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">
  1180. + Add VLAN
  1181. </button>
  1182. ` : ''}
  1183. <button onclick="openIfaceModal('${parent.name}')"
  1184. 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">
  1185. Edit
  1186. </button>
  1187. </td>
  1188. `;
  1189. tbody.appendChild(parentRow);
  1190. if (isExpanded) {
  1191. const drawerRow = document.createElement('tr');
  1192. drawerRow.className = 'bg-slate-950/80 border-b border-slate-800/90';
  1193. const drawerCell = document.createElement('td');
  1194. drawerCell.colSpan = 8;
  1195. drawerCell.className = 'p-0';
  1196. drawerCell.innerHTML = `
  1197. <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">
  1198. <div class="flex items-center justify-between mb-3">
  1199. <div class="flex items-center space-x-3">
  1200. <span class="font-bold text-xs text-white uppercase tracking-wider flex items-center gap-1.5 font-sans">
  1201. <span>VLAN Sub-interfaces on <code class="text-cyan-300 lowercase">${parent.name}</code></span>
  1202. </span>
  1203. <span class="text-[11px] bg-cyan-950 text-cyan-400 px-2 py-0.5 rounded-full border border-cyan-800/60 font-mono">
  1204. ${childVlans.length} Attached
  1205. </span>
  1206. </div>
  1207. <button onclick="openVlanModal('${parent.name}')"
  1208. 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">
  1209. <span>+ Create VLAN on ${parent.name}</span>
  1210. </button>
  1211. </div>
  1212. ${childVlans.length === 0 ? `
  1213. <div class="p-6 text-center border border-dashed border-slate-800 rounded-xl bg-slate-900/40 font-sans">
  1214. <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>
  1215. <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">
  1216. <span>+ Create Your First VLAN on ${parent.name}</span>
  1217. </button>
  1218. </div>
  1219. ` : `
  1220. <div class="overflow-x-auto rounded-lg border border-slate-800 bg-slate-900/90 shadow-inner">
  1221. <table class="w-full text-left text-xs font-mono">
  1222. <thead class="text-slate-400 bg-slate-950/70 border-b border-slate-800 uppercase tracking-wider text-[10px] font-sans">
  1223. <tr>
  1224. <th class="py-2.5 px-4">VLAN ID</th>
  1225. <th class="py-2.5 px-4">Interface Device</th>
  1226. <th class="py-2.5 px-4">Subnet Gateway</th>
  1227. <th class="py-2.5 px-4">Role / Alias</th>
  1228. <th class="py-2.5 px-4">MTU</th>
  1229. <th class="py-2.5 px-4">Throughput</th>
  1230. <th class="py-2.5 px-4">Status</th>
  1231. <th class="py-2.5 px-4 text-right">Actions</th>
  1232. </tr>
  1233. </thead>
  1234. <tbody class="divide-y divide-slate-800/70">
  1235. ${childVlans.map(v => {
  1236. const isVlanUp = v.state === 'UP';
  1237. return `
  1238. <tr class="hover:bg-slate-800/40 transition">
  1239. <td class="py-2.5 px-4">
  1240. <span class="px-2 py-0.5 rounded text-xs font-bold bg-cyan-950 text-cyan-300 border border-cyan-800 shadow-sm">
  1241. VLAN ${v.vlan_id}
  1242. </span>
  1243. </td>
  1244. <td class="py-2.5 px-4 font-bold text-white flex items-center gap-1.5">
  1245. <span class="text-cyan-500">└─</span>
  1246. <span class="cursor-pointer hover:text-cyan-400 flex items-center gap-1" onclick="openIfaceModal('${v.name}')" title="Configure / Rename ${v.name}">
  1247. <span>${v.name}</span>
  1248. <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>
  1249. </span>
  1250. </td>
  1251. <td class="py-2.5 px-4 text-emerald-400 font-medium">
  1252. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  1253. ${(() => {
  1254. const c = (state.dhcpClients || []).find(dc => dc.interface === v.name);
  1255. if (!c) return '';
  1256. 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';
  1257. 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>`;
  1258. })()}
  1259. </td>
  1260. <td class="py-2.5 px-4 font-sans text-slate-300">
  1261. <div class="flex items-center gap-1.5">
  1262. ${getRoleBadge(v.role || 'LAN')}
  1263. <span class="text-slate-400 text-xs">${v.description || '-'}</span>
  1264. </div>
  1265. </td>
  1266. <td class="py-2.5 px-4 text-slate-400">${v.mtu}</td>
  1267. <td class="py-2.5 px-4 text-[11px]">
  1268. <span id="vlan-rate-rx-${v.name}" class="text-emerald-400">↓ ${v.rate?.rx_human || '0 B/s'}</span>
  1269. <span id="vlan-rate-tx-${v.name}" class="text-cyan-400 ml-1.5">↑ ${v.rate?.tx_human || '0 B/s'}</span>
  1270. </td>
  1271. <td class="py-2.5 px-4 font-sans">
  1272. <button onclick="toggleInterfaceState('${v.name}', '${isVlanUp ? 'down' : 'up'}')"
  1273. class="flex items-center gap-1 text-[11px] font-semibold px-2 py-0.5 rounded-full ${
  1274. 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'
  1275. }">
  1276. <span class="w-1.5 h-1.5 rounded-full ${isVlanUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  1277. <span>${v.state}</span>
  1278. </button>
  1279. </td>
  1280. <td class="py-2.5 px-4 text-right space-x-1.5 font-sans">
  1281. ${(() => {
  1282. const c = (state.dhcpClients || []).find(dc => dc.interface === v.name);
  1283. if (c) {
  1284. 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>`;
  1285. }
  1286. if (!supportsDHCPClient(v)) {
  1287. return '';
  1288. }
  1289. 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>`;
  1290. })()}
  1291. <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>
  1292. <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>
  1293. </td>
  1294. </tr>
  1295. `;
  1296. }).join('')}
  1297. </tbody>
  1298. </table>
  1299. </div>
  1300. `}
  1301. </div>
  1302. `;
  1303. drawerRow.appendChild(drawerCell);
  1304. tbody.appendChild(drawerRow);
  1305. }
  1306. });
  1307. }
  1308. // Render VLANs Dedicated View
  1309. function renderVlansList() {
  1310. const tbody = document.getElementById('vlans-table-body');
  1311. if (!tbody) return;
  1312. const emptyState = document.getElementById('vlans-empty-state');
  1313. const countBadge = document.getElementById('vlans-table-count');
  1314. const query = (document.getElementById('vlan-search')?.value || '').toLowerCase();
  1315. const allVlans = state.vlans || [];
  1316. if (countBadge) countBadge.innerText = allVlans.length;
  1317. const filtered = allVlans.filter(v => {
  1318. if (!query) return true;
  1319. return v.name.toLowerCase().includes(query) ||
  1320. String(v.vlan_id).includes(query) ||
  1321. (v.description || '').toLowerCase().includes(query) ||
  1322. (v.ipv4 && v.ipv4.some(ip => ip.includes(query)));
  1323. });
  1324. if (allVlans.length === 0) {
  1325. emptyState.classList.remove('hidden');
  1326. tbody.innerHTML = '';
  1327. return;
  1328. }
  1329. emptyState.classList.add('hidden');
  1330. const sig = `${query}|` + filtered.map(v => `${v.name}:${v.state}:${(v.ipv4||[]).join(',')}:${v.vlan_id}:${v.mtu}`).join(';');
  1331. if (tbody.dataset.sig === sig) return;
  1332. tbody.dataset.sig = sig;
  1333. tbody.innerHTML = '';
  1334. filtered.forEach(v => {
  1335. const isUp = v.state === 'UP';
  1336. const tr = document.createElement('tr');
  1337. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  1338. tr.innerHTML = `
  1339. <td class="py-3 px-4">
  1340. <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">
  1341. VLAN ${v.vlan_id}
  1342. </span>
  1343. </td>
  1344. <td class="py-3 px-4 font-bold text-white">
  1345. <span class="cursor-pointer hover:text-cyan-400 flex items-center gap-1.5" onclick="openIfaceModal('${v.name}')" title="Configure / Rename ${v.name}">
  1346. <span>${v.name}</span>
  1347. <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>
  1348. </span>
  1349. </td>
  1350. <td class="py-3 px-4 text-slate-300">
  1351. <span class="bg-slate-800 text-slate-200 px-2 py-0.5 rounded text-[11px]">${v.parent_name || 'eth0'}</span>
  1352. </td>
  1353. <td class="py-3 px-4 text-emerald-400 font-medium">
  1354. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  1355. </td>
  1356. <td class="py-3 px-4 text-slate-300 font-sans">
  1357. <span class="text-slate-400 text-xs">${v.description || v.role || '-'}</span>
  1358. </td>
  1359. <td class="py-3 px-4 text-slate-400">${v.mtu}</td>
  1360. <td class="py-3 px-4 font-sans">
  1361. <button onclick="toggleInterfaceState('${v.name}', '${isUp ? 'down' : 'up'}')"
  1362. class="flex items-center gap-1.5 text-xs font-semibold px-2 py-0.5 rounded-full ${
  1363. 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'
  1364. }">
  1365. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  1366. <span>${v.state}</span>
  1367. </button>
  1368. </td>
  1369. <td class="py-3 px-4 text-right space-x-2 font-sans">
  1370. <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>
  1371. <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>
  1372. </td>
  1373. `;
  1374. tbody.appendChild(tr);
  1375. });
  1376. }
  1377. // Toggle interface UP / DOWN
  1378. async function toggleInterfaceState(name, newState) {
  1379. try {
  1380. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(name)}/state`, {
  1381. method: 'POST',
  1382. headers: { 'Content-Type': 'application/json' },
  1383. body: JSON.stringify({ state: newState })
  1384. });
  1385. const data = await res.json();
  1386. if (res.ok) {
  1387. showToast('Interface Updated', `Interface ${name} is now ${newState.toUpperCase()}`, 'success');
  1388. fetchData(false);
  1389. } else {
  1390. showToast('Error', data.message || 'Failed to toggle interface state', 'error');
  1391. }
  1392. } catch (err) {
  1393. showToast('Error', err.message, 'error');
  1394. }
  1395. }
  1396. // ---------------- MikroTik Flag & Utilities ----------------
  1397. function renderMikroTikFlag(running, disabled) {
  1398. if (running) {
  1399. 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>`;
  1400. }
  1401. if (disabled) {
  1402. 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>`;
  1403. }
  1404. 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>`;
  1405. }
  1406. function copyToClipboard(text, label = 'Text') {
  1407. navigator.clipboard.writeText(text).then(() => {
  1408. showToast('Copied', `${label} copied to clipboard`, 'success');
  1409. }).catch(() => {
  1410. prompt('Copy value:', text);
  1411. });
  1412. }
  1413. // ======================== PPP Profiles Shared Helper ========================
  1414. async function fetchPPPProfilesList() {
  1415. try {
  1416. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`);
  1417. if (res.ok) {
  1418. state.pppProfiles = await res.json();
  1419. }
  1420. } catch (err) {
  1421. console.error('Failed to load PPP profiles:', err);
  1422. }
  1423. }
  1424. function populateProfileSelect(selectId, selectedVal, defaultVal = 'default') {
  1425. const sel = document.getElementById(selectId);
  1426. if (!sel) return;
  1427. const profiles = (state.pppProfiles && state.pppProfiles.length > 0) ? state.pppProfiles : [
  1428. { name: 'default', use_encryption: 'no' },
  1429. { name: 'default-encryption', use_encryption: 'required' }
  1430. ];
  1431. sel.innerHTML = '';
  1432. profiles.forEach(p => {
  1433. const opt = document.createElement('option');
  1434. opt.value = p.name;
  1435. const encBadge = p.use_encryption === 'required' ? ' (MPPE-128)' : (p.use_encryption === 'yes' ? ' (MPPE)' : '');
  1436. opt.innerText = `${p.name}${encBadge}`;
  1437. sel.appendChild(opt);
  1438. });
  1439. if (selectedVal) {
  1440. sel.value = selectedVal;
  1441. } else {
  1442. sel.value = defaultVal;
  1443. }
  1444. if (!sel.value && sel.options.length > 0) {
  1445. sel.selectedIndex = 0;
  1446. }
  1447. }
  1448. // ======================== PPPoE Multi-Instance ========================
  1449. async function loadPPPoE(populateInputs = true) {
  1450. try {
  1451. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  1452. await fetchPPPProfilesList();
  1453. }
  1454. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`);
  1455. const list = await res.json();
  1456. state.pppoeList = Array.isArray(list) ? list : [];
  1457. const badge = document.getElementById('pppoe-count-badge');
  1458. if (badge) badge.innerText = `${state.pppoeList.length} Interface${state.pppoeList.length !== 1 ? 's' : ''}`;
  1459. const tbody = document.getElementById('pppoe-table-body');
  1460. const empty = document.getElementById('pppoe-empty');
  1461. if (!tbody) return;
  1462. tbody.innerHTML = '';
  1463. if (state.pppoeList.length === 0) {
  1464. if (empty) empty.classList.remove('hidden');
  1465. } else {
  1466. if (empty) empty.classList.add('hidden');
  1467. state.pppoeList.forEach(inst => {
  1468. const tr = document.createElement('tr');
  1469. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1470. tr.innerHTML = `
  1471. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  1472. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  1473. <td class="py-2.5 px-3 text-cyan-400 font-mono">${escapeHtml(inst.interface)}</td>
  1474. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  1475. <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>
  1476. <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>
  1477. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  1478. <td class="py-2.5 px-3 text-center">
  1479. <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'}">
  1480. ${inst.default_route ? 'Yes' : 'No'}
  1481. </span>
  1482. </td>
  1483. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  1484. ${inst.running ? `
  1485. <button onclick="disconnectPPPoEInstance('${inst.name}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  1486. ` : `
  1487. <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>
  1488. `}
  1489. <button onclick="togglePPPoEState('${inst.name}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  1490. ${inst.disabled ? 'Enable' : 'Disable'}
  1491. </button>
  1492. <button onclick="openEditPPPoEModal('${inst.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  1493. <button onclick="deletePPPoEInstance('${inst.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  1494. </td>
  1495. `;
  1496. tbody.appendChild(tr);
  1497. });
  1498. }
  1499. } catch (err) {
  1500. console.error('Failed to load PPPoE:', err);
  1501. }
  1502. }
  1503. function openAddPPPoEModal() {
  1504. document.getElementById('pppoe-modal-title').innerText = 'Add PPPoE Client Interface';
  1505. document.getElementById('pppoe-modal-edit-orig').value = '';
  1506. document.getElementById('pppoe-modal-name').value = `pppoe-out${(state.pppoeList || []).length + 1}`;
  1507. document.getElementById('pppoe-modal-name').readOnly = false;
  1508. document.getElementById('pppoe-modal-user').value = '';
  1509. document.getElementById('pppoe-modal-pass').value = '';
  1510. document.getElementById('pppoe-modal-service').value = '';
  1511. document.getElementById('pppoe-modal-mtu').value = '1492';
  1512. document.getElementById('pppoe-modal-defroute').checked = true;
  1513. document.getElementById('pppoe-modal-reconnect').checked = true;
  1514. document.getElementById('pppoe-modal-disabled').checked = false;
  1515. // Populate profiles
  1516. populateProfileSelect('pppoe-modal-profile', 'default', 'default');
  1517. // Populate interfaces
  1518. const sel = document.getElementById('pppoe-modal-iface');
  1519. sel.innerHTML = '';
  1520. (state.interfaces || []).forEach(i => {
  1521. if (i.name === 'lo') return;
  1522. const opt = document.createElement('option');
  1523. opt.value = i.name;
  1524. opt.innerText = `${i.name} (${i.role || i.type})`;
  1525. sel.appendChild(opt);
  1526. });
  1527. document.getElementById('pppoe-modal').classList.remove('hidden');
  1528. }
  1529. function openEditPPPoEModal(name) {
  1530. const inst = (state.pppoeList || []).find(i => i.name === name);
  1531. if (!inst) return;
  1532. document.getElementById('pppoe-modal-title').innerText = `Edit PPPoE Client: ${name}`;
  1533. document.getElementById('pppoe-modal-edit-orig').value = name;
  1534. document.getElementById('pppoe-modal-name').value = inst.name;
  1535. document.getElementById('pppoe-modal-name').readOnly = true;
  1536. document.getElementById('pppoe-modal-user').value = inst.username || '';
  1537. document.getElementById('pppoe-modal-pass').value = inst.password || '';
  1538. document.getElementById('pppoe-modal-service').value = inst.service_name || '';
  1539. document.getElementById('pppoe-modal-mtu').value = inst.mtu || 1492;
  1540. document.getElementById('pppoe-modal-defroute').checked = inst.default_route ?? true;
  1541. document.getElementById('pppoe-modal-reconnect').checked = inst.auto_reconnect ?? true;
  1542. document.getElementById('pppoe-modal-disabled').checked = !!inst.disabled;
  1543. // Populate profiles
  1544. populateProfileSelect('pppoe-modal-profile', inst.profile || 'default', 'default');
  1545. const sel = document.getElementById('pppoe-modal-iface');
  1546. sel.innerHTML = '';
  1547. (state.interfaces || []).forEach(i => {
  1548. if (i.name === 'lo') return;
  1549. const opt = document.createElement('option');
  1550. opt.value = i.name;
  1551. opt.innerText = `${i.name} (${i.role || i.type})`;
  1552. if (i.name === inst.interface) opt.selected = true;
  1553. sel.appendChild(opt);
  1554. });
  1555. document.getElementById('pppoe-modal').classList.remove('hidden');
  1556. }
  1557. function closePPPoEModal() {
  1558. document.getElementById('pppoe-modal').classList.add('hidden');
  1559. }
  1560. async function submitSavePPPoE(e) {
  1561. e.preventDefault();
  1562. const name = document.getElementById('pppoe-modal-name').value.trim();
  1563. const iface = document.getElementById('pppoe-modal-iface').value;
  1564. const user = document.getElementById('pppoe-modal-user').value.trim();
  1565. const pass = document.getElementById('pppoe-modal-pass').value;
  1566. const profile = document.getElementById('pppoe-modal-profile')?.value || 'default';
  1567. const service = document.getElementById('pppoe-modal-service').value.trim();
  1568. const mtu = parseInt(document.getElementById('pppoe-modal-mtu').value, 10) || 1492;
  1569. const defRoute = document.getElementById('pppoe-modal-defroute').checked;
  1570. const reconnect = document.getElementById('pppoe-modal-reconnect').checked;
  1571. const disabled = document.getElementById('pppoe-modal-disabled').checked;
  1572. try {
  1573. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`, {
  1574. method: 'POST',
  1575. headers: { 'Content-Type': 'application/json' },
  1576. body: JSON.stringify({
  1577. name,
  1578. interface: iface,
  1579. username: user,
  1580. password: pass,
  1581. profile: profile,
  1582. service_name: service,
  1583. mtu,
  1584. default_route: defRoute,
  1585. auto_reconnect: reconnect,
  1586. disabled
  1587. })
  1588. });
  1589. if (res.ok) {
  1590. showToast('PPPoE Saved', `Configuration for ${name} saved`, 'success');
  1591. closePPPoEModal();
  1592. loadPPPoE(false);
  1593. fetchData(false);
  1594. } else {
  1595. const err = await res.json();
  1596. showToast('Error', err.message || 'Failed to save PPPoE', 'error');
  1597. }
  1598. } catch (err) {
  1599. showToast('Error', err.message, 'error');
  1600. }
  1601. }
  1602. async function connectPPPoEInstance(name) {
  1603. try {
  1604. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  1605. if (res.ok) {
  1606. showToast('Connecting', `Dialing ${name}...`, 'info');
  1607. setTimeout(() => loadPPPoE(false), 2000);
  1608. }
  1609. } catch (err) {
  1610. showToast('Error', err.message, 'error');
  1611. }
  1612. }
  1613. async function disconnectPPPoEInstance(name) {
  1614. try {
  1615. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  1616. if (res.ok) {
  1617. showToast('Disconnected', `${name} session terminated`, 'info');
  1618. setTimeout(() => loadPPPoE(false), 1000);
  1619. }
  1620. } catch (err) {
  1621. showToast('Error', err.message, 'error');
  1622. }
  1623. }
  1624. async function togglePPPoEState(name, enable) {
  1625. try {
  1626. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/state`, {
  1627. method: 'POST',
  1628. headers: { 'Content-Type': 'application/json' },
  1629. body: JSON.stringify({ enabled: enable })
  1630. });
  1631. if (res.ok) {
  1632. showToast(enable ? 'Enabled' : 'Disabled', `${name} is now ${enable ? 'enabled' : 'disabled'}`, 'info');
  1633. loadPPPoE(false);
  1634. }
  1635. } catch (err) {
  1636. showToast('Error', err.message, 'error');
  1637. }
  1638. }
  1639. async function deletePPPoEInstance(name) {
  1640. if (!confirm(`Are you sure you want to delete PPPoE client ${name}?`)) return;
  1641. try {
  1642. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1643. if (res.ok) {
  1644. showToast('Deleted', `PPPoE client ${name} removed`, 'success');
  1645. loadPPPoE(false);
  1646. fetchData(false);
  1647. }
  1648. } catch (err) {
  1649. showToast('Error', err.message, 'error');
  1650. }
  1651. }
  1652. // ======================== WireGuard Multi-Interface & Multi-Peer ========================
  1653. state.wgSubTab = 'ifaces';
  1654. function switchWGSubTab(tab) {
  1655. state.wgSubTab = tab;
  1656. const ifacesPanel = document.getElementById('wg-subtab-ifaces');
  1657. const peersPanel = document.getElementById('wg-subtab-peers');
  1658. const ifacesBtn = document.getElementById('wg-subtab-btn-ifaces');
  1659. const peersBtn = document.getElementById('wg-subtab-btn-peers');
  1660. if (tab === 'ifaces') {
  1661. ifacesPanel?.classList.remove('hidden');
  1662. peersPanel?.classList.add('hidden');
  1663. 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';
  1664. 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';
  1665. } else {
  1666. ifacesPanel?.classList.add('hidden');
  1667. peersPanel?.classList.remove('hidden');
  1668. 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';
  1669. 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';
  1670. renderWGPeers();
  1671. }
  1672. }
  1673. async function loadWireGuard(populateInputs = true) {
  1674. try {
  1675. const [ifacesRes, peersRes] = await Promise.all([
  1676. fetch(`${API_BASE}/vpn/wireguard/interfaces`),
  1677. fetch(`${API_BASE}/vpn/wireguard/peers`)
  1678. ]);
  1679. const ifaces = ifacesRes.ok ? await ifacesRes.json() : [];
  1680. const peers = peersRes.ok ? await peersRes.json() : [];
  1681. state.wgInterfaces = Array.isArray(ifaces) ? ifaces : [];
  1682. state.wgPeers = Array.isArray(peers) ? peers : [];
  1683. // Badges
  1684. const ifacesCountBadge = document.getElementById('wg-ifaces-count');
  1685. if (ifacesCountBadge) ifacesCountBadge.innerText = `${state.wgInterfaces.length} Interfaces`;
  1686. const peersCountBadge = document.getElementById('wg-peers-count');
  1687. if (peersCountBadge) peersCountBadge.innerText = `${state.wgPeers.length} Peers`;
  1688. const subTabIfaces = document.getElementById('wg-subtab-badge-ifaces');
  1689. if (subTabIfaces) subTabIfaces.innerText = state.wgInterfaces.length;
  1690. const subTabPeers = document.getElementById('wg-subtab-badge-peers');
  1691. if (subTabPeers) subTabPeers.innerText = state.wgPeers.length;
  1692. // Render Interfaces
  1693. const ifacesTbody = document.getElementById('wg-ifaces-table-body');
  1694. const ifacesEmpty = document.getElementById('wg-ifaces-empty');
  1695. if (ifacesTbody) {
  1696. ifacesTbody.innerHTML = '';
  1697. if (state.wgInterfaces.length === 0) {
  1698. if (ifacesEmpty) ifacesEmpty.classList.remove('hidden');
  1699. } else {
  1700. if (ifacesEmpty) ifacesEmpty.classList.add('hidden');
  1701. state.wgInterfaces.forEach(iface => {
  1702. const peersOnIface = state.wgPeers.filter(p => p.interface === iface.name).length;
  1703. const tr = document.createElement('tr');
  1704. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1705. tr.innerHTML = `
  1706. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(iface.running, iface.disabled)}</td>
  1707. <td class="py-2.5 px-3">
  1708. <div class="flex items-center gap-1.5">
  1709. <span class="font-bold text-white">${escapeHtml(iface.name)}</span>
  1710. ${iface.comment ? `<span class="text-[10px] text-slate-400 font-sans italic">(${escapeHtml(iface.comment)})</span>` : ''}
  1711. </div>
  1712. </td>
  1713. <td class="py-2.5 px-3 text-amber-400 font-mono">${iface.listen_port}</td>
  1714. <td class="py-2.5 px-3 text-emerald-400 font-mono">${iface.address || '<span class="text-slate-600 font-sans">--</span>'}</td>
  1715. <td class="py-2.5 px-3 text-slate-300 font-mono">
  1716. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${iface.public_key}', 'Public Key')" title="Click to copy: ${iface.public_key}">
  1717. ${(iface.public_key || '').substring(0, 10)}... 📋
  1718. </span>
  1719. </td>
  1720. <td class="py-2.5 px-3 text-slate-400 font-mono">${iface.mtu || 1420}</td>
  1721. <td class="py-2.5 px-3 text-center">
  1722. <span class="px-2 py-0.5 rounded text-[10px] font-sans bg-slate-800 text-slate-300">${peersOnIface} peer${peersOnIface !== 1 ? 's' : ''}</span>
  1723. </td>
  1724. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  1725. ${iface.running ? `
  1726. <button onclick="stopWGInterface('${iface.name}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Stop</button>
  1727. ` : `
  1728. <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>
  1729. `}
  1730. <button onclick="toggleWGInterfaceState('${iface.name}', ${iface.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white font-medium">
  1731. ${iface.disabled ? 'Enable' : 'Disable'}
  1732. </button>
  1733. <button onclick="openEditWGInterfaceModal('${iface.name}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Edit</button>
  1734. <button onclick="deleteWGInterface('${iface.name}')" class="text-xs text-slate-500 hover:text-rose-400 font-medium">Delete</button>
  1735. </td>
  1736. `;
  1737. ifacesTbody.appendChild(tr);
  1738. });
  1739. }
  1740. }
  1741. // Populate filter dropdown in peers tab
  1742. const filterSel = document.getElementById('wg-peers-filter-iface');
  1743. if (filterSel) {
  1744. const currentVal = filterSel.value;
  1745. filterSel.innerHTML = '<option value="">All Interfaces</option>';
  1746. state.wgInterfaces.forEach(i => {
  1747. const opt = document.createElement('option');
  1748. opt.value = i.name;
  1749. opt.innerText = i.name;
  1750. if (i.name === currentVal) opt.selected = true;
  1751. filterSel.appendChild(opt);
  1752. });
  1753. }
  1754. renderWGPeers();
  1755. } catch (err) {
  1756. console.error('Failed to load WireGuard:', err);
  1757. }
  1758. }
  1759. function formatWGPeerEndpoint(address, port) {
  1760. if (!address || address === '(none)') return '--';
  1761. let addr = address.trim();
  1762. let p = port || 0;
  1763. while (addr.includes(':') && !addr.startsWith('[')) {
  1764. const lastColon = addr.lastIndexOf(':');
  1765. const maybePort = addr.substring(lastColon + 1);
  1766. if (!isNaN(parseInt(maybePort, 10)) && parseInt(maybePort, 10) > 0) {
  1767. if (!p) p = parseInt(maybePort, 10);
  1768. addr = addr.substring(0, lastColon);
  1769. } else {
  1770. break;
  1771. }
  1772. }
  1773. return p ? `${addr}:${p}` : addr;
  1774. }
  1775. function renderWGPeers() {
  1776. const filterSel = document.getElementById('wg-peers-filter-iface');
  1777. const selectedIface = filterSel ? filterSel.value : '';
  1778. const tbody = document.getElementById('wg-peers-table-body');
  1779. const empty = document.getElementById('wg-peers-empty');
  1780. if (!tbody) return;
  1781. tbody.innerHTML = '';
  1782. const filtered = selectedIface ? state.wgPeers.filter(p => p.interface === selectedIface) : state.wgPeers;
  1783. if (filtered.length === 0) {
  1784. if (empty) empty.classList.remove('hidden');
  1785. } else {
  1786. if (empty) empty.classList.add('hidden');
  1787. filtered.forEach(p => {
  1788. const isOnline = p.latest_handshake && !p.latest_handshake.includes('Never');
  1789. const tr = document.createElement('tr');
  1790. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1791. tr.innerHTML = `
  1792. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(isOnline, p.disabled)}</td>
  1793. <td class="py-2.5 px-3 font-mono font-bold text-rose-400">${escapeHtml(p.interface)}</td>
  1794. <td class="py-2.5 px-3 font-bold text-white font-sans">${escapeHtml(p.name || 'Unnamed')}</td>
  1795. <td class="py-2.5 px-3 text-slate-300 font-mono">
  1796. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${p.public_key}', 'Peer Public Key')" title="${p.public_key}">
  1797. ${(p.public_key || '').substring(0, 10)}... 📋
  1798. </span>
  1799. </td>
  1800. <td class="py-2.5 px-3 text-emerald-400 font-mono font-semibold">${(p.allowed_ips || []).join(', ')}</td>
  1801. <td class="py-2.5 px-3 text-slate-400 font-mono">${formatWGPeerEndpoint(p.endpoint_address, p.endpoint_port)}</td>
  1802. <td class="py-2.5 px-3 text-slate-300 font-sans">${p.latest_handshake || 'Never'}</td>
  1803. <td class="py-2.5 px-3 font-mono text-[11px]">
  1804. <span class="text-emerald-400">↓ ${p.transfer_rx_human || '0 B'}</span>
  1805. <span class="text-cyan-400 ml-1">↑ ${p.transfer_tx_human || '0 B'}</span>
  1806. </td>
  1807. <td class="py-2.5 px-3 text-right font-sans space-x-2 whitespace-nowrap">
  1808. <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">
  1809. ${p.disabled ? 'Enable' : 'Disable'}
  1810. </button>
  1811. <button onclick="openEditWGPeerModal('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Edit</button>
  1812. <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>
  1813. <button onclick="deleteWGPeer('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Delete</button>
  1814. </td>
  1815. `;
  1816. tbody.appendChild(tr);
  1817. });
  1818. }
  1819. }
  1820. function openAddWGInterfaceModal() {
  1821. document.getElementById('wg-iface-modal-title').innerText = 'Add WireGuard Interface';
  1822. document.getElementById('wg-iface-modal-edit-orig').value = '';
  1823. const nameEl = document.getElementById('wg-iface-modal-name');
  1824. nameEl.value = `wg${(state.wgInterfaces || []).length}`;
  1825. nameEl.readOnly = false;
  1826. document.getElementById('wg-iface-modal-port').value = 51820 + (state.wgInterfaces || []).length;
  1827. document.getElementById('wg-iface-modal-addr').value = `10.${10 + (state.wgInterfaces || []).length}.0.1/24`;
  1828. document.getElementById('wg-iface-modal-mtu').value = '1420';
  1829. document.getElementById('wg-iface-modal-comment').value = '';
  1830. document.getElementById('wg-iface-modal-pubkey').value = '';
  1831. document.getElementById('wg-iface-modal-privkey').value = '';
  1832. document.getElementById('wg-iface-modal-disabled').checked = false;
  1833. generateWGInterfaceKeys();
  1834. document.getElementById('wg-iface-modal').classList.remove('hidden');
  1835. }
  1836. function openEditWGInterfaceModal(name) {
  1837. const iface = (state.wgInterfaces || []).find(i => i.name === name);
  1838. if (!iface) return;
  1839. document.getElementById('wg-iface-modal-title').innerText = `Edit WireGuard Interface: ${name}`;
  1840. document.getElementById('wg-iface-modal-edit-orig').value = name;
  1841. const nameEl = document.getElementById('wg-iface-modal-name');
  1842. nameEl.value = iface.name;
  1843. nameEl.readOnly = false; // ALLOW RENAMING
  1844. document.getElementById('wg-iface-modal-port').value = iface.listen_port || 51820;
  1845. document.getElementById('wg-iface-modal-addr').value = iface.address || '';
  1846. document.getElementById('wg-iface-modal-mtu').value = iface.mtu || 1420;
  1847. document.getElementById('wg-iface-modal-comment').value = iface.comment || '';
  1848. document.getElementById('wg-iface-modal-pubkey').value = iface.public_key || '';
  1849. document.getElementById('wg-iface-modal-privkey').value = iface.private_key || '';
  1850. document.getElementById('wg-iface-modal-disabled').checked = !!iface.disabled;
  1851. document.getElementById('wg-iface-modal').classList.remove('hidden');
  1852. }
  1853. function closeAddWGInterfaceModal() {
  1854. document.getElementById('wg-iface-modal').classList.add('hidden');
  1855. }
  1856. async function generateWGInterfaceKeys() {
  1857. try {
  1858. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  1859. const keys = await res.json();
  1860. if (res.ok) {
  1861. document.getElementById('wg-iface-modal-privkey').value = keys.private_key;
  1862. document.getElementById('wg-iface-modal-pubkey').value = keys.public_key;
  1863. }
  1864. } catch (err) {
  1865. showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
  1866. }
  1867. }
  1868. async function onWGInterfacePrivKeyInput() {
  1869. const privKey = document.getElementById('wg-iface-modal-privkey').value.trim();
  1870. if (!privKey) return;
  1871. try {
  1872. const res = await fetch(`${API_BASE}/vpn/wireguard/calc-pubkey`, {
  1873. method: 'POST',
  1874. headers: { 'Content-Type': 'application/json' },
  1875. body: JSON.stringify({ private_key: privKey })
  1876. });
  1877. if (res.ok) {
  1878. const data = await res.json();
  1879. if (data.public_key) {
  1880. document.getElementById('wg-iface-modal-pubkey').value = data.public_key;
  1881. }
  1882. }
  1883. } catch (err) {
  1884. // Ignore while typing
  1885. }
  1886. }
  1887. function toggleWGPrivKeyVisibility() {
  1888. const el = document.getElementById('wg-iface-modal-privkey');
  1889. const btn = document.getElementById('btn-toggle-wg-privkey');
  1890. if (el.type === 'password') {
  1891. el.type = 'text';
  1892. btn.innerText = '🙈 Hide';
  1893. } else {
  1894. el.type = 'password';
  1895. btn.innerText = '👁️ Show';
  1896. }
  1897. }
  1898. function copyWGInterfacePubKey() {
  1899. const pub = document.getElementById('wg-iface-modal-pubkey').value;
  1900. if (pub) copyToClipboard(pub, 'Interface Public Key');
  1901. }
  1902. async function submitSaveWGInterface(e) {
  1903. e.preventDefault();
  1904. const origName = document.getElementById('wg-iface-modal-edit-orig').value.trim();
  1905. const name = document.getElementById('wg-iface-modal-name').value.trim();
  1906. const port = parseInt(document.getElementById('wg-iface-modal-port').value, 10) || 51820;
  1907. const addr = document.getElementById('wg-iface-modal-addr').value.trim();
  1908. const mtu = parseInt(document.getElementById('wg-iface-modal-mtu').value, 10) || 1420;
  1909. const comment = document.getElementById('wg-iface-modal-comment').value.trim();
  1910. const pub = document.getElementById('wg-iface-modal-pubkey').value.trim();
  1911. const priv = document.getElementById('wg-iface-modal-privkey').value.trim();
  1912. const disabled = document.getElementById('wg-iface-modal-disabled').checked;
  1913. try {
  1914. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces`, {
  1915. method: 'POST',
  1916. headers: { 'Content-Type': 'application/json' },
  1917. body: JSON.stringify({
  1918. orig_name: origName,
  1919. name,
  1920. listen_port: port,
  1921. address: addr,
  1922. mtu,
  1923. comment,
  1924. public_key: pub,
  1925. private_key: priv,
  1926. disabled
  1927. })
  1928. });
  1929. const data = await res.json();
  1930. if (res.ok) {
  1931. showToast('WireGuard Saved', `Interface ${name} configured successfully`, 'success');
  1932. closeAddWGInterfaceModal();
  1933. loadWireGuard(false);
  1934. fetchData(false);
  1935. } else {
  1936. showToast('Error', data.error || 'Failed to save interface', 'error');
  1937. }
  1938. } catch (err) {
  1939. showToast('Error', err.message, 'error');
  1940. }
  1941. }
  1942. async function startWGInterface(name) {
  1943. try {
  1944. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/start`, { method: 'POST' });
  1945. if (res.ok) {
  1946. showToast('Interface UP', `Started WireGuard interface ${name}`, 'success');
  1947. loadWireGuard(false);
  1948. fetchData(false);
  1949. }
  1950. } catch (err) {
  1951. showToast('Error', err.message, 'error');
  1952. }
  1953. }
  1954. async function stopWGInterface(name) {
  1955. try {
  1956. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  1957. if (res.ok) {
  1958. showToast('Interface DOWN', `Stopped WireGuard interface ${name}`, 'info');
  1959. loadWireGuard(false);
  1960. fetchData(false);
  1961. }
  1962. } catch (err) {
  1963. showToast('Error', err.message, 'error');
  1964. }
  1965. }
  1966. async function toggleWGInterfaceState(name, enable) {
  1967. try {
  1968. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/state`, {
  1969. method: 'POST',
  1970. headers: { 'Content-Type': 'application/json' },
  1971. body: JSON.stringify({ enabled: enable })
  1972. });
  1973. if (res.ok) {
  1974. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  1975. loadWireGuard(false);
  1976. fetchData(false);
  1977. }
  1978. } catch (err) {
  1979. showToast('Error', err.message, 'error');
  1980. }
  1981. }
  1982. async function deleteWGInterface(name) {
  1983. if (!confirm(`Are you sure you want to delete WireGuard interface ${name}? All associated peers will also be removed.`)) return;
  1984. try {
  1985. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1986. if (res.ok) {
  1987. showToast('Deleted', `Interface ${name} removed`, 'success');
  1988. loadWireGuard(false);
  1989. fetchData(false);
  1990. }
  1991. } catch (err) {
  1992. showToast('Error', err.message, 'error');
  1993. }
  1994. }
  1995. function populateWGPeerIfaceSelect(selectedIface = '') {
  1996. const sel = document.getElementById('wg-peer-modal-iface');
  1997. if (!sel) return;
  1998. sel.innerHTML = '';
  1999. (state.wgInterfaces || []).forEach(i => {
  2000. const opt = document.createElement('option');
  2001. opt.value = i.name;
  2002. opt.innerText = `${i.name} (${i.address || 'No IP'})`;
  2003. if (i.name === selectedIface) opt.selected = true;
  2004. sel.appendChild(opt);
  2005. });
  2006. }
  2007. function openAddWGPeerModal() {
  2008. if ((state.wgInterfaces || []).length === 0) {
  2009. showToast('No Interfaces', 'Please add a WireGuard interface first before adding peers', 'warning');
  2010. openAddWGInterfaceModal();
  2011. return;
  2012. }
  2013. document.getElementById('wg-peer-modal-title').innerText = 'Add WireGuard Peer';
  2014. document.getElementById('wg-peer-modal-edit-orig-iface').value = '';
  2015. document.getElementById('wg-peer-modal-edit-orig-pubkey').value = '';
  2016. populateWGPeerIfaceSelect();
  2017. document.getElementById('wg-peer-modal-name').value = '';
  2018. document.getElementById('wg-peer-modal-pubkey').value = '';
  2019. document.getElementById('wg-peer-modal-allowedips').value = '10.10.0.2/32';
  2020. document.getElementById('wg-peer-modal-endpoint').value = '';
  2021. document.getElementById('wg-peer-modal-port').value = '';
  2022. document.getElementById('wg-peer-modal-keepalive').value = '25';
  2023. document.getElementById('wg-peer-modal-preshared').value = '';
  2024. document.getElementById('wg-peer-modal-disabled').checked = false;
  2025. document.getElementById('wg-peer-key-warning').classList.add('hidden');
  2026. document.getElementById('wg-peer-gen-key-box').classList.add('hidden');
  2027. document.getElementById('wg-peer-modal').classList.remove('hidden');
  2028. }
  2029. function openEditWGPeerModal(ifaceName, pubKey) {
  2030. const peer = (state.wgPeers || []).find(p => p.interface === ifaceName && p.public_key === pubKey);
  2031. if (!peer) {
  2032. showToast('Not Found', 'Peer not found', 'warning');
  2033. return;
  2034. }
  2035. document.getElementById('wg-peer-modal-title').innerText = `Edit WireGuard Peer (${peer.name || ifaceName})`;
  2036. document.getElementById('wg-peer-modal-edit-orig-iface').value = peer.interface;
  2037. document.getElementById('wg-peer-modal-edit-orig-pubkey').value = peer.public_key;
  2038. populateWGPeerIfaceSelect(peer.interface);
  2039. document.getElementById('wg-peer-modal-name').value = peer.name || '';
  2040. document.getElementById('wg-peer-modal-pubkey').value = peer.public_key || '';
  2041. document.getElementById('wg-peer-modal-allowedips').value = (peer.allowed_ips || []).join(', ');
  2042. let epHost = (peer.endpoint_address || '').trim();
  2043. let epPort = peer.endpoint_port || '';
  2044. while (epHost.includes(':') && !epHost.startsWith('[')) {
  2045. const lastColon = epHost.lastIndexOf(':');
  2046. const maybePort = epHost.substring(lastColon + 1);
  2047. if (!isNaN(parseInt(maybePort, 10)) && parseInt(maybePort, 10) > 0) {
  2048. if (!epPort) epPort = parseInt(maybePort, 10);
  2049. epHost = epHost.substring(0, lastColon);
  2050. } else {
  2051. break;
  2052. }
  2053. }
  2054. document.getElementById('wg-peer-modal-endpoint').value = epHost;
  2055. document.getElementById('wg-peer-modal-port').value = epPort;
  2056. document.getElementById('wg-peer-modal-keepalive').value = peer.persistent_keepalive ?? 25;
  2057. document.getElementById('wg-peer-modal-preshared').value = peer.preshared_key || '';
  2058. document.getElementById('wg-peer-modal-disabled').checked = !!peer.disabled;
  2059. document.getElementById('wg-peer-key-warning').classList.add('hidden');
  2060. document.getElementById('wg-peer-gen-key-box').classList.add('hidden');
  2061. document.getElementById('wg-peer-modal').classList.remove('hidden');
  2062. }
  2063. function closeAddWGPeerModal() {
  2064. document.getElementById('wg-peer-modal').classList.add('hidden');
  2065. }
  2066. async function generatePeerKeypairHelper() {
  2067. try {
  2068. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  2069. const keys = await res.json();
  2070. if (res.ok) {
  2071. document.getElementById('wg-peer-modal-pubkey').value = keys.public_key;
  2072. document.getElementById('wg-peer-gen-privkey').value = keys.private_key;
  2073. document.getElementById('wg-peer-gen-key-box').classList.remove('hidden');
  2074. checkWGPeerKeyValidity();
  2075. showToast('Keypair Generated', 'Public key inserted and client private key ready to copy', 'info');
  2076. }
  2077. } catch (err) {
  2078. showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
  2079. }
  2080. }
  2081. function copyGeneratedPeerPrivKey() {
  2082. const priv = document.getElementById('wg-peer-gen-privkey').value;
  2083. if (priv) copyToClipboard(priv, 'Client Private Key');
  2084. }
  2085. async function generatePeerPSK() {
  2086. try {
  2087. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  2088. const keys = await res.json();
  2089. if (res.ok && keys.private_key) {
  2090. document.getElementById('wg-peer-modal-preshared').value = keys.private_key;
  2091. showToast('PSK Generated', 'Generated 256-bit preshared key', 'info');
  2092. }
  2093. } catch (err) {
  2094. showToast('Error', err.message, 'error');
  2095. }
  2096. }
  2097. function checkWGPeerKeyValidity() {
  2098. const ifaceName = document.getElementById('wg-peer-modal-iface').value;
  2099. const peerPubKey = document.getElementById('wg-peer-modal-pubkey').value.trim();
  2100. const warningEl = document.getElementById('wg-peer-key-warning');
  2101. if (!warningEl) return;
  2102. const targetIface = (state.wgInterfaces || []).find(i => i.name === ifaceName);
  2103. if (targetIface && targetIface.public_key && peerPubKey && targetIface.public_key === peerPubKey) {
  2104. warningEl.classList.remove('hidden');
  2105. } else {
  2106. warningEl.classList.add('hidden');
  2107. }
  2108. }
  2109. async function submitSaveWGPeer(e) {
  2110. e.preventDefault();
  2111. const origIface = document.getElementById('wg-peer-modal-edit-orig-iface').value.trim();
  2112. const origPubKey = document.getElementById('wg-peer-modal-edit-orig-pubkey').value.trim();
  2113. const iface = document.getElementById('wg-peer-modal-iface').value;
  2114. const name = document.getElementById('wg-peer-modal-name').value.trim();
  2115. const pub = document.getElementById('wg-peer-modal-pubkey').value.trim();
  2116. const allowed = document.getElementById('wg-peer-modal-allowedips').value
  2117. .split(',')
  2118. .map(s => s.trim())
  2119. .filter(s => s.length > 0);
  2120. let epHost = document.getElementById('wg-peer-modal-endpoint').value.trim();
  2121. let epPort = parseInt(document.getElementById('wg-peer-modal-port').value, 10) || 0;
  2122. while (epHost.includes(':') && !epHost.startsWith('[')) {
  2123. const lastColon = epHost.lastIndexOf(':');
  2124. const maybePort = epHost.substring(lastColon + 1);
  2125. if (!isNaN(parseInt(maybePort, 10)) && parseInt(maybePort, 10) > 0) {
  2126. if (!epPort) epPort = parseInt(maybePort, 10);
  2127. epHost = epHost.substring(0, lastColon);
  2128. } else {
  2129. break;
  2130. }
  2131. }
  2132. const keepalive = parseInt(document.getElementById('wg-peer-modal-keepalive').value, 10) || 0;
  2133. const psk = document.getElementById('wg-peer-modal-preshared').value.trim();
  2134. const disabled = document.getElementById('wg-peer-modal-disabled').checked;
  2135. // Validation
  2136. const targetIface = (state.wgInterfaces || []).find(i => i.name === iface);
  2137. if (targetIface && targetIface.public_key === pub) {
  2138. showToast('Invalid Peer Key', 'Peer public key cannot be the same as the interface public key!', 'error');
  2139. return;
  2140. }
  2141. try {
  2142. const res = await fetch(`${API_BASE}/vpn/wireguard/peers`, {
  2143. method: 'POST',
  2144. headers: { 'Content-Type': 'application/json' },
  2145. body: JSON.stringify({
  2146. orig_interface: origIface,
  2147. orig_public_key: origPubKey,
  2148. interface: iface,
  2149. name,
  2150. public_key: pub,
  2151. allowed_ips: allowed,
  2152. endpoint_address: epHost,
  2153. endpoint_port: epPort,
  2154. persistent_keepalive: keepalive,
  2155. preshared_key: psk,
  2156. disabled
  2157. })
  2158. });
  2159. const data = await res.json();
  2160. if (res.ok) {
  2161. showToast('Peer Saved', `Peer ${name} saved on ${iface}`, 'success');
  2162. closeAddWGPeerModal();
  2163. loadWireGuard(false);
  2164. } else {
  2165. showToast('Error', data.error || 'Failed to save peer', 'error');
  2166. }
  2167. } catch (err) {
  2168. showToast('Error', err.message, 'error');
  2169. }
  2170. }
  2171. async function toggleWGPeerState(iface, pubkey, enable) {
  2172. try {
  2173. const res = await fetch(`${API_BASE}/vpn/wireguard/peers/state`, {
  2174. method: 'POST',
  2175. headers: { 'Content-Type': 'application/json' },
  2176. body: JSON.stringify({ interface: iface, public_key: pubkey, enabled: enable })
  2177. });
  2178. const data = await res.json();
  2179. if (res.ok) {
  2180. showToast(enable ? 'Peer Enabled' : 'Peer Disabled', `Peer state updated on ${iface}`, 'info');
  2181. loadWireGuard(false);
  2182. } else {
  2183. showToast('Error', data.error || 'Failed to update peer state', 'error');
  2184. }
  2185. } catch (err) {
  2186. showToast('Error', err.message, 'error');
  2187. }
  2188. }
  2189. async function deleteWGPeer(iface, pubkey) {
  2190. if (!confirm(`Are you sure you want to remove peer from ${iface}?`)) return;
  2191. try {
  2192. const res = await fetch(`${API_BASE}/vpn/wireguard/peers/delete`, {
  2193. method: 'POST',
  2194. headers: { 'Content-Type': 'application/json' },
  2195. body: JSON.stringify({ interface: iface, public_key: pubkey })
  2196. });
  2197. const data = await res.json();
  2198. if (res.ok) {
  2199. showToast('Peer Deleted', 'WireGuard peer removed', 'success');
  2200. loadWireGuard(false);
  2201. } else {
  2202. showToast('Error', data.error || 'Failed to remove peer', 'error');
  2203. }
  2204. } catch (err) {
  2205. showToast('Error', err.message, 'error');
  2206. }
  2207. }
  2208. // ======================== IPSec FortiGate Phase 1 & 2 Multi-Tunnel Engine ========================
  2209. function switchIpsecModalTab(tab) {
  2210. const p1Tab = document.getElementById('tab-btn-ipsec-p1');
  2211. const p2Tab = document.getElementById('tab-btn-ipsec-p2');
  2212. const p1Content = document.getElementById('ipsec-tab-content-p1');
  2213. const p2Content = document.getElementById('ipsec-tab-content-p2');
  2214. const stepBtn = document.getElementById('btn-ipsec-switch-step');
  2215. if (tab === 'p1') {
  2216. if (p1Tab) {
  2217. 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';
  2218. }
  2219. if (p2Tab) {
  2220. 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';
  2221. }
  2222. if (p1Content) p1Content.classList.remove('hidden');
  2223. if (p2Content) p2Content.classList.add('hidden');
  2224. if (stepBtn) stepBtn.innerHTML = 'Next: Phase 2 Selectors &rarr;';
  2225. } else {
  2226. if (p1Tab) {
  2227. 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';
  2228. }
  2229. if (p2Tab) {
  2230. 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';
  2231. }
  2232. if (p1Content) p1Content.classList.add('hidden');
  2233. if (p2Content) p2Content.classList.remove('hidden');
  2234. if (stepBtn) stepBtn.innerHTML = '&larr; Back: Phase 1 (IKE)';
  2235. }
  2236. }
  2237. function toggleIpsecPhaseStep() {
  2238. const p1Content = document.getElementById('ipsec-tab-content-p1');
  2239. if (p1Content && !p1Content.classList.contains('hidden')) {
  2240. switchIpsecModalTab('p2');
  2241. } else {
  2242. switchIpsecModalTab('p1');
  2243. }
  2244. }
  2245. function toggleIpsecPskVisibility() {
  2246. const pskInput = document.getElementById('ipsec-modal-psk');
  2247. if (!pskInput) return;
  2248. pskInput.type = pskInput.type === 'password' ? 'text' : 'password';
  2249. }
  2250. function addIpsecLocalSubnet(val = '') {
  2251. const container = document.getElementById('ipsec-modal-local-subnets-container');
  2252. if (!container) return;
  2253. const row = document.createElement('div');
  2254. row.className = 'flex items-center gap-2 ipsec-subnet-row';
  2255. row.innerHTML = `
  2256. <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">
  2257. <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>
  2258. `;
  2259. container.appendChild(row);
  2260. }
  2261. function addIpsecRemoteSubnet(val = '') {
  2262. const container = document.getElementById('ipsec-modal-remote-subnets-container');
  2263. if (!container) return;
  2264. const row = document.createElement('div');
  2265. row.className = 'flex items-center gap-2 ipsec-subnet-row';
  2266. row.innerHTML = `
  2267. <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">
  2268. <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>
  2269. `;
  2270. container.appendChild(row);
  2271. }
  2272. function updateIpsecEspProposalFromPFS(val) {
  2273. const prop = document.getElementById('ipsec-modal-espprop');
  2274. if (!prop) return;
  2275. if (val === 'none') {
  2276. prop.value = 'aes256-sha256,aes128-sha256,default';
  2277. } else {
  2278. prop.value = `aes256-sha256-${val},aes128-sha256-${val},default`;
  2279. }
  2280. }
  2281. function updateIpsecIkeProposalFromDH(dh) {
  2282. const el = document.getElementById('ipsec-modal-ikeprop');
  2283. if (el) {
  2284. el.value = `aes256-sha256-${dh},aes128-sha256-${dh},default`;
  2285. }
  2286. }
  2287. function safeSetVal(id, val) {
  2288. const el = document.getElementById(id);
  2289. if (el) el.value = val;
  2290. }
  2291. function safeSetChecked(id, val) {
  2292. const el = document.getElementById(id);
  2293. if (el) el.checked = !!val;
  2294. }
  2295. function safeGetVal(id, def = '') {
  2296. const el = document.getElementById(id);
  2297. return el ? el.value : def;
  2298. }
  2299. async function loadIPSec(populateInputs = true) {
  2300. try {
  2301. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`);
  2302. const list = await res.json();
  2303. state.ipsecTunnels = Array.isArray(list) ? list : [];
  2304. const activeCount = state.ipsecTunnels.filter(t => t.running || t.status === 'ESTABLISHED').length;
  2305. const badge = document.getElementById('ipsec-sas-badge');
  2306. if (badge) badge.innerText = `${activeCount} Active SAs`;
  2307. const tbody = document.getElementById('ipsec-table-body');
  2308. const empty = document.getElementById('ipsec-empty');
  2309. if (!tbody) return;
  2310. tbody.innerHTML = '';
  2311. if (state.ipsecTunnels.length === 0) {
  2312. if (empty) empty.classList.remove('hidden');
  2313. } else {
  2314. if (empty) empty.classList.add('hidden');
  2315. state.ipsecTunnels.forEach(c => {
  2316. const isEstablished = c.running || c.status === 'ESTABLISHED';
  2317. const tr = document.createElement('tr');
  2318. tr.className = 'hover:bg-slate-800/40 transition text-xs select-none';
  2319. // Local subnets tags
  2320. const localList = (c.local_subnets && c.local_subnets.length > 0) ? c.local_subnets : (c.local_subnet ? [c.local_subnet] : ['0.0.0.0/0']);
  2321. 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('');
  2322. // Remote subnets tags
  2323. const remoteList = (c.remote_subnets && c.remote_subnets.length > 0) ? c.remote_subnets : (c.remote_subnet ? [c.remote_subnet] : ['0.0.0.0/0']);
  2324. 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('');
  2325. const ikeVersionBadge = (c.ike_version || 'ikev2').toUpperCase();
  2326. const p2Name = c.phase2_name || `${c.name}_p2`;
  2327. tr.innerHTML = `
  2328. <td class="py-2.5 px-3 text-center">
  2329. ${isEstablished ? `
  2330. <span class="inline-flex items-center gap-1.5 text-emerald-400 font-mono font-bold text-[11px]" title="Active SA Established">
  2331. <span class="w-2.5 h-2.5 rounded-full bg-emerald-400 animate-pulse"></span>
  2332. <span>UP</span>
  2333. </span>
  2334. ` : (c.disabled ? `
  2335. <span class="inline-flex items-center gap-1.5 text-slate-500 font-mono text-[11px]" title="Tunnel Disabled">
  2336. <span class="w-2 h-2 rounded-full bg-rose-500"></span>
  2337. <span>DOWN</span>
  2338. </span>
  2339. ` : `
  2340. <span class="inline-flex items-center gap-1.5 text-amber-400 font-mono text-[11px]" title="Disconnected / Idle">
  2341. <span class="w-2 h-2 rounded-full bg-amber-400"></span>
  2342. <span>IDLE</span>
  2343. </span>
  2344. `)}
  2345. </td>
  2346. <td class="py-2.5 px-4 font-bold text-white">
  2347. <div class="flex items-center gap-2">
  2348. <span class="text-amber-400">🛡</span>
  2349. <div>
  2350. <div>${escapeHtml(c.name)}</div>
  2351. <div class="text-[10px] text-slate-500 font-normal">P2: ${escapeHtml(p2Name)}</div>
  2352. </div>
  2353. </div>
  2354. </td>
  2355. <td class="py-2.5 px-4 text-slate-300 font-mono font-medium">${escapeHtml(c.remote_addrs || '%any')}</td>
  2356. <td class="py-2.5 px-4 font-sans">
  2357. <div class="flex items-center gap-1.5">
  2358. <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>
  2359. <span class="text-[10px] text-slate-400">${c.auth_method || 'PSK'}</span>
  2360. </div>
  2361. </td>
  2362. <td class="py-2.5 px-4">
  2363. <div class="space-y-1">
  2364. <div class="flex items-center flex-wrap gap-1">
  2365. <span class="text-[9px] text-cyan-400 uppercase font-bold mr-1">Local:</span>
  2366. ${localBadges}
  2367. </div>
  2368. <div class="flex items-center flex-wrap gap-1">
  2369. <span class="text-[9px] text-purple-400 uppercase font-bold mr-1">Remote:</span>
  2370. ${remoteBadges}
  2371. </div>
  2372. </div>
  2373. </td>
  2374. <td class="py-2.5 px-4 font-mono text-[11px] text-slate-400">
  2375. <div class="truncate max-w-[140px]" title="${escapeHtml(c.esp_proposals || '')}">
  2376. ${escapeHtml(c.esp_proposals || 'aes256-sha256')}
  2377. </div>
  2378. <div class="text-[10px] text-slate-500">PFS: ${escapeHtml(c.pfs_group || 'modp2048')}</div>
  2379. </td>
  2380. <td class="py-2.5 px-4 text-right space-x-2 font-sans">
  2381. ${isEstablished ? `
  2382. <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>
  2383. ` : `
  2384. <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>
  2385. `}
  2386. <button onclick="toggleIPSecState('${c.name}', ${c.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  2387. ${c.disabled ? 'Enable' : 'Disable'}
  2388. </button>
  2389. <button onclick="openEditIPSecModal('${c.name}')" class="text-xs text-amber-400 hover:text-amber-300">Edit</button>
  2390. <button onclick="deleteIPSecConn('${c.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2391. </td>
  2392. `;
  2393. tbody.appendChild(tr);
  2394. });
  2395. }
  2396. } catch (err) {
  2397. console.error('Failed to load IPSec:', err);
  2398. }
  2399. }
  2400. function openAddIPSecModal() {
  2401. const modal = document.getElementById('ipsec-modal');
  2402. if (!modal) return;
  2403. const title = document.getElementById('ipsec-modal-title');
  2404. if (title) title.innerText = 'Configure IPSec Site-to-Site Tunnel';
  2405. // Phase 1 Fields
  2406. safeSetVal('ipsec-modal-name', `tunnel-${(state.ipsecTunnels || []).length + 1}`);
  2407. const nameEl = document.getElementById('ipsec-modal-name');
  2408. if (nameEl) nameEl.readOnly = false;
  2409. safeSetVal('ipsec-modal-ikeversion', 'ikev2');
  2410. safeSetVal('ipsec-modal-ikever', 'ikev2');
  2411. safeSetVal('ipsec-modal-remotegw', '');
  2412. safeSetVal('ipsec-modal-localaddrs', '');
  2413. safeSetVal('ipsec-modal-comments', '');
  2414. safeSetVal('ipsec-modal-psk', '');
  2415. safeSetVal('ipsec-modal-ikeprop', 'aes256-sha256-modp2048,aes128-sha256-modp2048,default');
  2416. safeSetVal('ipsec-modal-dhgroup', 'modp2048');
  2417. safeSetVal('ipsec-modal-ikekeylife', '86400');
  2418. safeSetVal('ipsec-modal-localid', '');
  2419. safeSetVal('ipsec-modal-remoteid', '');
  2420. safeSetVal('ipsec-modal-dpd', 'on-demand');
  2421. // Phase 2 Fields
  2422. safeSetVal('ipsec-modal-p2name', `tunnel-${(state.ipsecTunnels || []).length + 1}_p2`);
  2423. safeSetVal('ipsec-modal-espkeylife', '28800');
  2424. safeSetVal('ipsec-modal-espprop', 'aes256-sha256-modp2048,aes128-sha256-modp2048,default');
  2425. safeSetVal('ipsec-modal-pfsgroup', 'modp2048');
  2426. safeSetChecked('ipsec-modal-autostart', true);
  2427. safeSetChecked('ipsec-modal-disabled', false);
  2428. // Clear & Populate default dynamic subnets
  2429. const localContainer = document.getElementById('ipsec-modal-local-subnets-container');
  2430. const remoteContainer = document.getElementById('ipsec-modal-remote-subnets-container');
  2431. if (localContainer) {
  2432. localContainer.innerHTML = '';
  2433. addIpsecLocalSubnet('192.168.10.0/24');
  2434. }
  2435. if (remoteContainer) {
  2436. remoteContainer.innerHTML = '';
  2437. addIpsecRemoteSubnet('192.168.20.0/24');
  2438. }
  2439. switchIpsecModalTab('p1');
  2440. modal.classList.remove('hidden');
  2441. }
  2442. function openEditIPSecModal(name) {
  2443. const modal = document.getElementById('ipsec-modal');
  2444. if (!modal) return;
  2445. const conn = (state.ipsecTunnels || []).find(c => c.name === name);
  2446. if (!conn) return;
  2447. const title = document.getElementById('ipsec-modal-title');
  2448. if (title) title.innerText = `Edit IPSec Tunnel: ${name}`;
  2449. // Phase 1 Fields
  2450. safeSetVal('ipsec-modal-name', conn.name);
  2451. const nameEl = document.getElementById('ipsec-modal-name');
  2452. if (nameEl) nameEl.readOnly = true;
  2453. safeSetVal('ipsec-modal-ikeversion', conn.ike_version || 'ikev2');
  2454. safeSetVal('ipsec-modal-ikever', conn.ike_version || 'ikev2');
  2455. safeSetVal('ipsec-modal-remotegw', conn.remote_addrs || '');
  2456. safeSetVal('ipsec-modal-localaddrs', conn.local_addrs || '');
  2457. safeSetVal('ipsec-modal-comments', conn.comment || '');
  2458. safeSetVal('ipsec-modal-psk', conn.preshared_key || '');
  2459. safeSetVal('ipsec-modal-ikeprop', conn.ike_proposals || 'aes256-sha256-modp2048,default');
  2460. safeSetVal('ipsec-modal-ikekeylife', conn.ike_keylife || 86400);
  2461. safeSetVal('ipsec-modal-localid', conn.local_id || '');
  2462. safeSetVal('ipsec-modal-remoteid', conn.remote_id || '');
  2463. safeSetVal('ipsec-modal-dpd', conn.dpd || 'on-demand');
  2464. // Phase 2 Fields
  2465. safeSetVal('ipsec-modal-p2name', conn.phase2_name || `${conn.name}_p2`);
  2466. safeSetVal('ipsec-modal-espkeylife', conn.esp_keylife || 28800);
  2467. safeSetVal('ipsec-modal-espprop', conn.esp_proposals || 'aes256-sha256-modp2048,default');
  2468. safeSetVal('ipsec-modal-pfsgroup', conn.pfs_group || 'modp2048');
  2469. safeSetChecked('ipsec-modal-autostart', conn.auto_start ?? true);
  2470. safeSetChecked('ipsec-modal-disabled', !!conn.disabled);
  2471. // Populate dynamic subnets
  2472. const localContainer = document.getElementById('ipsec-modal-local-subnets-container');
  2473. const remoteContainer = document.getElementById('ipsec-modal-remote-subnets-container');
  2474. if (localContainer) {
  2475. localContainer.innerHTML = '';
  2476. const locals = (conn.local_subnets && conn.local_subnets.length > 0) ? conn.local_subnets : (conn.local_subnet ? [conn.local_subnet] : ['192.168.10.0/24']);
  2477. locals.forEach(s => addIpsecLocalSubnet(s));
  2478. }
  2479. if (remoteContainer) {
  2480. remoteContainer.innerHTML = '';
  2481. const remotes = (conn.remote_subnets && conn.remote_subnets.length > 0) ? conn.remote_subnets : (conn.remote_subnet ? [conn.remote_subnet] : ['192.168.20.0/24']);
  2482. remotes.forEach(s => addIpsecRemoteSubnet(s));
  2483. }
  2484. switchIpsecModalTab('p1');
  2485. modal.classList.remove('hidden');
  2486. }
  2487. function closeAddIPSecModal() {
  2488. const modal = document.getElementById('ipsec-modal');
  2489. if (modal) modal.classList.add('hidden');
  2490. }
  2491. async function submitSaveIPSec(e) {
  2492. if (e) e.preventDefault();
  2493. const name = safeGetVal('ipsec-modal-name').trim();
  2494. if (!name) {
  2495. showToast('Error', 'Tunnel name is required', 'error');
  2496. return;
  2497. }
  2498. const ikeVersion = safeGetVal('ipsec-modal-ikeversion') || safeGetVal('ipsec-modal-ikever', 'ikev2');
  2499. const remotegw = safeGetVal('ipsec-modal-remotegw').trim();
  2500. const localAddrs = safeGetVal('ipsec-modal-localaddrs').trim() || '%any';
  2501. const comments = safeGetVal('ipsec-modal-comments').trim();
  2502. const psk = safeGetVal('ipsec-modal-psk');
  2503. const ikeProposals = safeGetVal('ipsec-modal-ikeprop', 'aes256-sha256-modp2048,default').trim();
  2504. const ikeKeylife = parseInt(safeGetVal('ipsec-modal-ikekeylife', '86400'), 10) || 86400;
  2505. const localId = safeGetVal('ipsec-modal-localid').trim();
  2506. const remoteId = safeGetVal('ipsec-modal-remoteid').trim();
  2507. const dpd = safeGetVal('ipsec-modal-dpd', 'on-demand');
  2508. const phase2Name = safeGetVal('ipsec-modal-p2name').trim() || `${name}_p2`;
  2509. const espProposals = safeGetVal('ipsec-modal-espprop', 'aes256-sha256-modp2048,default').trim();
  2510. const espKeylife = parseInt(safeGetVal('ipsec-modal-espkeylife', '28800'), 10) || 28800;
  2511. const pfsGroup = safeGetVal('ipsec-modal-pfsgroup', 'modp2048');
  2512. const autostart = document.getElementById('ipsec-modal-autostart')?.checked ?? true;
  2513. const disabled = document.getElementById('ipsec-modal-disabled')?.checked ?? false;
  2514. // Scrape dynamic local and remote subnets
  2515. const localInputs = document.querySelectorAll('#ipsec-modal-local-subnets-container input');
  2516. const localSubnets = [];
  2517. localInputs.forEach(inp => {
  2518. const v = inp.value.trim();
  2519. if (v) localSubnets.push(v);
  2520. });
  2521. const remoteInputs = document.querySelectorAll('#ipsec-modal-remote-subnets-container input');
  2522. const remoteSubnets = [];
  2523. remoteInputs.forEach(inp => {
  2524. const v = inp.value.trim();
  2525. if (v) remoteSubnets.push(v);
  2526. });
  2527. try {
  2528. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`, {
  2529. method: 'POST',
  2530. headers: { 'Content-Type': 'application/json' },
  2531. body: JSON.stringify({
  2532. name,
  2533. comment: comments,
  2534. ike_version: ikeVersion,
  2535. local_addrs: localAddrs,
  2536. remote_addrs: remotegw,
  2537. preshared_key: psk,
  2538. ike_proposals: ikeProposals,
  2539. ike_keylife: ikeKeylife,
  2540. local_id: localId,
  2541. remote_id: remoteId,
  2542. dpd: dpd,
  2543. phase2_name: phase2Name,
  2544. esp_proposals: espProposals,
  2545. esp_keylife: espKeylife,
  2546. pfs_group: pfsGroup,
  2547. pfs: pfsGroup !== 'none',
  2548. local_subnets: localSubnets,
  2549. remote_subnets: remoteSubnets,
  2550. local_subnet: localSubnets[0] || '0.0.0.0/0',
  2551. remote_subnet: remoteSubnets[0] || '0.0.0.0/0',
  2552. auto_start: autostart,
  2553. disabled
  2554. })
  2555. });
  2556. if (res.ok) {
  2557. showToast('IPSec Saved', `FortiGate Tunnel ${name} configured`, 'success');
  2558. closeAddIPSecModal();
  2559. loadIPSec(false);
  2560. } else {
  2561. const err = await res.json();
  2562. showToast('Error', err.error || 'Failed to save IPSec tunnel', 'error');
  2563. }
  2564. } catch (err) {
  2565. showToast('Error', err.message, 'error');
  2566. }
  2567. }
  2568. async function startIPSecTunnel(name) {
  2569. try {
  2570. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/start`, { method: 'POST' });
  2571. if (res.ok) {
  2572. showToast('Initiating Tunnel', `Attempting SA handshake for ${name}...`, 'info');
  2573. setTimeout(() => loadIPSec(false), 2000);
  2574. }
  2575. } catch (err) {
  2576. showToast('Error', err.message, 'error');
  2577. }
  2578. }
  2579. async function stopIPSecTunnel(name) {
  2580. try {
  2581. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  2582. if (res.ok) {
  2583. showToast('Terminated', `IPSec SA for ${name} closed`, 'info');
  2584. loadIPSec(false);
  2585. }
  2586. } catch (err) {
  2587. showToast('Error', err.message, 'error');
  2588. }
  2589. }
  2590. async function toggleIPSecState(name, enable) {
  2591. try {
  2592. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/state`, {
  2593. method: 'POST',
  2594. headers: { 'Content-Type': 'application/json' },
  2595. body: JSON.stringify({ enabled: enable })
  2596. });
  2597. if (res.ok) {
  2598. showToast(enable ? 'Enabled' : 'Disabled', `IPSec tunnel ${name} updated`, 'info');
  2599. loadIPSec(false);
  2600. }
  2601. } catch (err) {
  2602. showToast('Error', err.message, 'error');
  2603. }
  2604. }
  2605. async function deleteIPSecConn(name) {
  2606. if (!confirm(`Are you sure you want to delete IPSec tunnel ${name}?`)) return;
  2607. try {
  2608. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2609. if (res.ok) {
  2610. showToast('Deleted', `IPSec connection ${name} removed`, 'success');
  2611. loadIPSec(false);
  2612. fetchData(false);
  2613. }
  2614. } catch (err) {
  2615. showToast('Error', err.message, 'error');
  2616. }
  2617. }
  2618. // ======================== L2TP Multi-Instance ========================
  2619. async function loadL2TP(populateInputs = true) {
  2620. try {
  2621. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2622. await fetchPPPProfilesList();
  2623. }
  2624. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`);
  2625. const list = await res.json();
  2626. state.l2tpList = Array.isArray(list) ? list : [];
  2627. const badge = document.getElementById('l2tp-count-badge');
  2628. if (badge) badge.innerText = `${state.l2tpList.length} Client${state.l2tpList.length !== 1 ? 's' : ''}`;
  2629. const tbody = document.getElementById('l2tp-table-body');
  2630. const empty = document.getElementById('l2tp-empty');
  2631. if (!tbody) return;
  2632. tbody.innerHTML = '';
  2633. if (state.l2tpList.length === 0) {
  2634. if (empty) empty.classList.remove('hidden');
  2635. } else {
  2636. if (empty) empty.classList.add('hidden');
  2637. state.l2tpList.forEach(inst => {
  2638. const tr = document.createElement('tr');
  2639. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  2640. tr.innerHTML = `
  2641. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  2642. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  2643. <td class="py-2.5 px-3 text-cyan-400 font-mono">${escapeHtml(inst.connect_to)}</td>
  2644. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  2645. <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>
  2646. <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>
  2647. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  2648. <td class="py-2.5 px-3 text-center">
  2649. <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'}">
  2650. ${inst.default_route ? 'Yes' : 'No'}
  2651. </span>
  2652. </td>
  2653. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  2654. ${inst.running ? `
  2655. <button onclick="disconnectL2TPInstance('${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  2656. ` : `
  2657. <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>
  2658. `}
  2659. <button onclick="toggleL2TPState('${escapeHtml(inst.name)}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  2660. ${inst.disabled ? 'Enable' : 'Disable'}
  2661. </button>
  2662. <button onclick="openEditL2TPModal('${escapeHtml(inst.name)}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2663. <button onclick="deleteL2TPInstance('${escapeHtml(inst.name)}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2664. </td>
  2665. `;
  2666. tbody.appendChild(tr);
  2667. });
  2668. }
  2669. } catch (err) {
  2670. console.error('Failed to load L2TP:', err);
  2671. }
  2672. }
  2673. async function openAddL2TPModal() {
  2674. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2675. await fetchPPPProfilesList();
  2676. }
  2677. document.getElementById('l2tp-modal-title').innerText = 'Add L2TP Client Interface';
  2678. document.getElementById('l2tp-modal-name').value = `l2tp-out${(state.l2tpList || []).length + 1}`;
  2679. document.getElementById('l2tp-modal-name').readOnly = false;
  2680. document.getElementById('l2tp-modal-server').value = '';
  2681. document.getElementById('l2tp-modal-user').value = '';
  2682. document.getElementById('l2tp-modal-pass').value = '';
  2683. document.getElementById('l2tp-modal-ipsec').value = '';
  2684. document.getElementById('l2tp-modal-defroute').checked = true;
  2685. document.getElementById('l2tp-modal-disabled').checked = false;
  2686. populateProfileSelect('l2tp-modal-profile', 'default-encryption', 'default-encryption');
  2687. document.getElementById('l2tp-modal').classList.remove('hidden');
  2688. }
  2689. async function openEditL2TPModal(name) {
  2690. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2691. await fetchPPPProfilesList();
  2692. }
  2693. const inst = (state.l2tpList || []).find(i => i.name === name);
  2694. if (!inst) return;
  2695. document.getElementById('l2tp-modal-title').innerText = `Edit L2TP Client: ${name}`;
  2696. document.getElementById('l2tp-modal-name').value = inst.name;
  2697. document.getElementById('l2tp-modal-name').readOnly = true;
  2698. document.getElementById('l2tp-modal-server').value = inst.connect_to || '';
  2699. document.getElementById('l2tp-modal-user').value = inst.username || '';
  2700. document.getElementById('l2tp-modal-pass').value = inst.password || '';
  2701. document.getElementById('l2tp-modal-ipsec').value = inst.ipsec_secret || '';
  2702. document.getElementById('l2tp-modal-defroute').checked = inst.default_route ?? true;
  2703. document.getElementById('l2tp-modal-disabled').checked = !!inst.disabled;
  2704. populateProfileSelect('l2tp-modal-profile', inst.profile || 'default-encryption', 'default-encryption');
  2705. document.getElementById('l2tp-modal').classList.remove('hidden');
  2706. }
  2707. function closeL2TPModal() {
  2708. document.getElementById('l2tp-modal').classList.add('hidden');
  2709. }
  2710. async function submitSaveL2TP(e) {
  2711. e.preventDefault();
  2712. const name = document.getElementById('l2tp-modal-name').value.trim();
  2713. const server = document.getElementById('l2tp-modal-server').value.trim();
  2714. const user = document.getElementById('l2tp-modal-user').value.trim();
  2715. const pass = document.getElementById('l2tp-modal-pass').value;
  2716. const profile = document.getElementById('l2tp-modal-profile')?.value || 'default-encryption';
  2717. const ipsec = document.getElementById('l2tp-modal-ipsec').value;
  2718. const defRoute = document.getElementById('l2tp-modal-defroute').checked;
  2719. const disabled = document.getElementById('l2tp-modal-disabled').checked;
  2720. try {
  2721. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`, {
  2722. method: 'POST',
  2723. headers: { 'Content-Type': 'application/json' },
  2724. body: JSON.stringify({
  2725. name,
  2726. connect_to: server,
  2727. username: user,
  2728. password: pass,
  2729. profile: profile,
  2730. ipsec_secret: ipsec,
  2731. default_route: defRoute,
  2732. disabled
  2733. })
  2734. });
  2735. if (res.ok) {
  2736. showToast('L2TP Saved', `Client ${name} configuration saved`, 'success');
  2737. closeL2TPModal();
  2738. loadL2TP(false);
  2739. fetchData(false);
  2740. }
  2741. } catch (err) {
  2742. showToast('Error', err.message, 'error');
  2743. }
  2744. }
  2745. async function connectL2TPInstance(name) {
  2746. try {
  2747. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  2748. if (res.ok) {
  2749. showToast('Connecting', `Dialing L2TP ${name}...`, 'info');
  2750. setTimeout(() => loadL2TP(false), 2000);
  2751. }
  2752. } catch (err) {
  2753. showToast('Error', err.message, 'error');
  2754. }
  2755. }
  2756. async function disconnectL2TPInstance(name) {
  2757. try {
  2758. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  2759. if (res.ok) {
  2760. showToast('Disconnected', `L2TP tunnel ${name} terminated`, 'info');
  2761. loadL2TP(false);
  2762. }
  2763. } catch (err) {
  2764. showToast('Error', err.message, 'error');
  2765. }
  2766. }
  2767. async function toggleL2TPState(name, enable) {
  2768. try {
  2769. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/state`, {
  2770. method: 'POST',
  2771. headers: { 'Content-Type': 'application/json' },
  2772. body: JSON.stringify({ enabled: enable })
  2773. });
  2774. if (res.ok) {
  2775. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  2776. loadL2TP(false);
  2777. }
  2778. } catch (err) {
  2779. showToast('Error', err.message, 'error');
  2780. }
  2781. }
  2782. async function deleteL2TPInstance(name) {
  2783. if (!confirm(`Are you sure you want to delete L2TP client ${name}?`)) return;
  2784. try {
  2785. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2786. if (res.ok) {
  2787. showToast('Deleted', `L2TP client ${name} removed`, 'success');
  2788. loadL2TP(false);
  2789. fetchData(false);
  2790. }
  2791. } catch (err) {
  2792. showToast('Error', err.message, 'error');
  2793. }
  2794. }
  2795. // ======================== PPTP Multi-Instance ========================
  2796. async function loadPPTP(populateInputs = true) {
  2797. try {
  2798. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2799. await fetchPPPProfilesList();
  2800. }
  2801. const res = await fetch(`${API_BASE}/vpn/pptp/clients`);
  2802. const list = await res.json();
  2803. state.pptpList = Array.isArray(list) ? list : [];
  2804. const badge = document.getElementById('pptp-count-badge');
  2805. if (badge) badge.innerText = `${state.pptpList.length} Client${state.pptpList.length !== 1 ? 's' : ''}`;
  2806. const tbody = document.getElementById('pptp-table-body');
  2807. const empty = document.getElementById('pptp-empty');
  2808. if (!tbody) return;
  2809. tbody.innerHTML = '';
  2810. if (state.pptpList.length === 0) {
  2811. if (empty) empty.classList.remove('hidden');
  2812. } else {
  2813. if (empty) empty.classList.add('hidden');
  2814. state.pptpList.forEach(inst => {
  2815. const tr = document.createElement('tr');
  2816. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  2817. tr.innerHTML = `
  2818. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  2819. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  2820. <td class="py-2.5 px-3 text-purple-400 font-mono">${escapeHtml(inst.connect_to)}</td>
  2821. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  2822. <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>
  2823. <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>
  2824. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  2825. <td class="py-2.5 px-3 text-center">
  2826. <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'}">
  2827. ${inst.require_mppe ? 'MPPE-128' : 'None'}
  2828. </span>
  2829. </td>
  2830. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  2831. ${inst.running ? `
  2832. <button onclick="disconnectPPTPInstance('${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  2833. ` : `
  2834. <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>
  2835. `}
  2836. <button onclick="togglePPTPState('${escapeHtml(inst.name)}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  2837. ${inst.disabled ? 'Enable' : 'Disable'}
  2838. </button>
  2839. <button onclick="openEditPPTPModal('${escapeHtml(inst.name)}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2840. <button onclick="deletePPTPInstance('${escapeHtml(inst.name)}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2841. </td>
  2842. `;
  2843. tbody.appendChild(tr);
  2844. });
  2845. }
  2846. } catch (err) {
  2847. console.error('Failed to load PPTP:', err);
  2848. }
  2849. }
  2850. async function openAddPPTPModal() {
  2851. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2852. await fetchPPPProfilesList();
  2853. }
  2854. document.getElementById('pptp-modal-title').innerText = 'Add PPTP Client Interface';
  2855. document.getElementById('pptp-modal-name').value = `pptp-out${(state.pptpList || []).length + 1}`;
  2856. document.getElementById('pptp-modal-name').readOnly = false;
  2857. document.getElementById('pptp-modal-server').value = '';
  2858. document.getElementById('pptp-modal-user').value = '';
  2859. document.getElementById('pptp-modal-pass').value = '';
  2860. document.getElementById('pptp-modal-mppe').checked = true;
  2861. document.getElementById('pptp-modal-defroute').checked = true;
  2862. document.getElementById('pptp-modal-disabled').checked = false;
  2863. populateProfileSelect('pptp-modal-profile', 'default-encryption', 'default-encryption');
  2864. document.getElementById('pptp-modal').classList.remove('hidden');
  2865. }
  2866. async function openEditPPTPModal(name) {
  2867. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2868. await fetchPPPProfilesList();
  2869. }
  2870. const inst = (state.pptpList || []).find(i => i.name === name);
  2871. if (!inst) return;
  2872. document.getElementById('pptp-modal-title').innerText = `Edit PPTP Client: ${name}`;
  2873. document.getElementById('pptp-modal-name').value = inst.name;
  2874. document.getElementById('pptp-modal-name').readOnly = true;
  2875. document.getElementById('pptp-modal-server').value = inst.connect_to || '';
  2876. document.getElementById('pptp-modal-user').value = inst.username || '';
  2877. document.getElementById('pptp-modal-pass').value = inst.password || '';
  2878. document.getElementById('pptp-modal-mppe').checked = inst.require_mppe ?? true;
  2879. document.getElementById('pptp-modal-defroute').checked = inst.default_route ?? true;
  2880. document.getElementById('pptp-modal-disabled').checked = !!inst.disabled;
  2881. populateProfileSelect('pptp-modal-profile', inst.profile || 'default-encryption', 'default-encryption');
  2882. document.getElementById('pptp-modal').classList.remove('hidden');
  2883. }
  2884. function closePPTPModal() {
  2885. document.getElementById('pptp-modal').classList.add('hidden');
  2886. }
  2887. async function submitSavePPTP(e) {
  2888. e.preventDefault();
  2889. const name = document.getElementById('pptp-modal-name').value.trim();
  2890. const server = document.getElementById('pptp-modal-server').value.trim();
  2891. const user = document.getElementById('pptp-modal-user').value.trim();
  2892. const pass = document.getElementById('pptp-modal-pass').value;
  2893. const profile = document.getElementById('pptp-modal-profile')?.value || 'default-encryption';
  2894. const mppe = document.getElementById('pptp-modal-mppe').checked;
  2895. const defRoute = document.getElementById('pptp-modal-defroute').checked;
  2896. const disabled = document.getElementById('pptp-modal-disabled').checked;
  2897. try {
  2898. const res = await fetch(`${API_BASE}/vpn/pptp/clients`, {
  2899. method: 'POST',
  2900. headers: { 'Content-Type': 'application/json' },
  2901. body: JSON.stringify({
  2902. name,
  2903. connect_to: server,
  2904. username: user,
  2905. password: pass,
  2906. profile: profile,
  2907. require_mppe: mppe,
  2908. default_route: defRoute,
  2909. auto_reconnect: true,
  2910. disabled
  2911. })
  2912. });
  2913. if (res.ok) {
  2914. showToast('PPTP Saved', `Client ${name} configuration saved`, 'success');
  2915. closePPTPModal();
  2916. loadPPTP(false);
  2917. fetchData(false);
  2918. }
  2919. } catch (err) {
  2920. showToast('Error', err.message, 'error');
  2921. }
  2922. }
  2923. async function connectPPTPInstance(name) {
  2924. try {
  2925. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  2926. if (res.ok) {
  2927. showToast('Connecting', `Dialing PPTP ${name}...`, 'info');
  2928. setTimeout(() => loadPPTP(false), 2000);
  2929. }
  2930. } catch (err) {
  2931. showToast('Error', err.message, 'error');
  2932. }
  2933. }
  2934. async function disconnectPPTPInstance(name) {
  2935. try {
  2936. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  2937. if (res.ok) {
  2938. showToast('Disconnected', `PPTP tunnel ${name} terminated`, 'info');
  2939. loadPPTP(false);
  2940. }
  2941. } catch (err) {
  2942. showToast('Error', err.message, 'error');
  2943. }
  2944. }
  2945. async function togglePPTPState(name, enable) {
  2946. try {
  2947. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/state`, {
  2948. method: 'POST',
  2949. headers: { 'Content-Type': 'application/json' },
  2950. body: JSON.stringify({ enabled: enable })
  2951. });
  2952. if (res.ok) {
  2953. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  2954. loadPPTP(false);
  2955. }
  2956. } catch (err) {
  2957. showToast('Error', err.message, 'error');
  2958. }
  2959. }
  2960. async function deletePPTPInstance(name) {
  2961. if (!confirm(`Are you sure you want to delete PPTP client ${name}?`)) return;
  2962. try {
  2963. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2964. if (res.ok) {
  2965. showToast('Deleted', `PPTP client ${name} removed`, 'success');
  2966. loadPPTP(false);
  2967. fetchData(false);
  2968. }
  2969. } catch (err) {
  2970. showToast('Error', err.message, 'error');
  2971. }
  2972. }
  2973. // ---------------- Modal & Helper Functions ----------------
  2974. function openVlanModal(defaultParent = '') {
  2975. const select = document.getElementById('vlan-parent');
  2976. select.innerHTML = '';
  2977. const allIfaces = state.interfaces || [];
  2978. const eligible = allIfaces.filter(i => supportsVLAN(i));
  2979. if (eligible.length === 0) {
  2980. const opt = document.createElement('option');
  2981. opt.value = '';
  2982. opt.innerText = 'No VLAN-capable interfaces available';
  2983. select.appendChild(opt);
  2984. } else {
  2985. eligible.forEach(i => {
  2986. const opt = document.createElement('option');
  2987. opt.value = i.name;
  2988. opt.innerText = `${i.name} (${i.role || i.type || 'Ethernet'} - ${i.state})`;
  2989. if (i.name === defaultParent) opt.selected = true;
  2990. select.appendChild(opt);
  2991. });
  2992. }
  2993. document.getElementById('vlan-id').value = '';
  2994. document.getElementById('vlan-name').value = '';
  2995. document.getElementById('vlan-ip').value = '';
  2996. document.getElementById('vlan-desc').value = '';
  2997. populateRoleSelects('LAN');
  2998. autoSuggestVlanName();
  2999. document.getElementById('vlan-modal').classList.remove('hidden');
  3000. }
  3001. function closeVlanModal() {
  3002. document.getElementById('vlan-modal').classList.add('hidden');
  3003. }
  3004. function autoSuggestVlanName() {
  3005. const parent = document.getElementById('vlan-parent').value;
  3006. if (!parent) return;
  3007. const id = document.getElementById('vlan-id').value;
  3008. const nameInput = document.getElementById('vlan-name');
  3009. if (parent && id) nameInput.placeholder = `${parent}.${id}`;
  3010. }
  3011. function setSubnetPreset(cidr) {
  3012. const ipInput = document.getElementById('vlan-ip');
  3013. const id = document.getElementById('vlan-id').value || '10';
  3014. ipInput.value = `192.168.${id}.1${cidr}`;
  3015. }
  3016. async function submitCreateVlan(e) {
  3017. e.preventDefault();
  3018. const btn = document.getElementById('vlan-submit-btn');
  3019. btn.disabled = true;
  3020. btn.innerText = 'Creating...';
  3021. const parent = document.getElementById('vlan-parent').value;
  3022. if (!parent) {
  3023. showToast('Error', 'Please select a valid VLAN-capable parent interface', 'error');
  3024. btn.disabled = false;
  3025. btn.innerText = 'Create VLAN';
  3026. return;
  3027. }
  3028. const id = parseInt(document.getElementById('vlan-id').value, 10);
  3029. const name = document.getElementById('vlan-name').value.trim();
  3030. const ip = document.getElementById('vlan-ip').value.trim();
  3031. const role = document.getElementById('vlan-role').value;
  3032. const desc = document.getElementById('vlan-desc').value.trim();
  3033. try {
  3034. const res = await fetch(`${API_BASE}/vlans`, {
  3035. method: 'POST',
  3036. headers: { 'Content-Type': 'application/json' },
  3037. body: JSON.stringify({
  3038. parent_name: parent,
  3039. vlan_id: id,
  3040. name: name,
  3041. ip_address: ip,
  3042. role: role,
  3043. description: desc,
  3044. mtu: 1500,
  3045. auto_up: true
  3046. })
  3047. });
  3048. const data = await res.json();
  3049. if (res.ok) {
  3050. showToast('VLAN Created', `Created ${data.name} (VLAN ${data.vlan_id})`, 'success');
  3051. state.expandedParents.add(parent);
  3052. closeVlanModal();
  3053. await fetchData(true);
  3054. if (state.activeTab !== 'interfaces') navigate('interfaces');
  3055. } else {
  3056. showToast('Creation Failed', data.message || 'Failed to create VLAN', 'error');
  3057. }
  3058. } catch (err) {
  3059. showToast('Error', err.message, 'error');
  3060. } finally {
  3061. btn.disabled = false;
  3062. btn.innerText = 'Create VLAN';
  3063. }
  3064. }
  3065. async function confirmDeleteVlan(name) {
  3066. if (!confirm(`Delete VLAN interface ${name}?`)) return;
  3067. try {
  3068. const res = await fetch(`${API_BASE}/vlans/${encodeURIComponent(name)}`, { method: 'DELETE' });
  3069. if (res.ok) {
  3070. showToast('VLAN Deleted', `Interface ${name} removed`, 'success');
  3071. closeIfaceModal();
  3072. fetchData(true);
  3073. }
  3074. } catch (err) {
  3075. showToast('Error', err.message, 'error');
  3076. }
  3077. }
  3078. function openIfaceModal(name) {
  3079. const iface = (state.interfaces || []).find(i => i.name === name);
  3080. if (!iface) return;
  3081. state.currentModalIface = iface.name;
  3082. document.getElementById('modal-iface-name').innerText = iface.name;
  3083. document.getElementById('modal-iface-badge').innerText = iface.is_vlan ? `VLAN ${iface.vlan_id}` : iface.type;
  3084. document.getElementById('modal-iface-mtu').value = iface.mtu;
  3085. populateRoleSelects(iface.role || 'LAN');
  3086. document.getElementById('modal-iface-desc').value = iface.description || '';
  3087. const nameInput = document.getElementById('modal-iface-new-name');
  3088. const renameBtn = document.getElementById('modal-btn-rename');
  3089. const renameHelp = document.getElementById('modal-iface-rename-help');
  3090. if (nameInput) {
  3091. nameInput.value = iface.name;
  3092. if (iface.name === 'lo' || iface.type === 'loopback') {
  3093. nameInput.disabled = true;
  3094. if (renameBtn) renameBtn.disabled = true;
  3095. if (renameHelp) renameHelp.innerText = 'Loopback interface cannot be renamed.';
  3096. } else {
  3097. nameInput.disabled = false;
  3098. if (renameBtn) renameBtn.disabled = false;
  3099. if (renameHelp) renameHelp.innerText = 'Device name in Linux (max 15 characters). Automatically preserves operational link state and metadata.';
  3100. }
  3101. }
  3102. const delBtn = document.getElementById('modal-delete-vlan-btn');
  3103. if (iface.is_vlan) {
  3104. delBtn.classList.remove('hidden');
  3105. } else {
  3106. delBtn.classList.add('hidden');
  3107. }
  3108. renderModalIPs(iface);
  3109. document.getElementById('iface-modal').classList.remove('hidden');
  3110. }
  3111. function renderModalIPs(iface) {
  3112. const container = document.getElementById('modal-ip-list');
  3113. container.innerHTML = '';
  3114. const addrs = [...(iface.ipv4 || []), ...(iface.ipv6 || [])];
  3115. if (addrs.length === 0) {
  3116. container.innerHTML = `<span class="text-slate-500 text-xs font-sans">No IP addresses currently bound</span>`;
  3117. return;
  3118. }
  3119. addrs.forEach(addr => {
  3120. const row = document.createElement('div');
  3121. row.className = 'flex items-center justify-between p-2 rounded bg-slate-900 border border-slate-800';
  3122. row.innerHTML = `
  3123. <span class="text-white">${addr}</span>
  3124. <button onclick="removeInterfaceIP('${addr}')" class="text-[11px] text-rose-400 hover:text-rose-300 font-sans">Remove</button>
  3125. `;
  3126. container.appendChild(row);
  3127. });
  3128. }
  3129. function closeIfaceModal() {
  3130. document.getElementById('iface-modal').classList.add('hidden');
  3131. state.currentModalIface = null;
  3132. }
  3133. async function setIfaceState(name, newState) {
  3134. const target = name || state.currentModalIface;
  3135. if (!target) return;
  3136. await toggleInterfaceState(target, newState);
  3137. const updated = (state.interfaces || []).find(i => i.name === target);
  3138. if (updated) openIfaceModal(target);
  3139. }
  3140. async function applyMTU() {
  3141. const mtu = parseInt(document.getElementById('modal-iface-mtu').value, 10);
  3142. try {
  3143. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/mtu`, {
  3144. method: 'POST',
  3145. headers: { 'Content-Type': 'application/json' },
  3146. body: JSON.stringify({ mtu })
  3147. });
  3148. if (res.ok) {
  3149. showToast('MTU Applied', `Set MTU to ${mtu} on ${state.currentModalIface}`, 'success');
  3150. fetchData(false);
  3151. }
  3152. } catch (err) {
  3153. showToast('Error', err.message, 'error');
  3154. }
  3155. }
  3156. async function addInterfaceIP() {
  3157. const ip = document.getElementById('modal-new-ip').value.trim();
  3158. if (!ip) return;
  3159. try {
  3160. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  3161. method: 'POST',
  3162. headers: { 'Content-Type': 'application/json' },
  3163. body: JSON.stringify({ ip })
  3164. });
  3165. if (res.ok) {
  3166. showToast('IP Added', `Bound ${ip} to ${state.currentModalIface}`, 'success');
  3167. document.getElementById('modal-new-ip').value = '';
  3168. await fetchData(false);
  3169. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  3170. if (iface) renderModalIPs(iface);
  3171. } else {
  3172. const err = await res.json();
  3173. showToast('Error', err.error || err.message || 'Failed to add IP address', 'error');
  3174. }
  3175. } catch (err) {
  3176. showToast('Error', err.message, 'error');
  3177. }
  3178. }
  3179. async function removeInterfaceIP(ip) {
  3180. if (!confirm(`Remove IP ${ip}?`)) return;
  3181. try {
  3182. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  3183. method: 'DELETE',
  3184. headers: { 'Content-Type': 'application/json' },
  3185. body: JSON.stringify({ ip })
  3186. });
  3187. if (res.ok) {
  3188. showToast('IP Removed', `Removed ${ip}`, 'success');
  3189. await fetchData(false);
  3190. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  3191. if (iface) renderModalIPs(iface);
  3192. }
  3193. } catch (err) {
  3194. showToast('Error', err.message, 'error');
  3195. }
  3196. }
  3197. async function renameInterface() {
  3198. const oldName = state.currentModalIface;
  3199. const newNameInput = document.getElementById('modal-iface-new-name');
  3200. const newName = (newNameInput?.value || '').trim();
  3201. if (!oldName) return;
  3202. if (!newName) {
  3203. showToast('Warning', 'Interface name cannot be empty', 'warning');
  3204. return;
  3205. }
  3206. if (newName === oldName) {
  3207. showToast('Info', `Interface name is already "${oldName}"`, 'info');
  3208. return;
  3209. }
  3210. if (newName.length > 15) {
  3211. showToast('Validation Error', 'Interface name cannot exceed 15 characters (Linux IFNAMSIZ)', 'error');
  3212. return;
  3213. }
  3214. if (!/^[a-zA-Z0-9_][a-zA-Z0-9_.-]*$/.test(newName)) {
  3215. showToast('Validation Error', 'Name must contain only alphanumeric characters, underscores, hyphens or dots', 'error');
  3216. return;
  3217. }
  3218. const renameBtn = document.getElementById('modal-btn-rename');
  3219. if (renameBtn) {
  3220. renameBtn.disabled = true;
  3221. renameBtn.innerHTML = `<span class="animate-spin inline-block mr-1">⟳</span> Renaming...`;
  3222. }
  3223. try {
  3224. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(oldName)}/rename`, {
  3225. method: 'POST',
  3226. headers: { 'Content-Type': 'application/json' },
  3227. body: JSON.stringify({ new_name: newName })
  3228. });
  3229. const data = await res.json();
  3230. if (!res.ok) {
  3231. showToast('Rename Failed', data.error || data.message || 'Failed to rename interface', 'error');
  3232. return;
  3233. }
  3234. showToast('Interface Renamed', `Successfully renamed ${oldName} → ${newName}`, 'success');
  3235. state.currentModalIface = newName;
  3236. document.getElementById('modal-iface-name').innerText = newName;
  3237. // Refresh application state
  3238. await fetchData(false);
  3239. const updated = (state.interfaces || []).find(i => i.name === newName);
  3240. if (updated) {
  3241. openIfaceModal(newName);
  3242. } else {
  3243. closeIfaceModal();
  3244. }
  3245. } catch (err) {
  3246. showToast('Error', err.message, 'error');
  3247. } finally {
  3248. if (renameBtn) {
  3249. renameBtn.disabled = false;
  3250. renameBtn.innerHTML = `
  3251. <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>
  3252. <span>Rename</span>
  3253. `;
  3254. }
  3255. }
  3256. }
  3257. async function saveInterfaceMetadata() {
  3258. const oldName = state.currentModalIface;
  3259. const newName = (document.getElementById('modal-iface-new-name')?.value || '').trim();
  3260. const role = document.getElementById('modal-iface-role').value;
  3261. const desc = document.getElementById('modal-iface-desc').value.trim();
  3262. let targetName = oldName;
  3263. // If user changed the name before clicking Save Changes, execute rename first
  3264. if (newName && newName !== oldName && oldName !== 'lo') {
  3265. try {
  3266. const renameRes = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(oldName)}/rename`, {
  3267. method: 'POST',
  3268. headers: { 'Content-Type': 'application/json' },
  3269. body: JSON.stringify({ new_name: newName })
  3270. });
  3271. const data = await renameRes.json();
  3272. if (!renameRes.ok) {
  3273. showToast('Rename Failed', data.error || data.message || 'Could not rename interface', 'error');
  3274. return;
  3275. }
  3276. targetName = newName;
  3277. state.currentModalIface = newName;
  3278. showToast('Renamed', `Interface renamed from ${oldName} to ${newName}`, 'success');
  3279. } catch (err) {
  3280. showToast('Error', err.message, 'error');
  3281. return;
  3282. }
  3283. }
  3284. try {
  3285. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(targetName)}/metadata`, {
  3286. method: 'POST',
  3287. headers: { 'Content-Type': 'application/json' },
  3288. body: JSON.stringify({ role, description: desc })
  3289. });
  3290. if (res.ok) {
  3291. showToast('Saved', 'Interface configuration updated', 'success');
  3292. closeIfaceModal();
  3293. fetchData(false);
  3294. } else {
  3295. const err = await res.json();
  3296. showToast('Error', err.error || err.message || 'Failed to save metadata', 'error');
  3297. }
  3298. } catch (err) {
  3299. showToast('Error', err.message, 'error');
  3300. }
  3301. }
  3302. // ======================== MIKROTIK FIREWALL (/ip firewall) ========================
  3303. state.fwSubTab = 'filter';
  3304. state.routesSubTab = 'routes';
  3305. function renderRuleFlag(disabled, hasComment) {
  3306. let flags = '';
  3307. if (disabled) flags += '<span class="text-rose-400 font-bold" title="Disabled">X</span>';
  3308. if (hasComment) flags += '<span class="text-amber-400 font-bold ml-1" title="Has Comment">C</span>';
  3309. return flags || '<span class="text-slate-600">-</span>';
  3310. }
  3311. function renderActionBadge(action) {
  3312. const act = (action || '').toLowerCase();
  3313. let color = 'bg-slate-800 text-slate-300';
  3314. if (act === 'accept') color = 'bg-emerald-500/20 text-emerald-300 border border-emerald-500/30';
  3315. else if (act === 'drop' || act === 'reject') color = 'bg-rose-500/20 text-rose-300 border border-rose-500/30';
  3316. else if (act === 'masquerade' || act === 'src-nat' || act === 'dst-nat') color = 'bg-amber-500/20 text-amber-300 border border-amber-500/30';
  3317. else if (act.startsWith('mark-')) color = 'bg-purple-500/20 text-purple-300 border border-purple-500/30';
  3318. else if (act === 'log') color = 'bg-cyan-500/20 text-cyan-300 border border-cyan-500/30';
  3319. return `<span class="px-2 py-0.5 rounded text-[10px] font-mono font-semibold ${color}">${action}</span>`;
  3320. }
  3321. function switchFWSubTab(tab) {
  3322. state.fwSubTab = tab;
  3323. const tabs = ['filter', 'nat', 'mangle', 'addrlist', 'geo', 'connections'];
  3324. tabs.forEach(t => {
  3325. const panel = document.getElementById(`fw-subtab-${t}`);
  3326. const btn = document.getElementById(`fw-subtab-btn-${t}`);
  3327. if (panel) {
  3328. if (t === tab) panel.classList.remove('hidden');
  3329. else panel.classList.add('hidden');
  3330. }
  3331. if (btn) {
  3332. if (t === tab) {
  3333. 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';
  3334. } else {
  3335. 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';
  3336. }
  3337. }
  3338. });
  3339. const addBtn = document.getElementById('fw-primary-add-btn');
  3340. if (addBtn) {
  3341. if (tab === 'filter') addBtn.innerHTML = '<span>+ Add Filter Rule</span>';
  3342. else if (tab === 'nat') addBtn.innerHTML = '<span>+ Add NAT Rule</span>';
  3343. else if (tab === 'mangle') addBtn.innerHTML = '<span>+ Add Mangle Rule</span>';
  3344. else if (tab === 'addrlist') addBtn.innerHTML = '<span>+ Add Address List</span>';
  3345. else if (tab === 'geo') addBtn.innerHTML = '<span>⚙️ Schedule Settings</span>';
  3346. else if (tab === 'connections') addBtn.innerHTML = '<span>Refresh Flows</span>';
  3347. }
  3348. if (tab === 'filter') renderFilterRules();
  3349. else if (tab === 'nat') renderNATRules();
  3350. else if (tab === 'mangle') renderMangleRules();
  3351. else if (tab === 'addrlist') renderAddressLists();
  3352. else if (tab === 'geo') loadGeoIP();
  3353. else if (tab === 'connections') loadConnections();
  3354. setTimeout(initTableSorting, 50);
  3355. }
  3356. function openCurrentFWModal() {
  3357. if (state.fwSubTab === 'filter') openAddFilterModal();
  3358. else if (state.fwSubTab === 'nat') openAddNATModal();
  3359. else if (state.fwSubTab === 'mangle') openAddMangleModal();
  3360. else if (state.fwSubTab === 'addrlist') openAddAddrListModal();
  3361. else if (state.fwSubTab === 'geo') openGeoIntervalModal();
  3362. else if (state.fwSubTab === 'connections') loadConnections();
  3363. }
  3364. async function loadFirewall(populateDropdowns = true) {
  3365. try {
  3366. const [summaryRes, filterRes, natRes, mangleRes, addrlistRes, geoStatusRes, geoCountriesRes] = await Promise.all([
  3367. fetch(`${API_BASE}/firewall/summary`),
  3368. fetch(`${API_BASE}/firewall/filter`),
  3369. fetch(`${API_BASE}/firewall/nat`),
  3370. fetch(`${API_BASE}/firewall/mangle`),
  3371. fetch(`${API_BASE}/firewall/address-lists`),
  3372. fetch(`${API_BASE}/firewall/geoip/status`),
  3373. fetch(`${API_BASE}/firewall/geoip/countries`)
  3374. ]);
  3375. if (summaryRes.ok) state.fwSummary = await summaryRes.json();
  3376. if (filterRes.ok) state.filterRules = await filterRes.json();
  3377. if (natRes.ok) state.natRules = await natRes.json();
  3378. if (mangleRes.ok) state.mangleRules = await mangleRes.json();
  3379. if (addrlistRes.ok) state.addressLists = await addrlistRes.json();
  3380. if (geoStatusRes.ok) state.geoStatus = await geoStatusRes.json();
  3381. if (geoCountriesRes.ok) state.geoCountries = await geoCountriesRes.json();
  3382. // Badges
  3383. const bFilter = document.getElementById('fw-badge-filter');
  3384. if (bFilter) bFilter.innerText = (state.filterRules || []).length;
  3385. const bNat = document.getElementById('fw-badge-nat');
  3386. if (bNat) bNat.innerText = (state.natRules || []).length;
  3387. const bMangle = document.getElementById('fw-badge-mangle');
  3388. if (bMangle) bMangle.innerText = (state.mangleRules || []).length;
  3389. const bAddr = document.getElementById('fw-badge-addrlist');
  3390. if (bAddr) bAddr.innerText = (state.addressLists || []).length;
  3391. const bGeo = document.getElementById('fw-badge-geo');
  3392. if (bGeo) bGeo.innerText = state.geoStatus?.enabled_count || 0;
  3393. const sigFilter = (state.filterRules || []).map(r => `${r.id}:${r.chain}:${r.action}:${r.disabled}`).join(';');
  3394. const sigNat = (state.natRules || []).map(r => `${r.id}:${r.chain}:${r.action}:${r.disabled}`).join(';');
  3395. const sigMangle = (state.mangleRules || []).map(r => `${r.id}:${r.chain}:${r.action}:${r.disabled}`).join(';');
  3396. const sigAddr = (state.addressLists || []).map(a => `${a.id}:${a.name}:${a.address}:${a.disabled}`).join(';');
  3397. const tbodyFilter = document.getElementById('filter-table-body');
  3398. if (tbodyFilter) {
  3399. if (populateDropdowns || tbodyFilter.dataset.sig !== sigFilter) {
  3400. tbodyFilter.dataset.sig = sigFilter;
  3401. renderFilterRules();
  3402. } else {
  3403. // In-place live stats update (ZERO flicker)
  3404. (state.filterRules || []).forEach(r => {
  3405. const p = document.getElementById(`filter-pkts-${r.id}`);
  3406. if (p) p.innerText = `${(r.packets || 0).toLocaleString()}p`;
  3407. const b = document.getElementById(`filter-bytes-${r.id}`);
  3408. if (b) b.innerText = formatTraffic(r.bytes || 0).replace('/s', '');
  3409. });
  3410. }
  3411. }
  3412. const tbodyNat = document.getElementById('nat-table-body');
  3413. if (tbodyNat) {
  3414. if (populateDropdowns || tbodyNat.dataset.sig !== sigNat) {
  3415. tbodyNat.dataset.sig = sigNat;
  3416. renderNATRules();
  3417. } else {
  3418. (state.natRules || []).forEach(r => {
  3419. const p = document.getElementById(`nat-pkts-${r.id}`);
  3420. if (p) p.innerText = `${(r.packets || 0).toLocaleString()}p`;
  3421. const b = document.getElementById(`nat-bytes-${r.id}`);
  3422. if (b) b.innerText = formatTraffic(r.bytes || 0).replace('/s', '');
  3423. });
  3424. }
  3425. }
  3426. const tbodyMangle = document.getElementById('mangle-table-body');
  3427. if (tbodyMangle) {
  3428. if (populateDropdowns || tbodyMangle.dataset.sig !== sigMangle) {
  3429. tbodyMangle.dataset.sig = sigMangle;
  3430. renderMangleRules();
  3431. } else {
  3432. (state.mangleRules || []).forEach(r => {
  3433. const p = document.getElementById(`mangle-pkts-${r.id}`);
  3434. if (p) p.innerText = `${(r.packets || 0).toLocaleString()}p`;
  3435. const b = document.getElementById(`mangle-bytes-${r.id}`);
  3436. if (b) b.innerText = formatTraffic(r.bytes || 0).replace('/s', '');
  3437. });
  3438. }
  3439. }
  3440. const tbodyAddr = document.getElementById('addrlist-table-body');
  3441. if (tbodyAddr && (populateDropdowns || tbodyAddr.dataset.sig !== sigAddr)) {
  3442. tbodyAddr.dataset.sig = sigAddr;
  3443. renderAddressLists();
  3444. }
  3445. renderGeoCountries();
  3446. if (state.fwSubTab === 'connections') {
  3447. loadConnections();
  3448. }
  3449. } catch (err) {
  3450. console.error('Failed to load firewall:', err);
  3451. }
  3452. }
  3453. // ----------------- Filter Rules -----------------
  3454. function renderFilterRules() {
  3455. const chainFilter = document.getElementById('filter-filter-chain')?.value || '';
  3456. const tbody = document.getElementById('filter-table-body');
  3457. const empty = document.getElementById('filter-empty');
  3458. if (!tbody) return;
  3459. tbody.innerHTML = '';
  3460. const rules = (state.filterRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  3461. document.getElementById('filter-count-badge').innerText = `${rules.length} Rules`;
  3462. if (rules.length === 0) {
  3463. empty?.classList.remove('hidden');
  3464. return;
  3465. }
  3466. empty?.classList.add('hidden');
  3467. rules.forEach((r, idx) => {
  3468. const tr = document.createElement('tr');
  3469. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  3470. const ports = [r.src_port ? 's:' + r.src_port : '', r.dst_port ? 'd:' + r.dst_port : ''].filter(Boolean).join(' ');
  3471. const ifaces = [r.in_interface ? 'in:' + r.in_interface : '', r.out_interface ? 'out:' + r.out_interface : ''].filter(Boolean).join(' ');
  3472. let actionExtra = '';
  3473. if (r.action === 'reject') {
  3474. actionExtra = `<span class="block text-[10px] text-rose-300 font-mono mt-0.5">(${r.reject_with || 'icmp-net-unreach'})</span>`;
  3475. } else if (r.action === 'jump') {
  3476. actionExtra = `<span class="block text-[10px] text-yellow-300 font-mono mt-0.5">&rarr; ${r.jump_target || '-'}</span>`;
  3477. } else if (r.action.includes('address-list') || r.action.includes('address list')) {
  3478. actionExtra = `<span class="block text-[10px] text-emerald-300 font-mono mt-0.5">&rarr; ${r.address_list || '-'}</span>`;
  3479. } else if (r.action === 'log' && r.log_prefix) {
  3480. actionExtra = `<span class="block text-[10px] text-slate-400 font-mono mt-0.5">${r.log_prefix}</span>`;
  3481. }
  3482. tr.innerHTML = `
  3483. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  3484. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  3485. <td class="py-2.5 px-3 font-bold text-white">${r.chain}</td>
  3486. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  3487. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  3488. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}</td>
  3489. <td class="py-2.5 px-3 text-amber-400">${ports || '-'}</td>
  3490. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  3491. <td class="py-2.5 px-3">${renderActionBadge(r.action)}${actionExtra}</td>
  3492. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  3493. <span class="text-slate-300" id="filter-pkts-${r.id}">${(r.packets || 0).toLocaleString()}p</span> /
  3494. <span class="text-slate-500" id="filter-bytes-${r.id}">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  3495. </td>
  3496. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  3497. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  3498. <button onclick="moveFilterRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  3499. <button onclick="moveFilterRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  3500. <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>
  3501. <button onclick="openEditFilterModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  3502. <button onclick="deleteFilterRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  3503. </td>
  3504. `;
  3505. tbody.appendChild(tr);
  3506. });
  3507. }
  3508. function formatTarget(addr, list, geo) {
  3509. const parts = [];
  3510. if (addr) parts.push(`<span>${addr}</span>`);
  3511. if (list) {
  3512. const inv = list.startsWith('!') ? '!' : '';
  3513. const clean = list.replace(/^!/, '');
  3514. 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>`);
  3515. }
  3516. if (geo) {
  3517. const inv = geo.startsWith('!') ? '!' : '';
  3518. const clean = geo.replace(/^!/, '').replace(/^geo:/, '');
  3519. 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>`);
  3520. }
  3521. if (parts.length === 0) return '<span class="text-slate-600">0.0.0.0/0</span>';
  3522. return parts.join(' ');
  3523. }
  3524. function populateInterfaceSelect(selectId, currentVal = '') {
  3525. const sel = document.getElementById(selectId);
  3526. if (!sel) return;
  3527. sel.innerHTML = '<option value="">(Any Interface)</option>';
  3528. (state.interfaces || []).forEach(i => {
  3529. const opt = document.createElement('option');
  3530. opt.value = i.name;
  3531. opt.innerText = `${i.name} (${i.role || i.type})`;
  3532. if (i.name === currentVal) opt.selected = true;
  3533. sel.appendChild(opt);
  3534. });
  3535. }
  3536. function populateAddressListSelect(selectId, currentVal = '') {
  3537. const sel = document.getElementById(selectId);
  3538. if (!sel) return;
  3539. sel.innerHTML = '<option value="">(None)</option>';
  3540. const cleanVal = (currentVal || '').replace(/^!/, '');
  3541. const customNames = Array.from(new Set((state.addressLists || []).map(a => a.name))).sort();
  3542. customNames.forEach(name => {
  3543. const count = (state.addressLists || []).filter(a => a.name === name).length;
  3544. const opt = document.createElement('option');
  3545. opt.value = name;
  3546. opt.innerText = `${name} (${count} entries)`;
  3547. if (name === cleanVal) opt.selected = true;
  3548. sel.appendChild(opt);
  3549. });
  3550. if (cleanVal && !sel.querySelector(`option[value="${cleanVal}"]`)) {
  3551. const opt = document.createElement('option');
  3552. opt.value = cleanVal;
  3553. opt.innerText = cleanVal;
  3554. opt.selected = true;
  3555. sel.appendChild(opt);
  3556. }
  3557. populateCommonAddrListDatalist();
  3558. }
  3559. function populateCommonAddrListDatalist() {
  3560. const dl = document.getElementById('fw-addrlist-datalist');
  3561. if (!dl) return;
  3562. dl.innerHTML = '';
  3563. const names = Array.from(new Set((state.addressLists || []).map(a => a.name).filter(Boolean))).sort();
  3564. names.forEach(name => {
  3565. const opt = document.createElement('option');
  3566. opt.value = name;
  3567. dl.appendChild(opt);
  3568. });
  3569. }
  3570. function populateGeoIPSelect(selectId, currentVal = '') {
  3571. const sel = document.getElementById(selectId);
  3572. if (!sel) return;
  3573. sel.innerHTML = '<option value="">(None)</option>';
  3574. const cleanVal = (currentVal || '').replace(/^!/, '').replace(/^geo:/, '').toUpperCase();
  3575. // Presets optgroup
  3576. const grpPresets = document.createElement('optgroup');
  3577. grpPresets.label = '⚡ Regional Presets';
  3578. const presets = [
  3579. { code: 'EU', label: '🇪🇺 European Union (EU - 27 countries)' },
  3580. { code: 'BALKANS', label: '🏛️ Balkans (GR, CY, BG, RO, AL, etc.)' },
  3581. { code: 'BLOCKLIST', label: '🛡️ High-Risk Blocklist (CN, RU, IR, KP, BY)' }
  3582. ];
  3583. presets.forEach(p => {
  3584. const opt = document.createElement('option');
  3585. opt.value = p.code;
  3586. opt.innerText = p.label;
  3587. if (p.code === cleanVal) opt.selected = true;
  3588. grpPresets.appendChild(opt);
  3589. });
  3590. sel.appendChild(grpPresets);
  3591. // All Countries optgroup
  3592. const grpCountries = document.createElement('optgroup');
  3593. grpCountries.label = '🌍 All Countries';
  3594. const countries = (state.geoCountries || []).slice().sort((a, b) => a.name.localeCompare(b.name));
  3595. countries.forEach(c => {
  3596. const opt = document.createElement('option');
  3597. opt.value = c.code;
  3598. const subnetsInfo = c.subnet_count ? ` [${c.subnet_count.toLocaleString()} subnets]` : '';
  3599. opt.innerText = `${c.name} (${c.code})${subnetsInfo}`;
  3600. if (c.code === cleanVal) opt.selected = true;
  3601. grpCountries.appendChild(opt);
  3602. });
  3603. sel.appendChild(grpCountries);
  3604. }
  3605. // ==================== FIREWALL FILTER MODAL (ROUTEROS WEBFIG / WINBOX V4) ====================
  3606. function switchFwRuleTab(tab) {
  3607. state.activeFwRuleTab = tab;
  3608. document.querySelectorAll('.fw-rule-tab-btn').forEach(btn => {
  3609. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  3610. btn.classList.add('text-slate-400', 'border-transparent');
  3611. });
  3612. const activeBtn = document.getElementById(`fw-tab-btn-${tab}`);
  3613. if (activeBtn) {
  3614. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  3615. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  3616. }
  3617. document.querySelectorAll('.fw-rule-pane').forEach(p => p.classList.add('hidden'));
  3618. const activePane = document.getElementById(`fw-pane-${tab}`);
  3619. if (activePane) activePane.classList.remove('hidden');
  3620. if (tab === 'statistics') {
  3621. startFwStatPolling();
  3622. } else {
  3623. stopFwStatPolling();
  3624. }
  3625. }
  3626. function toggleFwField(fieldKey, expand) {
  3627. const plusBtn = document.getElementById(`fw-plus-${fieldKey}`);
  3628. const fieldBox = document.getElementById(`fw-field-${fieldKey}`);
  3629. if (!plusBtn || !fieldBox) return;
  3630. if (expand) {
  3631. plusBtn.classList.add('hidden');
  3632. fieldBox.classList.remove('hidden');
  3633. const valInput = document.getElementById(`fw-val-${fieldKey}`);
  3634. if (valInput) valInput.focus();
  3635. } else {
  3636. fieldBox.classList.add('hidden');
  3637. plusBtn.classList.remove('hidden');
  3638. const valInput = document.getElementById(`fw-val-${fieldKey}`);
  3639. if (valInput) {
  3640. if (valInput.tagName === 'SELECT') {
  3641. valInput.selectedIndex = 0;
  3642. } else {
  3643. valInput.value = '';
  3644. }
  3645. }
  3646. const invInput = document.getElementById(`fw-inv-${fieldKey}`);
  3647. if (invInput) invInput.checked = false;
  3648. if (fieldKey === 'cs') {
  3649. ['filter-modal-cs-established', 'filter-modal-cs-related', 'filter-modal-cs-new', 'filter-modal-cs-invalid', 'filter-modal-cs-untracked'].forEach(id => {
  3650. const el = document.getElementById(id);
  3651. if (el) el.checked = false;
  3652. });
  3653. }
  3654. if (fieldKey === 'natstate') {
  3655. ['filter-modal-nat-srcnat', 'filter-modal-nat-dstnat'].forEach(id => {
  3656. const el = document.getElementById(id);
  3657. if (el) el.checked = false;
  3658. });
  3659. }
  3660. if (fieldKey === 'days') {
  3661. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3662. const el = document.getElementById(`fw-day-${d}`);
  3663. if (el) el.checked = true;
  3664. });
  3665. }
  3666. }
  3667. }
  3668. function setFwFieldVal(fieldKey, value, hasInvert = false) {
  3669. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  3670. toggleFwField(fieldKey, true);
  3671. let strVal = String(value);
  3672. if (hasInvert) {
  3673. const inv = strVal.startsWith('!');
  3674. if (inv) strVal = strVal.slice(1);
  3675. const invEl = document.getElementById(`fw-inv-${fieldKey}`);
  3676. if (invEl) invEl.checked = inv;
  3677. }
  3678. const valEl = document.getElementById(`fw-val-${fieldKey}`);
  3679. if (valEl) valEl.value = strVal;
  3680. } else {
  3681. toggleFwField(fieldKey, false);
  3682. }
  3683. }
  3684. function getFwFieldVal(fieldKey, hasInvert = false) {
  3685. const fieldBox = document.getElementById(`fw-field-${fieldKey}`);
  3686. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  3687. const valEl = document.getElementById(`fw-val-${fieldKey}`);
  3688. let v = valEl ? valEl.value.trim() : '';
  3689. if (!v) return '';
  3690. if (hasInvert) {
  3691. const invEl = document.getElementById(`fw-inv-${fieldKey}`);
  3692. if (invEl && invEl.checked) {
  3693. v = '!' + v.replace(/^!/, '');
  3694. }
  3695. }
  3696. return v;
  3697. }
  3698. function toggleMaximizeFilterModal() {
  3699. const win = document.getElementById('filter-modal-window');
  3700. if (!win) return;
  3701. if (win.classList.contains('max-w-[720px]')) {
  3702. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  3703. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  3704. } else {
  3705. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  3706. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  3707. }
  3708. }
  3709. function openAddFilterModal() {
  3710. switchFwRuleTab('general');
  3711. const badge = document.getElementById('fw-modal-badge');
  3712. if (badge) badge.innerText = 'New...';
  3713. document.getElementById('filter-modal-id').value = '';
  3714. document.getElementById('filter-modal-enabled').checked = true;
  3715. document.getElementById('filter-modal-comment').value = '';
  3716. document.getElementById('filter-modal-chain').value = 'forward';
  3717. document.getElementById('filter-modal-action').value = 'accept';
  3718. document.getElementById('filter-modal-log').checked = false;
  3719. populateInterfaceSelect('fw-val-iniface');
  3720. populateInterfaceSelect('fw-val-outiface');
  3721. populateAddressListSelect('fw-val-srclist');
  3722. populateAddressListSelect('fw-val-dstlist');
  3723. populateGeoIPSelect('fw-val-srcgeo');
  3724. populateGeoIPSelect('fw-val-dstgeo');
  3725. const allFieldKeys = [
  3726. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  3727. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  3728. 'routingmark', 'conntype', 'cs', 'natstate',
  3729. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  3730. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  3731. 'ipsec', 'tlshost', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  3732. 'pktsize', 'random', 'tcpflags', 'icmpoptions', 'ipv4options', 'ttl',
  3733. 'time', 'days', 'limit', 'dstlimit', 'psd', 'logprefix'
  3734. ];
  3735. allFieldKeys.forEach(k => toggleFwField(k, false));
  3736. resetCurrentRuleCounters();
  3737. toggleFilterActionFields();
  3738. document.getElementById('filter-modal').classList.remove('hidden');
  3739. }
  3740. function openEditFilterModal(id) {
  3741. const r = (state.filterRules || []).find(rule => rule.id === id);
  3742. if (!r) return;
  3743. switchFwRuleTab('general');
  3744. const badge = document.getElementById('fw-modal-badge');
  3745. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  3746. document.getElementById('filter-modal-id').value = r.id;
  3747. document.getElementById('filter-modal-enabled').checked = !r.disabled;
  3748. document.getElementById('filter-modal-comment').value = r.comment || '';
  3749. document.getElementById('filter-modal-chain').value = r.chain || 'forward';
  3750. document.getElementById('filter-modal-action').value = r.action || 'accept';
  3751. document.getElementById('filter-modal-log').checked = !!r.log;
  3752. populateInterfaceSelect('fw-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  3753. populateInterfaceSelect('fw-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  3754. populateAddressListSelect('fw-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  3755. populateAddressListSelect('fw-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  3756. populateGeoIPSelect('fw-val-srcgeo', r.src_geoip || '');
  3757. populateGeoIPSelect('fw-val-dstgeo', r.dst_geoip || '');
  3758. setFwFieldVal('src', r.src_address, true);
  3759. setFwFieldVal('dst', r.dst_address, true);
  3760. setFwFieldVal('srclist', r.src_address_list, true);
  3761. setFwFieldVal('dstlist', r.dst_address_list, true);
  3762. setFwFieldVal('srcgeo', r.src_geoip, true);
  3763. setFwFieldVal('dstgeo', r.dst_geoip, true);
  3764. if (r.protocol && r.protocol !== 'all') {
  3765. setFwFieldVal('proto', r.protocol, true);
  3766. } else {
  3767. toggleFwField('proto', false);
  3768. }
  3769. setFwFieldVal('sport', r.src_port, true);
  3770. setFwFieldVal('dport', r.dst_port, true);
  3771. setFwFieldVal('anyport', r.any_port, true);
  3772. setFwFieldVal('iniface', r.in_interface, true);
  3773. setFwFieldVal('outiface', r.out_interface, true);
  3774. setFwFieldVal('inifacelist', r.in_interface_list, true);
  3775. setFwFieldVal('outifacelist', r.out_interface_list, true);
  3776. setFwFieldVal('pktmark', r.packet_mark, true);
  3777. setFwFieldVal('connmark', r.connection_mark, true);
  3778. setFwFieldVal('routingmark', r.routing_mark, true);
  3779. setFwFieldVal('conntype', r.connection_type, false);
  3780. const states = r.connection_state || [];
  3781. if (states.length > 0) {
  3782. toggleFwField('cs', true);
  3783. document.getElementById('filter-modal-cs-established').checked = states.includes('established');
  3784. document.getElementById('filter-modal-cs-related').checked = states.includes('related');
  3785. document.getElementById('filter-modal-cs-new').checked = states.includes('new');
  3786. document.getElementById('filter-modal-cs-invalid').checked = states.includes('invalid');
  3787. document.getElementById('filter-modal-cs-untracked').checked = states.includes('untracked');
  3788. } else {
  3789. toggleFwField('cs', false);
  3790. }
  3791. const natStates = r.connection_nat_state || [];
  3792. if (natStates.length > 0) {
  3793. toggleFwField('natstate', true);
  3794. document.getElementById('filter-modal-nat-srcnat').checked = natStates.includes('srcnat');
  3795. document.getElementById('filter-modal-nat-dstnat').checked = natStates.includes('dstnat');
  3796. } else {
  3797. toggleFwField('natstate', false);
  3798. }
  3799. // Advanced tab fields
  3800. setFwFieldVal('layer7', r.layer7_protocol, false);
  3801. setFwFieldVal('content', r.content, false);
  3802. setFwFieldVal('connbytes', r.connection_bytes, false);
  3803. setFwFieldVal('connrate', r.connection_rate, false);
  3804. setFwFieldVal('pcc', r.pcc, false);
  3805. setFwFieldVal('srcmac', r.src_mac_address, true);
  3806. setFwFieldVal('outbridgeport', r.out_bridge_port, false);
  3807. setFwFieldVal('inbridgeport', r.in_bridge_port, false);
  3808. setFwFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  3809. setFwFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  3810. setFwFieldVal('ipsec', r.ipsec_policy, false);
  3811. setFwFieldVal('tlshost', r.tls_host, false);
  3812. setFwFieldVal('ingresspriority', r.ingress_priority, false);
  3813. setFwFieldVal('priority', r.priority, false);
  3814. setFwFieldVal('dscp', r.dscp, false);
  3815. setFwFieldVal('tcpmss', r.tcp_mss, false);
  3816. if (r.tos) {
  3817. const tosEl = document.getElementById('fw-val-tos');
  3818. if (tosEl) tosEl.value = r.tos;
  3819. }
  3820. setFwFieldVal('pktsize', r.packet_size, false);
  3821. setFwFieldVal('random', r.random, false);
  3822. setFwFieldVal('tcpflags', r.tcp_flags, false);
  3823. setFwFieldVal('icmpoptions', r.icmp_options, false);
  3824. setFwFieldVal('ipv4options', r.ipv4_options, false);
  3825. setFwFieldVal('ttl', r.ttl, false);
  3826. // Extra tab fields
  3827. setFwFieldVal('time', r.time, false);
  3828. if (r.days) {
  3829. toggleFwField('days', true);
  3830. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3831. const chk = document.getElementById(`fw-day-${d}`);
  3832. if (chk) chk.checked = r.days.includes(d);
  3833. });
  3834. } else {
  3835. toggleFwField('days', false);
  3836. }
  3837. setFwFieldVal('limit', r.limit, false);
  3838. setFwFieldVal('dstlimit', r.dst_limit, false);
  3839. setFwFieldVal('psd', r.psd, false);
  3840. // Action fields
  3841. if (r.reject_with) {
  3842. const rwEl = document.getElementById('filter-modal-rejectwith');
  3843. if (rwEl) rwEl.value = r.reject_with;
  3844. }
  3845. if (r.jump_target) {
  3846. const jtEl = document.getElementById('filter-modal-jumptarget');
  3847. if (jtEl) jtEl.value = r.jump_target;
  3848. }
  3849. if (r.address_list) {
  3850. const alEl = document.getElementById('filter-modal-action-addrlist');
  3851. if (alEl) alEl.value = r.address_list;
  3852. }
  3853. if (r.address_list_timeout) {
  3854. const toEl = document.getElementById('filter-modal-action-timeout');
  3855. if (toEl) toEl.value = r.address_list_timeout;
  3856. }
  3857. setFwFieldVal('logprefix', r.log_prefix, false);
  3858. // Statistics
  3859. const bEl = document.getElementById('fw-stat-bytes');
  3860. const pEl = document.getElementById('fw-stat-packets');
  3861. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  3862. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  3863. state.fwLastBytes = r.bytes || 0;
  3864. state.fwLastPackets = r.packets || 0;
  3865. state.fwLastTimestamp = Date.now();
  3866. state.fwStatRateHistory = new Array(30).fill(0);
  3867. state.fwStatPktHistory = new Array(30).fill(0);
  3868. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  3869. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  3870. toggleFilterActionFields();
  3871. document.getElementById('filter-modal').classList.remove('hidden');
  3872. }
  3873. function closeFilterModal() {
  3874. stopFwStatPolling();
  3875. document.getElementById('filter-modal').classList.add('hidden');
  3876. }
  3877. function toggleFilterActionFields() {
  3878. const act = document.getElementById('filter-modal-action')?.value || 'accept';
  3879. const rejectBox = document.getElementById('filter-action-reject-box');
  3880. const jumpBox = document.getElementById('filter-action-jump-box');
  3881. const addrBox = document.getElementById('filter-action-addrlist-box');
  3882. if (rejectBox) {
  3883. if (act === 'reject') rejectBox.classList.remove('hidden');
  3884. else rejectBox.classList.add('hidden');
  3885. }
  3886. if (jumpBox) {
  3887. if (act === 'jump') jumpBox.classList.remove('hidden');
  3888. else jumpBox.classList.add('hidden');
  3889. }
  3890. if (addrBox) {
  3891. if (act === 'add-dst-to-address-list' || act === 'add-src-to-address-list' || act.includes('address-list') || act.includes('address list')) {
  3892. addrBox.classList.remove('hidden');
  3893. } else {
  3894. addrBox.classList.add('hidden');
  3895. }
  3896. }
  3897. if (act === 'log') {
  3898. const logEl = document.getElementById('filter-modal-log');
  3899. if (logEl) logEl.checked = true;
  3900. toggleFwField('logprefix', true);
  3901. }
  3902. }
  3903. function toggleFwLogPrefix() {
  3904. const isLog = document.getElementById('filter-modal-log')?.checked;
  3905. toggleFwField('logprefix', !!isLog);
  3906. }
  3907. function copyFilterRule() {
  3908. document.getElementById('filter-modal-id').value = '';
  3909. const badge = document.getElementById('fw-modal-badge');
  3910. if (badge) badge.innerText = 'New...';
  3911. showToast('Rule Cloned', 'Ready to save as a new rule copy', 'info');
  3912. }
  3913. function resetCurrentRuleCounters() {
  3914. state.fwStatRateHistory = new Array(30).fill(0);
  3915. state.fwStatPktHistory = new Array(30).fill(0);
  3916. state.fwLastBytes = 0;
  3917. state.fwLastPackets = 0;
  3918. state.fwLastTimestamp = Date.now();
  3919. const bEl = document.getElementById('fw-stat-bytes');
  3920. const pEl = document.getElementById('fw-stat-packets');
  3921. const rEl = document.getElementById('fw-stat-rate');
  3922. const prEl = document.getElementById('fw-stat-pktrate');
  3923. if (bEl) bEl.value = '0 B';
  3924. if (pEl) pEl.value = '0';
  3925. if (rEl) rEl.value = '0 bps';
  3926. if (prEl) prEl.value = '0 p/s';
  3927. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  3928. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  3929. showToast('Counters Reset', 'Rule counter display reset to 0', 'info');
  3930. }
  3931. async function resetAllFwCounters() {
  3932. try {
  3933. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  3934. if (res.ok) {
  3935. resetCurrentRuleCounters();
  3936. showToast('All Counters Reset', 'All firewall counters zeroed', 'success');
  3937. loadFirewall(false);
  3938. }
  3939. } catch (err) {
  3940. showToast('Error', err.message, 'error');
  3941. }
  3942. }
  3943. async function applyFilterRule(closeAfter = false) {
  3944. const id = document.getElementById('filter-modal-id').value;
  3945. const chain = document.getElementById('filter-modal-chain').value;
  3946. const action = document.getElementById('filter-modal-action').value;
  3947. const comment = document.getElementById('filter-modal-comment').value.trim();
  3948. const enabled = document.getElementById('filter-modal-enabled').checked;
  3949. const src = getFwFieldVal('src', true);
  3950. const dst = getFwFieldVal('dst', true);
  3951. const srclist = getFwFieldVal('srclist', true);
  3952. const dstlist = getFwFieldVal('dstlist', true);
  3953. const srcgeo = getFwFieldVal('srcgeo', true);
  3954. const dstgeo = getFwFieldVal('dstgeo', true);
  3955. const proto = getFwFieldVal('proto', true);
  3956. const sport = getFwFieldVal('sport', true);
  3957. const dport = getFwFieldVal('dport', true);
  3958. const anyport = getFwFieldVal('anyport', true);
  3959. const iniface = getFwFieldVal('iniface', true);
  3960. const outiface = getFwFieldVal('outiface', true);
  3961. const inifacelist = getFwFieldVal('inifacelist', true);
  3962. const outifacelist = getFwFieldVal('outifacelist', true);
  3963. const pktmark = getFwFieldVal('pktmark', true);
  3964. const connmark = getFwFieldVal('connmark', true);
  3965. const routingmark = getFwFieldVal('routingmark', true);
  3966. const conntype = getFwFieldVal('conntype', false);
  3967. const states = [];
  3968. const csBox = document.getElementById('fw-field-cs');
  3969. if (csBox && !csBox.classList.contains('hidden')) {
  3970. if (document.getElementById('filter-modal-cs-established')?.checked) states.push('established');
  3971. if (document.getElementById('filter-modal-cs-related')?.checked) states.push('related');
  3972. if (document.getElementById('filter-modal-cs-new')?.checked) states.push('new');
  3973. if (document.getElementById('filter-modal-cs-invalid')?.checked) states.push('invalid');
  3974. if (document.getElementById('filter-modal-cs-untracked')?.checked) states.push('untracked');
  3975. }
  3976. const natStates = [];
  3977. const natBox = document.getElementById('fw-field-natstate');
  3978. if (natBox && !natBox.classList.contains('hidden')) {
  3979. if (document.getElementById('filter-modal-nat-srcnat')?.checked) natStates.push('srcnat');
  3980. if (document.getElementById('filter-modal-nat-dstnat')?.checked) natStates.push('dstnat');
  3981. }
  3982. const payload = {
  3983. id,
  3984. chain,
  3985. action,
  3986. protocol: proto || 'all',
  3987. src_address: src,
  3988. dst_address: dst,
  3989. src_port: sport,
  3990. dst_port: dport,
  3991. any_port: anyport,
  3992. in_interface: iniface,
  3993. out_interface: outiface,
  3994. in_interface_list: inifacelist,
  3995. out_interface_list: outifacelist,
  3996. packet_mark: pktmark,
  3997. connection_mark: connmark,
  3998. routing_mark: routingmark,
  3999. connection_type: conntype,
  4000. connection_state: states,
  4001. connection_nat_state: natStates,
  4002. src_address_list: srclist,
  4003. dst_address_list: dstlist,
  4004. src_geoip: srcgeo,
  4005. dst_geoip: dstgeo,
  4006. comment,
  4007. disabled: !enabled,
  4008. // Advanced tab
  4009. layer7_protocol: getFwFieldVal('layer7', false),
  4010. content: getFwFieldVal('content', false),
  4011. connection_bytes: getFwFieldVal('connbytes', false),
  4012. connection_rate: getFwFieldVal('connrate', false),
  4013. pcc: getFwFieldVal('pcc', false),
  4014. src_mac_address: getFwFieldVal('srcmac', true),
  4015. out_bridge_port: getFwFieldVal('outbridgeport', false),
  4016. in_bridge_port: getFwFieldVal('inbridgeport', false),
  4017. in_bridge_port_list: getFwFieldVal('inbridgeportlist', false),
  4018. out_bridge_port_list: getFwFieldVal('outbridgeportlist', false),
  4019. ipsec_policy: getFwFieldVal('ipsec', false),
  4020. tls_host: getFwFieldVal('tlshost', false),
  4021. ingress_priority: getFwFieldVal('ingresspriority', false),
  4022. priority: getFwFieldVal('priority', false),
  4023. dscp: getFwFieldVal('dscp', false),
  4024. tcp_mss: getFwFieldVal('tcpmss', false),
  4025. tos: document.getElementById('fw-val-tos')?.value || '',
  4026. packet_size: getFwFieldVal('pktsize', false),
  4027. random: getFwFieldVal('random', false),
  4028. tcp_flags: getFwFieldVal('tcpflags', false),
  4029. icmp_options: getFwFieldVal('icmpoptions', false),
  4030. ipv4_options: getFwFieldVal('ipv4options', false),
  4031. ttl: getFwFieldVal('ttl', false),
  4032. // Extra tab
  4033. time: getFwFieldVal('time', false),
  4034. limit: getFwFieldVal('limit', false),
  4035. dst_limit: getFwFieldVal('dstlimit', false),
  4036. psd: getFwFieldVal('psd', false),
  4037. // Action tab
  4038. reject_with: action === 'reject' ? (document.getElementById('filter-modal-rejectwith')?.value || '') : '',
  4039. jump_target: action === 'jump' ? (document.getElementById('filter-modal-jumptarget')?.value || '') : '',
  4040. address_list: action.startsWith('add-') ? (document.getElementById('filter-modal-action-addrlist')?.value || '') : '',
  4041. address_list_timeout: action.startsWith('add-') ? (document.getElementById('filter-modal-action-timeout')?.value || '') : '',
  4042. log: document.getElementById('filter-modal-log')?.checked || false,
  4043. log_prefix: getFwFieldVal('logprefix', false)
  4044. };
  4045. try {
  4046. const res = await fetch(`${API_BASE}/firewall/filter`, {
  4047. method: 'POST',
  4048. headers: { 'Content-Type': 'application/json' },
  4049. body: JSON.stringify(payload)
  4050. });
  4051. if (res.ok) {
  4052. const data = await res.json();
  4053. showToast('Filter Rule Saved', 'Rule applied successfully to firewall', 'success');
  4054. loadFirewall(false);
  4055. if (closeAfter) {
  4056. closeFilterModal();
  4057. } else {
  4058. if (data.id) {
  4059. document.getElementById('filter-modal-id').value = data.id;
  4060. const badge = document.getElementById('fw-modal-badge');
  4061. if (badge) badge.innerText = `#${data.id}`;
  4062. }
  4063. }
  4064. } else {
  4065. const err = await res.json();
  4066. showToast('Error', err.message || 'Failed to save rule', 'error');
  4067. }
  4068. } catch (err) {
  4069. showToast('Error', err.message, 'error');
  4070. }
  4071. }
  4072. function submitSaveFilterRule(e) {
  4073. if (e && e.preventDefault) e.preventDefault();
  4074. return applyFilterRule(true);
  4075. }
  4076. function startFwStatPolling() {
  4077. stopFwStatPolling();
  4078. pollRuleStats();
  4079. state.fwStatInterval = setInterval(pollRuleStats, 1000);
  4080. }
  4081. function stopFwStatPolling() {
  4082. if (state.fwStatInterval) {
  4083. clearInterval(state.fwStatInterval);
  4084. state.fwStatInterval = null;
  4085. }
  4086. }
  4087. async function pollRuleStats() {
  4088. const id = document.getElementById('filter-modal-id')?.value;
  4089. if (!id) {
  4090. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory || new Array(30).fill(0), 'bps', 'fw-stat-legend-rate');
  4091. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory || new Array(30).fill(0), 'p/s', 'fw-stat-legend-pktrate');
  4092. return;
  4093. }
  4094. try {
  4095. const res = await fetch(`${API_BASE}/firewall/filter`);
  4096. if (!res.ok) return;
  4097. const rules = await res.json();
  4098. const r = rules.find(x => x.id === id);
  4099. if (!r) return;
  4100. const now = Date.now();
  4101. const dt = Math.max(0.2, (now - (state.fwLastTimestamp || now)) / 1000);
  4102. state.fwLastTimestamp = now;
  4103. const curBytes = r.bytes || 0;
  4104. const curPackets = r.packets || 0;
  4105. const deltaBytes = Math.max(0, curBytes - (state.fwLastBytes || curBytes));
  4106. const deltaPkts = Math.max(0, curPackets - (state.fwLastPackets || curPackets));
  4107. state.fwLastBytes = curBytes;
  4108. state.fwLastPackets = curPackets;
  4109. const rateBps = Math.round((deltaBytes * 8) / dt);
  4110. const ratePkt = Math.round(deltaPkts / dt);
  4111. if (!state.fwStatRateHistory) state.fwStatRateHistory = new Array(30).fill(0);
  4112. if (!state.fwStatPktHistory) state.fwStatPktHistory = new Array(30).fill(0);
  4113. state.fwStatRateHistory.push(rateBps);
  4114. if (state.fwStatRateHistory.length > 30) state.fwStatRateHistory.shift();
  4115. state.fwStatPktHistory.push(ratePkt);
  4116. if (state.fwStatPktHistory.length > 30) state.fwStatPktHistory.shift();
  4117. const bEl = document.getElementById('fw-stat-bytes');
  4118. const pEl = document.getElementById('fw-stat-packets');
  4119. const rEl = document.getElementById('fw-stat-rate');
  4120. const prEl = document.getElementById('fw-stat-pktrate');
  4121. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  4122. if (pEl) pEl.value = curPackets.toLocaleString();
  4123. if (rEl) rEl.value = formatBps(rateBps);
  4124. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  4125. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  4126. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  4127. } catch (e) {
  4128. console.error('Error polling rule stats', e);
  4129. }
  4130. }
  4131. function formatBps(bps) {
  4132. if (bps >= 1000000000) return (bps / 1000000000).toFixed(1) + ' Gbps';
  4133. if (bps >= 1000000) return (bps / 1000000).toFixed(1) + ' Mbps';
  4134. if (bps >= 1000) return (bps / 1000).toFixed(1) + ' kbps';
  4135. return bps + ' bps';
  4136. }
  4137. function renderFwSparkline(svgId, dataArray, unit, legendId) {
  4138. const svg = document.getElementById(svgId);
  4139. if (!svg) return;
  4140. const w = 500;
  4141. const h = 100;
  4142. const paddingRight = 45;
  4143. const graphWidth = w - paddingRight;
  4144. const maxVal = Math.max(5, ...dataArray);
  4145. const currentVal = dataArray[dataArray.length - 1] || 0;
  4146. const leg = document.getElementById(legendId);
  4147. if (leg) {
  4148. leg.innerText = unit === 'bps' ? formatBps(currentVal) : `${currentVal.toLocaleString()} p/s`;
  4149. }
  4150. let gridLines = '';
  4151. for (let i = 0; i <= 5; i++) {
  4152. const y = 8 + (i * (h - 18) / 5);
  4153. const valAtLevel = Math.round(maxVal * (5 - i) / 5);
  4154. const label = unit === 'bps' ? formatBps(valAtLevel) : `${valAtLevel} p/s`;
  4155. gridLines += `
  4156. <line x1="0" y1="${y.toFixed(1)}" x2="${graphWidth}" y2="${y.toFixed(1)}" stroke="#1e2c3e" stroke-width="1" />
  4157. <text x="${w - 2}" y="${(y + 3).toFixed(1)}" fill="#64748b" font-size="9" font-family="monospace" text-anchor="end">${label}</text>
  4158. `;
  4159. }
  4160. const step = graphWidth / (dataArray.length - 1);
  4161. const points = dataArray.map((val, idx) => {
  4162. const x = idx * step;
  4163. const y = (h - 10) - (val / maxVal) * (h - 20);
  4164. return `${x.toFixed(1)},${y.toFixed(1)}`;
  4165. });
  4166. const polylineStr = points.join(' ');
  4167. const areaPath = `M 0,${h - 10} L ${polylineStr} L ${graphWidth},${h - 10} Z`;
  4168. svg.innerHTML = `
  4169. ${gridLines}
  4170. <path d="${areaPath}" fill="rgba(14, 165, 233, 0.12)" />
  4171. <polyline fill="none" stroke="#38bdf8" stroke-width="1.8" stroke-linejoin="round" points="${polylineStr}" />
  4172. <circle cx="${graphWidth}" cy="${points[points.length - 1].split(',')[1]}" r="3" fill="#38bdf8" />
  4173. `;
  4174. }
  4175. async function moveFilterRule(id, dir) {
  4176. try {
  4177. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/move`, {
  4178. method: 'POST',
  4179. headers: { 'Content-Type': 'application/json' },
  4180. body: JSON.stringify({ direction: dir })
  4181. });
  4182. if (res.ok) loadFirewall(false);
  4183. } catch (err) {
  4184. showToast('Error', err.message, 'error');
  4185. }
  4186. }
  4187. async function toggleFilterRuleState(id, disabled) {
  4188. try {
  4189. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/state`, {
  4190. method: 'POST',
  4191. headers: { 'Content-Type': 'application/json' },
  4192. body: JSON.stringify({ disabled })
  4193. });
  4194. if (res.ok) loadFirewall(false);
  4195. } catch (err) {
  4196. showToast('Error', err.message, 'error');
  4197. }
  4198. }
  4199. async function deleteFilterRule(id) {
  4200. if (!confirm('Are you sure you want to delete this filter rule?')) return;
  4201. try {
  4202. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4203. if (res.ok) {
  4204. showToast('Deleted', 'Filter rule removed', 'success');
  4205. loadFirewall(false);
  4206. }
  4207. } catch (err) {
  4208. showToast('Error', err.message, 'error');
  4209. }
  4210. }
  4211. // ----------------- NAT Rules -----------------
  4212. function renderNATRules() {
  4213. const chainFilter = document.getElementById('nat-filter-chain')?.value || '';
  4214. const tbody = document.getElementById('nat-table-body');
  4215. const empty = document.getElementById('nat-empty');
  4216. if (!tbody) return;
  4217. tbody.innerHTML = '';
  4218. const rules = (state.natRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  4219. document.getElementById('nat-count-badge').innerText = `${rules.length} Rules`;
  4220. if (rules.length === 0) {
  4221. empty?.classList.remove('hidden');
  4222. return;
  4223. }
  4224. empty?.classList.add('hidden');
  4225. rules.forEach((r, idx) => {
  4226. const tr = document.createElement('tr');
  4227. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  4228. let toTarget = '-';
  4229. if (r.action === 'jump') {
  4230. toTarget = `<span class="text-yellow-300 font-mono font-bold">&rarr; ${r.jump_target || '-'}</span>`;
  4231. } else if (r.action.includes('address-list') || r.action.includes('address list')) {
  4232. toTarget = `<span class="text-emerald-300 font-mono font-bold">&rarr; ${r.address_list || '-'}</span>`;
  4233. } else if (r.action === 'redirect') {
  4234. toTarget = `<span class="text-amber-300 font-mono font-bold">ports:${r.to_ports || 'all'}</span>`;
  4235. } else if (r.action === 'masquerade') {
  4236. 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>`;
  4237. } else if (r.action === 'log') {
  4238. toTarget = `<span class="text-slate-400 font-mono font-bold">${r.log_prefix || 'log'}</span>`;
  4239. } else {
  4240. const parts = [r.to_addresses, r.to_ports].filter(Boolean);
  4241. toTarget = parts.length ? `<span class="text-amber-300 font-mono font-bold">${parts.join(':')}</span>` : '-';
  4242. }
  4243. const ifaces = [r.out_interface ? 'out:' + r.out_interface : '', r.in_interface ? 'in:' + r.in_interface : ''].filter(Boolean).join(' ');
  4244. tr.innerHTML = `
  4245. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  4246. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  4247. <td class="py-2.5 px-3 font-bold text-amber-400">${r.chain}</td>
  4248. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  4249. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  4250. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}${r.dst_port ? ':' + r.dst_port : ''}</td>
  4251. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  4252. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  4253. <td class="py-2.5 px-3 font-mono text-xs">${toTarget}</td>
  4254. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  4255. <span class="text-slate-300" id="nat-pkts-${r.id}">${(r.packets || 0).toLocaleString()}p</span> /
  4256. <span class="text-slate-500" id="nat-bytes-${r.id}">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  4257. </td>
  4258. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  4259. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  4260. <button onclick="moveNATRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  4261. <button onclick="moveNATRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  4262. <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>
  4263. <button onclick="openEditNATModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  4264. <button onclick="deleteNATRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  4265. </td>
  4266. `;
  4267. tbody.appendChild(tr);
  4268. });
  4269. }
  4270. // ==================== FIREWALL NAT MODAL (ROUTEROS WEBFIG / WINBOX V4) ====================
  4271. function switchNATRuleTab(tab) {
  4272. state.activeNATRuleTab = tab;
  4273. document.querySelectorAll('.nat-rule-tab-btn').forEach(btn => {
  4274. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  4275. btn.classList.add('text-slate-400', 'border-transparent');
  4276. });
  4277. const activeBtn = document.getElementById(`nat-tab-btn-${tab}`);
  4278. if (activeBtn) {
  4279. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  4280. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  4281. }
  4282. document.querySelectorAll('.nat-rule-pane').forEach(p => p.classList.add('hidden'));
  4283. const activePane = document.getElementById(`nat-pane-${tab}`);
  4284. if (activePane) activePane.classList.remove('hidden');
  4285. if (tab === 'statistics') {
  4286. startNATStatPolling();
  4287. } else {
  4288. stopNATStatPolling();
  4289. }
  4290. }
  4291. function toggleNATField(fieldKey, expand) {
  4292. const plusBtn = document.getElementById(`nat-plus-${fieldKey}`);
  4293. const fieldBox = document.getElementById(`nat-field-${fieldKey}`);
  4294. if (!plusBtn || !fieldBox) return;
  4295. if (expand) {
  4296. plusBtn.classList.add('hidden');
  4297. fieldBox.classList.remove('hidden');
  4298. const valInput = document.getElementById(`nat-val-${fieldKey}`);
  4299. if (valInput) valInput.focus();
  4300. } else {
  4301. fieldBox.classList.add('hidden');
  4302. plusBtn.classList.remove('hidden');
  4303. const valInput = document.getElementById(`nat-val-${fieldKey}`);
  4304. if (valInput) {
  4305. if (valInput.tagName === 'SELECT') {
  4306. valInput.selectedIndex = 0;
  4307. } else {
  4308. valInput.value = '';
  4309. }
  4310. }
  4311. const invInput = document.getElementById(`nat-inv-${fieldKey}`);
  4312. if (invInput) invInput.checked = false;
  4313. if (fieldKey === 'days') {
  4314. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  4315. const el = document.getElementById(`nat-day-${d}`);
  4316. if (el) el.checked = true;
  4317. });
  4318. }
  4319. }
  4320. }
  4321. function setNATFieldVal(fieldKey, value, hasInvert = false) {
  4322. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  4323. toggleNATField(fieldKey, true);
  4324. let strVal = String(value);
  4325. if (hasInvert) {
  4326. const inv = strVal.startsWith('!');
  4327. if (inv) strVal = strVal.slice(1);
  4328. const invEl = document.getElementById(`nat-inv-${fieldKey}`);
  4329. if (invEl) invEl.checked = inv;
  4330. }
  4331. const valEl = document.getElementById(`nat-val-${fieldKey}`);
  4332. if (valEl) valEl.value = strVal;
  4333. } else {
  4334. toggleNATField(fieldKey, false);
  4335. }
  4336. }
  4337. function getNATFieldVal(fieldKey, hasInvert = false) {
  4338. const fieldBox = document.getElementById(`nat-field-${fieldKey}`);
  4339. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  4340. const valEl = document.getElementById(`nat-val-${fieldKey}`);
  4341. let v = valEl ? valEl.value.trim() : '';
  4342. if (!v) return '';
  4343. if (hasInvert) {
  4344. const invEl = document.getElementById(`nat-inv-${fieldKey}`);
  4345. if (invEl && invEl.checked) {
  4346. v = '!' + v.replace(/^!/, '');
  4347. }
  4348. }
  4349. return v;
  4350. }
  4351. function toggleMaximizeNATModal() {
  4352. const win = document.getElementById('nat-modal-window');
  4353. if (!win) return;
  4354. if (win.classList.contains('max-w-[720px]')) {
  4355. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  4356. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  4357. } else {
  4358. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  4359. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  4360. }
  4361. }
  4362. function handleNATChainChange() {
  4363. const ch = document.getElementById('nat-modal-chain')?.value || 'srcnat';
  4364. const actSel = document.getElementById('nat-modal-action');
  4365. if (actSel) {
  4366. if (ch === 'srcnat' && (actSel.value === 'dst-nat' || actSel.value === 'redirect')) {
  4367. actSel.value = 'masquerade';
  4368. } else if (ch === 'dstnat' && (actSel.value === 'masquerade' || actSel.value === 'src-nat')) {
  4369. actSel.value = 'dst-nat';
  4370. }
  4371. }
  4372. toggleNATActionFields();
  4373. }
  4374. function toggleNATActionFields() {
  4375. const act = document.getElementById('nat-modal-action')?.value || 'masquerade';
  4376. const rowAddr = document.getElementById('nat-row-toaddr');
  4377. const rowPort = document.getElementById('nat-row-toport');
  4378. const jumpBox = document.getElementById('nat-action-jump-box');
  4379. const addrBox = document.getElementById('nat-action-addrlist-box');
  4380. // Hide all dynamic rows first
  4381. if (rowAddr) rowAddr.classList.add('hidden');
  4382. if (rowPort) rowPort.classList.add('hidden');
  4383. if (jumpBox) jumpBox.classList.add('hidden');
  4384. if (addrBox) addrBox.classList.add('hidden');
  4385. if (['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat'].includes(act)) {
  4386. if (rowAddr) rowAddr.classList.remove('hidden');
  4387. if (rowPort) rowPort.classList.remove('hidden');
  4388. } else if (act === 'redirect' || act === 'masquerade') {
  4389. if (rowPort) rowPort.classList.remove('hidden');
  4390. } else if (act === 'jump') {
  4391. if (jumpBox) jumpBox.classList.remove('hidden');
  4392. } else if (act.includes('address-list') || act.includes('address list')) {
  4393. if (addrBox) addrBox.classList.remove('hidden');
  4394. }
  4395. if (act === 'log') {
  4396. const logEl = document.getElementById('nat-modal-log');
  4397. if (logEl) logEl.checked = true;
  4398. toggleNATField('logprefix', true);
  4399. }
  4400. }
  4401. function toggleNATLogPrefix() {
  4402. const isLog = document.getElementById('nat-modal-log')?.checked;
  4403. toggleNATField('logprefix', !!isLog);
  4404. }
  4405. function openAddNATModal() {
  4406. switchNATRuleTab('general');
  4407. const badge = document.getElementById('nat-modal-badge');
  4408. if (badge) badge.innerText = 'New...';
  4409. document.getElementById('nat-modal-id').value = '';
  4410. document.getElementById('nat-modal-enabled').checked = true;
  4411. document.getElementById('nat-modal-comment').value = '';
  4412. document.getElementById('nat-modal-chain').value = 'srcnat';
  4413. document.getElementById('nat-modal-action').value = 'masquerade';
  4414. document.getElementById('nat-modal-toaddr').value = '';
  4415. document.getElementById('nat-modal-toport').value = '';
  4416. document.getElementById('nat-modal-log').checked = false;
  4417. populateInterfaceSelect('nat-val-iniface');
  4418. populateInterfaceSelect('nat-val-outiface');
  4419. populateAddressListSelect('nat-val-srclist');
  4420. populateAddressListSelect('nat-val-dstlist');
  4421. populateGeoIPSelect('nat-val-srcgeo');
  4422. populateGeoIPSelect('nat-val-dstgeo');
  4423. const allFieldKeys = [
  4424. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  4425. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  4426. 'routingmark', 'conntype',
  4427. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  4428. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  4429. 'ipsec', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  4430. 'pktsize', 'random', 'icmpoptions', 'ipv4options', 'ttl',
  4431. 'time', 'days', 'limit', 'dstlimit', 'psd', 'logprefix'
  4432. ];
  4433. allFieldKeys.forEach(k => toggleNATField(k, false));
  4434. resetCurrentNATRuleCounters();
  4435. toggleNATActionFields();
  4436. document.getElementById('nat-modal').classList.remove('hidden');
  4437. }
  4438. function openEditNATModal(id) {
  4439. const r = (state.natRules || []).find(rule => rule.id === id);
  4440. if (!r) return;
  4441. switchNATRuleTab('general');
  4442. const badge = document.getElementById('nat-modal-badge');
  4443. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  4444. document.getElementById('nat-modal-id').value = r.id;
  4445. document.getElementById('nat-modal-enabled').checked = !r.disabled;
  4446. document.getElementById('nat-modal-comment').value = r.comment || '';
  4447. document.getElementById('nat-modal-chain').value = r.chain || 'srcnat';
  4448. document.getElementById('nat-modal-action').value = r.action || 'masquerade';
  4449. document.getElementById('nat-modal-toaddr').value = r.to_addresses || '';
  4450. document.getElementById('nat-modal-toport').value = r.to_ports || '';
  4451. document.getElementById('nat-modal-log').checked = !!r.log;
  4452. populateInterfaceSelect('nat-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  4453. populateInterfaceSelect('nat-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  4454. populateAddressListSelect('nat-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  4455. populateAddressListSelect('nat-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  4456. populateGeoIPSelect('nat-val-srcgeo', r.src_geoip || '');
  4457. populateGeoIPSelect('nat-val-dstgeo', r.dst_geoip || '');
  4458. setNATFieldVal('src', r.src_address, true);
  4459. setNATFieldVal('dst', r.dst_address, true);
  4460. setNATFieldVal('srclist', r.src_address_list, true);
  4461. setNATFieldVal('dstlist', r.dst_address_list, true);
  4462. setNATFieldVal('srcgeo', r.src_geoip, true);
  4463. setNATFieldVal('dstgeo', r.dst_geoip, true);
  4464. if (r.protocol && r.protocol !== 'all') {
  4465. setNATFieldVal('proto', r.protocol, true);
  4466. } else {
  4467. toggleNATField('proto', false);
  4468. }
  4469. setNATFieldVal('sport', r.src_port, true);
  4470. setNATFieldVal('dport', r.dst_port, true);
  4471. setNATFieldVal('anyport', r.any_port, true);
  4472. setNATFieldVal('iniface', r.in_interface, true);
  4473. setNATFieldVal('outiface', r.out_interface, true);
  4474. setNATFieldVal('inifacelist', r.in_interface_list, true);
  4475. setNATFieldVal('outifacelist', r.out_interface_list, true);
  4476. setNATFieldVal('pktmark', r.packet_mark, true);
  4477. setNATFieldVal('connmark', r.connection_mark, true);
  4478. setNATFieldVal('routingmark', r.routing_mark, true);
  4479. setNATFieldVal('conntype', r.connection_type, false);
  4480. // Advanced tab fields
  4481. setNATFieldVal('layer7', r.layer7_protocol, false);
  4482. setNATFieldVal('content', r.content, false);
  4483. setNATFieldVal('connbytes', r.connection_bytes, false);
  4484. setNATFieldVal('connrate', r.connection_rate, false);
  4485. setNATFieldVal('pcc', r.pcc, false);
  4486. setNATFieldVal('srcmac', r.src_mac_address, true);
  4487. setNATFieldVal('outbridgeport', r.out_bridge_port, false);
  4488. setNATFieldVal('inbridgeport', r.in_bridge_port, false);
  4489. setNATFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  4490. setNATFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  4491. setNATFieldVal('ipsec', r.ipsec_policy, false);
  4492. setNATFieldVal('ingresspriority', r.ingress_priority, false);
  4493. setNATFieldVal('priority', r.priority, false);
  4494. setNATFieldVal('dscp', r.dscp, false);
  4495. setNATFieldVal('tcpmss', r.tcp_mss, false);
  4496. if (r.tos) {
  4497. const tosEl = document.getElementById('nat-val-tos');
  4498. if (tosEl) tosEl.value = r.tos;
  4499. }
  4500. setNATFieldVal('pktsize', r.packet_size, false);
  4501. setNATFieldVal('random', r.random, false);
  4502. setNATFieldVal('icmpoptions', r.icmp_options, false);
  4503. setNATFieldVal('ipv4options', r.ipv4_options, false);
  4504. setNATFieldVal('ttl', r.ttl, false);
  4505. // Extra tab fields
  4506. setNATFieldVal('time', r.time, false);
  4507. if (r.days) {
  4508. toggleNATField('days', true);
  4509. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  4510. const chk = document.getElementById(`nat-day-${d}`);
  4511. if (chk) chk.checked = r.days.includes(d);
  4512. });
  4513. } else {
  4514. toggleNATField('days', false);
  4515. }
  4516. setNATFieldVal('limit', r.limit, false);
  4517. setNATFieldVal('dstlimit', r.dst_limit, false);
  4518. setNATFieldVal('psd', r.psd, false);
  4519. // Action fields
  4520. if (r.jump_target) {
  4521. const jtEl = document.getElementById('nat-modal-jumptarget');
  4522. if (jtEl) jtEl.value = r.jump_target;
  4523. }
  4524. if (r.address_list) {
  4525. const alEl = document.getElementById('nat-modal-action-addrlist');
  4526. if (alEl) alEl.value = r.address_list;
  4527. }
  4528. if (r.address_list_timeout) {
  4529. const toEl = document.getElementById('nat-modal-action-timeout');
  4530. if (toEl) toEl.value = r.address_list_timeout;
  4531. }
  4532. setNATFieldVal('logprefix', r.log_prefix, false);
  4533. // Statistics
  4534. const bEl = document.getElementById('nat-stat-bytes');
  4535. const pEl = document.getElementById('nat-stat-packets');
  4536. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  4537. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  4538. state.natLastBytes = r.bytes || 0;
  4539. state.natLastPackets = r.packets || 0;
  4540. state.natLastTimestamp = Date.now();
  4541. state.natStatRateHistory = new Array(30).fill(0);
  4542. state.natStatPktHistory = new Array(30).fill(0);
  4543. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  4544. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  4545. toggleNATActionFields();
  4546. document.getElementById('nat-modal').classList.remove('hidden');
  4547. }
  4548. function closeNATModal() {
  4549. stopNATStatPolling();
  4550. document.getElementById('nat-modal').classList.add('hidden');
  4551. }
  4552. function copyNATRule() {
  4553. document.getElementById('nat-modal-id').value = '';
  4554. const badge = document.getElementById('nat-modal-badge');
  4555. if (badge) badge.innerText = 'New...';
  4556. showToast('Rule Cloned', 'Ready to save as a new NAT rule copy', 'info');
  4557. }
  4558. function resetCurrentNATRuleCounters() {
  4559. state.natStatRateHistory = new Array(30).fill(0);
  4560. state.natStatPktHistory = new Array(30).fill(0);
  4561. state.natLastBytes = 0;
  4562. state.natLastPackets = 0;
  4563. state.natLastTimestamp = Date.now();
  4564. const bEl = document.getElementById('nat-stat-bytes');
  4565. const pEl = document.getElementById('nat-stat-packets');
  4566. const rEl = document.getElementById('nat-stat-rate');
  4567. const prEl = document.getElementById('nat-stat-pktrate');
  4568. if (bEl) bEl.value = '0 B';
  4569. if (pEl) pEl.value = '0';
  4570. if (rEl) rEl.value = '0 bps';
  4571. if (prEl) prEl.value = '0 p/s';
  4572. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  4573. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  4574. showToast('Counters Reset', 'NAT rule counter display reset to 0', 'info');
  4575. }
  4576. async function applyNATRule(closeAfter = false) {
  4577. const id = document.getElementById('nat-modal-id').value;
  4578. const chain = document.getElementById('nat-modal-chain').value;
  4579. const action = document.getElementById('nat-modal-action').value;
  4580. const comment = document.getElementById('nat-modal-comment').value.trim();
  4581. const enabled = document.getElementById('nat-modal-enabled').checked;
  4582. const src = getNATFieldVal('src', true);
  4583. const dst = getNATFieldVal('dst', true);
  4584. const srclist = getNATFieldVal('srclist', true);
  4585. const dstlist = getNATFieldVal('dstlist', true);
  4586. const srcgeo = getNATFieldVal('srcgeo', true);
  4587. const dstgeo = getNATFieldVal('dstgeo', true);
  4588. const proto = getNATFieldVal('proto', true);
  4589. const sport = getNATFieldVal('sport', true);
  4590. const dport = getNATFieldVal('dport', true);
  4591. const anyport = getNATFieldVal('anyport', true);
  4592. const iniface = getNATFieldVal('iniface', true);
  4593. const outiface = getNATFieldVal('outiface', true);
  4594. const inifacelist = getNATFieldVal('inifacelist', true);
  4595. const outifacelist = getNATFieldVal('outifacelist', true);
  4596. const pktmark = getNATFieldVal('pktmark', true);
  4597. const connmark = getNATFieldVal('connmark', true);
  4598. const routingmark = getNATFieldVal('routingmark', true);
  4599. const conntype = getNATFieldVal('conntype', false);
  4600. const usesAddr = ['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat'].includes(action);
  4601. const usesPort = ['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat', 'redirect', 'masquerade'].includes(action);
  4602. const payload = {
  4603. id,
  4604. chain,
  4605. action,
  4606. to_addresses: usesAddr ? (document.getElementById('nat-modal-toaddr')?.value.trim() || '') : '',
  4607. to_ports: usesPort ? (document.getElementById('nat-modal-toport')?.value.trim() || '') : '',
  4608. protocol: proto || 'all',
  4609. src_address: src,
  4610. dst_address: dst,
  4611. src_port: sport,
  4612. dst_port: dport,
  4613. any_port: anyport,
  4614. in_interface: iniface,
  4615. out_interface: outiface,
  4616. in_interface_list: inifacelist,
  4617. out_interface_list: outifacelist,
  4618. packet_mark: pktmark,
  4619. connection_mark: connmark,
  4620. routing_mark: routingmark,
  4621. connection_type: conntype,
  4622. src_address_list: srclist,
  4623. dst_address_list: dstlist,
  4624. src_geoip: srcgeo,
  4625. dst_geoip: dstgeo,
  4626. comment,
  4627. disabled: !enabled,
  4628. // Advanced tab
  4629. layer7_protocol: getNATFieldVal('layer7', false),
  4630. content: getNATFieldVal('content', false),
  4631. connection_bytes: getNATFieldVal('connbytes', false),
  4632. connection_rate: getNATFieldVal('connrate', false),
  4633. pcc: getNATFieldVal('pcc', false),
  4634. src_mac_address: getNATFieldVal('srcmac', true),
  4635. out_bridge_port: getNATFieldVal('outbridgeport', false),
  4636. in_bridge_port: getNATFieldVal('inbridgeport', false),
  4637. in_bridge_port_list: getNATFieldVal('inbridgeportlist', false),
  4638. out_bridge_port_list: getNATFieldVal('outbridgeportlist', false),
  4639. ipsec_policy: getNATFieldVal('ipsec', false),
  4640. ingress_priority: getNATFieldVal('ingresspriority', false),
  4641. priority: getNATFieldVal('priority', false),
  4642. dscp: getNATFieldVal('dscp', false),
  4643. tcp_mss: getNATFieldVal('tcpmss', false),
  4644. tos: document.getElementById('nat-val-tos')?.value || '',
  4645. packet_size: getNATFieldVal('pktsize', false),
  4646. random: getNATFieldVal('random', false),
  4647. icmp_options: getNATFieldVal('icmpoptions', false),
  4648. ipv4_options: getNATFieldVal('ipv4options', false),
  4649. ttl: getNATFieldVal('ttl', false),
  4650. // Extra tab
  4651. time: getNATFieldVal('time', false),
  4652. limit: getNATFieldVal('limit', false),
  4653. dst_limit: getNATFieldVal('dstlimit', false),
  4654. psd: getNATFieldVal('psd', false),
  4655. // Action tab
  4656. jump_target: action === 'jump' ? (document.getElementById('nat-modal-jumptarget')?.value || '') : '',
  4657. address_list: action.includes('address') ? (document.getElementById('nat-modal-action-addrlist')?.value || '') : '',
  4658. address_list_timeout: action.includes('address') ? (document.getElementById('nat-modal-action-timeout')?.value || '') : '',
  4659. log: document.getElementById('nat-modal-log')?.checked || false,
  4660. log_prefix: getNATFieldVal('logprefix', false)
  4661. };
  4662. try {
  4663. const res = await fetch(`${API_BASE}/firewall/nat`, {
  4664. method: 'POST',
  4665. headers: { 'Content-Type': 'application/json' },
  4666. body: JSON.stringify(payload)
  4667. });
  4668. if (res.ok) {
  4669. const data = await res.json();
  4670. showToast('NAT Rule Saved', 'NAT mapping updated', 'success');
  4671. loadFirewall(false);
  4672. if (closeAfter) {
  4673. closeNATModal();
  4674. } else {
  4675. if (data.id) {
  4676. document.getElementById('nat-modal-id').value = data.id;
  4677. const badge = document.getElementById('nat-modal-badge');
  4678. if (badge) badge.innerText = `#${data.id}`;
  4679. }
  4680. }
  4681. } else {
  4682. const err = await res.json();
  4683. showToast('Error', err.message || 'Failed to save rule', 'error');
  4684. }
  4685. } catch (err) {
  4686. showToast('Error', err.message, 'error');
  4687. }
  4688. }
  4689. function submitSaveNATRule(e) {
  4690. if (e && e.preventDefault) e.preventDefault();
  4691. return applyNATRule(true);
  4692. }
  4693. function startNATStatPolling() {
  4694. stopNATStatPolling();
  4695. pollNATRuleStats();
  4696. state.natStatInterval = setInterval(pollNATRuleStats, 1000);
  4697. }
  4698. function stopNATStatPolling() {
  4699. if (state.natStatInterval) {
  4700. clearInterval(state.natStatInterval);
  4701. state.natStatInterval = null;
  4702. }
  4703. }
  4704. async function pollNATRuleStats() {
  4705. const id = document.getElementById('nat-modal-id')?.value;
  4706. if (!id) {
  4707. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory || new Array(30).fill(0), 'bps', 'nat-stat-legend-rate');
  4708. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory || new Array(30).fill(0), 'p/s', 'nat-stat-legend-pktrate');
  4709. return;
  4710. }
  4711. try {
  4712. const res = await fetch(`${API_BASE}/firewall/nat`);
  4713. if (!res.ok) return;
  4714. const rules = await res.json();
  4715. const r = rules.find(x => x.id === id);
  4716. if (!r) return;
  4717. const now = Date.now();
  4718. const dt = Math.max(0.2, (now - (state.natLastTimestamp || now)) / 1000);
  4719. state.natLastTimestamp = now;
  4720. const curBytes = r.bytes || 0;
  4721. const curPackets = r.packets || 0;
  4722. const deltaBytes = Math.max(0, curBytes - (state.natLastBytes || curBytes));
  4723. const deltaPkts = Math.max(0, curPackets - (state.natLastPackets || curPackets));
  4724. state.natLastBytes = curBytes;
  4725. state.natLastPackets = curPackets;
  4726. const rateBps = Math.round((deltaBytes * 8) / dt);
  4727. const ratePkt = Math.round(deltaPkts / dt);
  4728. if (!state.natStatRateHistory) state.natStatRateHistory = new Array(30).fill(0);
  4729. if (!state.natStatPktHistory) state.natStatPktHistory = new Array(30).fill(0);
  4730. state.natStatRateHistory.push(rateBps);
  4731. if (state.natStatRateHistory.length > 30) state.natStatRateHistory.shift();
  4732. state.natStatPktHistory.push(ratePkt);
  4733. if (state.natStatPktHistory.length > 30) state.natStatPktHistory.shift();
  4734. const bEl = document.getElementById('nat-stat-bytes');
  4735. const pEl = document.getElementById('nat-stat-packets');
  4736. const rEl = document.getElementById('nat-stat-rate');
  4737. const prEl = document.getElementById('nat-stat-pktrate');
  4738. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  4739. if (pEl) pEl.value = curPackets.toLocaleString();
  4740. if (rEl) rEl.value = formatBps(rateBps);
  4741. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  4742. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  4743. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  4744. } catch (e) {
  4745. console.error('Error polling NAT rule stats', e);
  4746. }
  4747. }
  4748. async function moveNATRule(id, dir) {
  4749. try {
  4750. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/move`, {
  4751. method: 'POST',
  4752. headers: { 'Content-Type': 'application/json' },
  4753. body: JSON.stringify({ direction: dir })
  4754. });
  4755. if (res.ok) loadFirewall(false);
  4756. } catch (err) {
  4757. showToast('Error', err.message, 'error');
  4758. }
  4759. }
  4760. async function toggleNATRuleState(id, disabled) {
  4761. try {
  4762. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/state`, {
  4763. method: 'POST',
  4764. headers: { 'Content-Type': 'application/json' },
  4765. body: JSON.stringify({ disabled })
  4766. });
  4767. if (res.ok) loadFirewall(false);
  4768. } catch (err) {
  4769. showToast('Error', err.message, 'error');
  4770. }
  4771. }
  4772. async function deleteNATRule(id) {
  4773. if (!confirm('Are you sure you want to delete this NAT rule?')) return;
  4774. try {
  4775. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4776. if (res.ok) {
  4777. showToast('Deleted', 'NAT rule removed', 'success');
  4778. loadFirewall(false);
  4779. }
  4780. } catch (err) {
  4781. showToast('Error', err.message, 'error');
  4782. }
  4783. }
  4784. // ----------------- Mangle Rules -----------------
  4785. function renderMangleRules() {
  4786. const chainFilter = document.getElementById('mangle-filter-chain')?.value || '';
  4787. const tbody = document.getElementById('mangle-table-body');
  4788. const empty = document.getElementById('mangle-empty');
  4789. if (!tbody) return;
  4790. tbody.innerHTML = '';
  4791. const rules = (state.mangleRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  4792. document.getElementById('mangle-count-badge').innerText = `${rules.length} Rules`;
  4793. if (rules.length === 0) {
  4794. empty?.classList.remove('hidden');
  4795. return;
  4796. }
  4797. empty?.classList.add('hidden');
  4798. rules.forEach((r, idx) => {
  4799. const tr = document.createElement('tr');
  4800. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  4801. let markVal = '<span class="text-slate-500">-</span>';
  4802. if (r.new_connection_mark) markVal = `<span class="text-cyan-300 font-mono font-bold">${r.new_connection_mark}</span>`;
  4803. else if (r.new_routing_mark) markVal = `<span class="text-amber-300 font-mono font-bold">${r.new_routing_mark}</span>`;
  4804. else if (r.new_packet_mark) markVal = `<span class="text-emerald-300 font-mono font-bold">${r.new_packet_mark}</span>`;
  4805. else if (r.new_mss) markVal = `<span class="text-sky-300 font-mono font-bold">mss:${r.new_mss}</span>`;
  4806. else if (r.new_dscp) markVal = `<span class="text-purple-300 font-mono font-bold">dscp:${r.new_dscp}</span>`;
  4807. else if (r.new_ttl) markVal = `<span class="text-blue-300 font-mono font-bold">ttl:${r.new_ttl}</span>`;
  4808. else if (r.new_priority) markVal = `<span class="text-indigo-300 font-mono font-bold">prio:${r.new_priority}</span>`;
  4809. else if (r.route) markVal = `<span class="text-orange-300 font-mono font-bold">route:${r.route}</span>`;
  4810. else if (r.sniff_target) markVal = `<span class="text-pink-300 font-mono font-bold">sniff:${r.sniff_target}</span>`;
  4811. else if (r.action === 'jump') markVal = `<span class="text-yellow-300 font-mono font-bold">&rarr; ${r.jump_target || '-'}</span>`;
  4812. 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>`;
  4813. else if (r.action === 'log') markVal = `<span class="text-slate-400 font-mono font-bold">${r.log_prefix || 'log'}</span>`;
  4814. tr.innerHTML = `
  4815. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  4816. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  4817. <td class="py-2.5 px-3 font-bold text-purple-400">${r.chain}</td>
  4818. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  4819. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  4820. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  4821. <td class="py-2.5 px-3 font-mono text-xs">${markVal}</td>
  4822. <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>
  4823. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  4824. <span class="text-slate-300" id="mangle-pkts-${r.id}">${(r.packets || 0).toLocaleString()}p</span> /
  4825. <span class="text-slate-500" id="mangle-bytes-${r.id}">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  4826. </td>
  4827. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  4828. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  4829. <button onclick="moveMangleRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  4830. <button onclick="moveMangleRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  4831. <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>
  4832. <button onclick="openEditMangleModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  4833. <button onclick="deleteMangleRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  4834. </td>
  4835. `;
  4836. tbody.appendChild(tr);
  4837. });
  4838. }
  4839. // ==================== FIREWALL MANGLE MODAL (ROUTEROS WEBFIG / WINBOX V4) ====================
  4840. function switchMangleRuleTab(tab) {
  4841. state.activeMangleRuleTab = tab;
  4842. document.querySelectorAll('.mangle-rule-tab-btn').forEach(btn => {
  4843. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  4844. btn.classList.add('text-slate-400', 'border-transparent');
  4845. });
  4846. const activeBtn = document.getElementById(`mangle-tab-btn-${tab}`);
  4847. if (activeBtn) {
  4848. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  4849. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  4850. }
  4851. document.querySelectorAll('.mangle-rule-pane').forEach(p => p.classList.add('hidden'));
  4852. const activePane = document.getElementById(`mangle-pane-${tab}`);
  4853. if (activePane) activePane.classList.remove('hidden');
  4854. if (tab === 'statistics') {
  4855. startMangleStatPolling();
  4856. } else {
  4857. stopMangleStatPolling();
  4858. }
  4859. }
  4860. function toggleMangleField(fieldKey, expand) {
  4861. const plusBtn = document.getElementById(`mangle-plus-${fieldKey}`);
  4862. const fieldBox = document.getElementById(`mangle-field-${fieldKey}`);
  4863. if (!plusBtn || !fieldBox) return;
  4864. if (expand) {
  4865. plusBtn.classList.add('hidden');
  4866. fieldBox.classList.remove('hidden');
  4867. const valInput = document.getElementById(`mangle-val-${fieldKey}`);
  4868. if (valInput) valInput.focus();
  4869. } else {
  4870. fieldBox.classList.add('hidden');
  4871. plusBtn.classList.remove('hidden');
  4872. const valInput = document.getElementById(`mangle-val-${fieldKey}`);
  4873. if (valInput) {
  4874. if (valInput.tagName === 'SELECT') {
  4875. valInput.selectedIndex = 0;
  4876. } else {
  4877. valInput.value = '';
  4878. }
  4879. }
  4880. const invInput = document.getElementById(`mangle-inv-${fieldKey}`);
  4881. if (invInput) invInput.checked = false;
  4882. if (fieldKey === 'cs') {
  4883. ['mangle-modal-cs-established', 'mangle-modal-cs-related', 'mangle-modal-cs-new', 'mangle-modal-cs-invalid', 'mangle-modal-cs-untracked'].forEach(id => {
  4884. const el = document.getElementById(id);
  4885. if (el) el.checked = false;
  4886. });
  4887. }
  4888. if (fieldKey === 'natstate') {
  4889. ['mangle-modal-nat-srcnat', 'mangle-modal-nat-dstnat'].forEach(id => {
  4890. const el = document.getElementById(id);
  4891. if (el) el.checked = false;
  4892. });
  4893. }
  4894. }
  4895. }
  4896. function setMangleFieldVal(fieldKey, value, hasInvert = false) {
  4897. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  4898. toggleMangleField(fieldKey, true);
  4899. let strVal = String(value);
  4900. if (hasInvert) {
  4901. const inv = strVal.startsWith('!');
  4902. if (inv) strVal = strVal.slice(1);
  4903. const invEl = document.getElementById(`mangle-inv-${fieldKey}`);
  4904. if (invEl) invEl.checked = inv;
  4905. }
  4906. const valEl = document.getElementById(`mangle-val-${fieldKey}`);
  4907. if (valEl) valEl.value = strVal;
  4908. } else {
  4909. toggleMangleField(fieldKey, false);
  4910. }
  4911. }
  4912. function getMangleFieldVal(fieldKey, hasInvert = false) {
  4913. const fieldBox = document.getElementById(`mangle-field-${fieldKey}`);
  4914. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  4915. const valEl = document.getElementById(`mangle-val-${fieldKey}`);
  4916. let v = valEl ? valEl.value.trim() : '';
  4917. if (!v) return '';
  4918. if (hasInvert) {
  4919. const invEl = document.getElementById(`mangle-inv-${fieldKey}`);
  4920. if (invEl && invEl.checked) {
  4921. v = '!' + v.replace(/^!/, '');
  4922. }
  4923. }
  4924. return v;
  4925. }
  4926. function toggleMaximizeMangleModal() {
  4927. const win = document.getElementById('mangle-modal-window');
  4928. if (!win) return;
  4929. if (win.classList.contains('max-w-[720px]')) {
  4930. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  4931. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  4932. } else {
  4933. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  4934. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  4935. }
  4936. }
  4937. function toggleMangleActionFields() {
  4938. const act = document.getElementById('mangle-modal-action')?.value || 'mark-connection';
  4939. // Hide all dynamic rows first
  4940. ['newconnmark', 'newroutingmark', 'newpktmark', 'newmss', 'newdscp', 'newttl', 'newpriority', 'route', 'sniff', 'passthrough'].forEach(id => {
  4941. const el = document.getElementById(`mangle-row-${id}`);
  4942. if (el) el.classList.add('hidden');
  4943. });
  4944. const jumpBox = document.getElementById('mangle-action-jump-box');
  4945. const addrBox = document.getElementById('mangle-action-addrlist-box');
  4946. if (jumpBox) jumpBox.classList.add('hidden');
  4947. if (addrBox) addrBox.classList.add('hidden');
  4948. // Activate matching rows
  4949. if (act === 'mark-connection') {
  4950. document.getElementById('mangle-row-newconnmark')?.classList.remove('hidden');
  4951. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4952. } else if (act === 'mark-routing') {
  4953. document.getElementById('mangle-row-newroutingmark')?.classList.remove('hidden');
  4954. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4955. } else if (act === 'mark-packet') {
  4956. document.getElementById('mangle-row-newpktmark')?.classList.remove('hidden');
  4957. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4958. } else if (act === 'change-mss') {
  4959. document.getElementById('mangle-row-newmss')?.classList.remove('hidden');
  4960. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4961. } else if (act === 'change-dscp') {
  4962. document.getElementById('mangle-row-newdscp')?.classList.remove('hidden');
  4963. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4964. } else if (act === 'change-ttl') {
  4965. document.getElementById('mangle-row-newttl')?.classList.remove('hidden');
  4966. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4967. } else if (act === 'set-priority') {
  4968. document.getElementById('mangle-row-newpriority')?.classList.remove('hidden');
  4969. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4970. } else if (act === 'route') {
  4971. document.getElementById('mangle-row-route')?.classList.remove('hidden');
  4972. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4973. } else if (act === 'sniff-pc' || act === 'sniff-tzsp') {
  4974. document.getElementById('mangle-row-sniff')?.classList.remove('hidden');
  4975. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4976. } else if (act === 'clear-df' || act === 'strip-ipv4-options') {
  4977. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4978. } else if (act === 'jump') {
  4979. if (jumpBox) jumpBox.classList.remove('hidden');
  4980. } else if (act.includes('address-list') || act.includes('address list')) {
  4981. if (addrBox) addrBox.classList.remove('hidden');
  4982. }
  4983. if (act === 'log') {
  4984. const logEl = document.getElementById('mangle-modal-log');
  4985. if (logEl) logEl.checked = true;
  4986. toggleMangleField('logprefix', true);
  4987. }
  4988. }
  4989. function toggleMangleLogPrefix() {
  4990. const isLog = document.getElementById('mangle-modal-log')?.checked;
  4991. toggleMangleField('logprefix', !!isLog);
  4992. }
  4993. const allMangleFieldKeys = [
  4994. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  4995. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  4996. 'routingmark', 'conntype', 'cs', 'natstate',
  4997. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  4998. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  4999. 'ipsec', 'tlshost', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  5000. 'pktsize', 'random', 'tcpflags', 'icmpoptions', 'ipv4options', 'ttl',
  5001. 'nth', 'connlimit', 'srcaddrtype', 'dstaddrtype', 'hotspot', 'ipfragment',
  5002. 'limit', 'dstlimit', 'time', 'psd', 'logprefix'
  5003. ];
  5004. function openAddMangleModal() {
  5005. switchMangleRuleTab('general');
  5006. const badge = document.getElementById('mangle-modal-badge');
  5007. if (badge) badge.innerText = 'New...';
  5008. document.getElementById('mangle-modal-id').value = '';
  5009. document.getElementById('mangle-modal-enabled').checked = true;
  5010. document.getElementById('mangle-modal-comment').value = '';
  5011. document.getElementById('mangle-modal-chain').value = 'prerouting';
  5012. document.getElementById('mangle-modal-action').value = 'mark-connection';
  5013. if (document.getElementById('mangle-modal-newconnmark')) document.getElementById('mangle-modal-newconnmark').value = '';
  5014. if (document.getElementById('mangle-modal-newroutingmark')) document.getElementById('mangle-modal-newroutingmark').value = '';
  5015. if (document.getElementById('mangle-modal-newpktmark')) document.getElementById('mangle-modal-newpktmark').value = '';
  5016. if (document.getElementById('mangle-modal-newmss')) document.getElementById('mangle-modal-newmss').value = '';
  5017. if (document.getElementById('mangle-modal-newdscp')) document.getElementById('mangle-modal-newdscp').value = '';
  5018. if (document.getElementById('mangle-modal-newttl')) document.getElementById('mangle-modal-newttl').value = '';
  5019. if (document.getElementById('mangle-modal-newpriority')) document.getElementById('mangle-modal-newpriority').value = '';
  5020. if (document.getElementById('mangle-modal-route')) document.getElementById('mangle-modal-route').value = '';
  5021. if (document.getElementById('mangle-modal-sniff')) document.getElementById('mangle-modal-sniff').value = '';
  5022. if (document.getElementById('mangle-modal-jumptarget')) document.getElementById('mangle-modal-jumptarget').value = '';
  5023. if (document.getElementById('mangle-modal-action-addrlist')) document.getElementById('mangle-modal-action-addrlist').value = '';
  5024. if (document.getElementById('mangle-modal-action-timeout')) document.getElementById('mangle-modal-action-timeout').value = '';
  5025. if (document.getElementById('mangle-modal-passthrough')) document.getElementById('mangle-modal-passthrough').checked = true;
  5026. if (document.getElementById('mangle-modal-log')) document.getElementById('mangle-modal-log').checked = false;
  5027. populateInterfaceSelect('mangle-val-iniface');
  5028. populateInterfaceSelect('mangle-val-outiface');
  5029. populateAddressListSelect('mangle-val-srclist');
  5030. populateAddressListSelect('mangle-val-dstlist');
  5031. populateGeoIPSelect('mangle-val-srcgeo');
  5032. populateGeoIPSelect('mangle-val-dstgeo');
  5033. allMangleFieldKeys.forEach(k => toggleMangleField(k, false));
  5034. resetCurrentMangleRuleCounters();
  5035. toggleMangleActionFields();
  5036. document.getElementById('mangle-modal').classList.remove('hidden');
  5037. }
  5038. function openEditMangleModal(id) {
  5039. const r = (state.mangleRules || []).find(rule => rule.id === id);
  5040. if (!r) return;
  5041. switchMangleRuleTab('general');
  5042. const badge = document.getElementById('mangle-modal-badge');
  5043. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  5044. document.getElementById('mangle-modal-id').value = r.id;
  5045. document.getElementById('mangle-modal-enabled').checked = !r.disabled;
  5046. document.getElementById('mangle-modal-comment').value = r.comment || '';
  5047. document.getElementById('mangle-modal-chain').value = r.chain || 'prerouting';
  5048. document.getElementById('mangle-modal-action').value = r.action || 'mark-connection';
  5049. if (document.getElementById('mangle-modal-newconnmark')) document.getElementById('mangle-modal-newconnmark').value = r.new_connection_mark || '';
  5050. if (document.getElementById('mangle-modal-newroutingmark')) document.getElementById('mangle-modal-newroutingmark').value = r.new_routing_mark || '';
  5051. if (document.getElementById('mangle-modal-newpktmark')) document.getElementById('mangle-modal-newpktmark').value = r.new_packet_mark || '';
  5052. if (document.getElementById('mangle-modal-newmss')) document.getElementById('mangle-modal-newmss').value = r.new_mss || '';
  5053. if (document.getElementById('mangle-modal-newdscp')) document.getElementById('mangle-modal-newdscp').value = r.new_dscp != null ? r.new_dscp : '';
  5054. if (document.getElementById('mangle-modal-newttl')) document.getElementById('mangle-modal-newttl').value = r.new_ttl || '';
  5055. if (document.getElementById('mangle-modal-newpriority')) document.getElementById('mangle-modal-newpriority').value = r.new_priority || '';
  5056. if (document.getElementById('mangle-modal-route')) document.getElementById('mangle-modal-route').value = r.route || '';
  5057. if (document.getElementById('mangle-modal-sniff')) document.getElementById('mangle-modal-sniff').value = r.sniff_target || '';
  5058. if (document.getElementById('mangle-modal-jumptarget')) document.getElementById('mangle-modal-jumptarget').value = r.jump_target || '';
  5059. if (document.getElementById('mangle-modal-action-addrlist')) document.getElementById('mangle-modal-action-addrlist').value = r.address_list || '';
  5060. if (document.getElementById('mangle-modal-action-timeout')) document.getElementById('mangle-modal-action-timeout').value = r.address_list_timeout || '';
  5061. if (document.getElementById('mangle-modal-passthrough')) document.getElementById('mangle-modal-passthrough').checked = r.passthrough ?? true;
  5062. if (document.getElementById('mangle-modal-log')) document.getElementById('mangle-modal-log').checked = !!r.log;
  5063. populateInterfaceSelect('mangle-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  5064. populateInterfaceSelect('mangle-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  5065. populateAddressListSelect('mangle-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  5066. populateAddressListSelect('mangle-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  5067. populateGeoIPSelect('mangle-val-srcgeo', r.src_geoip || '');
  5068. populateGeoIPSelect('mangle-val-dstgeo', r.dst_geoip || '');
  5069. setMangleFieldVal('src', r.src_address, true);
  5070. setMangleFieldVal('dst', r.dst_address, true);
  5071. setMangleFieldVal('srclist', r.src_address_list, true);
  5072. setMangleFieldVal('dstlist', r.dst_address_list, true);
  5073. setMangleFieldVal('srcgeo', r.src_geoip, true);
  5074. setMangleFieldVal('dstgeo', r.dst_geoip, true);
  5075. if (r.protocol && r.protocol !== 'all') {
  5076. setMangleFieldVal('proto', r.protocol, true);
  5077. } else {
  5078. toggleMangleField('proto', false);
  5079. }
  5080. setMangleFieldVal('sport', r.src_port, true);
  5081. setMangleFieldVal('dport', r.dst_port, true);
  5082. setMangleFieldVal('anyport', r.any_port, true);
  5083. setMangleFieldVal('iniface', r.in_interface, true);
  5084. setMangleFieldVal('outiface', r.out_interface, true);
  5085. setMangleFieldVal('inifacelist', r.in_interface_list, true);
  5086. setMangleFieldVal('outifacelist', r.out_interface_list, true);
  5087. setMangleFieldVal('pktmark', r.packet_mark, true);
  5088. setMangleFieldVal('connmark', r.connection_mark, true);
  5089. setMangleFieldVal('routingmark', r.routing_mark, true);
  5090. setMangleFieldVal('conntype', r.connection_type, false);
  5091. // Connection State
  5092. const states = r.connection_state || [];
  5093. if (states.length > 0) {
  5094. toggleMangleField('cs', true);
  5095. ['established', 'related', 'new', 'invalid', 'untracked'].forEach(s => {
  5096. const el = document.getElementById(`mangle-modal-cs-${s}`);
  5097. if (el) el.checked = states.includes(s);
  5098. });
  5099. } else {
  5100. toggleMangleField('cs', false);
  5101. }
  5102. // Connection NAT State
  5103. const natStates = r.connection_nat_state || [];
  5104. if (natStates.length > 0) {
  5105. toggleMangleField('natstate', true);
  5106. ['srcnat', 'dstnat'].forEach(s => {
  5107. const el = document.getElementById(`mangle-modal-nat-${s}`);
  5108. if (el) el.checked = natStates.includes(s);
  5109. });
  5110. } else {
  5111. toggleMangleField('natstate', false);
  5112. }
  5113. // Advanced tab fields
  5114. setMangleFieldVal('layer7', r.layer7_protocol, false);
  5115. setMangleFieldVal('content', r.content, false);
  5116. setMangleFieldVal('connbytes', r.connection_bytes, false);
  5117. setMangleFieldVal('connrate', r.connection_rate, false);
  5118. setMangleFieldVal('pcc', r.pcc, false);
  5119. setMangleFieldVal('srcmac', r.src_mac_address, true);
  5120. setMangleFieldVal('outbridgeport', r.out_bridge_port, false);
  5121. setMangleFieldVal('inbridgeport', r.in_bridge_port, false);
  5122. setMangleFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  5123. setMangleFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  5124. setMangleFieldVal('ipsec', r.ipsec_policy, false);
  5125. setMangleFieldVal('tlshost', r.tls_host, false);
  5126. setMangleFieldVal('ingresspriority', r.ingress_priority, false);
  5127. setMangleFieldVal('priority', r.priority, false);
  5128. setMangleFieldVal('dscp', r.dscp, false);
  5129. setMangleFieldVal('tcpmss', r.tcp_mss, false);
  5130. if (r.tos) {
  5131. const tosEl = document.getElementById('mangle-val-tos');
  5132. if (tosEl) tosEl.value = r.tos;
  5133. }
  5134. setMangleFieldVal('pktsize', r.packet_size, false);
  5135. setMangleFieldVal('random', r.random, false);
  5136. setMangleFieldVal('tcpflags', r.tcp_flags, false);
  5137. setMangleFieldVal('icmpoptions', r.icmp_options, false);
  5138. setMangleFieldVal('ipv4options', r.ipv4_options, false);
  5139. setMangleFieldVal('ttl', r.ttl, false);
  5140. // Extra tab fields
  5141. setMangleFieldVal('nth', r.nth, false);
  5142. setMangleFieldVal('connlimit', r.connection_limit, false);
  5143. setMangleFieldVal('srcaddrtype', r.src_address_type, false);
  5144. setMangleFieldVal('dstaddrtype', r.dst_address_type, false);
  5145. setMangleFieldVal('hotspot', r.hotspot, false);
  5146. setMangleFieldVal('ipfragment', r.ip_fragment, false);
  5147. setMangleFieldVal('limit', r.limit, false);
  5148. setMangleFieldVal('dstlimit', r.dst_limit, false);
  5149. setMangleFieldVal('time', r.time, false);
  5150. setMangleFieldVal('psd', r.psd, false);
  5151. // Action fields
  5152. if (r.jump_target) {
  5153. const jtEl = document.getElementById('mangle-modal-jumptarget');
  5154. if (jtEl) jtEl.value = r.jump_target;
  5155. }
  5156. if (r.address_list) {
  5157. const alEl = document.getElementById('mangle-modal-action-addrlist');
  5158. if (alEl) alEl.value = r.address_list;
  5159. }
  5160. if (r.address_list_timeout) {
  5161. const toEl = document.getElementById('mangle-modal-action-timeout');
  5162. if (toEl) toEl.value = r.address_list_timeout;
  5163. }
  5164. setMangleFieldVal('logprefix', r.log_prefix, false);
  5165. // Statistics
  5166. const bEl = document.getElementById('mangle-stat-bytes');
  5167. const pEl = document.getElementById('mangle-stat-packets');
  5168. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  5169. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  5170. state.mangleLastBytes = r.bytes || 0;
  5171. state.mangleLastPackets = r.packets || 0;
  5172. state.mangleLastTimestamp = Date.now();
  5173. state.mangleStatRateHistory = new Array(30).fill(0);
  5174. state.mangleStatPktHistory = new Array(30).fill(0);
  5175. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  5176. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  5177. toggleMangleActionFields();
  5178. document.getElementById('mangle-modal').classList.remove('hidden');
  5179. }
  5180. function closeMangleModal() {
  5181. stopMangleStatPolling();
  5182. document.getElementById('mangle-modal').classList.add('hidden');
  5183. }
  5184. function copyMangleRule() {
  5185. document.getElementById('mangle-modal-id').value = '';
  5186. const badge = document.getElementById('mangle-modal-badge');
  5187. if (badge) badge.innerText = 'New...';
  5188. showToast('Rule Cloned', 'Ready to save as a new Mangle rule copy', 'info');
  5189. }
  5190. function resetCurrentMangleRuleCounters() {
  5191. state.mangleStatRateHistory = new Array(30).fill(0);
  5192. state.mangleStatPktHistory = new Array(30).fill(0);
  5193. state.mangleLastBytes = 0;
  5194. state.mangleLastPackets = 0;
  5195. state.mangleLastTimestamp = Date.now();
  5196. const bEl = document.getElementById('mangle-stat-bytes');
  5197. const pEl = document.getElementById('mangle-stat-packets');
  5198. const rEl = document.getElementById('mangle-stat-rate');
  5199. const prEl = document.getElementById('mangle-stat-pktrate');
  5200. if (bEl) bEl.value = '0 B';
  5201. if (pEl) pEl.value = '0';
  5202. if (rEl) rEl.value = '0 bps';
  5203. if (prEl) prEl.value = '0 p/s';
  5204. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  5205. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  5206. showToast('Counters Reset', 'Mangle rule counter display reset to 0', 'info');
  5207. }
  5208. async function applyMangleRule(closeAfter = false) {
  5209. const id = document.getElementById('mangle-modal-id').value;
  5210. const chain = document.getElementById('mangle-modal-chain').value;
  5211. const action = document.getElementById('mangle-modal-action').value;
  5212. const comment = document.getElementById('mangle-modal-comment').value.trim();
  5213. const enabled = document.getElementById('mangle-modal-enabled').checked;
  5214. const src = getMangleFieldVal('src', true);
  5215. const dst = getMangleFieldVal('dst', true);
  5216. const srclist = getMangleFieldVal('srclist', true);
  5217. const dstlist = getMangleFieldVal('dstlist', true);
  5218. const srcgeo = getMangleFieldVal('srcgeo', true);
  5219. const dstgeo = getMangleFieldVal('dstgeo', true);
  5220. const proto = getMangleFieldVal('proto', true);
  5221. const sport = getMangleFieldVal('sport', true);
  5222. const dport = getMangleFieldVal('dport', true);
  5223. const anyport = getMangleFieldVal('anyport', true);
  5224. const iniface = getMangleFieldVal('iniface', true);
  5225. const outiface = getMangleFieldVal('outiface', true);
  5226. const inifacelist = getMangleFieldVal('inifacelist', true);
  5227. const outifacelist = getMangleFieldVal('outifacelist', true);
  5228. const pktmark = getMangleFieldVal('pktmark', true);
  5229. const connmark = getMangleFieldVal('connmark', true);
  5230. const routingmark = getMangleFieldVal('routingmark', true);
  5231. const conntype = getMangleFieldVal('conntype', false);
  5232. const states = [];
  5233. const csBox = document.getElementById('mangle-field-cs');
  5234. if (csBox && !csBox.classList.contains('hidden')) {
  5235. ['established', 'related', 'new', 'invalid', 'untracked'].forEach(s => {
  5236. if (document.getElementById(`mangle-modal-cs-${s}`)?.checked) states.push(s);
  5237. });
  5238. }
  5239. const natStates = [];
  5240. const natBox = document.getElementById('mangle-field-natstate');
  5241. if (natBox && !natBox.classList.contains('hidden')) {
  5242. ['srcnat', 'dstnat'].forEach(s => {
  5243. if (document.getElementById(`mangle-modal-nat-${s}`)?.checked) natStates.push(s);
  5244. });
  5245. }
  5246. const payload = {
  5247. id,
  5248. chain,
  5249. action,
  5250. protocol: proto || 'all',
  5251. src_address: src,
  5252. dst_address: dst,
  5253. src_port: sport,
  5254. dst_port: dport,
  5255. any_port: anyport,
  5256. in_interface: iniface,
  5257. out_interface: outiface,
  5258. in_interface_list: inifacelist,
  5259. out_interface_list: outifacelist,
  5260. packet_mark: pktmark,
  5261. connection_mark: connmark,
  5262. routing_mark: routingmark,
  5263. connection_type: conntype,
  5264. connection_state: states,
  5265. connection_nat_state: natStates,
  5266. src_address_list: srclist,
  5267. dst_address_list: dstlist,
  5268. src_geoip: srcgeo,
  5269. dst_geoip: dstgeo,
  5270. comment,
  5271. disabled: !enabled,
  5272. // Advanced tab
  5273. layer7_protocol: getMangleFieldVal('layer7', false),
  5274. content: getMangleFieldVal('content', false),
  5275. connection_bytes: getMangleFieldVal('connbytes', false),
  5276. connection_rate: getMangleFieldVal('connrate', false),
  5277. pcc: getMangleFieldVal('pcc', false),
  5278. src_mac_address: getMangleFieldVal('srcmac', true),
  5279. out_bridge_port: getMangleFieldVal('outbridgeport', false),
  5280. in_bridge_port: getMangleFieldVal('inbridgeport', false),
  5281. in_bridge_port_list: getMangleFieldVal('inbridgeportlist', false),
  5282. out_bridge_port_list: getMangleFieldVal('outbridgeportlist', false),
  5283. ipsec_policy: getMangleFieldVal('ipsec', false),
  5284. tls_host: getMangleFieldVal('tlshost', false),
  5285. ingress_priority: getMangleFieldVal('ingresspriority', false),
  5286. priority: getMangleFieldVal('priority', false),
  5287. dscp: getMangleFieldVal('dscp', false),
  5288. tcp_mss: getMangleFieldVal('tcpmss', false),
  5289. tos: document.getElementById('mangle-val-tos')?.value || '',
  5290. packet_size: getMangleFieldVal('pktsize', false),
  5291. random: getMangleFieldVal('random', false),
  5292. tcp_flags: getMangleFieldVal('tcpflags', false),
  5293. icmp_options: getMangleFieldVal('icmpoptions', false),
  5294. ipv4_options: getMangleFieldVal('ipv4options', false),
  5295. ttl: getMangleFieldVal('ttl', false),
  5296. // Extra tab
  5297. nth: getMangleFieldVal('nth', false),
  5298. connection_limit: getMangleFieldVal('connlimit', false),
  5299. src_address_type: getMangleFieldVal('srcaddrtype', false),
  5300. dst_address_type: getMangleFieldVal('dstaddrtype', false),
  5301. hotspot: getMangleFieldVal('hotspot', false),
  5302. ip_fragment: getMangleFieldVal('ipfragment', false),
  5303. limit: getMangleFieldVal('limit', false),
  5304. dst_limit: getMangleFieldVal('dstlimit', false),
  5305. time: getMangleFieldVal('time', false),
  5306. psd: getMangleFieldVal('psd', false),
  5307. // Action tab
  5308. new_connection_mark: action === 'mark-connection' ? (document.getElementById('mangle-modal-newconnmark')?.value.trim() || '') : '',
  5309. new_routing_mark: action === 'mark-routing' ? (document.getElementById('mangle-modal-newroutingmark')?.value.trim() || '') : '',
  5310. new_packet_mark: action === 'mark-packet' ? (document.getElementById('mangle-modal-newpktmark')?.value.trim() || '') : '',
  5311. new_mss: action === 'change-mss' ? (document.getElementById('mangle-modal-newmss')?.value.trim() || '') : '',
  5312. new_dscp: action === 'change-dscp' ? parseInt(document.getElementById('mangle-modal-newdscp')?.value || '0', 10) : 0,
  5313. new_ttl: action === 'change-ttl' ? (document.getElementById('mangle-modal-newttl')?.value.trim() || '') : '',
  5314. new_priority: action === 'set-priority' ? (document.getElementById('mangle-modal-newpriority')?.value.trim() || '') : '',
  5315. route: action === 'route' ? (document.getElementById('mangle-modal-route')?.value.trim() || '') : '',
  5316. sniff_target: (action === 'sniff-pc' || action === 'sniff-tzsp') ? (document.getElementById('mangle-modal-sniff')?.value.trim() || '') : '',
  5317. passthrough: document.getElementById('mangle-modal-passthrough')?.checked ?? true,
  5318. jump_target: action === 'jump' ? (document.getElementById('mangle-modal-jumptarget')?.value || '') : '',
  5319. address_list: action.includes('address') ? (document.getElementById('mangle-modal-action-addrlist')?.value || '') : '',
  5320. address_list_timeout: action.includes('address') ? (document.getElementById('mangle-modal-action-timeout')?.value || '') : '',
  5321. log: document.getElementById('mangle-modal-log')?.checked || false,
  5322. log_prefix: getMangleFieldVal('logprefix', false)
  5323. };
  5324. try {
  5325. const res = await fetch(`${API_BASE}/firewall/mangle`, {
  5326. method: 'POST',
  5327. headers: { 'Content-Type': 'application/json' },
  5328. body: JSON.stringify(payload)
  5329. });
  5330. if (res.ok) {
  5331. const data = await res.json();
  5332. showToast('Mangle Rule Saved', 'Marking rule updated', 'success');
  5333. loadFirewall(false);
  5334. if (closeAfter) {
  5335. closeMangleModal();
  5336. } else {
  5337. if (data.id) {
  5338. document.getElementById('mangle-modal-id').value = data.id;
  5339. const badge = document.getElementById('mangle-modal-badge');
  5340. if (badge) badge.innerText = `#${data.id}`;
  5341. }
  5342. }
  5343. } else {
  5344. const err = await res.json();
  5345. showToast('Error', err.message || 'Failed to save mangle rule', 'error');
  5346. }
  5347. } catch (err) {
  5348. showToast('Error', err.message, 'error');
  5349. }
  5350. }
  5351. function submitSaveMangleRule(e) {
  5352. if (e && e.preventDefault) e.preventDefault();
  5353. return applyMangleRule(true);
  5354. }
  5355. function startMangleStatPolling() {
  5356. stopMangleStatPolling();
  5357. pollMangleRuleStats();
  5358. state.mangleStatInterval = setInterval(pollMangleRuleStats, 1000);
  5359. }
  5360. function stopMangleStatPolling() {
  5361. if (state.mangleStatInterval) {
  5362. clearInterval(state.mangleStatInterval);
  5363. state.mangleStatInterval = null;
  5364. }
  5365. }
  5366. async function pollMangleRuleStats() {
  5367. const id = document.getElementById('mangle-modal-id')?.value;
  5368. if (!id) {
  5369. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory || new Array(30).fill(0), 'bps', 'mangle-stat-legend-rate');
  5370. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory || new Array(30).fill(0), 'p/s', 'mangle-stat-legend-pktrate');
  5371. return;
  5372. }
  5373. try {
  5374. const res = await fetch(`${API_BASE}/firewall/mangle`);
  5375. if (!res.ok) return;
  5376. const rules = await res.json();
  5377. const r = rules.find(x => x.id === id);
  5378. if (!r) return;
  5379. const now = Date.now();
  5380. const dt = Math.max(0.2, (now - (state.mangleLastTimestamp || now)) / 1000);
  5381. state.mangleLastTimestamp = now;
  5382. const curBytes = r.bytes || 0;
  5383. const curPackets = r.packets || 0;
  5384. const deltaBytes = Math.max(0, curBytes - (state.mangleLastBytes || curBytes));
  5385. const deltaPkts = Math.max(0, curPackets - (state.mangleLastPackets || curPackets));
  5386. state.mangleLastBytes = curBytes;
  5387. state.mangleLastPackets = curPackets;
  5388. const rateBps = Math.round((deltaBytes * 8) / dt);
  5389. const ratePkt = Math.round(deltaPkts / dt);
  5390. if (!state.mangleStatRateHistory) state.mangleStatRateHistory = new Array(30).fill(0);
  5391. if (!state.mangleStatPktHistory) state.mangleStatPktHistory = new Array(30).fill(0);
  5392. state.mangleStatRateHistory.push(rateBps);
  5393. if (state.mangleStatRateHistory.length > 30) state.mangleStatRateHistory.shift();
  5394. state.mangleStatPktHistory.push(ratePkt);
  5395. if (state.mangleStatPktHistory.length > 30) state.mangleStatPktHistory.shift();
  5396. const bEl = document.getElementById('mangle-stat-bytes');
  5397. const pEl = document.getElementById('mangle-stat-packets');
  5398. const rEl = document.getElementById('mangle-stat-rate');
  5399. const prEl = document.getElementById('mangle-stat-pktrate');
  5400. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  5401. if (pEl) pEl.value = curPackets.toLocaleString();
  5402. if (rEl) rEl.value = formatBps(rateBps);
  5403. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  5404. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  5405. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  5406. } catch (e) {
  5407. console.error('Error polling Mangle rule stats', e);
  5408. }
  5409. }
  5410. async function moveMangleRule(id, dir) {
  5411. try {
  5412. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/move`, {
  5413. method: 'POST',
  5414. headers: { 'Content-Type': 'application/json' },
  5415. body: JSON.stringify({ direction: dir })
  5416. });
  5417. if (res.ok) loadFirewall(false);
  5418. } catch (err) {
  5419. showToast('Error', err.message, 'error');
  5420. }
  5421. }
  5422. async function toggleMangleRuleState(id, disabled) {
  5423. try {
  5424. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/state`, {
  5425. method: 'POST',
  5426. headers: { 'Content-Type': 'application/json' },
  5427. body: JSON.stringify({ disabled })
  5428. });
  5429. if (res.ok) loadFirewall(false);
  5430. } catch (err) {
  5431. showToast('Error', err.message, 'error');
  5432. }
  5433. }
  5434. async function deleteMangleRule(id) {
  5435. if (!confirm('Are you sure you want to delete this mangle rule?')) return;
  5436. try {
  5437. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5438. if (res.ok) {
  5439. showToast('Deleted', 'Mangle rule removed', 'success');
  5440. loadFirewall(false);
  5441. }
  5442. } catch (err) {
  5443. showToast('Error', err.message, 'error');
  5444. }
  5445. }
  5446. // ----------------- Address Lists -----------------
  5447. function renderAddressLists() {
  5448. const filterList = document.getElementById('addrlist-filter-name')?.value || '';
  5449. const tbody = document.getElementById('addrlist-table-body');
  5450. const empty = document.getElementById('addrlist-empty');
  5451. if (!tbody) return;
  5452. tbody.innerHTML = '';
  5453. const entries = (state.addressLists || []).filter(e => !filterList || e.name === filterList);
  5454. document.getElementById('addrlist-count-badge').innerText = `${entries.length} Entries`;
  5455. // Update filter select
  5456. const sel = document.getElementById('addrlist-filter-name');
  5457. if (sel) {
  5458. const cur = sel.value;
  5459. sel.innerHTML = '<option value="">All Lists</option>';
  5460. const set = new Set((state.addressLists || []).map(a => a.name));
  5461. set.forEach(n => {
  5462. const opt = document.createElement('option');
  5463. opt.value = n;
  5464. opt.innerText = n;
  5465. if (n === cur) opt.selected = true;
  5466. sel.appendChild(opt);
  5467. });
  5468. }
  5469. if (entries.length === 0) {
  5470. empty?.classList.remove('hidden');
  5471. return;
  5472. }
  5473. empty?.classList.add('hidden');
  5474. entries.forEach((e, idx) => {
  5475. const tr = document.createElement('tr');
  5476. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${e.disabled ? 'opacity-50' : ''}`;
  5477. tr.setAttribute('ondblclick', `openEditAddrListModal('${e.id}')`);
  5478. tr.innerHTML = `
  5479. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  5480. <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>
  5481. <td class="py-2.5 px-3 font-bold text-white font-mono">${e.name}</td>
  5482. <td class="py-2.5 px-3 font-mono font-bold text-emerald-400">${e.address}</td>
  5483. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[150px]">${e.comment || '-'}</td>
  5484. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  5485. <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>
  5486. <button onclick="openEditAddrListModal('${e.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-medium">Edit</button>
  5487. <button onclick="deleteAddrList('${e.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  5488. </td>
  5489. `;
  5490. tbody.appendChild(tr);
  5491. });
  5492. populateCommonAddrListDatalist();
  5493. }
  5494. function openAddAddrListModal() {
  5495. document.getElementById('addrlist-modal-title').innerText = 'Add Address List Entry';
  5496. document.getElementById('addrlist-modal-id').value = '';
  5497. document.getElementById('addrlist-modal-name').value = '';
  5498. document.getElementById('addrlist-modal-addr').value = '';
  5499. document.getElementById('addrlist-modal-comment').value = '';
  5500. document.getElementById('addrlist-modal-disabled').checked = false;
  5501. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  5502. if (submitBtn) submitBtn.innerText = 'Add to List';
  5503. document.getElementById('addrlist-modal').classList.remove('hidden');
  5504. }
  5505. function openEditAddrListModal(id) {
  5506. const e = (state.addressLists || []).find(item => item.id === id);
  5507. if (!e) return;
  5508. document.getElementById('addrlist-modal-title').innerText = `Edit Address List Entry: ${e.name}`;
  5509. document.getElementById('addrlist-modal-id').value = e.id;
  5510. document.getElementById('addrlist-modal-name').value = e.name;
  5511. document.getElementById('addrlist-modal-addr').value = e.address;
  5512. document.getElementById('addrlist-modal-comment').value = e.comment || '';
  5513. document.getElementById('addrlist-modal-disabled').checked = !!e.disabled;
  5514. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  5515. if (submitBtn) submitBtn.innerText = 'Save Changes';
  5516. document.getElementById('addrlist-modal').classList.remove('hidden');
  5517. }
  5518. function closeAddrListModal() {
  5519. document.getElementById('addrlist-modal').classList.add('hidden');
  5520. }
  5521. async function submitSaveAddrList(e) {
  5522. e.preventDefault();
  5523. const id = document.getElementById('addrlist-modal-id').value;
  5524. const name = document.getElementById('addrlist-modal-name').value.trim();
  5525. const addr = document.getElementById('addrlist-modal-addr').value.trim();
  5526. const comment = document.getElementById('addrlist-modal-comment').value.trim();
  5527. const disabled = document.getElementById('addrlist-modal-disabled').checked;
  5528. try {
  5529. const res = await fetch(`${API_BASE}/firewall/address-lists`, {
  5530. method: 'POST',
  5531. headers: { 'Content-Type': 'application/json' },
  5532. body: JSON.stringify({ id, name, address: addr, comment, disabled })
  5533. });
  5534. if (res.ok) {
  5535. showToast('Address List Item Saved', `Saved ${addr} in ${name}`, 'success');
  5536. closeAddrListModal();
  5537. loadFirewall(false);
  5538. } else {
  5539. const err = await res.json();
  5540. showToast('Error', err.message || 'Failed to save address list', 'error');
  5541. }
  5542. } catch (err) {
  5543. showToast('Error', err.message, 'error');
  5544. }
  5545. }
  5546. async function toggleAddrListState(id, disabled) {
  5547. try {
  5548. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}/state`, {
  5549. method: 'POST',
  5550. headers: { 'Content-Type': 'application/json' },
  5551. body: JSON.stringify({ disabled })
  5552. });
  5553. if (res.ok) {
  5554. loadFirewall(false);
  5555. }
  5556. } catch (err) {
  5557. showToast('Error', err.message, 'error');
  5558. }
  5559. }
  5560. async function deleteAddrList(id) {
  5561. if (!confirm('Are you sure you want to delete this address list item?')) return;
  5562. try {
  5563. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5564. if (res.ok) {
  5565. showToast('Deleted', 'Address list item removed', 'info');
  5566. loadFirewall(false);
  5567. }
  5568. } catch (err) {
  5569. showToast('Error', err.message, 'error');
  5570. }
  5571. }
  5572. // ----------------- Geo-Location IP Management -----------------
  5573. async function loadGeoIP() {
  5574. try {
  5575. const [statusRes, countriesRes] = await Promise.all([
  5576. fetch(`${API_BASE}/firewall/geoip/status`),
  5577. fetch(`${API_BASE}/firewall/geoip/countries`)
  5578. ]);
  5579. if (statusRes.ok) state.geoStatus = await statusRes.json();
  5580. if (countriesRes.ok) state.geoCountries = await countriesRes.json();
  5581. updateGeoHeader();
  5582. renderGeoCountries();
  5583. } catch (err) {
  5584. console.error('Failed to load GeoIP:', err);
  5585. }
  5586. }
  5587. function getGeoUsageMap() {
  5588. const usage = {};
  5589. const checkRule = (r, type) => {
  5590. ['src_geoip', 'dst_geoip'].forEach(field => {
  5591. let val = (r && r[field]) || '';
  5592. let code = val.replace(/^!/, '').replace(/^geo:/, '').replace(/^geo_/, '').toUpperCase().trim();
  5593. if (code) {
  5594. if (!usage[code]) usage[code] = [];
  5595. const label = `${type} #${r.priority !== undefined ? r.priority : (r.id || '')}`;
  5596. if (!usage[code].includes(label)) usage[code].push(label);
  5597. }
  5598. });
  5599. };
  5600. (state.filterRules || []).forEach(r => checkRule(r, 'Filter'));
  5601. (state.natRules || []).forEach(r => checkRule(r, 'NAT'));
  5602. (state.mangleRules || []).forEach(r => checkRule(r, 'Mangle'));
  5603. return usage;
  5604. }
  5605. function updateGeoHeader() {
  5606. const s = state.geoStatus || {};
  5607. const statusBadge = document.getElementById('geo-status-badge');
  5608. if (statusBadge) {
  5609. statusBadge.innerText = s.auto_update ? 'Auto-Update ON' : 'Auto-Update OFF';
  5610. statusBadge.className = s.auto_update
  5611. ? 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-emerald-500/20 text-emerald-300 border border-emerald-500/30'
  5612. : 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 text-slate-400';
  5613. }
  5614. const intervalLabel = document.getElementById('geo-interval-label');
  5615. if (intervalLabel) {
  5616. intervalLabel.innerText = `Every ${s.interval_hours || 24}h`;
  5617. }
  5618. const usageMap = getGeoUsageMap();
  5619. const inUseCount = Object.keys(usageMap).length;
  5620. const activeCountEl = document.getElementById('geo-stat-active-countries');
  5621. if (activeCountEl) activeCountEl.innerText = inUseCount.toLocaleString();
  5622. const totalSubnetsEl = document.getElementById('geo-stat-total-subnets');
  5623. if (totalSubnetsEl) totalSubnetsEl.innerText = (s.total_subnets || 0).toLocaleString();
  5624. const lastSyncEl = document.getElementById('geo-stat-last-sync');
  5625. if (lastSyncEl) {
  5626. if (s.last_updated && !s.last_updated.startsWith('0001')) {
  5627. const d = new Date(s.last_updated);
  5628. lastSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  5629. } else {
  5630. lastSyncEl.innerText = 'Never (Sync Pending)';
  5631. }
  5632. }
  5633. const nextSyncEl = document.getElementById('geo-stat-next-sync');
  5634. if (nextSyncEl) {
  5635. if (s.next_update && !s.next_update.startsWith('0001')) {
  5636. const d = new Date(s.next_update);
  5637. nextSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  5638. } else {
  5639. nextSyncEl.innerText = '-';
  5640. }
  5641. }
  5642. const badge = document.getElementById('fw-badge-geo');
  5643. if (badge) badge.innerText = inUseCount || (state.geoCountries || []).filter(c => c.subnet_count > 0).length || 0;
  5644. }
  5645. function renderGeoCountries() {
  5646. const tbody = document.getElementById('geo-table-body');
  5647. const empty = document.getElementById('geo-empty');
  5648. if (!tbody) return;
  5649. tbody.innerHTML = '';
  5650. const q = (document.getElementById('geo-search-input')?.value || '').trim().toLowerCase();
  5651. const continent = document.getElementById('geo-continent-filter')?.value || '';
  5652. const inUseOnly = document.getElementById('geo-filter-inuse-only')?.checked;
  5653. const cachedOnly = document.getElementById('geo-filter-cached-only')?.checked;
  5654. const usageMap = getGeoUsageMap();
  5655. const countries = (state.geoCountries || []).filter(c => {
  5656. const isUsed = !!usageMap[c.code];
  5657. if (inUseOnly && !isUsed) return false;
  5658. if (cachedOnly && (!c.subnet_count || c.subnet_count === 0)) return false;
  5659. if (continent && c.continent !== continent) return false;
  5660. if (q) {
  5661. const matchCode = c.code.toLowerCase().includes(q);
  5662. const matchName = c.name.toLowerCase().includes(q);
  5663. if (!matchCode && !matchName) return false;
  5664. }
  5665. return true;
  5666. });
  5667. if (countries.length === 0) {
  5668. empty?.classList.remove('hidden');
  5669. return;
  5670. }
  5671. empty?.classList.add('hidden');
  5672. countries.forEach(c => {
  5673. const tr = document.createElement('tr');
  5674. const isUsed = !!usageMap[c.code];
  5675. const rulesUsing = usageMap[c.code] || [];
  5676. tr.className = `hover:bg-slate-800/40 transition text-xs ${isUsed ? 'bg-emerald-950/20' : ''}`;
  5677. let statusHtml = '';
  5678. if (isUsed) {
  5679. 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>`;
  5680. } else if (c.subnet_count > 0) {
  5681. 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>';
  5682. } else {
  5683. statusHtml = '<span class="px-2 py-0.5 rounded text-[10px] font-mono text-slate-500 bg-slate-800/60">READY</span>';
  5684. }
  5685. tr.innerHTML = `
  5686. <td class="py-2.5 px-3 text-center">
  5687. <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'}">
  5688. ${c.code}
  5689. </span>
  5690. </td>
  5691. <td class="py-2.5 px-3 font-bold text-white">${c.name}</td>
  5692. <td class="py-2.5 px-3 text-slate-400">${c.continent}</td>
  5693. <td class="py-2.5 px-3 font-mono ${c.subnet_count > 0 ? 'text-emerald-400 font-bold' : 'text-slate-500'}">
  5694. ${c.subnet_count > 0 ? c.subnet_count.toLocaleString() + ' CIDRs' : 'Not Cached'}
  5695. </td>
  5696. <td class="py-2.5 px-3 font-mono text-purple-300">${c.ipset_name}</td>
  5697. <td class="py-2.5 px-3">
  5698. ${statusHtml}
  5699. </td>
  5700. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  5701. <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>
  5702. <button onclick="viewGeoSubnets('${c.code}')" class="text-xs text-slate-400 hover:text-white" title="Preview Subnet Ranges">View</button>
  5703. </td>
  5704. `;
  5705. tbody.appendChild(tr);
  5706. });
  5707. }
  5708. function quickFilterGeo(preset) {
  5709. const searchInput = document.getElementById('geo-search-input');
  5710. const continentSel = document.getElementById('geo-continent-filter');
  5711. const inUseCheck = document.getElementById('geo-filter-inuse-only');
  5712. const cachedCheck = document.getElementById('geo-filter-cached-only');
  5713. if (searchInput) searchInput.value = '';
  5714. if (continentSel) continentSel.value = '';
  5715. if (inUseCheck) inUseCheck.checked = false;
  5716. if (cachedCheck) cachedCheck.checked = false;
  5717. if (preset === 'GR') {
  5718. if (searchInput) searchInput.value = 'Greece';
  5719. } else if (preset === 'Europe') {
  5720. if (continentSel) continentSel.value = 'Europe';
  5721. } else if (preset === 'HIGHRISK') {
  5722. if (searchInput) searchInput.value = 'China';
  5723. }
  5724. renderGeoCountries();
  5725. }
  5726. async function toggleGeoCountry(code, enabled) {
  5727. try {
  5728. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/toggle`, {
  5729. method: 'POST',
  5730. headers: { 'Content-Type': 'application/json' },
  5731. body: JSON.stringify({ enabled })
  5732. });
  5733. if (res.ok) {
  5734. showToast(enabled ? 'Country Enabled' : 'Country Disabled', `${code} ${enabled ? 'active in firewall' : 'removed from firewall'}`, 'success');
  5735. loadGeoIP();
  5736. } else {
  5737. const err = await res.json();
  5738. showToast('Error', err.message || 'Failed to toggle country', 'error');
  5739. }
  5740. } catch (err) {
  5741. showToast('Error', err.message, 'error');
  5742. }
  5743. }
  5744. async function updateGeoCountry(code) {
  5745. try {
  5746. showToast('Syncing Country', `Downloading latest IP blocks for ${code}...`, 'info');
  5747. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/update`, { method: 'POST' });
  5748. if (res.ok) {
  5749. const data = await res.json();
  5750. showToast('Synced', `Loaded ${data.subnets} CIDR blocks for ${code}`, 'success');
  5751. loadGeoIP();
  5752. } else {
  5753. const err = await res.json();
  5754. showToast('Sync Error', err.message || 'Failed to sync country', 'error');
  5755. }
  5756. } catch (err) {
  5757. showToast('Error', err.message, 'error');
  5758. }
  5759. }
  5760. async function triggerGeoUpdateNow() {
  5761. const spinner = document.getElementById('geo-update-spinner');
  5762. if (spinner) spinner.classList.remove('hidden');
  5763. try {
  5764. const res = await fetch(`${API_BASE}/firewall/geoip/update-now`, { method: 'POST' });
  5765. if (res.ok) {
  5766. showToast('Update Started', 'Updating all active GeoIP country zones in background...', 'info');
  5767. setTimeout(() => {
  5768. loadGeoIP();
  5769. if (spinner) spinner.classList.add('hidden');
  5770. }, 2500);
  5771. } else {
  5772. const err = await res.json();
  5773. showToast('Notice', err.message || 'Update in progress', 'info');
  5774. if (spinner) spinner.classList.add('hidden');
  5775. }
  5776. } catch (err) {
  5777. showToast('Error', err.message, 'error');
  5778. if (spinner) spinner.classList.add('hidden');
  5779. }
  5780. }
  5781. async function applyGeoPreset(preset) {
  5782. try {
  5783. const res = await fetch(`${API_BASE}/firewall/geoip/batch-toggle`, {
  5784. method: 'POST',
  5785. headers: { 'Content-Type': 'application/json' },
  5786. body: JSON.stringify({ preset, enabled: preset !== 'NONE' })
  5787. });
  5788. if (res.ok) {
  5789. showToast('Preset Applied', `Preset ${preset} updated in firewall`, 'success');
  5790. loadGeoIP();
  5791. }
  5792. } catch (err) {
  5793. showToast('Error', err.message, 'error');
  5794. }
  5795. }
  5796. function openGeoIntervalModal() {
  5797. const s = state.geoStatus || {};
  5798. document.getElementById('geo-cfg-autoupdate').checked = s.auto_update !== false;
  5799. const sel = document.getElementById('geo-cfg-interval');
  5800. const customBox = document.getElementById('geo-cfg-custom-box');
  5801. const customHoursInput = document.getElementById('geo-cfg-custom-hours');
  5802. const curHours = s.interval_hours || 24;
  5803. const matchOption = Array.from(sel.options).find(o => parseInt(o.value, 10) === curHours);
  5804. if (matchOption) {
  5805. sel.value = String(curHours);
  5806. customBox.classList.add('hidden');
  5807. } else {
  5808. sel.value = 'custom';
  5809. customHoursInput.value = curHours;
  5810. customBox.classList.remove('hidden');
  5811. }
  5812. document.getElementById('geo-interval-modal').classList.remove('hidden');
  5813. }
  5814. function closeGeoIntervalModal() {
  5815. document.getElementById('geo-interval-modal').classList.add('hidden');
  5816. }
  5817. function toggleCustomGeoInterval() {
  5818. const val = document.getElementById('geo-cfg-interval').value;
  5819. const customBox = document.getElementById('geo-cfg-custom-box');
  5820. if (val === 'custom') {
  5821. customBox.classList.remove('hidden');
  5822. } else {
  5823. customBox.classList.add('hidden');
  5824. }
  5825. }
  5826. async function submitGeoIntervalSettings(e) {
  5827. e.preventDefault();
  5828. const autoUpdate = document.getElementById('geo-cfg-autoupdate').checked;
  5829. const intervalVal = document.getElementById('geo-cfg-interval').value;
  5830. let hours = 24;
  5831. if (intervalVal === 'custom') {
  5832. hours = parseInt(document.getElementById('geo-cfg-custom-hours').value, 10) || 24;
  5833. } else {
  5834. hours = parseInt(intervalVal, 10) || 24;
  5835. }
  5836. try {
  5837. const res = await fetch(`${API_BASE}/firewall/geoip/config`, {
  5838. method: 'POST',
  5839. headers: { 'Content-Type': 'application/json' },
  5840. body: JSON.stringify({ auto_update: autoUpdate, interval_hours: hours })
  5841. });
  5842. if (res.ok) {
  5843. showToast('Schedule Saved', `Auto-update set to every ${hours} hours`, 'success');
  5844. closeGeoIntervalModal();
  5845. loadGeoIP();
  5846. } else {
  5847. const err = await res.json();
  5848. showToast('Error', err.message || 'Failed to save schedule', 'error');
  5849. }
  5850. } catch (err) {
  5851. showToast('Error', err.message, 'error');
  5852. }
  5853. }
  5854. async function viewGeoSubnets(code, name) {
  5855. if (!name) {
  5856. const found = (state.geoCountries || []).find(x => x.code === code);
  5857. name = found ? found.name : code;
  5858. }
  5859. document.getElementById('geo-subnets-title').innerText = `${name} (${code}) Subnets`;
  5860. document.getElementById('geo-subnets-subtitle').innerText = `Kernel IPSet: mk_geo_${code}`;
  5861. const listEl = document.getElementById('geo-subnets-list');
  5862. listEl.innerHTML = '<span class="text-slate-500">Loading subnets...</span>';
  5863. document.getElementById('geo-subnets-modal').classList.remove('hidden');
  5864. try {
  5865. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/subnets`);
  5866. if (res.ok) {
  5867. const data = await res.json();
  5868. const subnets = data.subnets || [];
  5869. if (subnets.length === 0) {
  5870. listEl.innerHTML = '<span class="text-slate-500">No cached subnets found. Click Sync to download this zone.</span>';
  5871. } else {
  5872. listEl.innerHTML = subnets.map(s => `<div>${s}</div>`).join('');
  5873. }
  5874. } else {
  5875. listEl.innerHTML = '<span class="text-rose-400">Failed to load subnets.</span>';
  5876. }
  5877. } catch (err) {
  5878. listEl.innerHTML = `<span class="text-rose-400">Error: ${err.message}</span>`;
  5879. }
  5880. }
  5881. function closeGeoSubnetsModal() {
  5882. document.getElementById('geo-subnets-modal').classList.add('hidden');
  5883. }
  5884. // ----------------- Active Connections Tracking -----------------
  5885. async function loadConnections() {
  5886. try {
  5887. const res = await fetch(`${API_BASE}/firewall/connections`);
  5888. const data = await res.json();
  5889. state.connections = Array.isArray(data) ? data : [];
  5890. document.getElementById('fw-badge-connections').innerText = state.connections.length;
  5891. document.getElementById('conns-count-badge').innerText = `${state.connections.length} Flows`;
  5892. renderConnections();
  5893. } catch (err) {
  5894. console.error('Failed to load connections:', err);
  5895. }
  5896. }
  5897. function renderConnections() {
  5898. const search = (document.getElementById('conns-search-input')?.value || '').toLowerCase();
  5899. const protoFilter = document.getElementById('conns-filter-proto')?.value || '';
  5900. const tbody = document.getElementById('conns-table-body');
  5901. const empty = document.getElementById('conns-empty');
  5902. if (!tbody) return;
  5903. tbody.innerHTML = '';
  5904. const conns = (state.connections || []).filter(c => {
  5905. if (protoFilter && c.protocol !== protoFilter) return false;
  5906. if (search) {
  5907. const line = `${c.protocol} ${c.src_address} ${c.dst_address} ${c.src_port} ${c.dst_port} ${c.tcp_state} ${c.connection_mark}`.toLowerCase();
  5908. if (!line.includes(search)) return false;
  5909. }
  5910. return true;
  5911. });
  5912. if (conns.length === 0) {
  5913. empty?.classList.remove('hidden');
  5914. return;
  5915. }
  5916. empty?.classList.add('hidden');
  5917. conns.slice(0, 150).forEach(c => {
  5918. const tr = document.createElement('tr');
  5919. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  5920. let stateColor = 'text-slate-400';
  5921. if (c.tcp_state === 'ESTABLISHED') stateColor = 'text-emerald-400 font-bold';
  5922. else if (c.tcp_state === 'TIME_WAIT' || c.tcp_state === 'SYN_SENT') stateColor = 'text-amber-400';
  5923. tr.innerHTML = `
  5924. <td class="py-2.5 px-3 font-bold text-cyan-400">${c.protocol}</td>
  5925. <td class="py-2.5 px-3 font-mono text-white">${c.src_address}:${c.src_port}</td>
  5926. <td class="py-2.5 px-3 font-mono text-white">${c.dst_address}:${c.dst_port}</td>
  5927. <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>
  5928. <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>
  5929. <td class="py-2.5 px-3 font-mono ${stateColor}">${c.tcp_state}</td>
  5930. <td class="py-2.5 px-3 font-mono text-purple-300">${c.connection_mark || '-'}</td>
  5931. <td class="py-2.5 px-3 text-slate-500">${c.timeout ? c.timeout + 's' : '-'}</td>
  5932. <td class="py-2.5 px-3 text-right font-sans">
  5933. <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>
  5934. </td>
  5935. `;
  5936. tbody.appendChild(tr);
  5937. });
  5938. }
  5939. async function killConnection(protocol, src, sport, dst, dport) {
  5940. try {
  5941. const res = await fetch(`${API_BASE}/firewall/connections/kill`, {
  5942. method: 'POST',
  5943. headers: { 'Content-Type': 'application/json' },
  5944. body: JSON.stringify({ protocol, src, sport, dst, dport })
  5945. });
  5946. if (res.ok) {
  5947. showToast('Terminated', `Killed flow ${src}:${sport} -> ${dst}:${dport}`, 'info');
  5948. loadConnections();
  5949. }
  5950. } catch (err) {
  5951. showToast('Error', err.message, 'error');
  5952. }
  5953. }
  5954. async function resetFirewallCounters() {
  5955. if (!confirm('Reset all firewall packet and byte counters to zero?')) return;
  5956. try {
  5957. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  5958. if (res.ok) {
  5959. showToast('Counters Reset', 'All rules counters reset to 0', 'success');
  5960. loadFirewall(false);
  5961. }
  5962. } catch (err) {
  5963. showToast('Error', err.message, 'error');
  5964. }
  5965. }
  5966. // ======================== MIKROTIK ROUTING & POLICY (/ip route) ========================
  5967. function switchRoutesSubTab(tab) {
  5968. state.routesSubTab = tab;
  5969. const tabs = ['routes', 'rules', 'tables'];
  5970. tabs.forEach(t => {
  5971. const panel = document.getElementById(`routes-subtab-${t}`);
  5972. const btn = document.getElementById(`routes-subtab-btn-${t}`);
  5973. if (panel) {
  5974. if (t === tab) panel.classList.remove('hidden');
  5975. else panel.classList.add('hidden');
  5976. }
  5977. if (btn) {
  5978. if (t === tab) {
  5979. 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';
  5980. } else {
  5981. 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';
  5982. }
  5983. }
  5984. });
  5985. setTimeout(initTableSorting, 50);
  5986. }
  5987. async function loadRoutes() {
  5988. try {
  5989. const [routesRes, rulesRes, tablesRes] = await Promise.all([
  5990. fetch(`${API_BASE}/routes`),
  5991. fetch(`${API_BASE}/routing/rules`),
  5992. fetch(`${API_BASE}/routing/tables`)
  5993. ]);
  5994. if (routesRes.ok) state.routes = await routesRes.json();
  5995. if (rulesRes.ok) state.policyRules = await rulesRes.json();
  5996. if (tablesRes.ok) state.routingTables = await tablesRes.json();
  5997. const bRoutes = document.getElementById('routes-badge-routes');
  5998. if (bRoutes) bRoutes.innerText = (state.routes || []).length;
  5999. const showSystem = document.getElementById('prule-show-system')?.checked;
  6000. const userRules = (state.policyRules || []).filter(pr => showSystem || (!pr.is_default && !pr.is_system));
  6001. const bRules = document.getElementById('routes-badge-rules');
  6002. if (bRules) bRules.innerText = userRules.length;
  6003. const bTables = document.getElementById('routes-badge-tables');
  6004. if (bTables) bTables.innerText = (state.routingTables || []).length;
  6005. const bRoutesCount = document.getElementById('badge-routes-count');
  6006. if (bRoutesCount) bRoutesCount.innerText = (state.routes || []).length;
  6007. renderRoutesList();
  6008. renderPolicyRules();
  6009. renderRoutingTables();
  6010. } catch (err) {
  6011. console.error('Failed to load routing:', err);
  6012. }
  6013. }
  6014. function getRouteProtocolBadge(proto) {
  6015. const p = (proto || 'static').toLowerCase();
  6016. switch (p) {
  6017. case 'bgp':
  6018. 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>`;
  6019. case 'ibgp':
  6020. 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>`;
  6021. case 'ospf':
  6022. 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>`;
  6023. case 'rip':
  6024. 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>`;
  6025. case 'static':
  6026. 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>`;
  6027. case 'connected':
  6028. 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>`;
  6029. case 'dhcp':
  6030. 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>`;
  6031. case 'multicast':
  6032. 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>`;
  6033. default:
  6034. 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>`;
  6035. }
  6036. }
  6037. function renderRoutesList() {
  6038. const tableFilter = document.getElementById('routes-filter-table')?.value || '';
  6039. const typeFilter = document.getElementById('routes-filter-type')?.value || '';
  6040. const tbody = document.getElementById('routes-table-body');
  6041. const empty = document.getElementById('routes-empty');
  6042. if (!tbody) return;
  6043. // Update table filter select
  6044. const sel = document.getElementById('routes-filter-table');
  6045. if (sel) {
  6046. const cur = sel.value;
  6047. sel.innerHTML = '<option value="">All Tables</option>';
  6048. (state.routingTables || []).forEach(t => {
  6049. const opt = document.createElement('option');
  6050. opt.value = t.name;
  6051. opt.innerText = t.name;
  6052. if (t.name === cur) opt.selected = true;
  6053. sel.appendChild(opt);
  6054. });
  6055. }
  6056. const routes = (state.routes || []).filter(r => {
  6057. if (tableFilter && r.routing_table !== tableFilter) return false;
  6058. if (typeFilter === 'ecmp' && !r.ecmp) return false;
  6059. if (typeFilter === 'multicast' && !r.multicast) return false;
  6060. if (typeFilter === 'static' && !r.static) return false;
  6061. if (typeFilter === 'dynamic' && !r.dynamic) return false;
  6062. if (typeFilter === 'connected' && !r.connect) return false;
  6063. if (typeFilter === 'bgp' && (r.protocol || '').toLowerCase() !== 'bgp' && (r.protocol || '').toLowerCase() !== 'ibgp') return false;
  6064. if (typeFilter === 'ospf' && (r.protocol || '').toLowerCase() !== 'ospf') return false;
  6065. if (typeFilter === 'dhcp' && (r.protocol || '').toLowerCase() !== 'dhcp') return false;
  6066. return true;
  6067. });
  6068. const ecmpCount = (state.routes || []).filter(r => r.ecmp).length;
  6069. const mcCount = (state.routes || []).filter(r => r.multicast).length;
  6070. let summaryText = `${routes.length} Routes`;
  6071. if (ecmpCount > 0) summaryText += ` • ${ecmpCount} ECMP`;
  6072. if (mcCount > 0) summaryText += ` • ${mcCount} Multicast/IGMP`;
  6073. const badgeEl = document.getElementById('routes-count-badge');
  6074. if (badgeEl) badgeEl.innerText = summaryText;
  6075. if (routes.length === 0) {
  6076. empty?.classList.remove('hidden');
  6077. tbody.innerHTML = '';
  6078. return;
  6079. }
  6080. empty?.classList.add('hidden');
  6081. const sig = `${tableFilter}|${typeFilter}|` + routes.map(r => `${r.id}:${r.active}:${r.disabled}:${r.distance}:${r.protocol}:${r.health_status}:${(r.health_rtt_ms || 0).toFixed(0)}`).join(';');
  6082. if (tbody.dataset.sig === sig) {
  6083. return; // Routes table unchanged! Do not wipe DOM or flicker!
  6084. }
  6085. tbody.dataset.sig = sig;
  6086. tbody.innerHTML = '';
  6087. routes.forEach(r => {
  6088. const tr = document.createElement('tr');
  6089. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${r.disabled ? 'opacity-50' : ''}`;
  6090. tr.setAttribute('ondblclick', `openEditRouteModal('${r.id}')`);
  6091. // Routing Flags string: D=Dynamic, A=Active, C=Connect, S=Static, E=ECMP, M=Multicast, X=Disabled
  6092. let flags = '';
  6093. if (r.dynamic) flags += 'D';
  6094. if (r.active) flags += 'A';
  6095. if (r.connect) flags += 'C';
  6096. if (r.static) flags += 'S';
  6097. if (r.ecmp) flags += 'E';
  6098. if (r.multicast) flags += 'M';
  6099. if (r.disabled) flags += 'X';
  6100. const isDefault = r.dst_address === 'default' || r.dst_address === '0.0.0.0/0';
  6101. let healthCell = `<span class="text-slate-600 font-mono text-[11px]">-</span>`;
  6102. if (r.check_gateway === 'internet') {
  6103. if (r.health_status === 'online') {
  6104. const ms = (r.health_rtt_ms || 0).toFixed(0);
  6105. healthCell = `
  6106. <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)">
  6107. <span class="w-1.5 h-1.5 rounded-full bg-emerald-400 animate-pulse"></span>
  6108. <span>Internet OK (${ms}ms)</span>
  6109. </span>
  6110. `;
  6111. } else if (r.health_status === 'offline') {
  6112. healthCell = `
  6113. <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.">
  6114. <span class="w-1.5 h-1.5 rounded-full bg-rose-400"></span>
  6115. <span>Internet Down</span>
  6116. </span>
  6117. `;
  6118. } else {
  6119. healthCell = `
  6120. <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">
  6121. <span class="w-1.5 h-1.5 rounded-full bg-amber-400 animate-ping"></span>
  6122. <span>Checking...</span>
  6123. </span>
  6124. `;
  6125. }
  6126. } else if (r.check_gateway === 'ping') {
  6127. if (r.health_status === 'online') {
  6128. healthCell = `
  6129. <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">
  6130. <span class="w-1.5 h-1.5 rounded-full bg-cyan-400"></span>
  6131. <span>Gateway OK (${(r.health_rtt_ms || 0).toFixed(0)}ms)</span>
  6132. </span>
  6133. `;
  6134. } else if (r.health_status === 'offline') {
  6135. healthCell = `
  6136. <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">
  6137. <span class="w-1.5 h-1.5 rounded-full bg-rose-400"></span>
  6138. <span>Gateway Dead</span>
  6139. </span>
  6140. `;
  6141. }
  6142. }
  6143. const flagDescriptions = [];
  6144. if (r.dynamic) flagDescriptions.push('Dynamic (D)');
  6145. if (r.active) flagDescriptions.push('Active (A)');
  6146. if (r.connect) flagDescriptions.push('Connected (C)');
  6147. if (r.static) flagDescriptions.push('Static (S)');
  6148. if (r.ecmp) flagDescriptions.push('ECMP - Equal-Cost Multi-Path (E)');
  6149. if (r.multicast) flagDescriptions.push('Multicast / IGMP Group (M)');
  6150. if (r.disabled) flagDescriptions.push('Disabled (X)');
  6151. tr.innerHTML = `
  6152. <td class="py-2.5 px-3 text-center">
  6153. <span class="px-1.5 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 ${
  6154. 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')
  6155. }" title="Flags: ${flagDescriptions.join(', ')}">
  6156. ${flags || '-'}
  6157. </span>
  6158. </td>
  6159. <td class="py-2.5 px-3">
  6160. <div class="flex items-center gap-1.5 flex-wrap">
  6161. <span class="font-bold ${isDefault ? 'text-cyan-300' : 'text-white'}">${escapeHtml(r.dst_address)}</span>
  6162. ${r.ecmp ? `
  6163. <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)">
  6164. <span>⚡ ECMP</span>
  6165. </span>
  6166. ` : ''}
  6167. ${r.multicast ? `
  6168. <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">
  6169. <span>IGMP</span>
  6170. </span>
  6171. ` : ''}
  6172. </div>
  6173. </td>
  6174. <td class="py-2.5 px-3">${getRouteProtocolBadge(r.protocol)}</td>
  6175. <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>
  6176. <td class="py-2.5 px-3 text-slate-400 font-mono">${(r.distance !== undefined && r.distance !== null) ? r.distance : 0}</td>
  6177. <td class="py-2.5 px-3 font-mono font-semibold text-purple-300">${r.routing_table || 'main'}</td>
  6178. <td class="py-2.5 px-3 text-emerald-400 font-mono">${r.interface || '-'}</td>
  6179. <td class="py-2.5 px-3">${healthCell}</td>
  6180. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]">${r.comment || '-'}</td>
  6181. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  6182. ${r.static ? `
  6183. <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>
  6184. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold">Edit</button>
  6185. <button onclick="deleteRoute('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  6186. ` : `
  6187. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">View</button>
  6188. `}
  6189. </td>
  6190. `;
  6191. tbody.appendChild(tr);
  6192. });
  6193. }
  6194. function openAddRouteModal() {
  6195. document.getElementById('route-modal-title').innerText = 'Add Static Route';
  6196. document.getElementById('route-modal-id').value = '';
  6197. document.getElementById('route-modal-old-dst').value = '';
  6198. document.getElementById('route-modal-old-gw').value = '';
  6199. document.getElementById('route-modal-old-distance').value = '';
  6200. document.getElementById('route-modal-old-table').value = '';
  6201. document.getElementById('route-modal-old-iface').value = '';
  6202. const dstInput = document.getElementById('route-modal-dst');
  6203. const gwInput = document.getElementById('route-modal-gw');
  6204. const distInput = document.getElementById('route-modal-distance');
  6205. const ifaceSelect = document.getElementById('route-modal-iface');
  6206. const tableSelect = document.getElementById('route-modal-table');
  6207. const commentInput = document.getElementById('route-modal-comment');
  6208. const disCheck = document.getElementById('route-modal-disabled');
  6209. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  6210. dstInput.disabled = false;
  6211. dstInput.value = '0.0.0.0/0';
  6212. gwInput.disabled = false;
  6213. gwInput.value = '';
  6214. distInput.disabled = false;
  6215. distInput.value = '1';
  6216. ifaceSelect.disabled = false;
  6217. tableSelect.disabled = false;
  6218. commentInput.disabled = false;
  6219. commentInput.value = '';
  6220. disCheck.disabled = false;
  6221. disCheck.checked = false;
  6222. if (saveBtn) saveBtn.classList.remove('hidden');
  6223. const checkGw = document.getElementById('route-modal-check-gw');
  6224. if (checkGw) checkGw.value = 'internet';
  6225. const checkTarget = document.getElementById('route-modal-check-target');
  6226. if (checkTarget) checkTarget.value = '1.1.1.1';
  6227. const checkInterval = document.getElementById('route-modal-check-interval');
  6228. if (checkInterval) checkInterval.value = '5';
  6229. const checkThresh = document.getElementById('route-modal-check-threshold');
  6230. if (checkThresh) checkThresh.value = '3';
  6231. toggleRouteCheckModeUI();
  6232. populateInterfaceSelect('route-modal-iface');
  6233. // Populate tables
  6234. tableSelect.innerHTML = '';
  6235. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  6236. const opt = document.createElement('option');
  6237. opt.value = t.name;
  6238. opt.innerText = t.name;
  6239. if (t.name === 'main') opt.selected = true;
  6240. tableSelect.appendChild(opt);
  6241. });
  6242. document.getElementById('route-modal').classList.remove('hidden');
  6243. }
  6244. function openEditRouteModal(id) {
  6245. const r = (state.routes || []).find(route => route.id === id);
  6246. if (!r) return;
  6247. const isStatic = !!r.static;
  6248. document.getElementById('route-modal-title').innerText = isStatic
  6249. ? `Edit Route: ${r.dst_address}`
  6250. : `Route Properties (Read Only): ${r.dst_address}`;
  6251. document.getElementById('route-modal-id').value = r.id;
  6252. document.getElementById('route-modal-old-dst').value = r.dst_address || '';
  6253. document.getElementById('route-modal-old-gw').value = r.gateway || '';
  6254. document.getElementById('route-modal-old-distance').value = (r.distance !== undefined && r.distance !== null) ? r.distance : '';
  6255. document.getElementById('route-modal-old-table').value = r.routing_table || 'main';
  6256. document.getElementById('route-modal-old-iface').value = r.interface || '';
  6257. const dstInput = document.getElementById('route-modal-dst');
  6258. const gwInput = document.getElementById('route-modal-gw');
  6259. const distInput = document.getElementById('route-modal-distance');
  6260. const ifaceSelect = document.getElementById('route-modal-iface');
  6261. const tableSelect = document.getElementById('route-modal-table');
  6262. const commentInput = document.getElementById('route-modal-comment');
  6263. const disCheck = document.getElementById('route-modal-disabled');
  6264. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  6265. dstInput.value = r.dst_address;
  6266. gwInput.value = r.gateway || '';
  6267. distInput.value = (r.distance !== undefined && r.distance !== null) ? r.distance : 1;
  6268. commentInput.value = r.comment || '';
  6269. disCheck.checked = !!r.disabled;
  6270. const checkGw = document.getElementById('route-modal-check-gw');
  6271. if (checkGw) checkGw.value = r.check_gateway || 'none';
  6272. const checkTarget = document.getElementById('route-modal-check-target');
  6273. if (checkTarget) checkTarget.value = r.check_target || '1.1.1.1';
  6274. const checkInterval = document.getElementById('route-modal-check-interval');
  6275. if (checkInterval) checkInterval.value = r.check_interval || 5;
  6276. const checkThresh = document.getElementById('route-modal-check-threshold');
  6277. if (checkThresh) checkThresh.value = r.check_threshold || 3;
  6278. toggleRouteCheckModeUI();
  6279. dstInput.disabled = !isStatic;
  6280. gwInput.disabled = !isStatic;
  6281. distInput.disabled = !isStatic;
  6282. ifaceSelect.disabled = !isStatic;
  6283. tableSelect.disabled = !isStatic;
  6284. commentInput.disabled = !isStatic;
  6285. disCheck.disabled = !isStatic;
  6286. if (checkGw) checkGw.disabled = !isStatic;
  6287. if (checkTarget) checkTarget.disabled = !isStatic;
  6288. if (checkInterval) checkInterval.disabled = !isStatic;
  6289. if (checkThresh) checkThresh.disabled = !isStatic;
  6290. if (saveBtn) {
  6291. if (isStatic) {
  6292. saveBtn.classList.remove('hidden');
  6293. } else {
  6294. saveBtn.classList.add('hidden');
  6295. }
  6296. }
  6297. populateInterfaceSelect('route-modal-iface', r.interface);
  6298. tableSelect.innerHTML = '';
  6299. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  6300. const opt = document.createElement('option');
  6301. opt.value = t.name;
  6302. opt.innerText = t.name;
  6303. if (t.name === (r.routing_table || 'main')) opt.selected = true;
  6304. tableSelect.appendChild(opt);
  6305. });
  6306. document.getElementById('route-modal').classList.remove('hidden');
  6307. }
  6308. function closeRouteModal() {
  6309. document.getElementById('route-modal').classList.add('hidden');
  6310. }
  6311. function setRouteCheckTarget(ip) {
  6312. const inp = document.getElementById('route-modal-check-target');
  6313. if (inp) inp.value = ip;
  6314. }
  6315. function toggleRouteCheckModeUI() {
  6316. const mode = document.getElementById('route-modal-check-gw')?.value || 'none';
  6317. const targetRow = document.getElementById('route-row-check-target');
  6318. const paramsRow = document.getElementById('route-row-check-params');
  6319. if (mode === 'none') {
  6320. if (targetRow) targetRow.classList.add('opacity-40', 'pointer-events-none');
  6321. if (paramsRow) paramsRow.classList.add('opacity-40', 'pointer-events-none');
  6322. } else if (mode === 'ping') {
  6323. if (targetRow) targetRow.classList.add('opacity-40', 'pointer-events-none');
  6324. if (paramsRow) paramsRow.classList.remove('opacity-40', 'pointer-events-none');
  6325. } else { // internet
  6326. if (targetRow) targetRow.classList.remove('opacity-40', 'pointer-events-none');
  6327. if (paramsRow) paramsRow.classList.remove('opacity-40', 'pointer-events-none');
  6328. }
  6329. }
  6330. async function submitSaveRoute(e) {
  6331. e.preventDefault();
  6332. const id = document.getElementById('route-modal-id').value;
  6333. const oldDst = document.getElementById('route-modal-old-dst')?.value || '';
  6334. const oldGw = document.getElementById('route-modal-old-gw')?.value || '';
  6335. const oldDistStr = document.getElementById('route-modal-old-distance')?.value;
  6336. const oldTable = document.getElementById('route-modal-old-table')?.value || '';
  6337. const oldIface = document.getElementById('route-modal-old-iface')?.value || '';
  6338. const dst = document.getElementById('route-modal-dst').value.trim();
  6339. const gw = document.getElementById('route-modal-gw').value.trim();
  6340. const table = document.getElementById('route-modal-table').value;
  6341. const distance = parseInt(document.getElementById('route-modal-distance').value, 10) || 0;
  6342. const iface = document.getElementById('route-modal-iface').value;
  6343. const comment = document.getElementById('route-modal-comment').value.trim();
  6344. const disabled = document.getElementById('route-modal-disabled').checked;
  6345. const check_gateway = document.getElementById('route-modal-check-gw')?.value || 'none';
  6346. const check_target = document.getElementById('route-modal-check-target')?.value.trim() || '1.1.1.1';
  6347. const check_interval = parseInt(document.getElementById('route-modal-check-interval')?.value, 10) || 5;
  6348. const check_threshold = parseInt(document.getElementById('route-modal-check-threshold')?.value, 10) || 3;
  6349. if (!dst) {
  6350. showToast('Error', 'Destination address is required', 'error');
  6351. return;
  6352. }
  6353. if (!gw && !iface) {
  6354. showToast('Error', 'Either Gateway IP or Interface must be specified', 'error');
  6355. return;
  6356. }
  6357. const payload = {
  6358. id,
  6359. old_dst_address: oldDst,
  6360. old_gateway: oldGw,
  6361. old_routing_table: oldTable,
  6362. old_interface: oldIface,
  6363. dst_address: dst,
  6364. gateway: gw || iface,
  6365. routing_table: table,
  6366. distance,
  6367. interface: iface,
  6368. comment,
  6369. disabled,
  6370. check_gateway,
  6371. check_target,
  6372. check_interval,
  6373. check_threshold
  6374. };
  6375. if (oldDistStr !== undefined && oldDistStr !== '') {
  6376. payload.old_distance = parseInt(oldDistStr, 10);
  6377. }
  6378. try {
  6379. const res = await fetch(`${API_BASE}/routes`, {
  6380. method: 'POST',
  6381. headers: { 'Content-Type': 'application/json' },
  6382. body: JSON.stringify(payload)
  6383. });
  6384. if (res.ok) {
  6385. showToast('Route Saved', `Route to ${dst} installed`, 'success');
  6386. closeRouteModal();
  6387. loadRoutes();
  6388. } else {
  6389. const err = await res.json();
  6390. showToast('Error', err.message || 'Failed to save route', 'error');
  6391. }
  6392. } catch (err) {
  6393. showToast('Error', err.message, 'error');
  6394. }
  6395. }
  6396. async function toggleRouteState(id, disabled) {
  6397. try {
  6398. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}/state`, {
  6399. method: 'POST',
  6400. headers: { 'Content-Type': 'application/json' },
  6401. body: JSON.stringify({ disabled })
  6402. });
  6403. if (res.ok) loadRoutes();
  6404. } catch (err) {
  6405. showToast('Error', err.message, 'error');
  6406. }
  6407. }
  6408. async function deleteRoute(id) {
  6409. if (!confirm('Are you sure you want to delete this route?')) return;
  6410. try {
  6411. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6412. if (res.ok) {
  6413. showToast('Deleted', 'Route removed', 'success');
  6414. loadRoutes();
  6415. }
  6416. } catch (err) {
  6417. showToast('Error', err.message, 'error');
  6418. }
  6419. }
  6420. // ----------------- Policy Rules (/ip route rule) -----------------
  6421. function renderPolicyRules() {
  6422. const tbody = document.getElementById('rules-table-body');
  6423. const empty = document.getElementById('rules-empty');
  6424. if (!tbody) return;
  6425. const showSystem = document.getElementById('prule-show-system')?.checked;
  6426. const filtered = (state.policyRules || []).filter(pr => showSystem || (!pr.is_default && !pr.is_system));
  6427. const countBadge = document.getElementById('rules-count-badge');
  6428. if (countBadge) countBadge.innerText = `${filtered.length} Rules`;
  6429. const bRules = document.getElementById('routes-badge-rules');
  6430. if (bRules) bRules.innerText = filtered.length;
  6431. if (filtered.length === 0) {
  6432. empty?.classList.remove('hidden');
  6433. tbody.innerHTML = '';
  6434. return;
  6435. }
  6436. empty?.classList.add('hidden');
  6437. const sig = `${showSystem}|` + filtered.map(pr => `${pr.id}:${pr.priority}:${pr.src_address}:${pr.dst_address}:${pr.table}:${pr.routing_mark}`).join(';');
  6438. if (tbody.dataset.sig === sig) return;
  6439. tbody.dataset.sig = sig;
  6440. tbody.innerHTML = '';
  6441. filtered.forEach(pr => {
  6442. const isSys = pr.is_default || pr.is_system;
  6443. const tr = document.createElement('tr');
  6444. tr.className = `hover:bg-slate-800/40 transition text-xs ${isSys ? 'opacity-70 bg-slate-950/20' : ''}`;
  6445. tr.innerHTML = `
  6446. <td class="py-2.5 px-3 font-mono text-cyan-400 font-bold">${pr.priority}</td>
  6447. <td class="py-2.5 px-3 font-mono text-white">${pr.src_address || '<span class="text-slate-600">all</span>'}</td>
  6448. <td class="py-2.5 px-3 font-mono text-white">${pr.dst_address || '<span class="text-slate-600">all</span>'}</td>
  6449. <td class="py-2.5 px-3 font-mono font-bold text-purple-300">${pr.routing_mark || '<span class="text-slate-600">-</span>'}</td>
  6450. <td class="py-2.5 px-3 font-mono font-bold text-amber-300">${pr.table}</td>
  6451. <td class="py-2.5 px-3 font-mono text-slate-300">${pr.action}</td>
  6452. <td class="py-2.5 px-3 text-right font-sans">
  6453. ${!pr.is_default ? `
  6454. <button onclick="deletePolicyRule('${pr.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  6455. ` : `<span class="text-slate-600 text-[10px]">Default</span>`}
  6456. </td>
  6457. `;
  6458. tbody.appendChild(tr);
  6459. });
  6460. }
  6461. function openAddPolicyRuleModal() {
  6462. const userRules = (state.policyRules || []).filter(pr => !pr.is_default && !pr.is_system);
  6463. document.getElementById('prule-modal-pref').value = userRules.length * 10 + 1000;
  6464. document.getElementById('prule-modal-mark').value = '';
  6465. document.getElementById('prule-modal-src').value = '';
  6466. document.getElementById('prule-modal-dst').value = '';
  6467. const sel = document.getElementById('prule-modal-table');
  6468. sel.innerHTML = '';
  6469. (state.routingTables || []).forEach(t => {
  6470. const opt = document.createElement('option');
  6471. opt.value = t.name;
  6472. opt.innerText = t.name;
  6473. sel.appendChild(opt);
  6474. });
  6475. document.getElementById('prule-modal').classList.remove('hidden');
  6476. }
  6477. function closePolicyRuleModal() {
  6478. document.getElementById('prule-modal').classList.add('hidden');
  6479. }
  6480. async function submitSavePolicyRule(e) {
  6481. e.preventDefault();
  6482. const pref = parseInt(document.getElementById('prule-modal-pref').value, 10) || 1000;
  6483. const mark = document.getElementById('prule-modal-mark').value.trim();
  6484. const src = document.getElementById('prule-modal-src').value.trim();
  6485. const dst = document.getElementById('prule-modal-dst').value.trim();
  6486. const table = document.getElementById('prule-modal-table').value;
  6487. const action = document.getElementById('prule-modal-action').value;
  6488. try {
  6489. const res = await fetch(`${API_BASE}/routing/rules`, {
  6490. method: 'POST',
  6491. headers: { 'Content-Type': 'application/json' },
  6492. body: JSON.stringify({ priority: pref, routing_mark: mark, src_address: src, dst_address: dst, table, action })
  6493. });
  6494. if (res.ok) {
  6495. showToast('Rule Added', `Policy rule installed for table ${table}`, 'success');
  6496. closePolicyRuleModal();
  6497. loadRoutes();
  6498. } else {
  6499. const err = await res.json();
  6500. showToast('Error', err.message, 'error');
  6501. }
  6502. } catch (err) {
  6503. showToast('Error', err.message, 'error');
  6504. }
  6505. }
  6506. async function deletePolicyRule(id) {
  6507. if (!confirm('Are you sure you want to remove this policy rule?')) return;
  6508. try {
  6509. const res = await fetch(`${API_BASE}/routing/rules/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6510. if (res.ok) {
  6511. showToast('Rule Removed', 'Policy rule deleted', 'success');
  6512. loadRoutes();
  6513. }
  6514. } catch (err) {
  6515. showToast('Error', err.message, 'error');
  6516. }
  6517. }
  6518. // ----------------- Routing Tables -----------------
  6519. function renderRoutingTables() {
  6520. const tbody = document.getElementById('tables-table-body');
  6521. if (!tbody) return;
  6522. const tables = state.routingTables || [];
  6523. const sig = tables.map(t => `${t.table_id}:${t.name}:${t.comment}`).join(';');
  6524. if (tbody.dataset.sig === sig) return;
  6525. tbody.dataset.sig = sig;
  6526. tbody.innerHTML = '';
  6527. (state.routingTables || []).forEach(t => {
  6528. const tr = document.createElement('tr');
  6529. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  6530. tr.innerHTML = `
  6531. <td class="py-2.5 px-3 text-cyan-400 font-bold">${t.table_id}</td>
  6532. <td class="py-2.5 px-3 font-bold text-white">${t.name}</td>
  6533. <td class="py-2.5 px-3 text-slate-400 italic">${t.comment || '-'}</td>
  6534. `;
  6535. tbody.appendChild(tr);
  6536. });
  6537. }
  6538. function openAddTableModal() {
  6539. document.getElementById('table-modal-name').value = '';
  6540. document.getElementById('table-modal-id').value = '';
  6541. document.getElementById('table-modal-comment').value = '';
  6542. document.getElementById('table-modal').classList.remove('hidden');
  6543. }
  6544. function closeTableModal() {
  6545. document.getElementById('table-modal').classList.add('hidden');
  6546. }
  6547. async function submitSaveTable(e) {
  6548. e.preventDefault();
  6549. const name = document.getElementById('table-modal-name').value.trim();
  6550. const id = parseInt(document.getElementById('table-modal-id').value, 10) || 0;
  6551. const comment = document.getElementById('table-modal-comment').value.trim();
  6552. try {
  6553. const res = await fetch(`${API_BASE}/routing/tables`, {
  6554. method: 'POST',
  6555. headers: { 'Content-Type': 'application/json' },
  6556. body: JSON.stringify({ name, table_id: id, comment })
  6557. });
  6558. if (res.ok) {
  6559. showToast('Table Created', `Routing table ${name} registered`, 'success');
  6560. closeTableModal();
  6561. loadRoutes();
  6562. } else {
  6563. const err = await res.json();
  6564. showToast('Error', err.message, 'error');
  6565. }
  6566. } catch (err) {
  6567. showToast('Error', err.message, 'error');
  6568. }
  6569. }
  6570. async function loadDebianConfig() {
  6571. const view = document.getElementById('debian-config-view');
  6572. view.innerText = 'Generating live configuration...';
  6573. try {
  6574. const res = await fetch(`${API_BASE}/debian/config`);
  6575. const data = await res.json();
  6576. view.innerText = data.content || '# Empty config';
  6577. } catch (err) {
  6578. view.innerText = 'Failed to generate Debian network config.';
  6579. }
  6580. }
  6581. async function saveDebianConfig() {
  6582. try {
  6583. const res = await fetch(`${API_BASE}/debian/apply`, { method: 'POST' });
  6584. const data = await res.json();
  6585. if (res.ok) {
  6586. showToast('Configuration Saved', data.message || 'Saved to /etc/network/interfaces.d/vlans.cfg', 'success');
  6587. loadDebianConfig();
  6588. }
  6589. } catch (err) {
  6590. showToast('Error', err.message, 'error');
  6591. }
  6592. }
  6593. function showToast(title, message, type = 'info') {
  6594. const container = document.getElementById('toast-container');
  6595. const toast = document.createElement('div');
  6596. const borderColors = {
  6597. success: 'border-emerald-500/40 bg-slate-900/95 text-emerald-400',
  6598. error: 'border-rose-500/40 bg-slate-900/95 text-rose-400',
  6599. info: 'border-cyan-500/40 bg-slate-900/95 text-cyan-400'
  6600. };
  6601. 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}`;
  6602. toast.innerHTML = `
  6603. <div class="flex-1">
  6604. <div class="font-bold text-xs text-white">${title}</div>
  6605. <div class="text-[11px] text-slate-300 mt-0.5 leading-relaxed font-sans">${message}</div>
  6606. </div>
  6607. `;
  6608. container.appendChild(toast);
  6609. requestAnimationFrame(() => toast.classList.remove('translate-y-2', 'opacity-0'));
  6610. setTimeout(() => {
  6611. toast.classList.add('opacity-0', 'translate-y-2');
  6612. setTimeout(() => toast.remove(), 300);
  6613. }, 4000);
  6614. }
  6615. function formatTraffic(bytesPerSec) {
  6616. if (bytesPerSec < 1024) return `${Math.round(bytesPerSec)} B/s`;
  6617. const kb = bytesPerSec / 1024;
  6618. if (kb < 1024) return `${kb.toFixed(1)} KB/s`;
  6619. const mb = kb / 1024;
  6620. return `${mb.toFixed(2)} MB/s`;
  6621. }
  6622. function toggleSidebar() {
  6623. const sb = document.getElementById('sidebar');
  6624. sb.classList.toggle('-translate-x-full');
  6625. }
  6626. // ======================== EoIP (Ethernet over IP) ========================
  6627. async function loadEoIP(populate = true) {
  6628. try {
  6629. const res = await fetch(`${API_BASE}/vpn/eoip`);
  6630. const data = await res.json();
  6631. state.eoipTunnels = Array.isArray(data) ? data : [];
  6632. const badge = document.getElementById('eoip-count-badge');
  6633. if (badge) badge.innerText = `${state.eoipTunnels.length} Tunnels`;
  6634. const sideBadge = document.getElementById('badge-eoip-count');
  6635. if (sideBadge) sideBadge.innerText = state.eoipTunnels.length;
  6636. renderEoIPTunnels();
  6637. } catch (err) {
  6638. console.error('Failed to load EoIP:', err);
  6639. }
  6640. }
  6641. function renderEoIPTunnels() {
  6642. const tbody = document.getElementById('eoip-table-body');
  6643. const empty = document.getElementById('eoip-empty');
  6644. if (!tbody) return;
  6645. tbody.innerHTML = '';
  6646. const tunnels = state.eoipTunnels || [];
  6647. if (tunnels.length === 0) {
  6648. empty?.classList.remove('hidden');
  6649. return;
  6650. }
  6651. empty?.classList.add('hidden');
  6652. tunnels.forEach(t => {
  6653. const tr = document.createElement('tr');
  6654. tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
  6655. tr.innerHTML = `
  6656. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.running, t.disabled)}</td>
  6657. <td class="py-2.5 px-3 font-bold text-white font-mono">${t.name}</td>
  6658. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${t.tunnel_id}</td>
  6659. <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>
  6660. <td class="py-2.5 px-3 text-cyan-300 font-mono">${t.remote_address}</td>
  6661. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.local_address || '(any)'}</td>
  6662. <td class="py-2.5 px-3 text-slate-300 font-mono text-[11px]">${t.mac_address || '-'}</td>
  6663. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.mtu || 1500}</td>
  6664. <td class="py-2.5 px-3 font-mono text-[11px]">
  6665. <span class="text-emerald-400">↓ ${t.rx_human || '0 B'}</span>
  6666. <span class="text-cyan-400 ml-1">↑ ${t.tx_human || '0 B'}</span>
  6667. </td>
  6668. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${t.comment || ''}">${t.comment || '-'}</td>
  6669. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  6670. <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>
  6671. <button onclick="openEditEoIPModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  6672. <button onclick="deleteEoIP('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  6673. </td>
  6674. `;
  6675. tbody.appendChild(tr);
  6676. });
  6677. }
  6678. function openAddEoIPModal() {
  6679. document.getElementById('eoip-modal-title').innerText = 'Add EoIP Tunnel';
  6680. document.getElementById('eoip-modal-id').value = '';
  6681. document.getElementById('eoip-modal-name').value = `eoip-tunnel${(state.eoipTunnels || []).length + 1}`;
  6682. document.getElementById('eoip-modal-tunnelid').value = (state.eoipTunnels || []).length + 10;
  6683. document.getElementById('eoip-modal-remote').value = '';
  6684. document.getElementById('eoip-modal-ip').value = '';
  6685. document.getElementById('eoip-modal-local').value = '';
  6686. document.getElementById('eoip-modal-mac').value = '';
  6687. document.getElementById('eoip-modal-mtu').value = '1500';
  6688. document.getElementById('eoip-modal-comment').value = '';
  6689. document.getElementById('eoip-modal-clampmss').checked = true;
  6690. document.getElementById('eoip-modal-disabled').checked = false;
  6691. document.getElementById('eoip-modal').classList.remove('hidden');
  6692. }
  6693. function openEditEoIPModal(id) {
  6694. const t = (state.eoipTunnels || []).find(tun => tun.id === id);
  6695. if (!t) return;
  6696. document.getElementById('eoip-modal-title').innerText = `Edit EoIP Tunnel (${t.name})`;
  6697. document.getElementById('eoip-modal-id').value = t.id;
  6698. document.getElementById('eoip-modal-name').value = t.name;
  6699. document.getElementById('eoip-modal-tunnelid').value = t.tunnel_id;
  6700. document.getElementById('eoip-modal-remote').value = t.remote_address;
  6701. document.getElementById('eoip-modal-ip').value = t.ip_address || '';
  6702. document.getElementById('eoip-modal-local').value = t.local_address || '';
  6703. document.getElementById('eoip-modal-mac').value = t.mac_address || '';
  6704. document.getElementById('eoip-modal-mtu').value = t.mtu || 1500;
  6705. document.getElementById('eoip-modal-comment').value = t.comment || '';
  6706. document.getElementById('eoip-modal-clampmss').checked = !!t.clamp_mss;
  6707. document.getElementById('eoip-modal-disabled').checked = !!t.disabled;
  6708. document.getElementById('eoip-modal').classList.remove('hidden');
  6709. }
  6710. function closeEoIPModal() {
  6711. document.getElementById('eoip-modal').classList.add('hidden');
  6712. }
  6713. async function submitSaveEoIP(e) {
  6714. e.preventDefault();
  6715. const id = document.getElementById('eoip-modal-id').value;
  6716. const name = document.getElementById('eoip-modal-name').value.trim();
  6717. const tunnelId = parseInt(document.getElementById('eoip-modal-tunnelid').value);
  6718. const remote = document.getElementById('eoip-modal-remote').value.trim();
  6719. const ipAddress = document.getElementById('eoip-modal-ip').value.trim();
  6720. const local = document.getElementById('eoip-modal-local').value.trim();
  6721. const mac = document.getElementById('eoip-modal-mac').value.trim();
  6722. const mtu = parseInt(document.getElementById('eoip-modal-mtu').value) || 1500;
  6723. const comment = document.getElementById('eoip-modal-comment').value.trim();
  6724. const clampMss = document.getElementById('eoip-modal-clampmss').checked;
  6725. const disabled = document.getElementById('eoip-modal-disabled').checked;
  6726. try {
  6727. const res = await fetch(`${API_BASE}/vpn/eoip`, {
  6728. method: 'POST',
  6729. headers: { 'Content-Type': 'application/json' },
  6730. body: JSON.stringify({
  6731. id,
  6732. name,
  6733. tunnel_id: tunnelId,
  6734. remote_address: remote,
  6735. ip_address: ipAddress,
  6736. local_address: local,
  6737. mac_address: mac,
  6738. mtu,
  6739. clamp_mss: clampMss,
  6740. comment,
  6741. disabled
  6742. })
  6743. });
  6744. if (res.ok) {
  6745. showToast('EoIP Saved', `Tunnel ${name} configured successfully`, 'success');
  6746. closeEoIPModal();
  6747. loadEoIP(false);
  6748. fetchData(false);
  6749. } else {
  6750. const err = await res.json();
  6751. showToast('Error', err.message, 'error');
  6752. }
  6753. } catch (err) {
  6754. showToast('Error', err.message, 'error');
  6755. }
  6756. }
  6757. async function toggleEoIPState(id, disabled) {
  6758. try {
  6759. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}/state`, {
  6760. method: 'POST',
  6761. headers: { 'Content-Type': 'application/json' },
  6762. body: JSON.stringify({ disabled })
  6763. });
  6764. if (res.ok) {
  6765. showToast(disabled ? 'Disabled' : 'Enabled', 'EoIP tunnel state updated', 'info');
  6766. loadEoIP(false);
  6767. fetchData(false);
  6768. }
  6769. } catch (err) {
  6770. showToast('Error', err.message, 'error');
  6771. }
  6772. }
  6773. async function deleteEoIP(id) {
  6774. if (!confirm('Are you sure you want to delete this EoIP tunnel?')) return;
  6775. try {
  6776. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6777. if (res.ok) {
  6778. showToast('Deleted', 'EoIP tunnel removed', 'success');
  6779. loadEoIP(false);
  6780. fetchData(false);
  6781. }
  6782. } catch (err) {
  6783. showToast('Error', err.message, 'error');
  6784. }
  6785. }
  6786. // ======================== AeroTUN (Custom Encrypted VPN with Adaptive LZ4) ========================
  6787. async function loadAeroTUN(populate = true) {
  6788. try {
  6789. const [tunnelsRes, statsRes] = await Promise.all([
  6790. fetch(`${API_BASE}/vpn/aerotun/tunnels`),
  6791. fetch(`${API_BASE}/vpn/aerotun/stats`)
  6792. ]);
  6793. if (tunnelsRes.ok) {
  6794. const data = await tunnelsRes.json();
  6795. state.aerotunTunnels = Array.isArray(data) ? data : [];
  6796. }
  6797. if (statsRes.ok) {
  6798. state.aerotunStats = await statsRes.json();
  6799. }
  6800. const countBadge = document.getElementById('aerotun-count-badge');
  6801. if (countBadge) countBadge.innerText = `${(state.aerotunTunnels || []).length} Tunnels`;
  6802. const sideBadge = document.getElementById('badge-aerotun-count');
  6803. if (sideBadge) sideBadge.innerText = (state.aerotunTunnels || []).length;
  6804. renderAeroTUN();
  6805. } catch (err) {
  6806. console.error('Failed to load AeroTUN:', err);
  6807. }
  6808. }
  6809. function renderAeroTUN() {
  6810. const tbody = document.getElementById('aerotun-table-body');
  6811. const empty = document.getElementById('aerotun-empty');
  6812. // Update summary cards
  6813. const stats = state.aerotunStats || {};
  6814. const tunnels = state.aerotunTunnels || [];
  6815. const statActive = document.getElementById('aerotun-stat-active');
  6816. if (statActive) {
  6817. const activeCount = tunnels.filter(t => t.running).length;
  6818. statActive.innerText = `${activeCount} / ${tunnels.length}`;
  6819. }
  6820. const statSaved = document.getElementById('aerotun-stat-saved');
  6821. if (statSaved) {
  6822. statSaved.innerText = formatBytes(stats.total_saved_bytes || 0);
  6823. }
  6824. const statRatio = document.getElementById('aerotun-stat-ratio');
  6825. if (statRatio) {
  6826. statRatio.innerText = stats.average_ratio || '1.00x (0% saved)';
  6827. }
  6828. const statTraffic = document.getElementById('aerotun-stat-traffic');
  6829. if (statTraffic) {
  6830. statTraffic.innerText = `↓ ${formatBytes(stats.total_rx_bytes || 0)} / ↑ ${formatBytes(stats.total_tx_bytes || 0)}`;
  6831. }
  6832. if (!tbody) return;
  6833. tbody.innerHTML = '';
  6834. if (tunnels.length === 0) {
  6835. empty?.classList.remove('hidden');
  6836. return;
  6837. }
  6838. empty?.classList.add('hidden');
  6839. tunnels.forEach(t => {
  6840. const tr = document.createElement('tr');
  6841. tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
  6842. const modeBadge = t.mode === 'server'
  6843. ? `<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>`
  6844. : `<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>`;
  6845. const endpointInfo = t.mode === 'server'
  6846. ? `<span class="text-sky-300 font-mono">Port :${t.listen_port || 51830}</span>`
  6847. : `<span class="text-indigo-300 font-mono">${escapeHtml(t.remote_endpoint || '(not set)')}</span>`;
  6848. const compBadge = t.compression
  6849. ? `<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>`
  6850. : `<span class="text-slate-500 text-[10px]">Off</span>`;
  6851. const activePeer = t.active_peer_endpoint
  6852. ? `<span class="text-emerald-400 font-mono text-[11px]" title="Last seen: ${t.last_handshake || 'just now'}">● ${escapeHtml(t.active_peer_endpoint)}</span>`
  6853. : `<span class="text-slate-500 text-[11px]">${t.mode === 'server' ? 'Waiting for peer...' : 'Connecting...'}</span>`;
  6854. const rawRx = formatBytes(t.rx_bytes || 0);
  6855. const rawTx = formatBytes(t.tx_bytes || 0);
  6856. const wireRx = formatBytes(t.wire_bytes_in || 0);
  6857. const wireTx = formatBytes(t.wire_bytes_out || 0);
  6858. tr.innerHTML = `
  6859. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.running, t.disabled)}</td>
  6860. <td class="py-2.5 px-3 font-bold text-white font-mono flex items-center gap-1.5">
  6861. <span>${escapeHtml(t.name)}</span>
  6862. ${t.default_route ? '<span class="text-[9px] px-1 rounded bg-amber-500/20 text-amber-300 border border-amber-500/30">DEF</span>' : ''}
  6863. </td>
  6864. <td class="py-2.5 px-3">${modeBadge}</td>
  6865. <td class="py-2.5 px-3 text-xs font-mono">${endpointInfo}</td>
  6866. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${escapeHtml(t.local_address || '-')}</td>
  6867. <td class="py-2.5 px-3">${compBadge}</td>
  6868. <td class="py-2.5 px-3">${activePeer}</td>
  6869. <td class="py-2.5 px-3 font-mono text-[11px]">
  6870. <span class="text-emerald-400">↓ ${rawRx}</span>
  6871. <span class="text-cyan-400 ml-1">↑ ${rawTx}</span>
  6872. </td>
  6873. <td class="py-2.5 px-3 font-mono text-[11px]">
  6874. <span class="text-slate-400">↓ ${wireRx}</span>
  6875. <span class="text-slate-400 ml-1">↑ ${wireTx}</span>
  6876. </td>
  6877. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(t.comment || '')}">${escapeHtml(t.comment || '-')}</td>
  6878. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  6879. ${t.running
  6880. ? `<button onclick="stopAeroTUNTunnel('${t.id}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Stop</button>`
  6881. : `<button onclick="startAeroTUNTunnel('${t.id}')" class="text-xs text-emerald-400 hover:text-emerald-300 font-medium">Start</button>`
  6882. }
  6883. <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>
  6884. <button onclick="openEditAeroTUNModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  6885. <button onclick="deleteAeroTUN('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  6886. </td>
  6887. `;
  6888. tbody.appendChild(tr);
  6889. });
  6890. }
  6891. function onAeroTUNModeChange() {
  6892. const mode = document.getElementById('aerotun-modal-mode').value;
  6893. const endpointInput = document.getElementById('aerotun-modal-endpoint');
  6894. const portInput = document.getElementById('aerotun-modal-port');
  6895. if (mode === 'server') {
  6896. if (!portInput.value) portInput.value = '51830';
  6897. endpointInput.placeholder = 'Optional / learned roaming peer';
  6898. } else {
  6899. endpointInput.placeholder = 'vpn.example.com:51830 (required)';
  6900. if (!portInput.value) portInput.value = '';
  6901. }
  6902. }
  6903. async function generateAeroTUNKey() {
  6904. try {
  6905. const res = await fetch(`${API_BASE}/vpn/aerotun/genkey`);
  6906. if (res.ok) {
  6907. const data = await res.json();
  6908. document.getElementById('aerotun-modal-psk').value = data.key;
  6909. showToast('Key Generated', 'Cryptographic 256-bit PSK generated', 'success');
  6910. }
  6911. } catch (err) {
  6912. const arr = new Uint8Array(32);
  6913. crypto.getRandomValues(arr);
  6914. const hex = Array.from(arr).map(b => b.toString(16).padStart(2, '0')).join('');
  6915. document.getElementById('aerotun-modal-psk').value = hex;
  6916. }
  6917. }
  6918. function openAddAeroTUNModal() {
  6919. const tunnels = state.aerotunTunnels || [];
  6920. document.getElementById('aerotun-modal-title').innerText = 'Add AeroTUN Interface';
  6921. document.getElementById('aerotun-modal-id').value = '';
  6922. document.getElementById('aerotun-modal-name').value = `aerotun${tunnels.length}`;
  6923. document.getElementById('aerotun-modal-mode').value = 'server';
  6924. document.getElementById('aerotun-modal-port').value = 51830 + tunnels.length;
  6925. document.getElementById('aerotun-modal-endpoint').value = '';
  6926. document.getElementById('aerotun-modal-local').value = `10.99.${tunnels.length}.1/24`;
  6927. document.getElementById('aerotun-modal-peer').value = `10.99.${tunnels.length}.2/24`;
  6928. document.getElementById('aerotun-modal-psk').value = '';
  6929. document.getElementById('aerotun-modal-mtu').value = '1420';
  6930. document.getElementById('aerotun-modal-comment').value = '';
  6931. document.getElementById('aerotun-modal-compression').checked = true;
  6932. document.getElementById('aerotun-modal-defroute').checked = false;
  6933. document.getElementById('aerotun-modal-disabled').checked = false;
  6934. generateAeroTUNKey();
  6935. onAeroTUNModeChange();
  6936. document.getElementById('aerotun-modal').classList.remove('hidden');
  6937. }
  6938. function openEditAeroTUNModal(id) {
  6939. const t = (state.aerotunTunnels || []).find(tun => tun.id === id);
  6940. if (!t) return;
  6941. document.getElementById('aerotun-modal-title').innerText = `Edit AeroTUN Interface (${t.name})`;
  6942. document.getElementById('aerotun-modal-id').value = t.id;
  6943. document.getElementById('aerotun-modal-name').value = t.name;
  6944. document.getElementById('aerotun-modal-mode').value = t.mode || 'server';
  6945. document.getElementById('aerotun-modal-port').value = t.listen_port || '';
  6946. document.getElementById('aerotun-modal-endpoint').value = t.remote_endpoint || '';
  6947. document.getElementById('aerotun-modal-local').value = t.local_address || '';
  6948. document.getElementById('aerotun-modal-peer').value = t.peer_address || '';
  6949. document.getElementById('aerotun-modal-psk').value = t.psk || '';
  6950. document.getElementById('aerotun-modal-mtu').value = t.mtu || 1420;
  6951. document.getElementById('aerotun-modal-comment').value = t.comment || '';
  6952. document.getElementById('aerotun-modal-compression').checked = !!t.compression;
  6953. document.getElementById('aerotun-modal-defroute').checked = !!t.default_route;
  6954. document.getElementById('aerotun-modal-disabled').checked = !!t.disabled;
  6955. onAeroTUNModeChange();
  6956. document.getElementById('aerotun-modal').classList.remove('hidden');
  6957. }
  6958. function closeAeroTUNModal() {
  6959. document.getElementById('aerotun-modal').classList.add('hidden');
  6960. }
  6961. async function submitSaveAeroTUN(e) {
  6962. e.preventDefault();
  6963. const id = document.getElementById('aerotun-modal-id').value;
  6964. const name = document.getElementById('aerotun-modal-name').value.trim();
  6965. const mode = document.getElementById('aerotun-modal-mode').value;
  6966. const port = parseInt(document.getElementById('aerotun-modal-port').value) || 0;
  6967. const endpoint = document.getElementById('aerotun-modal-endpoint').value.trim();
  6968. const local = document.getElementById('aerotun-modal-local').value.trim();
  6969. const peer = document.getElementById('aerotun-modal-peer').value.trim();
  6970. const psk = document.getElementById('aerotun-modal-psk').value.trim();
  6971. const mtu = parseInt(document.getElementById('aerotun-modal-mtu').value) || 1420;
  6972. const comment = document.getElementById('aerotun-modal-comment').value.trim();
  6973. const compression = document.getElementById('aerotun-modal-compression').checked;
  6974. const defaultRoute = document.getElementById('aerotun-modal-defroute').checked;
  6975. const disabled = document.getElementById('aerotun-modal-disabled').checked;
  6976. if (mode === 'client' && !endpoint) {
  6977. showToast('Validation Error', 'Remote endpoint (host:port) is required in client mode', 'error');
  6978. return;
  6979. }
  6980. if (!psk) {
  6981. showToast('Validation Error', 'Pre-shared key (PSK) is required', 'error');
  6982. return;
  6983. }
  6984. try {
  6985. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels`, {
  6986. method: 'POST',
  6987. headers: { 'Content-Type': 'application/json' },
  6988. body: JSON.stringify({
  6989. id,
  6990. name,
  6991. mode,
  6992. listen_port: port,
  6993. remote_endpoint: endpoint,
  6994. local_address: local,
  6995. peer_address: peer,
  6996. psk,
  6997. mtu,
  6998. compression,
  6999. default_route: defaultRoute,
  7000. comment,
  7001. disabled
  7002. })
  7003. });
  7004. if (res.ok) {
  7005. showToast('AeroTUN Saved', `Tunnel ${name} configured successfully`, 'success');
  7006. closeAeroTUNModal();
  7007. loadAeroTUN(false);
  7008. fetchData(false);
  7009. } else {
  7010. const err = await res.text();
  7011. showToast('Error Saving Tunnel', err, 'error');
  7012. }
  7013. } catch (err) {
  7014. showToast('Network Error', err.message, 'error');
  7015. }
  7016. }
  7017. async function startAeroTUNTunnel(id) {
  7018. try {
  7019. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/start`, { method: 'POST' });
  7020. if (res.ok) {
  7021. showToast('AeroTUN Started', 'Tunnel interface is active', 'success');
  7022. loadAeroTUN(false);
  7023. fetchData(false);
  7024. } else {
  7025. const err = await res.text();
  7026. showToast('Failed to Start', err, 'error');
  7027. }
  7028. } catch (err) {
  7029. showToast('Error', err.message, 'error');
  7030. }
  7031. }
  7032. async function stopAeroTUNTunnel(id) {
  7033. try {
  7034. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/stop`, { method: 'POST' });
  7035. if (res.ok) {
  7036. showToast('AeroTUN Stopped', 'Tunnel stopped', 'info');
  7037. loadAeroTUN(false);
  7038. fetchData(false);
  7039. } else {
  7040. const err = await res.text();
  7041. showToast('Failed to Stop', err, 'error');
  7042. }
  7043. } catch (err) {
  7044. showToast('Error', err.message, 'error');
  7045. }
  7046. }
  7047. async function toggleAeroTUNState(id, disabled) {
  7048. try {
  7049. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/state`, {
  7050. method: 'POST',
  7051. headers: { 'Content-Type': 'application/json' },
  7052. body: JSON.stringify({ disabled })
  7053. });
  7054. if (res.ok) {
  7055. showToast('State Updated', disabled ? 'Tunnel disabled' : 'Tunnel enabled', 'info');
  7056. loadAeroTUN(false);
  7057. fetchData(false);
  7058. }
  7059. } catch (err) {
  7060. showToast('Error', err.message, 'error');
  7061. }
  7062. }
  7063. async function deleteAeroTUN(id) {
  7064. if (!confirm('Are you sure you want to delete this AeroTUN tunnel?')) return;
  7065. try {
  7066. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7067. if (res.ok) {
  7068. showToast('Deleted', 'AeroTUN tunnel removed', 'success');
  7069. loadAeroTUN(false);
  7070. fetchData(false);
  7071. }
  7072. } catch (err) {
  7073. showToast('Error', err.message, 'error');
  7074. }
  7075. }
  7076. // ======================== PPP Central Hub & Servers ========================
  7077. function switchPPPSubTab(tab) {
  7078. state.pppSubTab = tab;
  7079. const tabs = ['secrets', 'profiles', 'pppoe', 'pptp', 'l2tp', 'active'];
  7080. tabs.forEach(t => {
  7081. const panel = document.getElementById(`ppp-subtab-${t}`);
  7082. const btn = document.getElementById(`ppp-subtab-btn-${t}`);
  7083. if (panel) {
  7084. if (t === tab) panel.classList.remove('hidden');
  7085. else panel.classList.add('hidden');
  7086. }
  7087. if (btn) {
  7088. if (t === tab) {
  7089. 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';
  7090. } else {
  7091. 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';
  7092. }
  7093. }
  7094. });
  7095. const addBtn = document.getElementById('ppp-primary-add-btn');
  7096. if (addBtn) {
  7097. if (tab === 'secrets') addBtn.innerHTML = '<span>+ Add User (Secret)</span>';
  7098. else if (tab === 'profiles') addBtn.innerHTML = '<span>+ Add Profile</span>';
  7099. else if (tab === 'active') addBtn.innerHTML = '<span>Refresh Sessions</span>';
  7100. else addBtn.innerHTML = '<span>Save Config</span>';
  7101. }
  7102. if (tab === 'active') loadPPPSessions();
  7103. }
  7104. function openCurrentPPPModal() {
  7105. if (state.pppSubTab === 'secrets') openAddPPPSecretModal();
  7106. else if (state.pppSubTab === 'profiles') openAddPPPProfileModal();
  7107. else if (state.pppSubTab === 'active') loadPPPSessions();
  7108. else if (state.pppSubTab === 'pppoe') document.querySelector('#ppp-subtab-pppoe form')?.requestSubmit();
  7109. else if (state.pppSubTab === 'pptp') document.querySelector('#ppp-subtab-pptp form')?.requestSubmit();
  7110. else if (state.pppSubTab === 'l2tp') document.querySelector('#ppp-subtab-l2tp form')?.requestSubmit();
  7111. }
  7112. async function loadPPP(populateDropdowns = true) {
  7113. await Promise.all([
  7114. loadPPPSecrets(),
  7115. loadPPPProfiles(),
  7116. loadPPPServers(),
  7117. loadPPPSessions()
  7118. ]);
  7119. }
  7120. async function loadPPPSecrets() {
  7121. try {
  7122. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`);
  7123. const data = await res.json();
  7124. state.pppSecrets = Array.isArray(data) ? data : [];
  7125. const b = document.getElementById('ppp-badge-secrets');
  7126. if (b) b.innerText = state.pppSecrets.length;
  7127. const b2 = document.getElementById('secrets-count-badge');
  7128. if (b2) b2.innerText = `${state.pppSecrets.length} Users`;
  7129. renderPPPSecrets();
  7130. } catch (err) {
  7131. console.error('Failed to load PPP secrets:', err);
  7132. }
  7133. }
  7134. function renderPPPSecrets() {
  7135. const tbody = document.getElementById('secrets-table-body');
  7136. const empty = document.getElementById('secrets-empty');
  7137. if (!tbody) return;
  7138. tbody.innerHTML = '';
  7139. const secrets = state.pppSecrets || [];
  7140. if (secrets.length === 0) {
  7141. empty?.classList.remove('hidden');
  7142. return;
  7143. }
  7144. empty?.classList.add('hidden');
  7145. secrets.forEach(s => {
  7146. const tr = document.createElement('tr');
  7147. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  7148. tr.innerHTML = `
  7149. <td class="py-2.5 px-3 text-center">${renderRuleFlag(s.disabled, !!s.comment)}</td>
  7150. <td class="py-2.5 px-3 font-bold text-white font-mono">${s.name}</td>
  7151. <td class="py-2.5 px-3 text-purple-300 font-mono font-semibold">${s.service}</td>
  7152. <td class="py-2.5 px-3 text-amber-300 font-mono">${s.profile}</td>
  7153. <td class="py-2.5 px-3 text-slate-400 font-mono">${s.local_address || '(profile)'}</td>
  7154. <td class="py-2.5 px-3 text-cyan-400 font-mono font-bold">${s.remote_address || '(profile)'}</td>
  7155. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]">${s.comment || '-'}</td>
  7156. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  7157. <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>
  7158. <button onclick="openEditPPPSecretModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  7159. <button onclick="deletePPPSecret('${s.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  7160. </td>
  7161. `;
  7162. tbody.appendChild(tr);
  7163. });
  7164. }
  7165. async function loadPPPProfiles() {
  7166. try {
  7167. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`);
  7168. const data = await res.json();
  7169. state.pppProfiles = Array.isArray(data) ? data : [];
  7170. const b = document.getElementById('ppp-badge-profiles');
  7171. if (b) b.innerText = state.pppProfiles.length;
  7172. const b2 = document.getElementById('profiles-count-badge');
  7173. if (b2) b2.innerText = `${state.pppProfiles.length} Profiles`;
  7174. // Populate profile selects across modals
  7175. const selects = ['secret-modal-profile', 'pppoe-server-profile', 'pptp-server-profile', 'l2tp-server-profile'];
  7176. selects.forEach(sid => {
  7177. const el = document.getElementById(sid);
  7178. if (!el) return;
  7179. const cur = el.value;
  7180. el.innerHTML = '';
  7181. state.pppProfiles.forEach(p => {
  7182. const opt = document.createElement('option');
  7183. opt.value = p.name;
  7184. opt.innerText = `${p.name} (${p.remote_address})`;
  7185. if (p.name === cur) opt.selected = true;
  7186. el.appendChild(opt);
  7187. });
  7188. });
  7189. renderPPPProfiles();
  7190. } catch (err) {
  7191. console.error('Failed to load PPP profiles:', err);
  7192. }
  7193. }
  7194. function renderPPPProfiles() {
  7195. const tbody = document.getElementById('profiles-table-body');
  7196. if (!tbody) return;
  7197. tbody.innerHTML = '';
  7198. (state.pppProfiles || []).forEach(p => {
  7199. const isDefault = p.name.startsWith('default');
  7200. const tr = document.createElement('tr');
  7201. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  7202. tr.innerHTML = `
  7203. <td class="py-2.5 px-3 font-bold text-white">${p.name}</td>
  7204. <td class="py-2.5 px-3 text-slate-300">${p.local_address}</td>
  7205. <td class="py-2.5 px-3 text-cyan-400 font-bold">${p.remote_address}</td>
  7206. <td class="py-2.5 px-3 text-slate-400">${p.dns_servers || '-'}</td>
  7207. <td class="py-2.5 px-3 text-purple-300 font-semibold">${p.use_encryption}</td>
  7208. <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>
  7209. <td class="py-2.5 px-3 text-slate-400 italic">${p.comment || '-'}</td>
  7210. <td class="py-2.5 px-3 text-right font-sans whitespace-nowrap">
  7211. ${!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>`}
  7212. </td>
  7213. `;
  7214. tbody.appendChild(tr);
  7215. });
  7216. }
  7217. async function loadPPPServers() {
  7218. try {
  7219. const [pppoeRes, pptpRes, l2tpRes, ipsecRes] = await Promise.all([
  7220. fetch(`${API_BASE}/vpn/servers/pppoe`),
  7221. fetch(`${API_BASE}/vpn/servers/pptp`),
  7222. fetch(`${API_BASE}/vpn/servers/l2tp`),
  7223. fetch(`${API_BASE}/vpn/servers/ipsec`)
  7224. ]);
  7225. if (pppoeRes.ok) {
  7226. state.pppoeServer = await pppoeRes.json();
  7227. const s = state.pppoeServer;
  7228. document.getElementById('pppoe-server-enabled').checked = !!s.enabled;
  7229. document.getElementById('pppoe-server-name').value = s.service_name || 'proxmox-pppoe';
  7230. populateInterfaceSelect('pppoe-server-iface', s.interface || 'eth0');
  7231. document.getElementById('pppoe-server-profile').value = s.default_profile || 'default';
  7232. document.getElementById('pppoe-server-mtu').value = s.max_mtu || 1480;
  7233. document.getElementById('pppoe-server-onesession').checked = !!s.one_session_per_host;
  7234. const pill = document.getElementById('pppoe-server-status-pill');
  7235. if (pill) {
  7236. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  7237. 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';
  7238. }
  7239. setDotBadge('ppp-badge-pppoe-state', s.running);
  7240. }
  7241. if (pptpRes.ok) {
  7242. state.pptpServer = await pptpRes.json();
  7243. const s = state.pptpServer;
  7244. document.getElementById('pptp-server-enabled').checked = !!s.enabled;
  7245. document.getElementById('pptp-server-port').value = s.port || 1723;
  7246. document.getElementById('pptp-server-profile').value = s.default_profile || 'default-encryption';
  7247. document.getElementById('pptp-server-mppe').checked = s.require_mppe !== false;
  7248. const pill = document.getElementById('pptp-server-status-pill');
  7249. if (pill) {
  7250. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  7251. 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';
  7252. }
  7253. setDotBadge('ppp-badge-pptp-state', s.running);
  7254. }
  7255. if (l2tpRes.ok) {
  7256. state.l2tpServer = await l2tpRes.json();
  7257. const s = state.l2tpServer;
  7258. document.getElementById('l2tp-server-enabled').checked = !!s.enabled;
  7259. document.getElementById('l2tp-server-port').value = s.port || 1701;
  7260. document.getElementById('l2tp-server-profile').value = s.default_profile || 'default';
  7261. document.getElementById('l2tp-server-useipsec').value = s.use_ipsec || 'no';
  7262. document.getElementById('l2tp-server-ipsecsecret').value = s.ipsec_secret || '';
  7263. const pill = document.getElementById('l2tp-server-status-pill');
  7264. if (pill) {
  7265. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  7266. 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';
  7267. }
  7268. setDotBadge('ppp-badge-l2tp-state', s.running);
  7269. }
  7270. if (ipsecRes.ok) {
  7271. state.ipsecServer = await ipsecRes.json();
  7272. const s = state.ipsecServer;
  7273. const modalEn = document.getElementById('modal-ipsec-server-enabled');
  7274. if (modalEn) modalEn.checked = !!s.enabled;
  7275. const modalPsk = document.getElementById('modal-ipsec-server-psk');
  7276. if (modalPsk) modalPsk.value = s.preshared_key || '';
  7277. const modalPool = document.getElementById('modal-ipsec-server-pool');
  7278. if (modalPool) modalPool.value = s.pool_address || '10.10.30.0/24';
  7279. const modalDns = document.getElementById('modal-ipsec-server-dns');
  7280. if (modalDns) modalDns.value = s.dns_servers || '1.1.1.1,8.8.8.8';
  7281. const modalSubnet = document.getElementById('modal-ipsec-server-subnet');
  7282. if (modalSubnet) modalSubnet.value = s.local_subnet || '0.0.0.0/0';
  7283. const pill = document.getElementById('modal-ipsec-server-status');
  7284. if (pill) {
  7285. pill.innerText = s.running ? 'ACTIVE RESPONDER' : 'STOPPED';
  7286. 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';
  7287. }
  7288. }
  7289. } catch (err) {
  7290. console.error('Failed to load VPN servers:', err);
  7291. }
  7292. }
  7293. async function loadPPPSessions() {
  7294. try {
  7295. const res = await fetch(`${API_BASE}/vpn/ppp/active`);
  7296. const data = await res.json();
  7297. state.pppActiveSessions = Array.isArray(data) ? data : [];
  7298. const b = document.getElementById('ppp-badge-active');
  7299. if (b) b.innerText = state.pppActiveSessions.length;
  7300. const sideB = document.getElementById('badge-ppp-sessions');
  7301. if (sideB) sideB.innerText = state.pppActiveSessions.length;
  7302. renderPPPSessions();
  7303. } catch (err) {
  7304. console.error('Failed to load active PPP sessions:', err);
  7305. }
  7306. }
  7307. function renderPPPSessions() {
  7308. const tbody = document.getElementById('active-ppp-table-body');
  7309. const empty = document.getElementById('active-ppp-empty');
  7310. if (!tbody) return;
  7311. tbody.innerHTML = '';
  7312. const list = state.pppActiveSessions || [];
  7313. if (list.length === 0) {
  7314. empty?.classList.remove('hidden');
  7315. return;
  7316. }
  7317. empty?.classList.add('hidden');
  7318. list.forEach(s => {
  7319. const tr = document.createElement('tr');
  7320. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  7321. tr.innerHTML = `
  7322. <td class="py-2.5 px-3 font-bold text-white">${s.interface}</td>
  7323. <td class="py-2.5 px-3 font-semibold text-violet-300">${s.username}</td>
  7324. <td class="py-2.5 px-3 text-cyan-400 uppercase">${s.service}</td>
  7325. <td class="py-2.5 px-3 text-emerald-400 font-bold">${s.address || '-'}</td>
  7326. <td class="py-2.5 px-3 text-slate-400">${s.uptime}</td>
  7327. <td class="py-2.5 px-3 text-[11px]">
  7328. <span class="text-emerald-400">↓ ${s.rx_human || '0 B'}</span>
  7329. <span class="text-cyan-400 ml-1">↑ ${s.tx_human || '0 B'}</span>
  7330. </td>
  7331. <td class="py-2.5 px-3 text-right font-sans">
  7332. <button onclick="disconnectPPPSession('${s.interface}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  7333. </td>
  7334. `;
  7335. tbody.appendChild(tr);
  7336. });
  7337. }
  7338. async function disconnectPPPSession(iface) {
  7339. if (!confirm(`Disconnect session ${iface}?`)) return;
  7340. try {
  7341. const res = await fetch(`${API_BASE}/vpn/ppp/active/${encodeURIComponent(iface)}`, { method: 'DELETE' });
  7342. if (res.ok) {
  7343. showToast('Disconnected', `Session ${iface} terminated`, 'info');
  7344. loadPPPSessions();
  7345. }
  7346. } catch (err) {
  7347. showToast('Error', err.message, 'error');
  7348. }
  7349. }
  7350. // PPP Secret Modal handlers
  7351. function openAddPPPSecretModal() {
  7352. document.getElementById('secret-modal-title').innerText = 'Add PPP Secret';
  7353. document.getElementById('secret-modal-id').value = '';
  7354. document.getElementById('secret-modal-name').value = '';
  7355. document.getElementById('secret-modal-password').value = '';
  7356. document.getElementById('secret-modal-service').value = 'any';
  7357. document.getElementById('secret-modal-profile').value = 'default';
  7358. document.getElementById('secret-modal-local').value = '';
  7359. document.getElementById('secret-modal-remote').value = '';
  7360. document.getElementById('secret-modal-comment').value = '';
  7361. document.getElementById('secret-modal-disabled').checked = false;
  7362. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  7363. }
  7364. function openEditPPPSecretModal(id) {
  7365. const s = (state.pppSecrets || []).find(sec => sec.id === id);
  7366. if (!s) return;
  7367. document.getElementById('secret-modal-title').innerText = `Edit PPP Secret (${s.name})`;
  7368. document.getElementById('secret-modal-id').value = s.id;
  7369. document.getElementById('secret-modal-name').value = s.name;
  7370. document.getElementById('secret-modal-password').value = s.password;
  7371. document.getElementById('secret-modal-service').value = s.service || 'any';
  7372. document.getElementById('secret-modal-profile').value = s.profile || 'default';
  7373. document.getElementById('secret-modal-local').value = s.local_address || '';
  7374. document.getElementById('secret-modal-remote').value = s.remote_address || '';
  7375. document.getElementById('secret-modal-comment').value = s.comment || '';
  7376. document.getElementById('secret-modal-disabled').checked = !!s.disabled;
  7377. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  7378. }
  7379. function closePPPSecretModal() {
  7380. document.getElementById('ppp-secret-modal').classList.add('hidden');
  7381. }
  7382. async function submitSavePPPSecret(e) {
  7383. e.preventDefault();
  7384. const id = document.getElementById('secret-modal-id').value;
  7385. const name = document.getElementById('secret-modal-name').value.trim();
  7386. const password = document.getElementById('secret-modal-password').value.trim();
  7387. const service = document.getElementById('secret-modal-service').value;
  7388. const profile = document.getElementById('secret-modal-profile').value;
  7389. const local = document.getElementById('secret-modal-local').value.trim();
  7390. const remote = document.getElementById('secret-modal-remote').value.trim();
  7391. const comment = document.getElementById('secret-modal-comment').value.trim();
  7392. const disabled = document.getElementById('secret-modal-disabled').checked;
  7393. try {
  7394. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`, {
  7395. method: 'POST',
  7396. headers: { 'Content-Type': 'application/json' },
  7397. body: JSON.stringify({
  7398. id,
  7399. name,
  7400. password,
  7401. service,
  7402. profile,
  7403. local_address: local,
  7404. remote_address: remote,
  7405. comment,
  7406. disabled
  7407. })
  7408. });
  7409. if (res.ok) {
  7410. showToast('Secret Saved', `User ${name} saved to PPP database`, 'success');
  7411. closePPPSecretModal();
  7412. loadPPPSecrets();
  7413. } else {
  7414. const err = await res.json();
  7415. showToast('Error', err.message, 'error');
  7416. }
  7417. } catch (err) {
  7418. showToast('Error', err.message, 'error');
  7419. }
  7420. }
  7421. async function togglePPPSecretState(id, disabled) {
  7422. try {
  7423. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}/state`, {
  7424. method: 'POST',
  7425. headers: { 'Content-Type': 'application/json' },
  7426. body: JSON.stringify({ disabled })
  7427. });
  7428. if (res.ok) {
  7429. showToast(disabled ? 'Disabled' : 'Enabled', 'Secret user state updated', 'info');
  7430. loadPPPSecrets();
  7431. }
  7432. } catch (err) {
  7433. showToast('Error', err.message, 'error');
  7434. }
  7435. }
  7436. async function deletePPPSecret(id) {
  7437. if (!confirm('Are you sure you want to delete this secret account?')) return;
  7438. try {
  7439. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7440. if (res.ok) {
  7441. showToast('Deleted', 'Secret account removed', 'success');
  7442. loadPPPSecrets();
  7443. }
  7444. } catch (err) {
  7445. showToast('Error', err.message, 'error');
  7446. }
  7447. }
  7448. // PPP Profile Modal handlers
  7449. function openAddPPPProfileModal() {
  7450. document.getElementById('profile-modal-name').value = '';
  7451. document.getElementById('profile-modal-local').value = '10.10.10.1';
  7452. document.getElementById('profile-modal-remote').value = '10.10.10.10-10.10.10.50';
  7453. document.getElementById('profile-modal-dns').value = '1.1.1.1,8.8.8.8';
  7454. document.getElementById('profile-modal-encryption').value = 'required';
  7455. document.getElementById('profile-modal-onlyone').checked = true;
  7456. document.getElementById('profile-modal-comment').value = '';
  7457. document.getElementById('ppp-profile-modal').classList.remove('hidden');
  7458. }
  7459. function closePPPProfileModal() {
  7460. document.getElementById('ppp-profile-modal').classList.add('hidden');
  7461. }
  7462. async function submitSavePPPProfile(e) {
  7463. e.preventDefault();
  7464. const name = document.getElementById('profile-modal-name').value.trim();
  7465. const local = document.getElementById('profile-modal-local').value.trim();
  7466. const remote = document.getElementById('profile-modal-remote').value.trim();
  7467. const dns = document.getElementById('profile-modal-dns').value.trim();
  7468. const enc = document.getElementById('profile-modal-encryption').value;
  7469. const onlyone = document.getElementById('profile-modal-onlyone').checked;
  7470. const comment = document.getElementById('profile-modal-comment').value.trim();
  7471. try {
  7472. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`, {
  7473. method: 'POST',
  7474. headers: { 'Content-Type': 'application/json' },
  7475. body: JSON.stringify({
  7476. id: name,
  7477. name,
  7478. local_address: local,
  7479. remote_address: remote,
  7480. dns_servers: dns,
  7481. use_encryption: enc,
  7482. only_one: onlyone,
  7483. comment
  7484. })
  7485. });
  7486. if (res.ok) {
  7487. showToast('Profile Saved', `PPP profile ${name} created`, 'success');
  7488. closePPPProfileModal();
  7489. loadPPPProfiles();
  7490. } else {
  7491. const err = await res.json();
  7492. showToast('Error', err.message, 'error');
  7493. }
  7494. } catch (err) {
  7495. showToast('Error', err.message, 'error');
  7496. }
  7497. }
  7498. async function deletePPPProfile(name) {
  7499. if (!confirm(`Delete PPP profile ${name}?`)) return;
  7500. try {
  7501. const res = await fetch(`${API_BASE}/vpn/ppp/profiles/${encodeURIComponent(name)}`, { method: 'DELETE' });
  7502. if (res.ok) {
  7503. showToast('Deleted', 'Profile removed', 'success');
  7504. loadPPPProfiles();
  7505. } else {
  7506. const err = await res.json();
  7507. showToast('Error', err.message, 'error');
  7508. }
  7509. } catch (err) {
  7510. showToast('Error', err.message, 'error');
  7511. }
  7512. }
  7513. // Server Config submissions
  7514. async function savePPPoEServerConfig(e) {
  7515. e.preventDefault();
  7516. const enabled = document.getElementById('pppoe-server-enabled').checked;
  7517. const name = document.getElementById('pppoe-server-name').value.trim();
  7518. const iface = document.getElementById('pppoe-server-iface').value;
  7519. const profile = document.getElementById('pppoe-server-profile').value;
  7520. const mtu = parseInt(document.getElementById('pppoe-server-mtu').value) || 1480;
  7521. const onesession = document.getElementById('pppoe-server-onesession').checked;
  7522. try {
  7523. const res = await fetch(`${API_BASE}/vpn/servers/pppoe`, {
  7524. method: 'POST',
  7525. headers: { 'Content-Type': 'application/json' },
  7526. body: JSON.stringify({
  7527. enabled,
  7528. service_name: name,
  7529. interface: iface,
  7530. default_profile: profile,
  7531. max_mtu: mtu,
  7532. max_mru: mtu,
  7533. one_session_per_host: onesession
  7534. })
  7535. });
  7536. if (res.ok) {
  7537. showToast('PPPoE Server', enabled ? 'PPPoE Server started' : 'PPPoE Server stopped', 'success');
  7538. loadPPPServers();
  7539. fetchData(false);
  7540. } else {
  7541. const err = await res.json();
  7542. showToast('Error', err.message, 'error');
  7543. }
  7544. } catch (err) {
  7545. showToast('Error', err.message, 'error');
  7546. }
  7547. }
  7548. async function savePPTPServerConfig(e) {
  7549. e.preventDefault();
  7550. const enabled = document.getElementById('pptp-server-enabled').checked;
  7551. const port = parseInt(document.getElementById('pptp-server-port').value) || 1723;
  7552. const profile = document.getElementById('pptp-server-profile').value;
  7553. const mppe = document.getElementById('pptp-server-mppe').checked;
  7554. try {
  7555. const res = await fetch(`${API_BASE}/vpn/servers/pptp`, {
  7556. method: 'POST',
  7557. headers: { 'Content-Type': 'application/json' },
  7558. body: JSON.stringify({
  7559. enabled,
  7560. port,
  7561. default_profile: profile,
  7562. require_mppe: mppe
  7563. })
  7564. });
  7565. if (res.ok) {
  7566. showToast('PPTP Server', enabled ? 'PPTP Server started' : 'PPTP Server stopped', 'success');
  7567. loadPPPServers();
  7568. fetchData(false);
  7569. } else {
  7570. const err = await res.json();
  7571. showToast('Error', err.message, 'error');
  7572. }
  7573. } catch (err) {
  7574. showToast('Error', err.message, 'error');
  7575. }
  7576. }
  7577. async function saveL2TPServerConfig(e) {
  7578. e.preventDefault();
  7579. const enabled = document.getElementById('l2tp-server-enabled').checked;
  7580. const port = parseInt(document.getElementById('l2tp-server-port').value) || 1701;
  7581. const profile = document.getElementById('l2tp-server-profile').value;
  7582. const useipsec = document.getElementById('l2tp-server-useipsec').value;
  7583. const psk = document.getElementById('l2tp-server-ipsecsecret').value.trim();
  7584. try {
  7585. const res = await fetch(`${API_BASE}/vpn/servers/l2tp`, {
  7586. method: 'POST',
  7587. headers: { 'Content-Type': 'application/json' },
  7588. body: JSON.stringify({
  7589. enabled,
  7590. port,
  7591. default_profile: profile,
  7592. use_ipsec: useipsec,
  7593. ipsec_secret: psk
  7594. })
  7595. });
  7596. if (res.ok) {
  7597. showToast('L2TP Server', enabled ? 'L2TP Server started' : 'L2TP Server stopped', 'success');
  7598. loadPPPServers();
  7599. fetchData(false);
  7600. } else {
  7601. const err = await res.json();
  7602. showToast('Error', err.message, 'error');
  7603. }
  7604. } catch (err) {
  7605. showToast('Error', err.message, 'error');
  7606. }
  7607. }
  7608. // IPSec Server Modal
  7609. function openIPSecServerModal() {
  7610. loadPPPServers();
  7611. document.getElementById('ipsec-server-modal').classList.remove('hidden');
  7612. }
  7613. function closeIPSecServerModal() {
  7614. document.getElementById('ipsec-server-modal').classList.add('hidden');
  7615. }
  7616. async function submitSaveIPSecServer(e) {
  7617. e.preventDefault();
  7618. const enabled = document.getElementById('modal-ipsec-server-enabled').checked;
  7619. const psk = document.getElementById('modal-ipsec-server-psk').value.trim();
  7620. const pool = document.getElementById('modal-ipsec-server-pool').value.trim();
  7621. const dns = document.getElementById('modal-ipsec-server-dns').value.trim();
  7622. const subnet = document.getElementById('modal-ipsec-server-subnet').value.trim();
  7623. try {
  7624. const res = await fetch(`${API_BASE}/vpn/servers/ipsec`, {
  7625. method: 'POST',
  7626. headers: { 'Content-Type': 'application/json' },
  7627. body: JSON.stringify({
  7628. enabled,
  7629. preshared_key: psk,
  7630. pool_address: pool,
  7631. dns_servers: dns,
  7632. local_subnet: subnet
  7633. })
  7634. });
  7635. if (res.ok) {
  7636. showToast('IPSec Server', enabled ? 'IKEv2 Roadwarrior responder active' : 'IPSec Server stopped', 'success');
  7637. closeIPSecServerModal();
  7638. loadPPPServers();
  7639. fetchData(false);
  7640. } else {
  7641. const err = await res.json();
  7642. showToast('Error', err.message, 'error');
  7643. }
  7644. } catch (err) {
  7645. showToast('Error', err.message, 'error');
  7646. }
  7647. }
  7648. // WireGuard Client Config Viewer
  7649. let currentWGClientConf = '';
  7650. async function openWGClientConfModal(iface, clientIP) {
  7651. try {
  7652. const res = await fetch(`${API_BASE}/vpn/wireguard/client-config`, {
  7653. method: 'POST',
  7654. headers: { 'Content-Type': 'application/json' },
  7655. body: JSON.stringify({
  7656. interface: iface,
  7657. address: clientIP || '10.10.0.2/32',
  7658. dns: '1.1.1.1, 8.8.8.8'
  7659. })
  7660. });
  7661. if (res.ok) {
  7662. const data = await res.json();
  7663. currentWGClientConf = data.config;
  7664. document.getElementById('wg-client-conf-text').value = currentWGClientConf;
  7665. document.getElementById('wg-client-conf-modal').classList.remove('hidden');
  7666. } else {
  7667. const err = await res.json();
  7668. showToast('Error', err.message, 'error');
  7669. }
  7670. } catch (err) {
  7671. showToast('Error', err.message, 'error');
  7672. }
  7673. }
  7674. function closeWGClientConfModal() {
  7675. document.getElementById('wg-client-conf-modal').classList.add('hidden');
  7676. }
  7677. function copyWGClientConf() {
  7678. if (!currentWGClientConf) return;
  7679. copyToClipboard(currentWGClientConf, 'WireGuard Client Profile');
  7680. }
  7681. function downloadWGClientConf() {
  7682. if (!currentWGClientConf) return;
  7683. const blob = new Blob([currentWGClientConf], { type: 'text/plain;charset=utf-8' });
  7684. const a = document.createElement('a');
  7685. a.href = URL.createObjectURL(blob);
  7686. a.download = 'wireguard-client.conf';
  7687. document.body.appendChild(a);
  7688. a.click();
  7689. document.body.removeChild(a);
  7690. showToast('Downloaded', 'wireguard-client.conf saved', 'success');
  7691. }
  7692. // =========================================================================
  7693. // DYNAMIC ROUTING (FRRouting BGP & OSPFv2)
  7694. // =========================================================================
  7695. state.activeDynSubTab = 'bgp-peers';
  7696. state.activeBgpSubTab = 'bgp-peers';
  7697. state.activeOspfTab = 'instances';
  7698. state.bgpInstance = null;
  7699. state.bgpPeers = [];
  7700. state.bgpNets = [];
  7701. state.bgpRoutes = [];
  7702. state.ospfInstance = null;
  7703. state.ospfInstances = [];
  7704. state.ospfAreas = [];
  7705. state.ospfAreaRanges = [];
  7706. state.ospfTemplates = [];
  7707. state.ospfLiveInterfaces = [];
  7708. state.ospfStaticNbrs = [];
  7709. state.ospfNeighbors = [];
  7710. state.ospfLSA = [];
  7711. state.ospfRoutes = [];
  7712. state.selectedOspfRow = {
  7713. instances: null,
  7714. areas: null,
  7715. 'area-ranges': null,
  7716. templates: null,
  7717. interfaces: null,
  7718. 'static-nbrs': null,
  7719. neighbors: null,
  7720. lsa: null,
  7721. };
  7722. state.ospfSort = {
  7723. instances: { col: 'name', asc: true },
  7724. areas: { col: 'name', asc: true },
  7725. ranges: { col: 'area', asc: true },
  7726. templates: { col: 'interfaces', asc: true },
  7727. live_ifaces: { col: 'interface', asc: true },
  7728. snbrs: { col: 'address', asc: true },
  7729. neighbors: { col: 'address', asc: true },
  7730. lsa: { col: 'instance', asc: true },
  7731. };
  7732. function switchBgpSubTab(subTab) {
  7733. state.activeBgpSubTab = subTab;
  7734. const tabs = ['bgp-peers', 'bgp-nets', 'bgp-routes'];
  7735. tabs.forEach(t => {
  7736. const el = document.getElementById(`dyn-subtab-${t}`);
  7737. const btn = document.getElementById(`bgp-subtab-btn-${t}`);
  7738. if (el) el.classList.toggle('hidden', t !== subTab);
  7739. if (btn) {
  7740. if (t === subTab) {
  7741. 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';
  7742. } else {
  7743. 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';
  7744. }
  7745. }
  7746. });
  7747. }
  7748. function switchOspfTab(tabName) {
  7749. state.activeOspfTab = tabName;
  7750. const tabs = ['instances', 'areas', 'area-ranges', 'templates', 'interfaces', 'static-nbrs', 'neighbors', 'lsa'];
  7751. tabs.forEach(t => {
  7752. const pane = document.getElementById(`ospf-pane-${t}`);
  7753. const btn = document.getElementById(`ospf-tab-btn-${t}`);
  7754. if (pane) pane.classList.toggle('hidden', t !== tabName);
  7755. if (btn) {
  7756. if (t === tabName) {
  7757. 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';
  7758. } else {
  7759. 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';
  7760. }
  7761. }
  7762. });
  7763. }
  7764. function switchOspfSubTab(tab) {
  7765. // Legacy alias
  7766. if (tab === 'ospf-ifaces') switchOspfTab('templates');
  7767. else if (tab === 'ospf-areas') switchOspfTab('areas');
  7768. else if (tab === 'ospf-nbrs') switchOspfTab('neighbors');
  7769. else switchOspfTab('instances');
  7770. }
  7771. function switchDynSubTab(subTab) {
  7772. if (subTab.startsWith('bgp')) {
  7773. if (state.activeTab !== 'bgp') navigate('bgp');
  7774. switchBgpSubTab(subTab);
  7775. } else if (subTab.startsWith('ospf')) {
  7776. if (state.activeTab !== 'ospf') navigate('ospf');
  7777. switchOspfTab('instances');
  7778. }
  7779. }
  7780. async function loadDynamicRouting(showToastMsg = false) {
  7781. try {
  7782. const fetchSafeJson = async (url) => {
  7783. try {
  7784. const r = await fetch(url);
  7785. return r.ok ? await r.json() : null;
  7786. } catch (e) {
  7787. return null;
  7788. }
  7789. };
  7790. const [
  7791. sum, bgpInst, bgpPeers, bgpNets, bgpRoutes,
  7792. ospfInsts, ospfAreas, ospfRanges, ospfTemplates, ospfLiveIfaces, ospfStaticNbrs, ospfNbrs, ospfLsa, filters,
  7793. selectRules, commLists, asLists
  7794. ] = await Promise.all([
  7795. fetchSafeJson(`${API_BASE}/routing/dynamic/summary`),
  7796. fetchSafeJson(`${API_BASE}/routing/bgp/instance`),
  7797. fetchSafeJson(`${API_BASE}/routing/bgp/peers`),
  7798. fetchSafeJson(`${API_BASE}/routing/bgp/networks`),
  7799. fetchSafeJson(`${API_BASE}/routing/bgp/routes`),
  7800. fetchSafeJson(`${API_BASE}/routing/ospf/instances`),
  7801. fetchSafeJson(`${API_BASE}/routing/ospf/areas`),
  7802. fetchSafeJson(`${API_BASE}/routing/ospf/area-ranges`),
  7803. fetchSafeJson(`${API_BASE}/routing/ospf/templates`),
  7804. fetchSafeJson(`${API_BASE}/routing/ospf/interfaces-live`),
  7805. fetchSafeJson(`${API_BASE}/routing/ospf/static-neighbors`),
  7806. fetchSafeJson(`${API_BASE}/routing/ospf/neighbors`),
  7807. fetchSafeJson(`${API_BASE}/routing/ospf/lsa`),
  7808. fetchSafeJson(`${API_BASE}/routing/filters`),
  7809. fetchSafeJson(`${API_BASE}/routing/filters/select-rules`),
  7810. fetchSafeJson(`${API_BASE}/routing/filters/community-lists`),
  7811. fetchSafeJson(`${API_BASE}/routing/filters/as-lists`)
  7812. ]);
  7813. if (sum) state.dynSummary = sum;
  7814. if (bgpInst) state.bgpInstance = bgpInst;
  7815. if (bgpPeers) state.bgpPeers = bgpPeers;
  7816. if (bgpNets) state.bgpNets = bgpNets;
  7817. if (bgpRoutes) state.bgpRoutes = bgpRoutes;
  7818. if (ospfInsts) state.ospfInstances = ospfInsts;
  7819. if (ospfAreas) state.ospfAreas = ospfAreas;
  7820. if (ospfRanges) state.ospfAreaRanges = ospfRanges;
  7821. if (ospfTemplates) state.ospfTemplates = ospfTemplates;
  7822. if (ospfLiveIfaces) state.ospfLiveInterfaces = ospfLiveIfaces;
  7823. if (ospfStaticNbrs) state.ospfStaticNbrs = ospfStaticNbrs;
  7824. if (ospfNbrs) state.ospfNeighbors = ospfNbrs;
  7825. if (ospfLsa) state.ospfLSA = ospfLsa;
  7826. if (filters) state.routingFilters = filters;
  7827. if (selectRules) state.routingSelectRules = selectRules;
  7828. if (commLists) state.routingCommunityLists = commLists;
  7829. if (asLists) state.routingASLists = asLists;
  7830. try { renderBgpStatusPill(); } catch(e) { console.error('renderBgpStatusPill error:', e); }
  7831. try { renderBgpPeers(); } catch(e) { console.error('renderBgpPeers error:', e); }
  7832. try { renderBgpNetworks(); } catch(e) { console.error('renderBgpNetworks error:', e); }
  7833. try { renderBgpRoutes(); } catch(e) { console.error('renderBgpRoutes error:', e); }
  7834. try { renderOspfInstances(); } catch(e) { console.error('renderOspfInstances error:', e); }
  7835. try { renderOspfAreas(); } catch(e) { console.error('renderOspfAreas error:', e); }
  7836. try { renderOspfAreaRanges(); } catch(e) { console.error('renderOspfAreaRanges error:', e); }
  7837. try { renderOspfTemplates(); } catch(e) { console.error('renderOspfTemplates error:', e); }
  7838. try { renderOspfLiveInterfaces(); } catch(e) { console.error('renderOspfLiveInterfaces error:', e); }
  7839. try { renderOspfStaticNbrs(); } catch(e) { console.error('renderOspfStaticNbrs error:', e); }
  7840. try { renderOspfNeighbors(); } catch(e) { console.error('renderOspfNeighbors error:', e); }
  7841. try { renderOspfLSA(); } catch(e) { console.error('renderOspfLSA error:', e); }
  7842. try { renderRoutingFilters(); } catch(e) { console.error('renderRoutingFilters error:', e); }
  7843. try { updateBadges(); } catch(e) { console.error('updateBadges error:', e); }
  7844. if (showToastMsg) showToast('Refreshed', 'Dynamic routing telemetry updated', 'info');
  7845. } catch (err) {
  7846. console.error('Failed to load dynamic routing:', err);
  7847. if (showToastMsg) showToast('Notice', 'Unable to refresh dynamic routing telemetry', 'warning');
  7848. }
  7849. }
  7850. async function loadOspfAll() {
  7851. await loadDynamicRouting(true);
  7852. }
  7853. function renderBgpStatusPill() {
  7854. const pill = document.getElementById('bgp-live-status-pill');
  7855. if (!pill) return;
  7856. const inst = state.bgpInstance;
  7857. if (!inst || !inst.enabled) {
  7858. pill.className = 'text-[10px] px-2 py-0.5 rounded font-mono bg-slate-800 text-slate-400 border border-slate-700';
  7859. pill.innerText = 'BGP DISABLED';
  7860. } else if (inst.running) {
  7861. 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';
  7862. pill.innerText = `BGP ACTIVE (AS ${inst.as})`;
  7863. } else {
  7864. 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';
  7865. pill.innerText = 'BGP STARTING...';
  7866. }
  7867. }
  7868. function renderBgpPeers() {
  7869. const tbody = document.getElementById('bgp-peers-table-body');
  7870. if (!tbody) return;
  7871. const empty = document.getElementById('bgp-peers-empty');
  7872. const countBadge = document.getElementById('bgp-peers-count-badge');
  7873. const navBadge = document.getElementById('dyn-badge-bgp-peers');
  7874. const peers = state.bgpPeers || [];
  7875. if (countBadge) countBadge.innerText = `${peers.length} Peers`;
  7876. if (navBadge) navBadge.innerText = peers.length;
  7877. if (peers.length === 0) {
  7878. tbody.innerHTML = '';
  7879. if (empty) empty.classList.remove('hidden');
  7880. return;
  7881. }
  7882. if (empty) empty.classList.add('hidden');
  7883. const sig = peers.map(p => `${p.name}:${p.state}:${p.uptime}:${p.prefix_received}:${p.prefix_sent}:${p.disabled}`).join(';');
  7884. if (tbody.dataset.sig === sig) return;
  7885. tbody.dataset.sig = sig;
  7886. tbody.innerHTML = peers.map(p => {
  7887. let flagA = !p.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  7888. let flagE = p.state === 'Established' ? '<span class="text-emerald-400 font-bold ml-1" title="Established">E</span>' : '';
  7889. let flagX = p.disabled ? '<span class="text-rose-400 font-bold ml-1" title="Disabled">X</span>' : '';
  7890. let stateBadge = '';
  7891. if (p.disabled) {
  7892. 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>';
  7893. } else if (p.state === 'Established') {
  7894. 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>';
  7895. } else if (p.state === 'Connect' || p.state === 'Active') {
  7896. 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>`;
  7897. } else {
  7898. 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>`;
  7899. }
  7900. return `
  7901. <tr class="hover:bg-slate-800/40 transition">
  7902. <td class="py-2.5 px-3 text-center tracking-wider">${flagA}${flagE}${flagX}</td>
  7903. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(p.name)}</td>
  7904. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(p.remote_address)}</td>
  7905. <td class="py-2.5 px-3">
  7906. <div class="font-bold text-slate-200">AS ${p.remote_as}</div>
  7907. ${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>`}
  7908. </td>
  7909. <td class="py-2.5 px-3">${stateBadge}</td>
  7910. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(p.uptime || '-')}</td>
  7911. <td class="py-2.5 px-3 text-slate-300">
  7912. <span class="text-emerald-400 font-bold">↓ ${p.prefix_received || 0}</span> /
  7913. <span class="text-blue-400 font-bold">↑ ${p.prefix_sent || 0}</span>
  7914. </td>
  7915. <td class="py-2.5 px-3 font-mono text-[11px] whitespace-nowrap">
  7916. ${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> ` : ''}
  7917. ${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>` : ''}
  7918. ${!p.in_filter && !p.out_filter ? '<span class="text-slate-600">-</span>' : ''}
  7919. </td>
  7920. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(p.comment || '')}</td>
  7921. <td class="py-2.5 px-3 text-right space-x-1.5 whitespace-nowrap font-sans">
  7922. <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'}">
  7923. ${p.disabled ? 'Enable' : 'Disable'}
  7924. </button>
  7925. <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">
  7926. Edit
  7927. </button>
  7928. <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">
  7929. Delete
  7930. </button>
  7931. </td>
  7932. </tr>
  7933. `;
  7934. }).join('');
  7935. }
  7936. function renderBgpNetworks() {
  7937. const tbody = document.getElementById('bgp-nets-table-body');
  7938. if (!tbody) return;
  7939. const empty = document.getElementById('bgp-nets-empty');
  7940. const countBadge = document.getElementById('bgp-nets-count-badge');
  7941. const navBadge = document.getElementById('dyn-badge-bgp-nets');
  7942. const nets = state.bgpNets || [];
  7943. if (countBadge) countBadge.innerText = `${nets.length} Networks`;
  7944. if (navBadge) navBadge.innerText = nets.length;
  7945. if (nets.length === 0) {
  7946. tbody.innerHTML = '';
  7947. if (empty) empty.classList.remove('hidden');
  7948. return;
  7949. }
  7950. if (empty) empty.classList.add('hidden');
  7951. const sig = nets.map(n => `${n.network}:${n.disabled}:${n.comment}`).join(';');
  7952. if (tbody.dataset.sig === sig) return;
  7953. tbody.dataset.sig = sig;
  7954. tbody.innerHTML = nets.map(n => `
  7955. <tr class="hover:bg-slate-800/40 transition">
  7956. <td class="py-2.5 px-3 font-semibold text-purple-300 font-mono">${escapeHtml(n.network)}</td>
  7957. <td class="py-2.5 px-3">
  7958. ${n.disabled
  7959. ? '<span class="px-2 py-0.5 rounded-full text-[10px] bg-slate-800 text-slate-400 border border-slate-700">Disabled</span>'
  7960. : '<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>'}
  7961. </td>
  7962. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(n.comment || '')}</td>
  7963. <td class="py-2.5 px-3 text-right space-x-1 font-sans">
  7964. <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">
  7965. Delete
  7966. </button>
  7967. </td>
  7968. </tr>
  7969. `).join('');
  7970. }
  7971. function renderBgpRoutes() {
  7972. const tbody = document.getElementById('bgp-routes-table-body');
  7973. if (!tbody) return;
  7974. const empty = document.getElementById('bgp-routes-empty');
  7975. const countBadge = document.getElementById('bgp-routes-count-badge');
  7976. const navBadge = document.getElementById('dyn-badge-bgp-routes');
  7977. const routes = state.bgpRoutes || [];
  7978. if (countBadge) countBadge.innerText = `${routes.length} Routes`;
  7979. if (navBadge) navBadge.innerText = routes.length;
  7980. if (routes.length === 0) {
  7981. tbody.innerHTML = '';
  7982. if (empty) empty.classList.remove('hidden');
  7983. return;
  7984. }
  7985. if (empty) empty.classList.add('hidden');
  7986. const sig = routes.map(r => `${r.prefix}:${r.next_hop}:${r.metric}:${r.path}`).join(';');
  7987. if (tbody.dataset.sig === sig) return;
  7988. tbody.dataset.sig = sig;
  7989. tbody.innerHTML = routes.map(r => `
  7990. <tr class="hover:bg-slate-800/40 transition">
  7991. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.prefix)}</td>
  7992. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(r.next_hop || '-')}</td>
  7993. <td class="py-2.5 px-3 text-slate-300">${r.metric}</td>
  7994. <td class="py-2.5 px-3 text-slate-300">${r.weight}</td>
  7995. <td class="py-2.5 px-3 text-amber-300">${escapeHtml(r.path || 'i')}</td>
  7996. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.origin || 'IGP')}</td>
  7997. </tr>
  7998. `).join('');
  7999. }
  8000. // =========================================================================
  8001. // ROUTEROS v7 OSPF TABLE RENDERING & SORTING
  8002. // =========================================================================
  8003. function sortOspfTable(tab, col) {
  8004. if (!state.ospfSort) state.ospfSort = {};
  8005. if (!state.ospfSort[tab]) state.ospfSort[tab] = { col: col, asc: true };
  8006. if (state.ospfSort[tab].col === col) {
  8007. state.ospfSort[tab].asc = !state.ospfSort[tab].asc;
  8008. } else {
  8009. state.ospfSort[tab].col = col;
  8010. state.ospfSort[tab].asc = true;
  8011. }
  8012. const asc = state.ospfSort[tab].asc;
  8013. let list = [];
  8014. if (tab === 'instances') list = state.ospfInstances || [];
  8015. else if (tab === 'areas') list = state.ospfAreas || [];
  8016. else if (tab === 'ranges') list = state.ospfAreaRanges || [];
  8017. else if (tab === 'templates') list = state.ospfTemplates || [];
  8018. else if (tab === 'live_ifaces') list = state.ospfLiveInterfaces || [];
  8019. else if (tab === 'snbrs') list = state.ospfStaticNbrs || [];
  8020. else if (tab === 'neighbors') list = state.ospfNeighbors || [];
  8021. else if (tab === 'lsa') list = state.ospfLSA || [];
  8022. list.sort((a, b) => {
  8023. let valA = a[col] ?? '';
  8024. let valB = b[col] ?? '';
  8025. if (typeof valA === 'number' && typeof valB === 'number') {
  8026. return asc ? valA - valB : valB - valA;
  8027. }
  8028. return asc ? String(valA).localeCompare(String(valB)) : String(valB).localeCompare(String(valA));
  8029. });
  8030. if (tab === 'instances') renderOspfInstances();
  8031. else if (tab === 'areas') renderOspfAreas();
  8032. else if (tab === 'ranges') renderOspfAreaRanges();
  8033. else if (tab === 'templates') renderOspfTemplates();
  8034. else if (tab === 'live_ifaces') renderOspfLiveInterfaces();
  8035. else if (tab === 'snbrs') renderOspfStaticNbrs();
  8036. else if (tab === 'neighbors') renderOspfNeighbors();
  8037. else if (tab === 'lsa') renderOspfLSA();
  8038. }
  8039. function selectOspfRow(tab, id) {
  8040. if (!state.selectedOspfRow) state.selectedOspfRow = {};
  8041. state.selectedOspfRow[tab] = id;
  8042. if (tab === 'instances') {
  8043. renderOspfInstances();
  8044. const btnEn = document.getElementById('btn-ospf-inst-enable');
  8045. const btnDis = document.getElementById('btn-ospf-inst-disable');
  8046. const btnRem = document.getElementById('btn-ospf-inst-remove');
  8047. const btnCom = document.getElementById('btn-ospf-inst-comment');
  8048. if (btnEn) btnEn.disabled = false;
  8049. if (btnDis) btnDis.disabled = false;
  8050. if (btnRem) btnRem.disabled = false;
  8051. if (btnCom) btnCom.disabled = false;
  8052. } else if (tab === 'areas') {
  8053. renderOspfAreas();
  8054. const btnEn = document.getElementById('btn-ospf-area-enable');
  8055. const btnDis = document.getElementById('btn-ospf-area-disable');
  8056. const btnRem = document.getElementById('btn-ospf-area-remove');
  8057. const btnCom = document.getElementById('btn-ospf-area-comment');
  8058. if (btnEn) btnEn.disabled = false;
  8059. if (btnDis) btnDis.disabled = false;
  8060. if (btnRem) btnRem.disabled = false;
  8061. if (btnCom) btnCom.disabled = false;
  8062. } else if (tab === 'ranges') {
  8063. renderOspfAreaRanges();
  8064. const btnEn = document.getElementById('btn-ospf-range-enable');
  8065. const btnDis = document.getElementById('btn-ospf-range-disable');
  8066. const btnRem = document.getElementById('btn-ospf-range-remove');
  8067. const btnCom = document.getElementById('btn-ospf-range-comment');
  8068. if (btnEn) btnEn.disabled = false;
  8069. if (btnDis) btnDis.disabled = false;
  8070. if (btnRem) btnRem.disabled = false;
  8071. if (btnCom) btnCom.disabled = false;
  8072. } else if (tab === 'templates') {
  8073. renderOspfTemplates();
  8074. const btnEn = document.getElementById('btn-ospf-tmpl-enable');
  8075. const btnDis = document.getElementById('btn-ospf-tmpl-disable');
  8076. const btnRem = document.getElementById('btn-ospf-tmpl-remove');
  8077. const btnCom = document.getElementById('btn-ospf-tmpl-comment');
  8078. if (btnEn) btnEn.disabled = false;
  8079. if (btnDis) btnDis.disabled = false;
  8080. if (btnRem) btnRem.disabled = false;
  8081. if (btnCom) btnCom.disabled = false;
  8082. } else if (tab === 'snbrs') {
  8083. renderOspfStaticNbrs();
  8084. const btnEn = document.getElementById('btn-ospf-snbr-enable');
  8085. const btnDis = document.getElementById('btn-ospf-snbr-disable');
  8086. const btnRem = document.getElementById('btn-ospf-snbr-remove');
  8087. const btnCom = document.getElementById('btn-ospf-snbr-comment');
  8088. if (btnEn) btnEn.disabled = false;
  8089. if (btnDis) btnDis.disabled = false;
  8090. if (btnRem) btnRem.disabled = false;
  8091. if (btnCom) btnCom.disabled = false;
  8092. }
  8093. }
  8094. // TAB 1: INSTANCES
  8095. function renderOspfInstances() {
  8096. const tbody = document.getElementById('ospf-instances-table-body');
  8097. if (!tbody) return;
  8098. const countEl = document.getElementById('ospf-instances-footer-count');
  8099. const filter = (document.getElementById('filter-ospf-instances')?.value || '').toLowerCase();
  8100. let list = state.ospfInstances || [];
  8101. if (filter) {
  8102. list = list.filter(i => (i.name || '').toLowerCase().includes(filter) || (i.router_id || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  8103. }
  8104. if (countEl) countEl.innerText = list.length;
  8105. const selId = state.selectedOspfRow?.instances;
  8106. tbody.innerHTML = list.map((inst, idx) => {
  8107. const isSel = inst.id === selId;
  8108. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  8109. const flagD = inst.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  8110. return `
  8111. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('instances', '${inst.id}')" ondblclick="openEditOspfInstanceModal('${inst.id}')">
  8112. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  8113. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🔀'}</td>
  8114. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(inst.comment || '')}</td>
  8115. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  8116. <span class="text-sky-400">↳</span> <span>${escapeHtml(inst.name || 'Default')}</span>
  8117. </td>
  8118. <td class="py-1.5 px-3">${inst.version || 2}</td>
  8119. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(inst.vrf || 'main')}</td>
  8120. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(inst.router_id || '192.168.131.56')}</td>
  8121. </tr>
  8122. `;
  8123. }).join('');
  8124. }
  8125. // TAB 2: AREAS
  8126. function renderOspfAreas() {
  8127. const tbody = document.getElementById('ospf-areas-table-body');
  8128. if (!tbody) return;
  8129. const countEl = document.getElementById('ospf-areas-footer-count');
  8130. const filter = (document.getElementById('filter-ospf-areas')?.value || '').toLowerCase();
  8131. let list = state.ospfAreas || [];
  8132. if (filter) {
  8133. list = list.filter(a => (a.name || '').toLowerCase().includes(filter) || (a.area_id || '').toLowerCase().includes(filter) || (a.comment || '').toLowerCase().includes(filter));
  8134. }
  8135. if (countEl) countEl.innerText = list.length;
  8136. const selId = state.selectedOspfRow?.areas;
  8137. tbody.innerHTML = list.map((a, idx) => {
  8138. const isSel = a.id === selId;
  8139. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  8140. const flagD = a.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  8141. return `
  8142. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('areas', '${a.id}')" ondblclick="openEditOspfAreaModal('${a.id}')">
  8143. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  8144. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🌐'}</td>
  8145. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(a.comment || '')}</td>
  8146. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  8147. <span class="text-sky-400">↳</span> <span>${escapeHtml(a.name || 'Default')}</span>
  8148. </td>
  8149. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(a.instance || 'Default')}</td>
  8150. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(a.area_id || '0.0.0.0')}</td>
  8151. <td class="py-1.5 px-3 font-mono text-slate-400">${escapeHtml(a.area_type || 'default')}</td>
  8152. </tr>
  8153. `;
  8154. }).join('');
  8155. }
  8156. // TAB 3: AREA RANGES
  8157. function renderOspfAreaRanges() {
  8158. const tbody = document.getElementById('ospf-ranges-table-body');
  8159. if (!tbody) return;
  8160. const countEl = document.getElementById('ospf-ranges-footer-count');
  8161. const filter = (document.getElementById('filter-ospf-area-ranges')?.value || '').toLowerCase();
  8162. let list = state.ospfAreaRanges || [];
  8163. if (filter) {
  8164. list = list.filter(r => (r.prefix || '').toLowerCase().includes(filter) || (r.area || '').toLowerCase().includes(filter) || (r.comment || '').toLowerCase().includes(filter));
  8165. }
  8166. if (countEl) countEl.innerText = list.length;
  8167. const selId = state.selectedOspfRow?.['area-ranges'];
  8168. tbody.innerHTML = list.map((r, idx) => {
  8169. const isSel = r.id === selId;
  8170. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  8171. const flagD = r.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  8172. return `
  8173. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('ranges', '${r.id}')" ondblclick="openEditOspfAreaRangeModal('${r.id}')">
  8174. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  8175. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🏷'}</td>
  8176. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(r.comment || '')}</td>
  8177. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(r.area || 'Default')}</td>
  8178. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(r.prefix || '')}</td>
  8179. <td class="py-1.5 px-3">${r.cost || 1}</td>
  8180. <td class="py-1.5 px-3">${r.advertise !== false ? 'yes' : 'no'}</td>
  8181. </tr>
  8182. `;
  8183. }).join('');
  8184. }
  8185. // TAB 4: INTERFACE TEMPLATES
  8186. function renderOspfTemplates() {
  8187. const tbody = document.getElementById('ospf-templates-table-body');
  8188. if (!tbody) return;
  8189. const countEl = document.getElementById('ospf-templates-footer-count');
  8190. const filter = (document.getElementById('filter-ospf-templates')?.value || '').toLowerCase();
  8191. let list = state.ospfTemplates || [];
  8192. if (filter) {
  8193. list = list.filter(t => (t.interfaces || t.interface || '').toLowerCase().includes(filter) || (t.networks || t.network || '').toLowerCase().includes(filter) || (t.comment || '').toLowerCase().includes(filter));
  8194. }
  8195. if (countEl) countEl.innerText = list.length;
  8196. const selId = state.selectedOspfRow?.templates;
  8197. tbody.innerHTML = list.map((t, idx) => {
  8198. const isSel = t.id === selId;
  8199. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  8200. const ifaces = t.interfaces || t.interface || 'all';
  8201. const nets = t.networks || t.network || '';
  8202. const flagD = t.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  8203. return `
  8204. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('templates', '${t.id}')" ondblclick="openEditOspfTemplateModal('${t.id}')">
  8205. <td class="py-1.5 px-3 w-8 text-center text-slate-500 font-bold">${idx}</td>
  8206. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🔀'}</td>
  8207. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(t.comment || '')}</td>
  8208. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  8209. <span class="text-sky-400">↳</span> <span>${escapeHtml(ifaces)}</span>
  8210. </td>
  8211. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(t.area || 'Default')}</td>
  8212. <td class="py-1.5 px-3 font-mono text-sky-300">${escapeHtml(nets)}</td>
  8213. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(t.network_type || 'broadcast')}</td>
  8214. <td class="py-1.5 px-3">${t.cost || 1}</td>
  8215. <td class="py-1.5 px-3">${t.priority || 128}</td>
  8216. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(t.auth || t.auth_type || '')}</td>
  8217. </tr>
  8218. `;
  8219. }).join('');
  8220. }
  8221. // TAB 5: LIVE INTERFACES
  8222. function renderOspfLiveInterfaces() {
  8223. const tbody = document.getElementById('ospf-live-interfaces-table-body');
  8224. if (!tbody) return;
  8225. const countEl = document.getElementById('ospf-live-interfaces-footer-count');
  8226. const filter = (document.getElementById('filter-ospf-interfaces')?.value || '').toLowerCase();
  8227. let list = state.ospfLiveInterfaces || [];
  8228. if (filter) {
  8229. list = list.filter(i => (i.interface || '').toLowerCase().includes(filter) || (i.address || '').toLowerCase().includes(filter) || (i.state || '').toLowerCase().includes(filter));
  8230. }
  8231. if (countEl) countEl.innerText = list.length;
  8232. tbody.innerHTML = list.map(i => `
  8233. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  8234. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(i.flags || 'D')}</td>
  8235. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(i.interface || '')}</td>
  8236. <td class="py-1.5 px-3 font-mono text-sky-300 font-medium">${escapeHtml(i.address || '')}</td>
  8237. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(i.area || 'Default')}</td>
  8238. <td class="py-1.5 px-3 text-center text-slate-400">${i.instance_id || 0}</td>
  8239. <td class="py-1.5 px-3 font-mono text-amber-300 lowercase">${escapeHtml(i.state || 'waiting')}</td>
  8240. <td class="py-1.5 px-3">${i.cost || 1}</td>
  8241. <td class="py-1.5 px-3">${i.priority || 128}</td>
  8242. </tr>
  8243. `).join('');
  8244. }
  8245. // TAB 6: STATIC NEIGHBORS
  8246. function renderOspfStaticNbrs() {
  8247. const tbody = document.getElementById('ospf-snbrs-table-body');
  8248. if (!tbody) return;
  8249. const countEl = document.getElementById('ospf-snbrs-footer-count');
  8250. const filter = (document.getElementById('filter-ospf-static-nbrs')?.value || '').toLowerCase();
  8251. let list = state.ospfStaticNbrs || [];
  8252. if (filter) {
  8253. list = list.filter(n => (n.address || '').toLowerCase().includes(filter) || (n.area || '').toLowerCase().includes(filter) || (n.comment || '').toLowerCase().includes(filter));
  8254. }
  8255. if (countEl) countEl.innerText = list.length;
  8256. const selId = state.selectedOspfRow?.['static-nbrs'];
  8257. tbody.innerHTML = list.map((n, idx) => {
  8258. const isSel = n.id === selId;
  8259. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  8260. const flagD = n.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  8261. return `
  8262. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('snbrs', '${n.id}')" ondblclick="openEditOspfStaticNbrModal('${n.id}')">
  8263. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  8264. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '📡'}</td>
  8265. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(n.comment || '')}</td>
  8266. <td class="py-1.5 px-3 font-semibold font-mono text-sky-300">${escapeHtml(n.address || '')}</td>
  8267. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(n.area || 'Default')}</td>
  8268. <td class="py-1.5 px-3">${n.poll_interval || 120}s</td>
  8269. <td class="py-1.5 px-3">${n.cost || 1}</td>
  8270. </tr>
  8271. `;
  8272. }).join('');
  8273. }
  8274. // TAB 7: LIVE NEIGHBORS
  8275. function renderOspfNeighbors() {
  8276. const tbody = document.getElementById('ospf-neighbors-table-body');
  8277. if (!tbody) return;
  8278. const countEl = document.getElementById('ospf-neighbors-footer-count');
  8279. const filter = (document.getElementById('filter-ospf-neighbors')?.value || '').toLowerCase();
  8280. let list = state.ospfNeighbors || [];
  8281. if (filter) {
  8282. list = list.filter(n => (n.address || '').toLowerCase().includes(filter) || (n.state || '').toLowerCase().includes(filter) || (n.instance || '').toLowerCase().includes(filter));
  8283. }
  8284. if (countEl) countEl.innerText = list.length;
  8285. tbody.innerHTML = list.map(n => `
  8286. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  8287. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(n.flags || 'D')}</td>
  8288. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(n.comment || '')}</td>
  8289. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  8290. <span class="text-sky-400">↳</span> <span>${escapeHtml(n.instance || 'Default')}</span>
  8291. </td>
  8292. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(n.area || 'Default')}</td>
  8293. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(n.address || '')}</td>
  8294. <td class="py-1.5 px-3 font-mono font-bold text-emerald-400">${escapeHtml(n.state || 'Full')}</td>
  8295. <td class="py-1.5 px-3 text-slate-400">${n.state_changes ?? 6}</td>
  8296. </tr>
  8297. `).join('');
  8298. }
  8299. // TAB 8: LINK-STATE DATABASE (LSA)
  8300. function renderOspfLSA() {
  8301. const tbody = document.getElementById('ospf-lsa-table-body');
  8302. if (!tbody) return;
  8303. const countEl = document.getElementById('ospf-lsa-footer-count');
  8304. const filter = (document.getElementById('filter-ospf-lsa')?.value || '').toLowerCase();
  8305. let list = state.ospfLSA || [];
  8306. if (filter) {
  8307. list = list.filter(l => (l.type || '').toLowerCase().includes(filter) || (l.originator || '').toLowerCase().includes(filter) || (l.id || '').toLowerCase().includes(filter));
  8308. }
  8309. if (countEl) countEl.innerText = list.length;
  8310. tbody.innerHTML = list.map(l => `
  8311. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  8312. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(l.flags || 'D')}</td>
  8313. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  8314. <span class="text-sky-400">↳</span> <span>${escapeHtml(l.instance || 'Default')}</span>
  8315. </td>
  8316. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(l.area || 'Default')}</td>
  8317. <td class="py-1.5 px-3 font-mono text-amber-300">${escapeHtml(l.type || 'router')}</td>
  8318. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(l.originator || '')}</td>
  8319. <td class="py-1.5 px-3 font-mono text-sky-300 font-medium">${escapeHtml(l.id || '')}</td>
  8320. <td class="py-1.5 px-3 text-slate-500">${escapeHtml(l.link || '')}</td>
  8321. <td class="py-1.5 px-3 text-slate-500">${l.link_index ?? 0}</td>
  8322. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(l.sequence || '')}</td>
  8323. <td class="py-1.5 px-3 text-slate-400">${l.age ?? 0}</td>
  8324. </tr>
  8325. `).join('');
  8326. }
  8327. function renderOspfStatusPill() {
  8328. // Maintained for backward compatibility
  8329. const pill = document.getElementById('ospf-live-status-pill');
  8330. if (!pill) return;
  8331. 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';
  8332. pill.innerText = 'OSPF ACTIVE';
  8333. }
  8334. function renderOspfInterfaces() {
  8335. renderOspfTemplates();
  8336. }
  8337. function renderOspfRoutes() {
  8338. // Routes retained in background
  8339. }
  8340. // BGP Modals & Actions
  8341. function openBgpInstanceModal() {
  8342. const inst = state.bgpInstance || { enabled: false, as: 65001, router_id: '192.168.131.56', hold_time: 180, keepalive_time: 60 };
  8343. document.getElementById('modal-bgp-enabled').checked = !!inst.enabled;
  8344. document.getElementById('modal-bgp-as').value = inst.as || 65001;
  8345. document.getElementById('modal-bgp-router-id').value = inst.router_id || '';
  8346. document.getElementById('modal-bgp-keepalive').value = inst.keepalive_time || 60;
  8347. document.getElementById('modal-bgp-holdtime').value = inst.hold_time || 180;
  8348. document.getElementById('modal-bgp-redist-conn').checked = !!inst.redistribute_connected;
  8349. document.getElementById('modal-bgp-redist-static').checked = !!inst.redistribute_static;
  8350. document.getElementById('modal-bgp-redist-ospf').checked = !!inst.redistribute_ospf;
  8351. document.getElementById('bgp-instance-modal').classList.remove('hidden');
  8352. }
  8353. function closeBgpInstanceModal() {
  8354. document.getElementById('bgp-instance-modal').classList.add('hidden');
  8355. }
  8356. async function submitBgpInstance(e) {
  8357. e.preventDefault();
  8358. const payload = {
  8359. enabled: document.getElementById('modal-bgp-enabled').checked,
  8360. as: parseInt(document.getElementById('modal-bgp-as').value, 10),
  8361. router_id: document.getElementById('modal-bgp-router-id').value.trim(),
  8362. keepalive_time: parseInt(document.getElementById('modal-bgp-keepalive').value, 10),
  8363. hold_time: parseInt(document.getElementById('modal-bgp-holdtime').value, 10),
  8364. redistribute_connected: document.getElementById('modal-bgp-redist-conn').checked,
  8365. redistribute_static: document.getElementById('modal-bgp-redist-static').checked,
  8366. redistribute_ospf: document.getElementById('modal-bgp-redist-ospf').checked
  8367. };
  8368. try {
  8369. const res = await fetch(`${API_BASE}/routing/bgp/instance`, {
  8370. method: 'POST',
  8371. headers: { 'Content-Type': 'application/json' },
  8372. body: JSON.stringify(payload)
  8373. });
  8374. if (res.ok) {
  8375. closeBgpInstanceModal();
  8376. showToast('Success', 'BGP instance configuration updated', 'success');
  8377. loadDynamicRouting();
  8378. } else {
  8379. const err = await res.json();
  8380. showToast('Error', err.error || 'Failed to update BGP instance', 'error');
  8381. }
  8382. } catch (err) {
  8383. showToast('Error', err.message, 'error');
  8384. }
  8385. }
  8386. // ----------------- BGP Peer Connection Modal (RouterOS v7) -----------------
  8387. function switchBgpPeerModalTab(tab) {
  8388. const tabs = ['general', 'extra', 'attributes', 'filter'];
  8389. tabs.forEach(t => {
  8390. const pane = document.getElementById(`bgp-peer-tab-${t}`);
  8391. const btn = document.getElementById(`bgp-peer-tab-btn-${t}`);
  8392. if (t === tab) {
  8393. if (pane) pane.classList.remove('hidden');
  8394. if (btn) btn.className = 'px-4 py-2 text-xs font-bold border-b-2 border-cyan-500 text-white transition';
  8395. } else {
  8396. if (pane) pane.classList.add('hidden');
  8397. 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';
  8398. }
  8399. });
  8400. }
  8401. function addOutputNetworkRow(val = '') {
  8402. const container = document.getElementById('modal-bgp-output-networks-container');
  8403. if (!container) return;
  8404. const row = document.createElement('div');
  8405. row.className = 'flex items-center gap-2 output-net-row';
  8406. row.innerHTML = `
  8407. <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">
  8408. <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>
  8409. `;
  8410. container.appendChild(row);
  8411. }
  8412. function parseBgpTime(val) {
  8413. if (!val) return 0;
  8414. val = String(val).trim();
  8415. if (val.includes(':')) {
  8416. const parts = val.split(':').map(x => parseInt(x, 10) || 0);
  8417. if (parts.length === 3) return parts[0] * 3600 + parts[1] * 60 + parts[2];
  8418. if (parts.length === 2) return parts[0] * 60 + parts[1];
  8419. }
  8420. return parseInt(val, 10) || 0;
  8421. }
  8422. function formatBgpTime(secs) {
  8423. if (!secs || secs <= 0) return '00:00:00';
  8424. const h = Math.floor(secs / 3600);
  8425. const m = Math.floor((secs % 3600) / 60);
  8426. const s = secs % 60;
  8427. return `${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`;
  8428. }
  8429. function populateBgpRoutingTables() {
  8430. const sel = document.getElementById('modal-bgp-peer-routing-table');
  8431. if (!sel) return;
  8432. const cur = sel.value || 'main';
  8433. sel.innerHTML = '<option value="main">main</option>';
  8434. (state.routingTables || []).forEach(t => {
  8435. if (t.name !== 'main') {
  8436. const opt = document.createElement('option');
  8437. opt.value = t.name;
  8438. opt.innerText = t.name;
  8439. sel.appendChild(opt);
  8440. }
  8441. });
  8442. sel.value = cur;
  8443. }
  8444. function openAddBgpPeerModal() {
  8445. document.getElementById('bgp-peer-form').reset();
  8446. document.getElementById('modal-bgp-peer-id').value = '';
  8447. document.getElementById('bgp-peer-modal-title').innerText = 'New...';
  8448. // General Tab
  8449. document.getElementById('modal-bgp-peer-enabled').checked = true;
  8450. document.getElementById('modal-bgp-peer-comment').value = '';
  8451. document.getElementById('modal-bgp-peer-name').value = '';
  8452. if (document.getElementById('modal-bgp-peer-instance')) document.getElementById('modal-bgp-peer-instance').value = 'bgp-instance-1';
  8453. if (document.getElementById('modal-bgp-peer-template')) document.getElementById('modal-bgp-peer-template').value = '';
  8454. document.getElementById('modal-bgp-peer-local-as').value = '';
  8455. document.getElementById('modal-bgp-peer-afi-ip').checked = true;
  8456. document.getElementById('modal-bgp-peer-afi-ipv6').checked = false;
  8457. if (document.getElementById('modal-bgp-peer-afi-l2vpn')) document.getElementById('modal-bgp-peer-afi-l2vpn').checked = false;
  8458. if (document.getElementById('modal-bgp-peer-afi-vpnv4')) document.getElementById('modal-bgp-peer-afi-vpnv4').checked = false;
  8459. if (document.getElementById('modal-bgp-peer-afi-l2vpn-cisco')) document.getElementById('modal-bgp-peer-afi-l2vpn-cisco').checked = false;
  8460. document.getElementById('modal-bgp-peer-router-id').value = '';
  8461. document.getElementById('modal-bgp-peer-remote-addr').value = '';
  8462. document.getElementById('modal-bgp-peer-remote-port').value = '';
  8463. document.getElementById('modal-bgp-peer-remote-as').value = '';
  8464. if (document.getElementById('modal-bgp-peer-remote-allow-as')) document.getElementById('modal-bgp-peer-remote-allow-as').value = '';
  8465. document.getElementById('modal-bgp-peer-local-addr').value = '';
  8466. document.getElementById('modal-bgp-peer-local-port').value = '';
  8467. document.getElementById('modal-bgp-peer-local-role').value = 'ebgp';
  8468. document.getElementById('modal-bgp-peer-password').value = '';
  8469. document.getElementById('modal-bgp-peer-multihop').checked = false;
  8470. if (document.getElementById('modal-bgp-peer-tx-ttl')) document.getElementById('modal-bgp-peer-tx-ttl').value = '';
  8471. if (document.getElementById('modal-bgp-peer-rx-min-ttl')) document.getElementById('modal-bgp-peer-rx-min-ttl').value = '';
  8472. document.getElementById('modal-bgp-peer-connect').checked = true;
  8473. document.getElementById('modal-bgp-peer-listen').checked = true;
  8474. // Extra Tab
  8475. document.getElementById('modal-bgp-peer-holdtime').value = '00:00:30';
  8476. document.getElementById('modal-bgp-peer-keepalive').value = '00:00:10';
  8477. if (document.getElementById('modal-bgp-peer-use-bfd')) document.getElementById('modal-bgp-peer-use-bfd').checked = false;
  8478. if (document.getElementById('modal-bgp-peer-vrf')) document.getElementById('modal-bgp-peer-vrf').value = 'main';
  8479. if (document.getElementById('modal-bgp-peer-no-client-reflect')) document.getElementById('modal-bgp-peer-no-client-reflect').checked = true;
  8480. document.getElementById('modal-bgp-peer-redist-conn').checked = false;
  8481. document.getElementById('modal-bgp-peer-redist-static').checked = true;
  8482. if (document.getElementById('modal-bgp-peer-redist-rip')) document.getElementById('modal-bgp-peer-redist-rip').checked = false;
  8483. document.getElementById('modal-bgp-peer-redist-ospf').checked = false;
  8484. document.getElementById('modal-bgp-peer-redist-bgp').checked = false;
  8485. if (document.getElementById('modal-bgp-peer-redist-vpn')) document.getElementById('modal-bgp-peer-redist-vpn').checked = false;
  8486. if (document.getElementById('modal-bgp-peer-redist-dhcp')) document.getElementById('modal-bgp-peer-redist-dhcp').checked = false;
  8487. if (document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn')) document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn').checked = false;
  8488. if (document.getElementById('modal-bgp-peer-redist-slaac')) document.getElementById('modal-bgp-peer-redist-slaac').checked = false;
  8489. document.getElementById('modal-bgp-peer-default-orig').checked = false;
  8490. if (document.getElementById('modal-bgp-peer-network-blackhole')) document.getElementById('modal-bgp-peer-network-blackhole').checked = false;
  8491. if (document.getElementById('modal-bgp-peer-no-early-cut')) document.getElementById('modal-bgp-peer-no-early-cut').checked = false;
  8492. if (document.getElementById('modal-bgp-peer-keep-sent-attrs')) document.getElementById('modal-bgp-peer-keep-sent-attrs').checked = false;
  8493. if (document.getElementById('modal-bgp-peer-input-affinity')) document.getElementById('modal-bgp-peer-input-affinity').value = '';
  8494. if (document.getElementById('modal-bgp-peer-output-affinity')) document.getElementById('modal-bgp-peer-output-affinity').value = '';
  8495. // Attributes Tab
  8496. document.getElementById('modal-bgp-peer-nexthop-choice').value = 'force-self';
  8497. document.getElementById('modal-bgp-peer-default-prepend').value = 0;
  8498. document.getElementById('modal-bgp-peer-allow-as-in').value = 0;
  8499. if (document.getElementById('modal-bgp-peer-ignore-as-path-len')) document.getElementById('modal-bgp-peer-ignore-as-path-len').checked = false;
  8500. document.getElementById('modal-bgp-peer-remove-priv-as').checked = false;
  8501. document.getElementById('modal-bgp-peer-as-override').checked = false;
  8502. // Filter Tab
  8503. populateFilterChainsDatalist();
  8504. document.getElementById('modal-bgp-peer-in-filter').value = '';
  8505. if (document.getElementById('modal-bgp-peer-in-accept-nlri')) document.getElementById('modal-bgp-peer-in-accept-nlri').value = '';
  8506. if (document.getElementById('modal-bgp-peer-in-accept-comm')) document.getElementById('modal-bgp-peer-in-accept-comm').value = '';
  8507. if (document.getElementById('modal-bgp-peer-in-accept-ext-comm')) document.getElementById('modal-bgp-peer-in-accept-ext-comm').value = '';
  8508. if (document.getElementById('modal-bgp-peer-in-accept-large-comm')) document.getElementById('modal-bgp-peer-in-accept-large-comm').value = '';
  8509. if (document.getElementById('modal-bgp-peer-in-filter-comm')) document.getElementById('modal-bgp-peer-in-filter-comm').value = '';
  8510. if (document.getElementById('modal-bgp-peer-in-filter-ext-comm')) document.getElementById('modal-bgp-peer-in-filter-ext-comm').value = '';
  8511. if (document.getElementById('modal-bgp-peer-in-filter-large-comm')) document.getElementById('modal-bgp-peer-in-filter-large-comm').value = '';
  8512. if (document.getElementById('modal-bgp-peer-in-filter-unknown')) document.getElementById('modal-bgp-peer-in-filter-unknown').checked = false;
  8513. document.getElementById('modal-bgp-peer-out-filter').value = '';
  8514. if (document.getElementById('modal-bgp-peer-out-selection-policy')) document.getElementById('modal-bgp-peer-out-selection-policy').value = 'disabled';
  8515. if (document.getElementById('modal-bgp-peer-out-network-name')) document.getElementById('modal-bgp-peer-out-network-name').value = '';
  8516. populateBgpRoutingTables();
  8517. const container = document.getElementById('modal-bgp-output-networks-container');
  8518. if (container) {
  8519. container.innerHTML = '';
  8520. addOutputNetworkRow('');
  8521. }
  8522. const removeBtn = document.getElementById('modal-btn-remove-peer');
  8523. if (removeBtn) removeBtn.classList.add('hidden');
  8524. switchBgpPeerModalTab('general');
  8525. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  8526. }
  8527. function populateFilterChainsDatalist() {
  8528. const dl = document.getElementById('filter-chains-list');
  8529. if (!dl) return;
  8530. const chains = new Set();
  8531. (state.routingFilters || []).forEach(f => {
  8532. if (f.chain) chains.add(f.chain);
  8533. });
  8534. if (chains.size === 0) {
  8535. chains.add('awmn');
  8536. chains.add('bgp-in');
  8537. chains.add('bgp-out');
  8538. }
  8539. dl.innerHTML = '';
  8540. chains.forEach(c => {
  8541. const opt = document.createElement('option');
  8542. opt.value = c;
  8543. dl.appendChild(opt);
  8544. });
  8545. }
  8546. function openEditBgpPeerModal(id) {
  8547. const p = (state.bgpPeers || []).find(item => item.id === id);
  8548. if (!p) return;
  8549. populateBgpRoutingTables();
  8550. populateFilterChainsDatalist();
  8551. document.getElementById('modal-bgp-peer-id').value = p.id;
  8552. document.getElementById('bgp-peer-modal-title').innerText = p.name || p.id;
  8553. // General Tab
  8554. document.getElementById('modal-bgp-peer-enabled').checked = p.enabled !== false && !p.disabled;
  8555. document.getElementById('modal-bgp-peer-comment').value = p.comment || '';
  8556. document.getElementById('modal-bgp-peer-name').value = p.name || '';
  8557. if (document.getElementById('modal-bgp-peer-instance')) document.getElementById('modal-bgp-peer-instance').value = p.instance || 'bgp-instance-1';
  8558. if (document.getElementById('modal-bgp-peer-template')) document.getElementById('modal-bgp-peer-template').value = p.template || '';
  8559. document.getElementById('modal-bgp-peer-local-as').value = p.local_as || '';
  8560. document.getElementById('modal-bgp-peer-router-id').value = p.router_id || '';
  8561. document.getElementById('modal-bgp-peer-afi-ip').checked = true;
  8562. document.getElementById('modal-bgp-peer-afi-ipv6').checked = p.afi === 'ipv6';
  8563. document.getElementById('modal-bgp-peer-remote-addr').value = p.remote_address || '';
  8564. document.getElementById('modal-bgp-peer-remote-port').value = p.remote_port || '';
  8565. document.getElementById('modal-bgp-peer-remote-as').value = p.remote_as || '';
  8566. if (document.getElementById('modal-bgp-peer-remote-allow-as')) document.getElementById('modal-bgp-peer-remote-allow-as').value = p.remote_allow_as || '';
  8567. document.getElementById('modal-bgp-peer-local-addr').value = p.local_address || '';
  8568. document.getElementById('modal-bgp-peer-local-port').value = p.local_port || '';
  8569. document.getElementById('modal-bgp-peer-local-role').value = p.local_role || 'ebgp';
  8570. document.getElementById('modal-bgp-peer-password').value = p.password || '';
  8571. document.getElementById('modal-bgp-peer-multihop').checked = !!p.multihop;
  8572. if (document.getElementById('modal-bgp-peer-tx-ttl')) document.getElementById('modal-bgp-peer-tx-ttl').value = p.tx_ttl || '';
  8573. if (document.getElementById('modal-bgp-peer-rx-min-ttl')) document.getElementById('modal-bgp-peer-rx-min-ttl').value = p.rx_min_ttl || '';
  8574. document.getElementById('modal-bgp-peer-connect').checked = p.connect !== false;
  8575. document.getElementById('modal-bgp-peer-listen').checked = p.listen !== false;
  8576. // Extra Tab
  8577. document.getElementById('modal-bgp-peer-holdtime').value = p.hold_time ? formatBgpTime(p.hold_time) : '00:00:30';
  8578. document.getElementById('modal-bgp-peer-keepalive').value = p.keepalive_time ? formatBgpTime(p.keepalive_time) : '00:00:10';
  8579. if (document.getElementById('modal-bgp-peer-use-bfd')) document.getElementById('modal-bgp-peer-use-bfd').checked = !!p.use_bfd;
  8580. document.getElementById('modal-bgp-peer-routing-table').value = p.routing_table || 'main';
  8581. if (document.getElementById('modal-bgp-peer-vrf')) document.getElementById('modal-bgp-peer-vrf').value = p.vrf || 'main';
  8582. if (document.getElementById('modal-bgp-peer-no-client-reflect')) document.getElementById('modal-bgp-peer-no-client-reflect').checked = p.no_client_reflect !== false;
  8583. document.getElementById('modal-bgp-peer-redist-conn').checked = !!p.redist_connected;
  8584. document.getElementById('modal-bgp-peer-redist-static').checked = p.redist_static !== false;
  8585. if (document.getElementById('modal-bgp-peer-redist-rip')) document.getElementById('modal-bgp-peer-redist-rip').checked = !!p.redist_rip;
  8586. document.getElementById('modal-bgp-peer-redist-ospf').checked = !!p.redist_ospf;
  8587. document.getElementById('modal-bgp-peer-redist-bgp').checked = !!p.redist_bgp;
  8588. if (document.getElementById('modal-bgp-peer-redist-vpn')) document.getElementById('modal-bgp-peer-redist-vpn').checked = !!p.redist_vpn;
  8589. if (document.getElementById('modal-bgp-peer-redist-dhcp')) document.getElementById('modal-bgp-peer-redist-dhcp').checked = !!p.redist_dhcp;
  8590. 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;
  8591. if (document.getElementById('modal-bgp-peer-redist-slaac')) document.getElementById('modal-bgp-peer-redist-slaac').checked = !!p.redist_slaac;
  8592. document.getElementById('modal-bgp-peer-default-orig').checked = !!p.default_originate;
  8593. if (document.getElementById('modal-bgp-peer-network-blackhole')) document.getElementById('modal-bgp-peer-network-blackhole').checked = !!p.network_blackhole;
  8594. if (document.getElementById('modal-bgp-peer-no-early-cut')) document.getElementById('modal-bgp-peer-no-early-cut').checked = !!p.no_early_cut;
  8595. if (document.getElementById('modal-bgp-peer-keep-sent-attrs')) document.getElementById('modal-bgp-peer-keep-sent-attrs').checked = !!p.keep_sent_attrs;
  8596. if (document.getElementById('modal-bgp-peer-input-affinity')) document.getElementById('modal-bgp-peer-input-affinity').value = p.input_affinity || '';
  8597. if (document.getElementById('modal-bgp-peer-output-affinity')) document.getElementById('modal-bgp-peer-output-affinity').value = p.output_affinity || '';
  8598. // Attributes Tab
  8599. document.getElementById('modal-bgp-peer-nexthop-choice').value = p.nexthop_choice || (p.nexthop_self ? 'force-self' : 'default');
  8600. document.getElementById('modal-bgp-peer-default-prepend').value = p.default_prepend || 0;
  8601. document.getElementById('modal-bgp-peer-allow-as-in').value = p.allow_as_in || 0;
  8602. 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;
  8603. document.getElementById('modal-bgp-peer-remove-priv-as').checked = !!p.remove_private_as;
  8604. document.getElementById('modal-bgp-peer-as-override').checked = !!p.as_override;
  8605. // Filter Tab
  8606. document.getElementById('modal-bgp-peer-in-filter').value = p.in_filter || '';
  8607. if (document.getElementById('modal-bgp-peer-in-accept-nlri')) document.getElementById('modal-bgp-peer-in-accept-nlri').value = p.in_accept_nlri || '';
  8608. if (document.getElementById('modal-bgp-peer-in-accept-comm')) document.getElementById('modal-bgp-peer-in-accept-comm').value = p.in_accept_communities || '';
  8609. 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 || '';
  8610. 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 || '';
  8611. if (document.getElementById('modal-bgp-peer-in-filter-comm')) document.getElementById('modal-bgp-peer-in-filter-comm').value = p.in_filter_communities || '';
  8612. 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 || '';
  8613. 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 || '';
  8614. if (document.getElementById('modal-bgp-peer-in-filter-unknown')) document.getElementById('modal-bgp-peer-in-filter-unknown').checked = !!p.in_filter_unknown;
  8615. document.getElementById('modal-bgp-peer-out-filter').value = p.out_filter || '';
  8616. if (document.getElementById('modal-bgp-peer-out-selection-policy')) document.getElementById('modal-bgp-peer-out-selection-policy').value = p.out_selection_policy || 'disabled';
  8617. if (document.getElementById('modal-bgp-peer-out-network-name')) document.getElementById('modal-bgp-peer-out-network-name').value = p.output_network || '';
  8618. // Output Networks
  8619. const container = document.getElementById('modal-bgp-output-networks-container');
  8620. if (container) {
  8621. container.innerHTML = '';
  8622. if (p.output_networks && p.output_networks.length > 0) {
  8623. p.output_networks.forEach(net => addOutputNetworkRow(net));
  8624. } else {
  8625. addOutputNetworkRow('');
  8626. }
  8627. }
  8628. const removeBtn = document.getElementById('modal-btn-remove-peer');
  8629. if (removeBtn) removeBtn.classList.remove('hidden');
  8630. switchBgpPeerModalTab('general');
  8631. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  8632. }
  8633. function copyCurrentBgpPeer() {
  8634. document.getElementById('modal-bgp-peer-id').value = '';
  8635. const nameEl = document.getElementById('modal-bgp-peer-name');
  8636. if (nameEl) nameEl.value = (nameEl.value || 'peer') + '-copy';
  8637. document.getElementById('bgp-peer-modal-title').innerText = 'New...';
  8638. const removeBtn = document.getElementById('modal-btn-remove-peer');
  8639. if (removeBtn) removeBtn.classList.add('hidden');
  8640. showToast('Cloned', 'BGP connection copied to new draft', 'info');
  8641. }
  8642. function removeCurrentBgpPeer() {
  8643. const id = document.getElementById('modal-bgp-peer-id')?.value;
  8644. if (!id) return;
  8645. deleteBgpPeer(id);
  8646. closeBgpPeerModal();
  8647. }
  8648. function closeBgpPeerModal() {
  8649. document.getElementById('bgp-peer-modal').classList.add('hidden');
  8650. }
  8651. function getBgpPeerFormData() {
  8652. const netInputs = document.querySelectorAll('#modal-bgp-output-networks-container .output-net-row input');
  8653. const outputNetworks = [];
  8654. netInputs.forEach(inp => {
  8655. const v = inp.value.trim();
  8656. if (v) outputNetworks.push(v);
  8657. });
  8658. const enabled = document.getElementById('modal-bgp-peer-enabled').checked;
  8659. return {
  8660. id: document.getElementById('modal-bgp-peer-id').value,
  8661. name: document.getElementById('modal-bgp-peer-name').value.trim(),
  8662. enabled: enabled,
  8663. disabled: !enabled,
  8664. comment: document.getElementById('modal-bgp-peer-comment').value.trim(),
  8665. instance: document.getElementById('modal-bgp-peer-instance')?.value.trim() || 'bgp-instance-1',
  8666. template: document.getElementById('modal-bgp-peer-template')?.value.trim() || '',
  8667. local_as: parseInt(document.getElementById('modal-bgp-peer-local-as')?.value, 10) || 0,
  8668. router_id: document.getElementById('modal-bgp-peer-router-id').value.trim(),
  8669. afi: document.getElementById('modal-bgp-peer-afi-ipv6').checked ? 'ipv6' : 'ip',
  8670. remote_address: document.getElementById('modal-bgp-peer-remote-addr').value.trim(),
  8671. remote_port: parseInt(document.getElementById('modal-bgp-peer-remote-port').value, 10) || 0,
  8672. remote_as: parseInt(document.getElementById('modal-bgp-peer-remote-as').value, 10) || 0,
  8673. remote_allow_as: document.getElementById('modal-bgp-peer-remote-allow-as')?.value.trim() || '',
  8674. local_address: document.getElementById('modal-bgp-peer-local-addr').value.trim(),
  8675. local_port: parseInt(document.getElementById('modal-bgp-peer-local-port').value, 10) || 0,
  8676. local_role: document.getElementById('modal-bgp-peer-local-role').value,
  8677. password: document.getElementById('modal-bgp-peer-password').value,
  8678. multihop: document.getElementById('modal-bgp-peer-multihop').checked,
  8679. tx_ttl: parseInt(document.getElementById('modal-bgp-peer-tx-ttl')?.value, 10) || 0,
  8680. rx_min_ttl: parseInt(document.getElementById('modal-bgp-peer-rx-min-ttl')?.value, 10) || 0,
  8681. connect: document.getElementById('modal-bgp-peer-connect').checked,
  8682. listen: document.getElementById('modal-bgp-peer-listen').checked,
  8683. hold_time: parseBgpTime(document.getElementById('modal-bgp-peer-holdtime').value),
  8684. keepalive_time: parseBgpTime(document.getElementById('modal-bgp-peer-keepalive').value),
  8685. use_bfd: document.getElementById('modal-bgp-peer-use-bfd')?.checked || false,
  8686. routing_table: document.getElementById('modal-bgp-peer-routing-table').value,
  8687. vrf: document.getElementById('modal-bgp-peer-vrf')?.value.trim() || 'main',
  8688. no_client_reflect: document.getElementById('modal-bgp-peer-no-client-reflect')?.checked || false,
  8689. redist_connected: document.getElementById('modal-bgp-peer-redist-conn').checked,
  8690. redist_static: document.getElementById('modal-bgp-peer-redist-static').checked,
  8691. redist_rip: document.getElementById('modal-bgp-peer-redist-rip')?.checked || false,
  8692. redist_ospf: document.getElementById('modal-bgp-peer-redist-ospf').checked,
  8693. redist_bgp: document.getElementById('modal-bgp-peer-redist-bgp').checked,
  8694. redist_vpn: document.getElementById('modal-bgp-peer-redist-vpn')?.checked || false,
  8695. redist_dhcp: document.getElementById('modal-bgp-peer-redist-dhcp')?.checked || false,
  8696. redist_bgp_mpls_vpn: document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn')?.checked || false,
  8697. redist_slaac: document.getElementById('modal-bgp-peer-redist-slaac')?.checked || false,
  8698. default_originate: document.getElementById('modal-bgp-peer-default-orig').checked,
  8699. network_blackhole: document.getElementById('modal-bgp-peer-network-blackhole')?.checked || false,
  8700. no_early_cut: document.getElementById('modal-bgp-peer-no-early-cut')?.checked || false,
  8701. keep_sent_attrs: document.getElementById('modal-bgp-peer-keep-sent-attrs')?.checked || false,
  8702. input_affinity: (document.getElementById('modal-bgp-peer-input-affinity')?.value || '').trim(),
  8703. output_affinity: (document.getElementById('modal-bgp-peer-output-affinity')?.value || '').trim(),
  8704. nexthop_choice: document.getElementById('modal-bgp-peer-nexthop-choice').value,
  8705. nexthop_self: document.getElementById('modal-bgp-peer-nexthop-choice').value === 'force-self',
  8706. default_prepend: parseInt(document.getElementById('modal-bgp-peer-default-prepend').value, 10) || 0,
  8707. allow_as_in: parseInt(document.getElementById('modal-bgp-peer-allow-as-in').value, 10) || 0,
  8708. ignore_as_path_len: document.getElementById('modal-bgp-peer-ignore-as-path-len')?.checked || false,
  8709. remove_private_as: document.getElementById('modal-bgp-peer-remove-priv-as').checked,
  8710. as_override: document.getElementById('modal-bgp-peer-as-override').checked,
  8711. in_filter: (document.getElementById('modal-bgp-peer-in-filter')?.value || '').trim(),
  8712. in_accept_nlri: (document.getElementById('modal-bgp-peer-in-accept-nlri')?.value || '').trim(),
  8713. in_accept_communities: (document.getElementById('modal-bgp-peer-in-accept-comm')?.value || '').trim(),
  8714. in_accept_ext_communities: (document.getElementById('modal-bgp-peer-in-accept-ext-comm')?.value || '').trim(),
  8715. in_accept_large_communities: (document.getElementById('modal-bgp-peer-in-accept-large-comm')?.value || '').trim(),
  8716. in_filter_communities: (document.getElementById('modal-bgp-peer-in-filter-comm')?.value || '').trim(),
  8717. in_filter_ext_communities: (document.getElementById('modal-bgp-peer-in-filter-ext-comm')?.value || '').trim(),
  8718. in_filter_large_communities: (document.getElementById('modal-bgp-peer-in-filter-large-comm')?.value || '').trim(),
  8719. in_filter_unknown: document.getElementById('modal-bgp-peer-in-filter-unknown')?.checked || false,
  8720. out_filter: (document.getElementById('modal-bgp-peer-out-filter')?.value || '').trim(),
  8721. out_selection_policy: document.getElementById('modal-bgp-peer-out-selection-policy')?.value || 'disabled',
  8722. output_network: (document.getElementById('modal-bgp-peer-out-network-name')?.value || '').trim(),
  8723. output_networks: outputNetworks
  8724. };
  8725. }
  8726. async function submitBgpPeer(e) {
  8727. if (e) e.preventDefault();
  8728. const payload = getBgpPeerFormData();
  8729. try {
  8730. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  8731. method: 'POST',
  8732. headers: { 'Content-Type': 'application/json' },
  8733. body: JSON.stringify(payload)
  8734. });
  8735. if (res.ok) {
  8736. closeBgpPeerModal();
  8737. showToast('Success', 'BGP Connection saved', 'success');
  8738. loadDynamicRouting();
  8739. } else {
  8740. const err = await res.json();
  8741. showToast('Error', err.error || 'Failed to save peer', 'error');
  8742. }
  8743. } catch (err) {
  8744. showToast('Error', err.message, 'error');
  8745. }
  8746. }
  8747. async function applyBgpPeerModal(e) {
  8748. if (e) e.preventDefault();
  8749. const payload = getBgpPeerFormData();
  8750. try {
  8751. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  8752. method: 'POST',
  8753. headers: { 'Content-Type': 'application/json' },
  8754. body: JSON.stringify(payload)
  8755. });
  8756. if (res.ok) {
  8757. const data = await res.json();
  8758. if (data.peer && data.peer.id) {
  8759. document.getElementById('modal-bgp-peer-id').value = data.peer.id;
  8760. document.getElementById('bgp-peer-modal-title').innerText = data.peer.name || data.peer.id;
  8761. document.getElementById('modal-btn-remove-peer')?.classList.remove('hidden');
  8762. }
  8763. showToast('Applied', 'BGP Connection applied', 'success');
  8764. loadDynamicRouting();
  8765. } else {
  8766. const err = await res.json();
  8767. showToast('Error', err.error || 'Failed to apply peer', 'error');
  8768. }
  8769. } catch (err) {
  8770. showToast('Error', err.message, 'error');
  8771. }
  8772. }
  8773. async function deleteBgpPeer(id) {
  8774. if (!confirm('Are you sure you want to delete this BGP peer connection?')) return;
  8775. try {
  8776. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8777. if (res.ok) {
  8778. showToast('Deleted', 'BGP peer removed', 'success');
  8779. loadDynamicRouting();
  8780. }
  8781. } catch (err) {
  8782. showToast('Error', err.message, 'error');
  8783. }
  8784. }
  8785. async function toggleBgpPeerState(id, disabled) {
  8786. try {
  8787. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}/state`, {
  8788. method: 'POST',
  8789. headers: { 'Content-Type': 'application/json' },
  8790. body: JSON.stringify({ disabled })
  8791. });
  8792. if (res.ok) {
  8793. showToast('Updated', `Peer ${disabled ? 'disabled' : 'enabled'}`, 'success');
  8794. loadDynamicRouting();
  8795. }
  8796. } catch (err) {
  8797. showToast('Error', err.message, 'error');
  8798. }
  8799. }
  8800. function openAddBgpNetworkModal() {
  8801. document.getElementById('bgp-network-form').reset();
  8802. document.getElementById('modal-bgp-net-id').value = '';
  8803. document.getElementById('bgp-network-modal').classList.remove('hidden');
  8804. }
  8805. function closeBgpNetworkModal() {
  8806. document.getElementById('bgp-network-modal').classList.add('hidden');
  8807. }
  8808. async function submitBgpNetwork(e) {
  8809. e.preventDefault();
  8810. const payload = {
  8811. id: document.getElementById('modal-bgp-net-id').value,
  8812. network: document.getElementById('modal-bgp-net-cidr').value.trim(),
  8813. comment: document.getElementById('modal-bgp-net-comment').value.trim(),
  8814. disabled: document.getElementById('modal-bgp-net-disabled').checked
  8815. };
  8816. try {
  8817. const res = await fetch(`${API_BASE}/routing/bgp/networks`, {
  8818. method: 'POST',
  8819. headers: { 'Content-Type': 'application/json' },
  8820. body: JSON.stringify(payload)
  8821. });
  8822. if (res.ok) {
  8823. closeBgpNetworkModal();
  8824. showToast('Success', 'BGP network advertisement saved', 'success');
  8825. loadDynamicRouting();
  8826. } else {
  8827. const err = await res.json();
  8828. showToast('Error', err.error || 'Failed to save network', 'error');
  8829. }
  8830. } catch (err) {
  8831. showToast('Error', err.message, 'error');
  8832. }
  8833. }
  8834. async function deleteBgpNetwork(id) {
  8835. if (!confirm('Are you sure you want to stop announcing this network?')) return;
  8836. try {
  8837. const res = await fetch(`${API_BASE}/routing/bgp/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8838. if (res.ok) {
  8839. showToast('Deleted', 'Network advertisement removed', 'success');
  8840. loadDynamicRouting();
  8841. }
  8842. } catch (err) {
  8843. showToast('Error', err.message, 'error');
  8844. }
  8845. }
  8846. // =========================================================================
  8847. // ROUTEROS v7 OSPF MODALS & ACTIONS
  8848. // =========================================================================
  8849. // --- 1. OSPF INSTANCE ---
  8850. function openOspfInstanceModal(id = null) {
  8851. const isEdit = !!id;
  8852. const inst = (state.ospfInstances || []).find(i => i.id === id) || {
  8853. id: '',
  8854. name: 'Default',
  8855. version: 2,
  8856. vrf: 'main',
  8857. router_id: '192.168.131.56',
  8858. routing_table: 'main',
  8859. enabled: true,
  8860. redistribute_connected: false,
  8861. redistribute_static: true,
  8862. redistribute_bgp: false,
  8863. comment: ''
  8864. };
  8865. document.getElementById('ospf-instance-modal-title').innerText = isEdit ? inst.name : 'New...';
  8866. document.getElementById('modal-ospf-inst-id').value = isEdit ? inst.id : '';
  8867. document.getElementById('modal-ospf-inst-enabled').checked = !inst.disabled;
  8868. document.getElementById('modal-ospf-inst-comment').value = inst.comment || '';
  8869. document.getElementById('modal-ospf-inst-name').value = inst.name || 'Default';
  8870. document.getElementById('modal-ospf-inst-version').value = inst.version || 2;
  8871. document.getElementById('modal-ospf-inst-vrf').value = inst.vrf || 'main';
  8872. document.getElementById('modal-ospf-inst-router-id').value = inst.router_id || '';
  8873. document.getElementById('modal-ospf-inst-routing-table').value = inst.routing_table || 'main';
  8874. document.getElementById('modal-ospf-inst-redist-conn').checked = !!inst.redistribute_connected;
  8875. document.getElementById('modal-ospf-inst-redist-static').checked = inst.redistribute_static !== false;
  8876. document.getElementById('modal-ospf-inst-redist-bgp').checked = !!inst.redistribute_bgp;
  8877. const btnRem = document.getElementById('btn-ospf-inst-modal-remove');
  8878. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  8879. document.getElementById('ospf-instance-modal').classList.remove('hidden');
  8880. }
  8881. function openEditOspfInstanceModal(id) {
  8882. openOspfInstanceModal(id);
  8883. }
  8884. function closeOspfInstanceModal() {
  8885. document.getElementById('ospf-instance-modal').classList.add('hidden');
  8886. }
  8887. async function submitOspfInstance(e) {
  8888. if (e) e.preventDefault();
  8889. const payload = {
  8890. id: document.getElementById('modal-ospf-inst-id').value,
  8891. name: document.getElementById('modal-ospf-inst-name').value.trim() || 'Default',
  8892. version: parseInt(document.getElementById('modal-ospf-inst-version').value, 10) || 2,
  8893. vrf: document.getElementById('modal-ospf-inst-vrf').value.trim() || 'main',
  8894. router_id: document.getElementById('modal-ospf-inst-router-id').value.trim(),
  8895. routing_table: document.getElementById('modal-ospf-inst-routing-table').value.trim() || 'main',
  8896. enabled: document.getElementById('modal-ospf-inst-enabled').checked,
  8897. disabled: !document.getElementById('modal-ospf-inst-enabled').checked,
  8898. comment: document.getElementById('modal-ospf-inst-comment').value.trim(),
  8899. redistribute_connected: document.getElementById('modal-ospf-inst-redist-conn').checked,
  8900. redistribute_static: document.getElementById('modal-ospf-inst-redist-static').checked,
  8901. redistribute_bgp: document.getElementById('modal-ospf-inst-redist-bgp').checked
  8902. };
  8903. try {
  8904. const res = await fetch(`${API_BASE}/routing/ospf/instances`, {
  8905. method: 'POST',
  8906. headers: { 'Content-Type': 'application/json' },
  8907. body: JSON.stringify(payload)
  8908. });
  8909. if (res.ok) {
  8910. closeOspfInstanceModal();
  8911. showToast('Saved', 'OSPF instance updated', 'success');
  8912. loadDynamicRouting();
  8913. } else {
  8914. const err = await res.json();
  8915. showToast('Error', err.error || 'Failed to save OSPF instance', 'error');
  8916. }
  8917. } catch (err) {
  8918. showToast('Error', err.message, 'error');
  8919. }
  8920. }
  8921. function applyOspfInstanceForm() {
  8922. submitOspfInstance(null);
  8923. }
  8924. function copyOspfInstance() {
  8925. document.getElementById('modal-ospf-inst-id').value = '';
  8926. document.getElementById('modal-ospf-inst-name').value += '-copy';
  8927. document.getElementById('ospf-instance-modal-title').innerText = 'New...';
  8928. showToast('Copied', 'Duplicated as new OSPF instance', 'info');
  8929. }
  8930. async function deleteCurrentOspfInstance() {
  8931. const id = document.getElementById('modal-ospf-inst-id').value;
  8932. if (!id) return;
  8933. if (!confirm('Are you sure you want to remove this OSPF instance?')) return;
  8934. try {
  8935. const res = await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8936. if (res.ok) {
  8937. closeOspfInstanceModal();
  8938. showToast('Removed', 'OSPF instance deleted', 'success');
  8939. loadDynamicRouting();
  8940. }
  8941. } catch (err) {
  8942. showToast('Error', err.message, 'error');
  8943. }
  8944. }
  8945. async function enableSelectedOspfInstance() {
  8946. const id = state.selectedOspfRow?.instances;
  8947. if (!id) return;
  8948. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}/state`, {
  8949. method: 'POST',
  8950. headers: { 'Content-Type': 'application/json' },
  8951. body: JSON.stringify({ disabled: false })
  8952. });
  8953. loadDynamicRouting();
  8954. }
  8955. async function disableSelectedOspfInstance() {
  8956. const id = state.selectedOspfRow?.instances;
  8957. if (!id) return;
  8958. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}/state`, {
  8959. method: 'POST',
  8960. headers: { 'Content-Type': 'application/json' },
  8961. body: JSON.stringify({ disabled: true })
  8962. });
  8963. loadDynamicRouting();
  8964. }
  8965. async function removeSelectedOspfInstance() {
  8966. const id = state.selectedOspfRow?.instances;
  8967. if (!id) return;
  8968. if (!confirm('Delete selected OSPF instance?')) return;
  8969. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8970. loadDynamicRouting();
  8971. }
  8972. async function promptCommentOspfInstance() {
  8973. const id = state.selectedOspfRow?.instances;
  8974. if (!id) return;
  8975. const inst = (state.ospfInstances || []).find(i => i.id === id);
  8976. if (!inst) return;
  8977. const comment = prompt('Enter comment for OSPF instance:', inst.comment || '');
  8978. if (comment === null) return;
  8979. inst.comment = comment;
  8980. await fetch(`${API_BASE}/routing/ospf/instances`, {
  8981. method: 'POST',
  8982. headers: { 'Content-Type': 'application/json' },
  8983. body: JSON.stringify(inst)
  8984. });
  8985. loadDynamicRouting();
  8986. }
  8987. // --- 2. OSPF AREA ---
  8988. function populateOspfAreaDropdowns() {
  8989. const instSelect = document.getElementById('modal-ospf-area-instance');
  8990. if (instSelect) {
  8991. const cur = instSelect.value;
  8992. instSelect.innerHTML = (state.ospfInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)}</option>`).join('');
  8993. if (instSelect.innerHTML === '') instSelect.innerHTML = '<option value="Default">Default</option>';
  8994. if (cur) instSelect.value = cur;
  8995. }
  8996. }
  8997. function openOspfAreaModal(id = null) {
  8998. const isEdit = !!id;
  8999. populateOspfAreaDropdowns();
  9000. const area = (state.ospfAreas || []).find(a => a.id === id) || {
  9001. id: '',
  9002. name: 'Default',
  9003. instance: 'Default',
  9004. area_id: '0.0.0.0',
  9005. area_type: 'default',
  9006. default_cost: 1,
  9007. no_summaries: false,
  9008. disabled: false,
  9009. comment: ''
  9010. };
  9011. document.getElementById('ospf-area-modal-title').innerText = isEdit ? area.name : 'New...';
  9012. document.getElementById('modal-ospf-area-id').value = isEdit ? area.id : '';
  9013. document.getElementById('modal-ospf-area-enabled').checked = !area.disabled;
  9014. document.getElementById('modal-ospf-area-comment').value = area.comment || '';
  9015. document.getElementById('modal-ospf-area-name').value = area.name || 'Default';
  9016. document.getElementById('modal-ospf-area-instance').value = area.instance || 'Default';
  9017. document.getElementById('modal-ospf-area-areaid').value = area.area_id || '0.0.0.0';
  9018. document.getElementById('modal-ospf-area-type').value = area.area_type || 'default';
  9019. document.getElementById('modal-ospf-area-default-cost').value = area.default_cost || 1;
  9020. document.getElementById('modal-ospf-area-no-summaries').checked = !!area.no_summaries;
  9021. const btnRem = document.getElementById('btn-ospf-area-modal-remove');
  9022. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  9023. document.getElementById('ospf-area-modal').classList.remove('hidden');
  9024. }
  9025. function openEditOspfAreaModal(id) {
  9026. openOspfAreaModal(id);
  9027. }
  9028. function closeOspfAreaModal() {
  9029. document.getElementById('ospf-area-modal').classList.add('hidden');
  9030. }
  9031. async function submitOspfArea(e) {
  9032. if (e) e.preventDefault();
  9033. const payload = {
  9034. id: document.getElementById('modal-ospf-area-id').value,
  9035. name: document.getElementById('modal-ospf-area-name').value.trim() || 'Default',
  9036. instance: document.getElementById('modal-ospf-area-instance').value.trim() || 'Default',
  9037. area_id: document.getElementById('modal-ospf-area-areaid').value.trim() || '0.0.0.0',
  9038. area_type: document.getElementById('modal-ospf-area-type').value,
  9039. default_cost: parseInt(document.getElementById('modal-ospf-area-default-cost').value, 10) || 1,
  9040. no_summaries: document.getElementById('modal-ospf-area-no-summaries').checked,
  9041. disabled: !document.getElementById('modal-ospf-area-enabled').checked,
  9042. comment: document.getElementById('modal-ospf-area-comment').value.trim()
  9043. };
  9044. try {
  9045. const res = await fetch(`${API_BASE}/routing/ospf/areas`, {
  9046. method: 'POST',
  9047. headers: { 'Content-Type': 'application/json' },
  9048. body: JSON.stringify(payload)
  9049. });
  9050. if (res.ok) {
  9051. closeOspfAreaModal();
  9052. showToast('Saved', 'OSPF area saved', 'success');
  9053. loadDynamicRouting();
  9054. } else {
  9055. const err = await res.json();
  9056. showToast('Error', err.error || 'Failed to save area', 'error');
  9057. }
  9058. } catch (err) {
  9059. showToast('Error', err.message, 'error');
  9060. }
  9061. }
  9062. function applyOspfAreaForm() {
  9063. submitOspfArea(null);
  9064. }
  9065. function copyOspfArea() {
  9066. document.getElementById('modal-ospf-area-id').value = '';
  9067. document.getElementById('modal-ospf-area-name').value += '-copy';
  9068. document.getElementById('ospf-area-modal-title').innerText = 'New...';
  9069. showToast('Copied', 'Duplicated as new OSPF area', 'info');
  9070. }
  9071. async function deleteCurrentOspfArea() {
  9072. const id = document.getElementById('modal-ospf-area-id').value;
  9073. if (!id) return;
  9074. if (!confirm('Are you sure you want to remove this OSPF area?')) return;
  9075. try {
  9076. const res = await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9077. if (res.ok) {
  9078. closeOspfAreaModal();
  9079. showToast('Removed', 'OSPF area deleted', 'success');
  9080. loadDynamicRouting();
  9081. }
  9082. } catch (err) {
  9083. showToast('Error', err.message, 'error');
  9084. }
  9085. }
  9086. async function enableSelectedOspfArea() {
  9087. const id = state.selectedOspfRow?.areas;
  9088. if (!id) return;
  9089. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}/state`, {
  9090. method: 'POST',
  9091. headers: { 'Content-Type': 'application/json' },
  9092. body: JSON.stringify({ disabled: false })
  9093. });
  9094. loadDynamicRouting();
  9095. }
  9096. async function disableSelectedOspfArea() {
  9097. const id = state.selectedOspfRow?.areas;
  9098. if (!id) return;
  9099. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}/state`, {
  9100. method: 'POST',
  9101. headers: { 'Content-Type': 'application/json' },
  9102. body: JSON.stringify({ disabled: true })
  9103. });
  9104. loadDynamicRouting();
  9105. }
  9106. async function removeSelectedOspfArea() {
  9107. const id = state.selectedOspfRow?.areas;
  9108. if (!id) return;
  9109. if (!confirm('Delete selected OSPF area?')) return;
  9110. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9111. loadDynamicRouting();
  9112. }
  9113. async function promptCommentOspfArea() {
  9114. const id = state.selectedOspfRow?.areas;
  9115. if (!id) return;
  9116. const area = (state.ospfAreas || []).find(a => a.id === id);
  9117. if (!area) return;
  9118. const comment = prompt('Enter comment for OSPF area:', area.comment || '');
  9119. if (comment === null) return;
  9120. area.comment = comment;
  9121. await fetch(`${API_BASE}/routing/ospf/areas`, {
  9122. method: 'POST',
  9123. headers: { 'Content-Type': 'application/json' },
  9124. body: JSON.stringify(area)
  9125. });
  9126. loadDynamicRouting();
  9127. }
  9128. // --- 3. OSPF AREA RANGE ---
  9129. function populateAreaRangeDropdowns() {
  9130. const select = document.getElementById('modal-ospf-range-area');
  9131. if (select) {
  9132. const cur = select.value;
  9133. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  9134. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  9135. if (cur) select.value = cur;
  9136. }
  9137. }
  9138. function openOspfAreaRangeModal(id = null) {
  9139. const isEdit = !!id;
  9140. populateAreaRangeDropdowns();
  9141. const r = (state.ospfAreaRanges || []).find(it => it.id === id) || {
  9142. id: '',
  9143. area: 'Default',
  9144. prefix: '',
  9145. cost: 1,
  9146. advertise: true,
  9147. disabled: false,
  9148. comment: ''
  9149. };
  9150. document.getElementById('ospf-area-range-modal-title').innerText = isEdit ? r.prefix : 'New...';
  9151. document.getElementById('modal-ospf-range-id').value = isEdit ? r.id : '';
  9152. document.getElementById('modal-ospf-range-enabled').checked = !r.disabled;
  9153. document.getElementById('modal-ospf-range-comment').value = r.comment || '';
  9154. document.getElementById('modal-ospf-range-area').value = r.area || 'Default';
  9155. document.getElementById('modal-ospf-range-prefix').value = r.prefix || '';
  9156. document.getElementById('modal-ospf-range-cost').value = r.cost || 1;
  9157. document.getElementById('modal-ospf-range-advertise').checked = r.advertise !== false;
  9158. const btnRem = document.getElementById('btn-ospf-range-modal-remove');
  9159. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  9160. document.getElementById('ospf-area-range-modal').classList.remove('hidden');
  9161. }
  9162. function openEditOspfAreaRangeModal(id) {
  9163. openOspfAreaRangeModal(id);
  9164. }
  9165. function closeOspfAreaRangeModal() {
  9166. document.getElementById('ospf-area-range-modal').classList.add('hidden');
  9167. }
  9168. async function submitOspfAreaRange(e) {
  9169. if (e) e.preventDefault();
  9170. const payload = {
  9171. id: document.getElementById('modal-ospf-range-id').value,
  9172. area: document.getElementById('modal-ospf-range-area').value,
  9173. prefix: document.getElementById('modal-ospf-range-prefix').value.trim(),
  9174. cost: parseInt(document.getElementById('modal-ospf-range-cost').value, 10) || 1,
  9175. advertise: document.getElementById('modal-ospf-range-advertise').checked,
  9176. disabled: !document.getElementById('modal-ospf-range-enabled').checked,
  9177. comment: document.getElementById('modal-ospf-range-comment').value.trim()
  9178. };
  9179. try {
  9180. const res = await fetch(`${API_BASE}/routing/ospf/area-ranges`, {
  9181. method: 'POST',
  9182. headers: { 'Content-Type': 'application/json' },
  9183. body: JSON.stringify(payload)
  9184. });
  9185. if (res.ok) {
  9186. closeOspfAreaRangeModal();
  9187. showToast('Saved', 'Area range saved', 'success');
  9188. loadDynamicRouting();
  9189. } else {
  9190. const err = await res.json();
  9191. showToast('Error', err.error || 'Failed to save area range', 'error');
  9192. }
  9193. } catch (err) {
  9194. showToast('Error', err.message, 'error');
  9195. }
  9196. }
  9197. function applyOspfAreaRangeForm() {
  9198. submitOspfAreaRange(null);
  9199. }
  9200. async function deleteCurrentOspfAreaRange() {
  9201. const id = document.getElementById('modal-ospf-range-id').value;
  9202. if (!id) return;
  9203. if (!confirm('Delete this area range?')) return;
  9204. try {
  9205. await fetch(`${API_BASE}/routing/ospf/area-ranges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9206. closeOspfAreaRangeModal();
  9207. showToast('Removed', 'Area range removed', 'success');
  9208. loadDynamicRouting();
  9209. } catch (err) {
  9210. showToast('Error', err.message, 'error');
  9211. }
  9212. }
  9213. async function enableSelectedOspfAreaRange() {
  9214. const id = state.selectedOspfRow?.['area-ranges'];
  9215. if (!id) return;
  9216. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  9217. if (!r) return;
  9218. r.disabled = false;
  9219. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  9220. loadDynamicRouting();
  9221. }
  9222. async function disableSelectedOspfAreaRange() {
  9223. const id = state.selectedOspfRow?.['area-ranges'];
  9224. if (!id) return;
  9225. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  9226. if (!r) return;
  9227. r.disabled = true;
  9228. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  9229. loadDynamicRouting();
  9230. }
  9231. async function removeSelectedOspfAreaRange() {
  9232. const id = state.selectedOspfRow?.['area-ranges'];
  9233. if (!id) return;
  9234. if (!confirm('Delete selected area range?')) return;
  9235. await fetch(`${API_BASE}/routing/ospf/area-ranges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9236. loadDynamicRouting();
  9237. }
  9238. async function promptCommentOspfAreaRange() {
  9239. const id = state.selectedOspfRow?.['area-ranges'];
  9240. if (!id) return;
  9241. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  9242. if (!r) return;
  9243. const comment = prompt('Enter comment for area range:', r.comment || '');
  9244. if (comment === null) return;
  9245. r.comment = comment;
  9246. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  9247. loadDynamicRouting();
  9248. }
  9249. // --- 4. OSPF INTERFACE TEMPLATE ---
  9250. function switchOspfTemplateTab(tab) {
  9251. const tabGen = document.getElementById('ospf-tmpl-tab-general');
  9252. const tabAuth = document.getElementById('ospf-tmpl-tab-auth');
  9253. const btnGen = document.getElementById('ospf-tmpl-tab-btn-general');
  9254. const btnAuth = document.getElementById('ospf-tmpl-tab-btn-auth');
  9255. if (tab === 'general') {
  9256. if (tabGen) tabGen.classList.remove('hidden');
  9257. if (tabAuth) tabAuth.classList.add('hidden');
  9258. if (btnGen) btnGen.className = 'px-4 py-2 text-xs font-bold border-b-2 border-sky-500 text-white transition';
  9259. 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';
  9260. } else {
  9261. if (tabGen) tabGen.classList.add('hidden');
  9262. if (tabAuth) tabAuth.classList.remove('hidden');
  9263. 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';
  9264. if (btnAuth) btnAuth.className = 'px-4 py-2 text-xs font-bold border-b-2 border-sky-500 text-white transition';
  9265. }
  9266. }
  9267. function populateTemplateAreaDropdowns() {
  9268. const select = document.getElementById('modal-ospf-tmpl-area');
  9269. if (select) {
  9270. const cur = select.value;
  9271. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  9272. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  9273. if (cur) select.value = cur;
  9274. }
  9275. }
  9276. function openOspfTemplateModal(id = null) {
  9277. const isEdit = !!id;
  9278. populateTemplateAreaDropdowns();
  9279. switchOspfTemplateTab('general');
  9280. const tmpl = (state.ospfTemplates || []).find(t => t.id === id) || {
  9281. id: '',
  9282. interfaces: '',
  9283. area: 'Default',
  9284. networks: '',
  9285. network_type: 'broadcast',
  9286. cost: 1,
  9287. priority: 128,
  9288. passive: false,
  9289. hello_interval: 10,
  9290. dead_interval: 40,
  9291. auth: 'none',
  9292. auth_key: '',
  9293. disabled: false,
  9294. comment: ''
  9295. };
  9296. document.getElementById('ospf-template-modal-title').innerText = isEdit ? (tmpl.interfaces || tmpl.networks || 'Template') : 'New...';
  9297. document.getElementById('modal-ospf-tmpl-id').value = isEdit ? tmpl.id : '';
  9298. document.getElementById('modal-ospf-tmpl-enabled').checked = !tmpl.disabled;
  9299. document.getElementById('modal-ospf-tmpl-comment').value = tmpl.comment || '';
  9300. document.getElementById('modal-ospf-tmpl-interfaces').value = tmpl.interfaces || tmpl.interface || '';
  9301. document.getElementById('modal-ospf-tmpl-area').value = tmpl.area || 'Default';
  9302. document.getElementById('modal-ospf-tmpl-networks').value = tmpl.networks || tmpl.network || '';
  9303. document.getElementById('modal-ospf-tmpl-net-type').value = tmpl.network_type || 'broadcast';
  9304. document.getElementById('modal-ospf-tmpl-cost').value = tmpl.cost || 1;
  9305. document.getElementById('modal-ospf-tmpl-priority').value = tmpl.priority || 128;
  9306. document.getElementById('modal-ospf-tmpl-passive').checked = !!tmpl.passive;
  9307. document.getElementById('modal-ospf-tmpl-hello').value = tmpl.hello_interval || 10;
  9308. document.getElementById('modal-ospf-tmpl-dead').value = tmpl.dead_interval || 40;
  9309. document.getElementById('modal-ospf-tmpl-auth').value = tmpl.auth || tmpl.auth_type || 'none';
  9310. document.getElementById('modal-ospf-tmpl-auth-key').value = tmpl.auth_key || '';
  9311. const btnRem = document.getElementById('btn-ospf-tmpl-modal-remove');
  9312. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  9313. document.getElementById('ospf-template-modal').classList.remove('hidden');
  9314. }
  9315. function openEditOspfTemplateModal(id) {
  9316. openOspfTemplateModal(id);
  9317. }
  9318. function closeOspfTemplateModal() {
  9319. document.getElementById('ospf-template-modal').classList.add('hidden');
  9320. }
  9321. async function submitOspfTemplate(e) {
  9322. if (e) e.preventDefault();
  9323. const payload = {
  9324. id: document.getElementById('modal-ospf-tmpl-id').value,
  9325. interfaces: document.getElementById('modal-ospf-tmpl-interfaces').value.trim(),
  9326. interface: document.getElementById('modal-ospf-tmpl-interfaces').value.trim(),
  9327. area: document.getElementById('modal-ospf-tmpl-area').value,
  9328. networks: document.getElementById('modal-ospf-tmpl-networks').value.trim(),
  9329. network: document.getElementById('modal-ospf-tmpl-networks').value.trim(),
  9330. network_type: document.getElementById('modal-ospf-tmpl-net-type').value,
  9331. cost: parseInt(document.getElementById('modal-ospf-tmpl-cost').value, 10) || 1,
  9332. priority: parseInt(document.getElementById('modal-ospf-tmpl-priority').value, 10) || 128,
  9333. passive: document.getElementById('modal-ospf-tmpl-passive').checked,
  9334. hello_interval: parseInt(document.getElementById('modal-ospf-tmpl-hello').value, 10) || 10,
  9335. dead_interval: parseInt(document.getElementById('modal-ospf-tmpl-dead').value, 10) || 40,
  9336. auth: document.getElementById('modal-ospf-tmpl-auth').value,
  9337. auth_type: document.getElementById('modal-ospf-tmpl-auth').value,
  9338. auth_key: document.getElementById('modal-ospf-tmpl-auth-key').value,
  9339. disabled: !document.getElementById('modal-ospf-tmpl-enabled').checked,
  9340. comment: document.getElementById('modal-ospf-tmpl-comment').value.trim()
  9341. };
  9342. try {
  9343. const res = await fetch(`${API_BASE}/routing/ospf/templates`, {
  9344. method: 'POST',
  9345. headers: { 'Content-Type': 'application/json' },
  9346. body: JSON.stringify(payload)
  9347. });
  9348. if (res.ok) {
  9349. closeOspfTemplateModal();
  9350. showToast('Saved', 'Interface template saved', 'success');
  9351. loadDynamicRouting();
  9352. } else {
  9353. const err = await res.json();
  9354. showToast('Error', err.error || 'Failed to save interface template', 'error');
  9355. }
  9356. } catch (err) {
  9357. showToast('Error', err.message, 'error');
  9358. }
  9359. }
  9360. function applyOspfTemplateForm() {
  9361. submitOspfTemplate(null);
  9362. }
  9363. function copyOspfTemplate() {
  9364. document.getElementById('modal-ospf-tmpl-id').value = '';
  9365. document.getElementById('ospf-template-modal-title').innerText = 'New...';
  9366. showToast('Copied', 'Duplicated as new template', 'info');
  9367. }
  9368. async function deleteCurrentOspfTemplate() {
  9369. const id = document.getElementById('modal-ospf-tmpl-id').value;
  9370. if (!id) return;
  9371. if (!confirm('Delete this interface template?')) return;
  9372. try {
  9373. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9374. closeOspfTemplateModal();
  9375. showToast('Removed', 'Interface template deleted', 'success');
  9376. loadDynamicRouting();
  9377. } catch (err) {
  9378. showToast('Error', err.message, 'error');
  9379. }
  9380. }
  9381. async function enableSelectedOspfTemplate() {
  9382. const id = state.selectedOspfRow?.templates;
  9383. if (!id) return;
  9384. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  9385. method: 'POST',
  9386. headers: { 'Content-Type': 'application/json' },
  9387. body: JSON.stringify({ disabled: false })
  9388. });
  9389. loadDynamicRouting();
  9390. }
  9391. async function disableSelectedOspfTemplate() {
  9392. const id = state.selectedOspfRow?.templates;
  9393. if (!id) return;
  9394. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  9395. method: 'POST',
  9396. headers: { 'Content-Type': 'application/json' },
  9397. body: JSON.stringify({ disabled: true })
  9398. });
  9399. loadDynamicRouting();
  9400. }
  9401. async function removeSelectedOspfTemplate() {
  9402. const id = state.selectedOspfRow?.templates;
  9403. if (!id) return;
  9404. if (!confirm('Delete selected interface template?')) return;
  9405. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9406. loadDynamicRouting();
  9407. }
  9408. async function promptCommentOspfTemplate() {
  9409. const id = state.selectedOspfRow?.templates;
  9410. if (!id) return;
  9411. const tmpl = (state.ospfTemplates || []).find(t => t.id === id);
  9412. if (!tmpl) return;
  9413. const comment = prompt('Enter comment for template:', tmpl.comment || '');
  9414. if (comment === null) return;
  9415. tmpl.comment = comment;
  9416. await fetch(`${API_BASE}/routing/ospf/templates`, {
  9417. method: 'POST',
  9418. headers: { 'Content-Type': 'application/json' },
  9419. body: JSON.stringify(tmpl)
  9420. });
  9421. loadDynamicRouting();
  9422. }
  9423. // --- 5. OSPF STATIC NEIGHBOR ---
  9424. function populateStaticNbrAreaDropdowns() {
  9425. const select = document.getElementById('modal-ospf-snbr-area');
  9426. if (select) {
  9427. const cur = select.value;
  9428. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  9429. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  9430. if (cur) select.value = cur;
  9431. }
  9432. }
  9433. function openOspfStaticNbrModal(id = null) {
  9434. const isEdit = !!id;
  9435. populateStaticNbrAreaDropdowns();
  9436. const nbr = (state.ospfStaticNbrs || []).find(n => n.id === id) || {
  9437. id: '',
  9438. address: '',
  9439. area: 'Default',
  9440. poll_interval: 120,
  9441. cost: 1,
  9442. disabled: false,
  9443. comment: ''
  9444. };
  9445. document.getElementById('ospf-static-nbr-modal-title').innerText = isEdit ? nbr.address : 'New...';
  9446. document.getElementById('modal-ospf-snbr-id').value = isEdit ? nbr.id : '';
  9447. document.getElementById('modal-ospf-snbr-enabled').checked = !nbr.disabled;
  9448. document.getElementById('modal-ospf-snbr-comment').value = nbr.comment || '';
  9449. document.getElementById('modal-ospf-snbr-address').value = nbr.address || '';
  9450. document.getElementById('modal-ospf-snbr-area').value = nbr.area || 'Default';
  9451. document.getElementById('modal-ospf-snbr-poll').value = nbr.poll_interval || 120;
  9452. document.getElementById('modal-ospf-snbr-cost').value = nbr.cost || 1;
  9453. const btnRem = document.getElementById('btn-ospf-snbr-modal-remove');
  9454. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  9455. document.getElementById('ospf-static-nbr-modal').classList.remove('hidden');
  9456. }
  9457. function openEditOspfStaticNbrModal(id) {
  9458. openOspfStaticNbrModal(id);
  9459. }
  9460. function closeOspfStaticNbrModal() {
  9461. document.getElementById('ospf-static-nbr-modal').classList.add('hidden');
  9462. }
  9463. async function submitOspfStaticNbr(e) {
  9464. if (e) e.preventDefault();
  9465. const payload = {
  9466. id: document.getElementById('modal-ospf-snbr-id').value,
  9467. address: document.getElementById('modal-ospf-snbr-address').value.trim(),
  9468. area: document.getElementById('modal-ospf-snbr-area').value,
  9469. poll_interval: parseInt(document.getElementById('modal-ospf-snbr-poll').value, 10) || 120,
  9470. cost: parseInt(document.getElementById('modal-ospf-snbr-cost').value, 10) || 1,
  9471. disabled: !document.getElementById('modal-ospf-snbr-enabled').checked,
  9472. comment: document.getElementById('modal-ospf-snbr-comment').value.trim()
  9473. };
  9474. try {
  9475. const res = await fetch(`${API_BASE}/routing/ospf/static-neighbors`, {
  9476. method: 'POST',
  9477. headers: { 'Content-Type': 'application/json' },
  9478. body: JSON.stringify(payload)
  9479. });
  9480. if (res.ok) {
  9481. closeOspfStaticNbrModal();
  9482. showToast('Saved', 'Static neighbor saved', 'success');
  9483. loadDynamicRouting();
  9484. } else {
  9485. const err = await res.json();
  9486. showToast('Error', err.error || 'Failed to save static neighbor', 'error');
  9487. }
  9488. } catch (err) {
  9489. showToast('Error', err.message, 'error');
  9490. }
  9491. }
  9492. function applyOspfStaticNbrForm() {
  9493. submitOspfStaticNbr(null);
  9494. }
  9495. async function deleteCurrentOspfStaticNbr() {
  9496. const id = document.getElementById('modal-ospf-snbr-id').value;
  9497. if (!id) return;
  9498. if (!confirm('Delete this static neighbor?')) return;
  9499. try {
  9500. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9501. closeOspfStaticNbrModal();
  9502. showToast('Removed', 'Static neighbor removed', 'success');
  9503. loadDynamicRouting();
  9504. } catch (err) {
  9505. showToast('Error', err.message, 'error');
  9506. }
  9507. }
  9508. async function enableSelectedOspfStaticNbr() {
  9509. const id = state.selectedOspfRow?.['static-nbrs'];
  9510. if (!id) return;
  9511. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  9512. if (!n) return;
  9513. n.disabled = false;
  9514. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  9515. loadDynamicRouting();
  9516. }
  9517. async function disableSelectedOspfStaticNbr() {
  9518. const id = state.selectedOspfRow?.['static-nbrs'];
  9519. if (!id) return;
  9520. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  9521. if (!n) return;
  9522. n.disabled = true;
  9523. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  9524. loadDynamicRouting();
  9525. }
  9526. async function removeSelectedOspfStaticNbr() {
  9527. const id = state.selectedOspfRow?.['static-nbrs'];
  9528. if (!id) return;
  9529. if (!confirm('Delete selected static neighbor?')) return;
  9530. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9531. loadDynamicRouting();
  9532. }
  9533. async function promptCommentOspfStaticNbr() {
  9534. const id = state.selectedOspfRow?.['static-nbrs'];
  9535. if (!id) return;
  9536. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  9537. if (!n) return;
  9538. const comment = prompt('Enter comment for static neighbor:', n.comment || '');
  9539. if (comment === null) return;
  9540. n.comment = comment;
  9541. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  9542. loadDynamicRouting();
  9543. }
  9544. // Backward-compat aliases
  9545. function openAddOspfInterfaceModal() { openOspfTemplateModal(); }
  9546. function openEditOspfInterfaceModal(id) { openEditOspfTemplateModal(id); }
  9547. function closeOspfInterfaceModal() { closeOspfTemplateModal(); }
  9548. function submitOspfInterface(e) { submitOspfTemplate(e); }
  9549. function deleteOspfInterface(id) {
  9550. fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' }).then(() => loadDynamicRouting());
  9551. }
  9552. function toggleOspfInterfaceState(id, disabled) {
  9553. fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  9554. method: 'POST',
  9555. headers: { 'Content-Type': 'application/json' },
  9556. body: JSON.stringify({ disabled })
  9557. }).then(() => loadDynamicRouting());
  9558. }
  9559. function openAddOspfAreaModal() { openOspfAreaModal(); }
  9560. function deleteOspfArea(id) {
  9561. fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' }).then(() => loadDynamicRouting());
  9562. }
  9563. // ============================================================================
  9564. // ==================== MIKROTIK BRIDGE SUBSYSTEM ==============================
  9565. // ============================================================================
  9566. function switchBridgeSubTab(tab) {
  9567. state.bridgeSubTab = tab;
  9568. const tabs = ['bridges', 'ports', 'vlans', 'hosts'];
  9569. tabs.forEach(t => {
  9570. const panel = document.getElementById(`bridge-subtab-${t}`);
  9571. const btn = document.getElementById(`bridge-subtab-btn-${t}`);
  9572. if (panel) {
  9573. if (t === tab) panel.classList.remove('hidden');
  9574. else panel.classList.add('hidden');
  9575. }
  9576. if (btn) {
  9577. if (t === tab) {
  9578. 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';
  9579. } else {
  9580. 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';
  9581. }
  9582. }
  9583. });
  9584. const addBtn = document.getElementById('bridge-top-action-btn');
  9585. if (addBtn) {
  9586. if (tab === 'bridges') addBtn.innerHTML = '<span>+ Add Bridge</span>';
  9587. else if (tab === 'ports') addBtn.innerHTML = '<span>+ Add Port</span>';
  9588. else if (tab === 'vlans') addBtn.innerHTML = '<span>+ Add VLAN Entry</span>';
  9589. else if (tab === 'hosts') addBtn.innerHTML = '<span>🔄 Refresh MACs</span>';
  9590. }
  9591. if (tab === 'hosts') loadBridgeHosts();
  9592. setTimeout(initTableSorting, 50);
  9593. }
  9594. function openCurrentBridgeModal() {
  9595. if (state.bridgeSubTab === 'bridges') openAddBridgeModal();
  9596. else if (state.bridgeSubTab === 'ports') openAddBridgePortModal();
  9597. else if (state.bridgeSubTab === 'vlans') openAddBridgeVLANModal();
  9598. else if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  9599. }
  9600. async function loadBridge() {
  9601. try {
  9602. const [bridgesRes, portsRes, vlansRes, summaryRes, eoipRes, vlanIfacesRes] = await Promise.all([
  9603. fetch(`${API_BASE}/bridge/bridges`),
  9604. fetch(`${API_BASE}/bridge/ports`),
  9605. fetch(`${API_BASE}/bridge/vlans`),
  9606. fetch(`${API_BASE}/bridge/summary`),
  9607. fetch(`${API_BASE}/vpn/eoip`),
  9608. fetch(`${API_BASE}/vlans`)
  9609. ]);
  9610. if (bridgesRes.ok) state.bridges = await bridgesRes.json();
  9611. if (portsRes.ok) state.bridgePorts = await portsRes.json();
  9612. if (vlansRes.ok) state.bridgeVLANs = await vlansRes.json();
  9613. if (summaryRes.ok) state.bridgeSummary = await summaryRes.json();
  9614. if (eoipRes && eoipRes.ok) state.eoipTunnels = await eoipRes.json();
  9615. if (vlanIfacesRes && vlanIfacesRes.ok) state.vlans = await vlanIfacesRes.json();
  9616. // Badges & Stats
  9617. const bBridges = document.getElementById('bridge-badge-bridges');
  9618. if (bBridges) bBridges.innerText = (state.bridges || []).length;
  9619. const bPorts = document.getElementById('bridge-badge-ports');
  9620. if (bPorts) bPorts.innerText = (state.bridgePorts || []).length;
  9621. const bVlans = document.getElementById('bridge-badge-vlans');
  9622. if (bVlans) bVlans.innerText = (state.bridgeVLANs || []).length;
  9623. const bHosts = document.getElementById('bridge-badge-hosts');
  9624. if (bHosts) bHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  9625. const sBr = document.getElementById('bridge-stat-bridges');
  9626. if (sBr) sBr.innerText = (state.bridges || []).length;
  9627. const sPorts = document.getElementById('bridge-stat-ports');
  9628. if (sPorts) sPorts.innerText = (state.bridgePorts || []).length;
  9629. const sHosts = document.getElementById('bridge-stat-hosts');
  9630. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  9631. renderBridges();
  9632. renderBridgePorts();
  9633. renderBridgeVLANs();
  9634. if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  9635. } catch (err) {
  9636. console.error('Failed to load bridge subsystem:', err);
  9637. }
  9638. }
  9639. // ----------------- Bridges -----------------
  9640. function renderBridges() {
  9641. const tbody = document.getElementById('bridge-table-body');
  9642. const empty = document.getElementById('bridge-empty-bridges');
  9643. const countBadge = document.getElementById('bridge-count-badge');
  9644. if (!tbody) return;
  9645. tbody.innerHTML = '';
  9646. const bridges = state.bridges || [];
  9647. if (countBadge) countBadge.innerText = `${bridges.length} Bridges`;
  9648. if (bridges.length === 0) {
  9649. empty?.classList.remove('hidden');
  9650. return;
  9651. }
  9652. empty?.classList.add('hidden');
  9653. bridges.forEach((b, idx) => {
  9654. const tr = document.createElement('tr');
  9655. tr.className = `hover:bg-slate-800/40 transition text-xs ${b.disabled ? 'opacity-50' : ''}`;
  9656. // Format IP addresses pill list
  9657. let ipsHtml = '<span class="text-slate-600 font-sans">None</span>';
  9658. if (b.ip_addresses && b.ip_addresses.length > 0) {
  9659. ipsHtml = b.ip_addresses.map(ip => `
  9660. <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">
  9661. <span>${ip}</span>
  9662. <button onclick="deleteBridgeIP('${b.id}', '${ip}')" class="text-slate-500 hover:text-rose-400 font-bold ml-0.5">×</button>
  9663. </span>
  9664. `).join(' ');
  9665. }
  9666. const runningFlag = b.running ? '<span class="text-emerald-400 font-bold" title="Running (R)">R</span>' : '<span class="text-slate-600">-</span>';
  9667. const disabledFlag = b.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '';
  9668. const flagDisplay = `${runningFlag}${disabledFlag ? ' ' + disabledFlag : ''}`;
  9669. tr.innerHTML = `
  9670. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  9671. <td class="py-2.5 px-3 text-center font-mono">${flagDisplay}</td>
  9672. <td class="py-2.5 px-3 font-bold text-white text-sm">
  9673. <span class="text-sky-400 mr-1.5">🌉</span>${b.name}
  9674. </td>
  9675. <td class="py-2.5 px-3 text-slate-300">${b.mtu}</td>
  9676. <td class="py-2.5 px-3 font-mono text-slate-300 text-[11px]">${b.mac_address || '-'}</td>
  9677. <td class="py-2.5 px-3">
  9678. <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>
  9679. </td>
  9680. <td class="py-2.5 px-3 text-center">
  9681. ${b.vlan_filtering ? '<span class="text-emerald-400 font-bold">yes</span>' : '<span class="text-slate-500">no</span>'}
  9682. </td>
  9683. <td class="py-2.5 px-3 font-mono">${b.pvid || 1}</td>
  9684. <td class="py-2.5 px-3">
  9685. <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>
  9686. </td>
  9687. <td class="py-2.5 px-3">
  9688. <div class="flex items-center gap-1.5 flex-wrap">
  9689. ${ipsHtml}
  9690. <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>
  9691. </div>
  9692. </td>
  9693. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  9694. <span class="text-emerald-400">↓ ${b.rx_human || '0 B'}</span> / <span class="text-cyan-400">↑ ${b.tx_human || '0 B'}</span>
  9695. </td>
  9696. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${b.comment || ''}">${b.comment || '-'}</td>
  9697. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  9698. <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>
  9699. <button onclick="openEditBridgeModal('${b.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  9700. <button onclick="deleteBridge('${b.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  9701. </td>
  9702. `;
  9703. tbody.appendChild(tr);
  9704. });
  9705. }
  9706. function openAddBridgeModal() {
  9707. document.getElementById('bridge-modal-title').innerText = 'Add Bridge Interface';
  9708. document.getElementById('bridge-modal-id').value = '';
  9709. document.getElementById('bridge-modal-name').value = 'bridge1';
  9710. document.getElementById('bridge-modal-name').disabled = false;
  9711. document.getElementById('bridge-modal-mtu').value = '1500';
  9712. document.getElementById('bridge-modal-mac').value = '';
  9713. document.getElementById('bridge-modal-stp').value = 'rstp';
  9714. document.getElementById('bridge-modal-priority').value = '32768';
  9715. document.getElementById('bridge-modal-vlanfiltering').checked = false;
  9716. document.getElementById('bridge-modal-pvid').value = '1';
  9717. document.getElementById('bridge-modal-fastforward').checked = true;
  9718. document.getElementById('bridge-modal-comment').value = '';
  9719. document.getElementById('bridge-modal-disabled').checked = false;
  9720. toggleBridgeModalVlanFiltering();
  9721. document.getElementById('bridge-modal').classList.remove('hidden');
  9722. }
  9723. function openEditBridgeModal(id) {
  9724. const b = (state.bridges || []).find(x => x.id === id);
  9725. if (!b) return;
  9726. document.getElementById('bridge-modal-title').innerText = `Edit Bridge (${b.name})`;
  9727. document.getElementById('bridge-modal-id').value = b.id;
  9728. document.getElementById('bridge-modal-name').value = b.name;
  9729. document.getElementById('bridge-modal-name').disabled = true;
  9730. document.getElementById('bridge-modal-mtu').value = b.mtu || 1500;
  9731. document.getElementById('bridge-modal-mac').value = b.mac_address || '';
  9732. document.getElementById('bridge-modal-stp').value = b.stp || 'rstp';
  9733. document.getElementById('bridge-modal-priority').value = b.priority || 32768;
  9734. document.getElementById('bridge-modal-vlanfiltering').checked = !!b.vlan_filtering;
  9735. document.getElementById('bridge-modal-pvid').value = b.pvid || 1;
  9736. document.getElementById('bridge-modal-fastforward').checked = b.fast_forward !== false;
  9737. document.getElementById('bridge-modal-comment').value = b.comment || '';
  9738. document.getElementById('bridge-modal-disabled').checked = !!b.disabled;
  9739. toggleBridgeModalVlanFiltering();
  9740. document.getElementById('bridge-modal').classList.remove('hidden');
  9741. }
  9742. function closeBridgeModal() {
  9743. document.getElementById('bridge-modal').classList.add('hidden');
  9744. }
  9745. function toggleBridgeModalVlanFiltering() {
  9746. const chk = document.getElementById('bridge-modal-vlanfiltering').checked;
  9747. const pvidBox = document.getElementById('bridge-modal-pvid-box');
  9748. if (pvidBox) {
  9749. if (chk) pvidBox.classList.remove('opacity-40');
  9750. else pvidBox.classList.add('opacity-40');
  9751. }
  9752. }
  9753. async function submitSaveBridge(e) {
  9754. e.preventDefault();
  9755. const id = document.getElementById('bridge-modal-id').value;
  9756. const name = document.getElementById('bridge-modal-name').value.trim();
  9757. const mtu = parseInt(document.getElementById('bridge-modal-mtu').value, 10) || 1500;
  9758. const mac = document.getElementById('bridge-modal-mac').value.trim();
  9759. const stp = document.getElementById('bridge-modal-stp').value;
  9760. const priority = parseInt(document.getElementById('bridge-modal-priority').value, 10) || 32768;
  9761. const vlanFiltering = document.getElementById('bridge-modal-vlanfiltering').checked;
  9762. const pvid = parseInt(document.getElementById('bridge-modal-pvid').value, 10) || 1;
  9763. const fastForward = document.getElementById('bridge-modal-fastforward').checked;
  9764. const comment = document.getElementById('bridge-modal-comment').value.trim();
  9765. const disabled = document.getElementById('bridge-modal-disabled').checked;
  9766. try {
  9767. const res = await fetch(`${API_BASE}/bridge/bridges`, {
  9768. method: 'POST',
  9769. headers: { 'Content-Type': 'application/json' },
  9770. body: JSON.stringify({
  9771. id,
  9772. name,
  9773. mtu,
  9774. mac_address: mac,
  9775. stp,
  9776. priority,
  9777. vlan_filtering: vlanFiltering,
  9778. pvid,
  9779. fast_forward: fastForward,
  9780. comment,
  9781. disabled
  9782. })
  9783. });
  9784. if (res.ok) {
  9785. showToast('Bridge Saved', `Bridge ${name} configured`, 'success');
  9786. closeBridgeModal();
  9787. loadBridge();
  9788. fetchData(false);
  9789. } else {
  9790. const err = await res.json();
  9791. showToast('Error', err.error || err.message || 'Failed to save bridge', 'error');
  9792. }
  9793. } catch (err) {
  9794. showToast('Error', err.message, 'error');
  9795. }
  9796. }
  9797. async function toggleBridgeState(id, disabled) {
  9798. try {
  9799. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/state`, {
  9800. method: 'POST',
  9801. headers: { 'Content-Type': 'application/json' },
  9802. body: JSON.stringify({ disabled })
  9803. });
  9804. if (res.ok) {
  9805. loadBridge();
  9806. fetchData(false);
  9807. }
  9808. } catch (err) {
  9809. showToast('Error', err.message, 'error');
  9810. }
  9811. }
  9812. async function deleteBridge(id) {
  9813. const b = (state.bridges || []).find(x => x.id === id);
  9814. const name = b ? b.name : id;
  9815. if (!confirm(`Are you sure you want to delete bridge '${name}'? All member ports will be detached.`)) return;
  9816. try {
  9817. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9818. if (res.ok) {
  9819. showToast('Deleted', `Bridge ${name} deleted`, 'success');
  9820. loadBridge();
  9821. fetchData(false);
  9822. } else {
  9823. const err = await res.json();
  9824. showToast('Error', err.error || err.message || 'Failed to delete bridge', 'error');
  9825. }
  9826. } catch (err) {
  9827. showToast('Error', err.message, 'error');
  9828. }
  9829. }
  9830. // ----------------- Bridge IP Assignments -----------------
  9831. function openAddBridgeIPModal(id, name) {
  9832. document.getElementById('bridge-ip-modal-id').value = id;
  9833. document.getElementById('bridge-ip-modal-sub').innerText = name;
  9834. document.getElementById('bridge-ip-modal-cidr').value = '';
  9835. document.getElementById('bridge-ip-modal').classList.remove('hidden');
  9836. }
  9837. function closeBridgeIPModal() {
  9838. document.getElementById('bridge-ip-modal').classList.add('hidden');
  9839. }
  9840. async function submitAddBridgeIP(e) {
  9841. e.preventDefault();
  9842. const id = document.getElementById('bridge-ip-modal-id').value;
  9843. const ip = document.getElementById('bridge-ip-modal-cidr').value.trim();
  9844. try {
  9845. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  9846. method: 'POST',
  9847. headers: { 'Content-Type': 'application/json' },
  9848. body: JSON.stringify({ ip })
  9849. });
  9850. if (res.ok) {
  9851. showToast('IP Assigned', `${ip} assigned to bridge`, 'success');
  9852. closeBridgeIPModal();
  9853. loadBridge();
  9854. fetchData(false);
  9855. } else {
  9856. const err = await res.json();
  9857. showToast('Error', err.error || err.message || 'Failed to add IP', 'error');
  9858. }
  9859. } catch (err) {
  9860. showToast('Error', err.message, 'error');
  9861. }
  9862. }
  9863. async function deleteBridgeIP(id, ip) {
  9864. if (!confirm(`Remove IP address ${ip} from bridge?`)) return;
  9865. try {
  9866. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  9867. method: 'DELETE',
  9868. headers: { 'Content-Type': 'application/json' },
  9869. body: JSON.stringify({ ip })
  9870. });
  9871. if (res.ok) {
  9872. showToast('IP Removed', `${ip} removed from bridge`, 'success');
  9873. loadBridge();
  9874. fetchData(false);
  9875. }
  9876. } catch (err) {
  9877. showToast('Error', err.message, 'error');
  9878. }
  9879. }
  9880. // ----------------- Bridge Ports -----------------
  9881. function renderBridgePorts() {
  9882. const tbody = document.getElementById('bridge-ports-table-body');
  9883. const empty = document.getElementById('bridge-empty-ports');
  9884. const countBadge = document.getElementById('bridge-ports-count-badge');
  9885. const filterBridge = document.getElementById('bridge-ports-filter-bridge')?.value || '';
  9886. if (!tbody) return;
  9887. tbody.innerHTML = '';
  9888. // Update filter select
  9889. populateBridgeSelect('bridge-ports-filter-bridge', filterBridge, true);
  9890. const ports = (state.bridgePorts || []).filter(p => !filterBridge || p.bridge === filterBridge);
  9891. if (countBadge) countBadge.innerText = `${ports.length} Ports`;
  9892. if (ports.length === 0) {
  9893. empty?.classList.remove('hidden');
  9894. return;
  9895. }
  9896. empty?.classList.add('hidden');
  9897. ports.forEach((p, idx) => {
  9898. const tr = document.createElement('tr');
  9899. tr.className = `hover:bg-slate-800/40 transition text-xs ${p.disabled ? 'opacity-50' : ''}`;
  9900. const disabledFlag = p.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  9901. tr.innerHTML = `
  9902. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  9903. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  9904. <td class="py-2.5 px-3 font-bold text-white text-sm">
  9905. <span class="text-emerald-400 mr-1.5">🔌</span>${p.interface}
  9906. </td>
  9907. <td class="py-2.5 px-3 font-semibold text-sky-400">${p.bridge}</td>
  9908. <td class="py-2.5 px-3 font-mono">${p.pvid || 1}</td>
  9909. <td class="py-2.5 px-3 text-slate-300">${p.frame_types}</td>
  9910. <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>
  9911. <td class="py-2.5 px-3">
  9912. ${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>'}
  9913. </td>
  9914. <td class="py-2.5 px-3">
  9915. <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>
  9916. </td>
  9917. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${p.comment || ''}">${p.comment || '-'}</td>
  9918. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  9919. <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>
  9920. <button onclick="openEditBridgePortModal('${p.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  9921. <button onclick="deleteBridgePort('${p.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  9922. </td>
  9923. `;
  9924. tbody.appendChild(tr);
  9925. });
  9926. }
  9927. function openAddBridgePortModal() {
  9928. document.getElementById('bridge-port-modal-title').innerText = 'Add Port to Bridge';
  9929. document.getElementById('bridge-port-modal-id').value = '';
  9930. populateBridgeSelect('bridge-port-modal-bridge');
  9931. populateBridgePortCandidateSelect('bridge-port-modal-interface');
  9932. document.getElementById('bridge-port-modal-pvid').value = '1';
  9933. document.getElementById('bridge-port-modal-frametypes').value = 'admit-all';
  9934. document.getElementById('bridge-port-modal-ingressfiltering').checked = false;
  9935. document.getElementById('bridge-port-modal-horizon').value = '0';
  9936. document.getElementById('bridge-port-modal-pathcost').value = '10';
  9937. document.getElementById('bridge-port-modal-priority').value = '128';
  9938. document.getElementById('bridge-port-modal-learn').checked = true;
  9939. document.getElementById('bridge-port-modal-comment').value = '';
  9940. document.getElementById('bridge-port-modal-disabled').checked = false;
  9941. document.getElementById('bridge-port-modal').classList.remove('hidden');
  9942. }
  9943. function openEditBridgePortModal(id) {
  9944. const p = (state.bridgePorts || []).find(x => x.id === id);
  9945. if (!p) return;
  9946. document.getElementById('bridge-port-modal-title').innerText = `Edit Bridge Port (${p.interface})`;
  9947. document.getElementById('bridge-port-modal-id').value = p.id;
  9948. populateBridgeSelect('bridge-port-modal-bridge', p.bridge);
  9949. populateBridgePortCandidateSelect('bridge-port-modal-interface', p.interface);
  9950. document.getElementById('bridge-port-modal-pvid').value = p.pvid || 1;
  9951. document.getElementById('bridge-port-modal-frametypes').value = p.frame_types || 'admit-all';
  9952. document.getElementById('bridge-port-modal-ingressfiltering').checked = !!p.ingress_filtering;
  9953. document.getElementById('bridge-port-modal-horizon').value = p.horizon || 0;
  9954. document.getElementById('bridge-port-modal-pathcost').value = p.path_cost || 10;
  9955. document.getElementById('bridge-port-modal-priority').value = p.priority || 128;
  9956. document.getElementById('bridge-port-modal-learn').checked = p.learn !== false;
  9957. document.getElementById('bridge-port-modal-comment').value = p.comment || '';
  9958. document.getElementById('bridge-port-modal-disabled').checked = !!p.disabled;
  9959. document.getElementById('bridge-port-modal').classList.remove('hidden');
  9960. }
  9961. function closeBridgePortModal() {
  9962. document.getElementById('bridge-port-modal').classList.add('hidden');
  9963. }
  9964. async function submitSaveBridgePort(e) {
  9965. e.preventDefault();
  9966. const id = document.getElementById('bridge-port-modal-id').value;
  9967. const bridge = document.getElementById('bridge-port-modal-bridge').value;
  9968. const iface = document.getElementById('bridge-port-modal-interface').value;
  9969. const pvid = parseInt(document.getElementById('bridge-port-modal-pvid').value, 10) || 1;
  9970. const frameTypes = document.getElementById('bridge-port-modal-frametypes').value;
  9971. const ingressFiltering = document.getElementById('bridge-port-modal-ingressfiltering').checked;
  9972. const horizon = parseInt(document.getElementById('bridge-port-modal-horizon').value, 10) || 0;
  9973. const pathCost = parseInt(document.getElementById('bridge-port-modal-pathcost').value, 10) || 10;
  9974. const priority = parseInt(document.getElementById('bridge-port-modal-priority').value, 10) || 128;
  9975. const learn = document.getElementById('bridge-port-modal-learn').checked;
  9976. const comment = document.getElementById('bridge-port-modal-comment').value.trim();
  9977. const disabled = document.getElementById('bridge-port-modal-disabled').checked;
  9978. try {
  9979. const res = await fetch(`${API_BASE}/bridge/ports`, {
  9980. method: 'POST',
  9981. headers: { 'Content-Type': 'application/json' },
  9982. body: JSON.stringify({
  9983. id,
  9984. bridge,
  9985. interface: iface,
  9986. pvid,
  9987. frame_types: frameTypes,
  9988. ingress_filtering: ingressFiltering,
  9989. horizon,
  9990. path_cost: pathCost,
  9991. priority,
  9992. learn,
  9993. comment,
  9994. disabled
  9995. })
  9996. });
  9997. if (res.ok) {
  9998. showToast('Port Attached', `${iface} added to ${bridge}`, 'success');
  9999. closeBridgePortModal();
  10000. loadBridge();
  10001. fetchData(false);
  10002. } else {
  10003. const err = await res.json();
  10004. showToast('Error', err.error || err.message || 'Failed to save port', 'error');
  10005. }
  10006. } catch (err) {
  10007. showToast('Error', err.message, 'error');
  10008. }
  10009. }
  10010. async function toggleBridgePortState(id, disabled) {
  10011. try {
  10012. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}/state`, {
  10013. method: 'POST',
  10014. headers: { 'Content-Type': 'application/json' },
  10015. body: JSON.stringify({ disabled })
  10016. });
  10017. if (res.ok) {
  10018. loadBridge();
  10019. fetchData(false);
  10020. }
  10021. } catch (err) {
  10022. showToast('Error', err.message, 'error');
  10023. }
  10024. }
  10025. async function deleteBridgePort(id) {
  10026. const p = (state.bridgePorts || []).find(x => x.id === id);
  10027. const iface = p ? p.interface : id;
  10028. if (!confirm(`Detach interface '${iface}' from bridge?`)) return;
  10029. try {
  10030. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10031. if (res.ok) {
  10032. showToast('Port Detached', `${iface} removed from bridge`, 'success');
  10033. loadBridge();
  10034. fetchData(false);
  10035. }
  10036. } catch (err) {
  10037. showToast('Error', err.message, 'error');
  10038. }
  10039. }
  10040. // ----------------- Bridge VLANs -----------------
  10041. function renderBridgeVLANs() {
  10042. const tbody = document.getElementById('bridge-vlans-table-body');
  10043. const empty = document.getElementById('bridge-empty-vlans');
  10044. const countBadge = document.getElementById('bridge-vlans-count-badge');
  10045. const filterBridge = document.getElementById('bridge-vlans-filter-bridge')?.value || '';
  10046. if (!tbody) return;
  10047. tbody.innerHTML = '';
  10048. populateBridgeSelect('bridge-vlans-filter-bridge', filterBridge, true);
  10049. const vlans = (state.bridgeVLANs || []).filter(v => !filterBridge || v.bridge === filterBridge);
  10050. if (countBadge) countBadge.innerText = `${vlans.length} Entries`;
  10051. if (vlans.length === 0) {
  10052. empty?.classList.remove('hidden');
  10053. return;
  10054. }
  10055. empty?.classList.add('hidden');
  10056. vlans.forEach((v, idx) => {
  10057. const tr = document.createElement('tr');
  10058. tr.className = `hover:bg-slate-800/40 transition text-xs ${v.disabled ? 'opacity-50' : ''}`;
  10059. const taggedHtml = (v.tagged && v.tagged.length > 0)
  10060. ? 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(' ')
  10061. : '<span class="text-slate-600">none</span>';
  10062. const untaggedHtml = (v.untagged && v.untagged.length > 0)
  10063. ? 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(' ')
  10064. : '<span class="text-slate-600">none</span>';
  10065. const disabledFlag = v.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  10066. tr.innerHTML = `
  10067. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  10068. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  10069. <td class="py-2.5 px-3 font-semibold text-sky-400">${v.bridge}</td>
  10070. <td class="py-2.5 px-3 font-bold text-white font-mono text-sm">${v.vlan_ids}</td>
  10071. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${taggedHtml}</div></td>
  10072. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${untaggedHtml}</div></td>
  10073. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${v.comment || ''}">${v.comment || '-'}</td>
  10074. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  10075. <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>
  10076. <button onclick="openEditBridgeVLANModal('${v.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  10077. <button onclick="deleteBridgeVLAN('${v.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  10078. </td>
  10079. `;
  10080. tbody.appendChild(tr);
  10081. });
  10082. }
  10083. function openAddBridgeVLANModal() {
  10084. document.getElementById('bridge-vlan-modal-title').innerText = 'Add Bridge VLAN Entry';
  10085. document.getElementById('bridge-vlan-modal-id').value = '';
  10086. populateBridgeSelect('bridge-vlan-modal-bridge');
  10087. document.getElementById('bridge-vlan-modal-vlanids').value = '';
  10088. document.getElementById('bridge-vlan-modal-comment').value = '';
  10089. document.getElementById('bridge-vlan-modal-disabled').checked = false;
  10090. updateBridgeVlanPortCheckboxes();
  10091. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  10092. }
  10093. function openEditBridgeVLANModal(id) {
  10094. const v = (state.bridgeVLANs || []).find(x => x.id === id);
  10095. if (!v) return;
  10096. document.getElementById('bridge-vlan-modal-title').innerText = `Edit Bridge VLAN (${v.vlan_ids})`;
  10097. document.getElementById('bridge-vlan-modal-id').value = v.id;
  10098. populateBridgeSelect('bridge-vlan-modal-bridge', v.bridge);
  10099. document.getElementById('bridge-vlan-modal-vlanids').value = v.vlan_ids;
  10100. document.getElementById('bridge-vlan-modal-comment').value = v.comment || '';
  10101. document.getElementById('bridge-vlan-modal-disabled').checked = !!v.disabled;
  10102. updateBridgeVlanPortCheckboxes(v.tagged || [], v.untagged || []);
  10103. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  10104. }
  10105. function closeBridgeVlanModal() {
  10106. document.getElementById('bridge-vlan-modal').classList.add('hidden');
  10107. }
  10108. function updateBridgeVlanPortCheckboxes(taggedSelected = [], untaggedSelected = []) {
  10109. const selBridge = document.getElementById('bridge-vlan-modal-bridge')?.value || '';
  10110. const taggedBox = document.getElementById('bridge-vlan-tagged-ports');
  10111. const untaggedBox = document.getElementById('bridge-vlan-untagged-ports');
  10112. if (!taggedBox || !untaggedBox) return;
  10113. // Ports belonging to the selected bridge
  10114. const memberPorts = (state.bridgePorts || []).filter(p => !selBridge || p.bridge === selBridge);
  10115. if (memberPorts.length === 0) {
  10116. taggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  10117. untaggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  10118. return;
  10119. }
  10120. taggedBox.innerHTML = memberPorts.map(p => `
  10121. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  10122. <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">
  10123. <span>${p.interface}</span>
  10124. </label>
  10125. `).join('');
  10126. untaggedBox.innerHTML = memberPorts.map(p => `
  10127. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  10128. <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">
  10129. <span>${p.interface}</span>
  10130. </label>
  10131. `).join('');
  10132. }
  10133. async function submitSaveBridgeVLAN(e) {
  10134. e.preventDefault();
  10135. const id = document.getElementById('bridge-vlan-modal-id').value;
  10136. const bridge = document.getElementById('bridge-vlan-modal-bridge').value;
  10137. const vlanIDs = document.getElementById('bridge-vlan-modal-vlanids').value.trim();
  10138. const comment = document.getElementById('bridge-vlan-modal-comment').value.trim();
  10139. const disabled = document.getElementById('bridge-vlan-modal-disabled').checked;
  10140. const tagged = Array.from(document.querySelectorAll('input[name="bvlan-tagged"]:checked')).map(x => x.value);
  10141. const untagged = Array.from(document.querySelectorAll('input[name="bvlan-untagged"]:checked')).map(x => x.value);
  10142. try {
  10143. const res = await fetch(`${API_BASE}/bridge/vlans`, {
  10144. method: 'POST',
  10145. headers: { 'Content-Type': 'application/json' },
  10146. body: JSON.stringify({
  10147. id,
  10148. bridge,
  10149. vlan_ids: vlanIDs,
  10150. tagged,
  10151. untagged,
  10152. comment,
  10153. disabled
  10154. })
  10155. });
  10156. if (res.ok) {
  10157. showToast('VLAN Entry Saved', `VLAN ${vlanIDs} configured on ${bridge}`, 'success');
  10158. closeBridgeVlanModal();
  10159. loadBridge();
  10160. } else {
  10161. const err = await res.json();
  10162. showToast('Error', err.error || err.message || 'Failed to save VLAN entry', 'error');
  10163. }
  10164. } catch (err) {
  10165. showToast('Error', err.message, 'error');
  10166. }
  10167. }
  10168. async function toggleBridgeVLANState(id, disabled) {
  10169. try {
  10170. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}/state`, {
  10171. method: 'POST',
  10172. headers: { 'Content-Type': 'application/json' },
  10173. body: JSON.stringify({ disabled })
  10174. });
  10175. if (res.ok) loadBridge();
  10176. } catch (err) {
  10177. showToast('Error', err.message, 'error');
  10178. }
  10179. }
  10180. async function deleteBridgeVLAN(id) {
  10181. if (!confirm('Delete this bridge VLAN entry?')) return;
  10182. try {
  10183. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10184. if (res.ok) {
  10185. showToast('Deleted', 'VLAN entry removed from bridge', 'success');
  10186. loadBridge();
  10187. }
  10188. } catch (err) {
  10189. showToast('Error', err.message, 'error');
  10190. }
  10191. }
  10192. // ----------------- Hosts / MAC Table -----------------
  10193. async function loadBridgeHosts() {
  10194. const filterBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || '';
  10195. populateBridgeSelect('bridge-hosts-filter-bridge', filterBridge, true);
  10196. try {
  10197. const url = filterBridge ? `${API_BASE}/bridge/hosts?bridge=${encodeURIComponent(filterBridge)}` : `${API_BASE}/bridge/hosts`;
  10198. const res = await fetch(url);
  10199. if (res.ok) {
  10200. state.bridgeHosts = await res.json();
  10201. renderBridgeHosts();
  10202. }
  10203. } catch (err) {
  10204. console.error('Failed to load bridge hosts:', err);
  10205. }
  10206. }
  10207. function renderBridgeHosts() {
  10208. const tbody = document.getElementById('bridge-hosts-table-body');
  10209. const empty = document.getElementById('bridge-empty-hosts');
  10210. const countBadge = document.getElementById('bridge-hosts-count-badge');
  10211. const search = (document.getElementById('bridge-hosts-search')?.value || '').toLowerCase().trim();
  10212. if (!tbody) return;
  10213. tbody.innerHTML = '';
  10214. const hosts = (state.bridgeHosts || []).filter(h => {
  10215. if (!search) return true;
  10216. return (h.mac || '').toLowerCase().includes(search) || (h.interface || '').toLowerCase().includes(search) || (h.bridge || '').toLowerCase().includes(search);
  10217. });
  10218. if (countBadge) countBadge.innerText = `${hosts.length} Hosts`;
  10219. if (hosts.length === 0) {
  10220. empty?.classList.remove('hidden');
  10221. return;
  10222. }
  10223. empty?.classList.add('hidden');
  10224. hosts.forEach(h => {
  10225. const tr = document.createElement('tr');
  10226. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  10227. let flagBadges = '';
  10228. 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>';
  10229. 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>';
  10230. 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>';
  10231. tr.innerHTML = `
  10232. <td class="py-2.5 px-3 font-mono font-bold text-white text-sm">${h.mac}</td>
  10233. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${h.interface || '-'}</td>
  10234. <td class="py-2.5 px-3 font-mono text-sky-400">${h.bridge || '-'}</td>
  10235. <td class="py-2.5 px-3 font-mono">${h.vlan_id || 1}</td>
  10236. <td class="py-2.5 px-3 font-mono text-slate-400">${h.age ? h.age.toFixed(1) + 's' : '-'}</td>
  10237. <td class="py-2.5 px-3">${flagBadges}</td>
  10238. `;
  10239. tbody.appendChild(tr);
  10240. });
  10241. }
  10242. async function flushBridgeHosts() {
  10243. const selBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || (state.bridges[0] ? state.bridges[0].name : '');
  10244. if (!selBridge) {
  10245. showToast('Notice', 'Please select a bridge to flush dynamic MACs', 'info');
  10246. return;
  10247. }
  10248. if (!confirm(`Flush all dynamic learned MAC addresses on bridge '${selBridge}'?`)) return;
  10249. try {
  10250. const res = await fetch(`${API_BASE}/bridge/hosts/flush`, {
  10251. method: 'POST',
  10252. headers: { 'Content-Type': 'application/json' },
  10253. body: JSON.stringify({ bridge: selBridge })
  10254. });
  10255. if (res.ok) {
  10256. showToast('FDB Flushed', `Dynamic MACs flushed on ${selBridge}`, 'success');
  10257. loadBridgeHosts();
  10258. }
  10259. } catch (err) {
  10260. showToast('Error', err.message, 'error');
  10261. }
  10262. }
  10263. // ----------------- Helpers -----------------
  10264. function populateBridgeSelect(selectId, currentVal = '', includeAll = false) {
  10265. const sel = document.getElementById(selectId);
  10266. if (!sel) return;
  10267. const prevVal = currentVal || sel.value;
  10268. sel.innerHTML = includeAll ? '<option value="">All Bridges</option>' : '';
  10269. (state.bridges || []).forEach(b => {
  10270. const opt = document.createElement('option');
  10271. opt.value = b.name;
  10272. opt.innerText = `${b.name} (${b.ports_count} ports)`;
  10273. if (b.name === prevVal) opt.selected = true;
  10274. sel.appendChild(opt);
  10275. });
  10276. }
  10277. function populateBridgePortCandidateSelect(selectId, currentVal = '') {
  10278. const sel = document.getElementById(selectId);
  10279. if (!sel) return;
  10280. sel.innerHTML = '<option value="">(Select Interface...)</option>';
  10281. // 1. Physical Interfaces
  10282. const grpPhys = document.createElement('optgroup');
  10283. grpPhys.label = 'Physical Interfaces';
  10284. (state.interfaces || []).filter(i => i.type !== 'bridge' && i.type !== 'vlan' && i.type !== 'loopback').forEach(i => {
  10285. const opt = document.createElement('option');
  10286. opt.value = i.name;
  10287. opt.innerText = `${i.name} (${i.role || i.type})`;
  10288. if (i.name === currentVal) opt.selected = true;
  10289. grpPhys.appendChild(opt);
  10290. });
  10291. if (grpPhys.children.length > 0) sel.appendChild(grpPhys);
  10292. // 2. VLAN Sub-interfaces
  10293. const grpVlans = document.createElement('optgroup');
  10294. grpVlans.label = 'VLAN Sub-interfaces (802.1Q)';
  10295. (state.vlans || []).forEach(v => {
  10296. const opt = document.createElement('option');
  10297. opt.value = v.name;
  10298. opt.innerText = `${v.name} (VLAN ${v.vlan_id})`;
  10299. if (v.name === currentVal) opt.selected = true;
  10300. grpVlans.appendChild(opt);
  10301. });
  10302. if (grpVlans.children.length > 0) sel.appendChild(grpVlans);
  10303. // 3. EoIP Tunnels (MikroTik EoIP bridging!)
  10304. const grpEoip = document.createElement('optgroup');
  10305. grpEoip.label = 'EoIP Tunnels (Layer 2 VPN)';
  10306. (state.eoipTunnels || []).forEach(t => {
  10307. const opt = document.createElement('option');
  10308. opt.value = t.name;
  10309. opt.innerText = `${t.name} (Tunnel ID: ${t.tunnel_id} -> ${t.remote_address})`;
  10310. if (t.name === currentVal) opt.selected = true;
  10311. grpEoip.appendChild(opt);
  10312. });
  10313. if (grpEoip.children.length > 0) sel.appendChild(grpEoip);
  10314. }
  10315. // -------------------------------------------------------------
  10316. // RouterOS v7 Routing Filters Management (/routing filter)
  10317. // -------------------------------------------------------------
  10318. if (!state.activeRoutingFilterTab) state.activeRoutingFilterTab = 'rules';
  10319. if (!state.selectedFilterRow) state.selectedFilterRow = {};
  10320. if (!state.rfSort) state.rfSort = {};
  10321. function switchRoutingFilterTab(tab) {
  10322. state.activeRoutingFilterTab = tab;
  10323. const tabs = ['rules', 'select-rules', 'community-lists', 'as-lists'];
  10324. tabs.forEach(t => {
  10325. const btn = document.getElementById(`tab-rf-${t}`);
  10326. const content = document.getElementById(`tab-content-rf-${t}`);
  10327. if (btn) {
  10328. if (t === tab) {
  10329. 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';
  10330. } else {
  10331. btn.className = 'px-3 py-1 text-xs font-semibold rounded text-slate-400 hover:text-white hover:bg-slate-800 transition';
  10332. }
  10333. }
  10334. if (content) {
  10335. if (t === tab) content.classList.remove('hidden');
  10336. else content.classList.add('hidden');
  10337. }
  10338. });
  10339. const chainContainer = document.getElementById('rf-chain-filter-container');
  10340. if (chainContainer) {
  10341. if (tab === 'rules' || tab === 'select-rules') chainContainer.classList.remove('hidden');
  10342. else chainContainer.classList.add('hidden');
  10343. }
  10344. renderRoutingFilters();
  10345. }
  10346. function selectFilterRow(tab, id) {
  10347. if (state.selectedFilterRow[tab] === id) {
  10348. delete state.selectedFilterRow[tab];
  10349. } else {
  10350. state.selectedFilterRow[tab] = id;
  10351. }
  10352. if (tab === 'rules') renderRoutingFilterRules();
  10353. else if (tab === 'select-rules') renderRoutingFilterSelectRules();
  10354. else if (tab === 'community-lists') renderRoutingFilterCommunityLists();
  10355. else if (tab === 'as-lists') renderRoutingFilterASLists();
  10356. }
  10357. function openRoutingFilterNewModal() {
  10358. const tab = state.activeRoutingFilterTab || 'rules';
  10359. if (tab === 'rules') openAddRoutingFilterModal();
  10360. else if (tab === 'select-rules') openAddSelectRuleModal();
  10361. else if (tab === 'community-lists') openAddCommunityListModal();
  10362. else if (tab === 'as-lists') openAddASListModal();
  10363. }
  10364. function toggleSelectedRoutingFilter(disabled) {
  10365. const tab = state.activeRoutingFilterTab || 'rules';
  10366. const id = state.selectedFilterRow[tab];
  10367. if (!id) {
  10368. showToast('Select Row', 'Please click on a row to select it first', 'info');
  10369. return;
  10370. }
  10371. if (tab === 'rules') toggleRoutingFilterState(id, disabled);
  10372. else if (tab === 'select-rules') toggleSelectRuleState(id, disabled);
  10373. else if (tab === 'community-lists') toggleCommunityListState(id, disabled);
  10374. else if (tab === 'as-lists') toggleASListState(id, disabled);
  10375. }
  10376. function removeSelectedRoutingFilter() {
  10377. const tab = state.activeRoutingFilterTab || 'rules';
  10378. const id = state.selectedFilterRow[tab];
  10379. if (!id) {
  10380. showToast('Select Row', 'Please click on a row to select it first', 'info');
  10381. return;
  10382. }
  10383. if (tab === 'rules') deleteRoutingFilter(id);
  10384. else if (tab === 'select-rules') deleteSelectRule(id);
  10385. else if (tab === 'community-lists') deleteCommunityList(id);
  10386. else if (tab === 'as-lists') deleteASList(id);
  10387. }
  10388. function searchRoutingFilters(q) {
  10389. state.rfSearchQuery = (q || '').trim().toLowerCase();
  10390. renderRoutingFilters();
  10391. }
  10392. function sortFilterTable(tab, col) {
  10393. if (!state.rfSort) state.rfSort = {};
  10394. if (!state.rfSort[tab]) state.rfSort[tab] = { col: col, asc: true };
  10395. if (state.rfSort[tab].col === col) {
  10396. state.rfSort[tab].asc = !state.rfSort[tab].asc;
  10397. } else {
  10398. state.rfSort[tab].col = col;
  10399. state.rfSort[tab].asc = true;
  10400. }
  10401. const asc = state.rfSort[tab].asc;
  10402. let list = [];
  10403. if (tab === 'rules') list = state.routingFilters || [];
  10404. else if (tab === 'select-rules') list = state.routingSelectRules || [];
  10405. else if (tab === 'community-lists') list = state.routingCommunityLists || [];
  10406. else if (tab === 'as-lists') list = state.routingASLists || [];
  10407. list.sort((a, b) => {
  10408. let valA = a[col] ?? '';
  10409. let valB = b[col] ?? '';
  10410. if (col === 'flags') {
  10411. valA = a.disabled ? 'X' : 'A';
  10412. valB = b.disabled ? 'X' : 'A';
  10413. }
  10414. if (typeof valA === 'number' && typeof valB === 'number') {
  10415. return asc ? valA - valB : valB - valA;
  10416. }
  10417. return asc ? String(valA).localeCompare(String(valB)) : String(valB).localeCompare(String(valA));
  10418. });
  10419. const allCols = ['flags', 'rule_order', 'chain', 'rule', 'name', 'communities', 'range', 'regexp', 'comment'];
  10420. allCols.forEach(c => {
  10421. const el = document.getElementById(`sort-icon-${tab}-${c}`);
  10422. if (el) el.innerText = (c === col) ? (asc ? '▲' : '▼') : '';
  10423. });
  10424. if (tab === 'rules') renderRoutingFilterRules();
  10425. else if (tab === 'select-rules') renderRoutingFilterSelectRules();
  10426. else if (tab === 'community-lists') renderRoutingFilterCommunityLists();
  10427. else if (tab === 'as-lists') renderRoutingFilterASLists();
  10428. }
  10429. function renderRoutingFilters() {
  10430. const navBadge = document.getElementById('badge-filters-count');
  10431. const allRules = state.routingFilters || [];
  10432. if (navBadge) navBadge.innerText = allRules.length;
  10433. // Populate chain filter select options and datalist
  10434. const chainSelect = document.getElementById('routing-filter-chain-select');
  10435. const chainDatalist = document.getElementById('dl-routing-chains');
  10436. const uniqueChains = Array.from(new Set(allRules.map(r => r.chain).filter(Boolean))).sort();
  10437. if (chainSelect) {
  10438. const currentVal = state.filterChainSelected || 'all';
  10439. chainSelect.innerHTML = `<option value="all">All Chains (${allRules.length})</option>` +
  10440. uniqueChains.map(ch => {
  10441. const count = allRules.filter(r => r.chain === ch).length;
  10442. return `<option value="${escapeHtml(ch)}"${currentVal === ch ? ' selected' : ''}>${escapeHtml(ch)} (${count})</option>`;
  10443. }).join('');
  10444. chainSelect.value = currentVal;
  10445. }
  10446. if (chainDatalist) {
  10447. chainDatalist.innerHTML = uniqueChains.map(ch => `<option value="${escapeHtml(ch)}">`).join('');
  10448. }
  10449. renderRoutingFilterRules();
  10450. renderRoutingFilterSelectRules();
  10451. renderRoutingFilterCommunityLists();
  10452. renderRoutingFilterASLists();
  10453. }
  10454. function filterRoutingFiltersByChain(chain) {
  10455. state.filterChainSelected = chain;
  10456. renderRoutingFilters();
  10457. }
  10458. // -------------------------------------------------------------
  10459. // TAB 1: RULES (/routing filter rule)
  10460. // -------------------------------------------------------------
  10461. function renderRoutingFilterRules() {
  10462. const tbody = document.getElementById('routing-filter-rules-tbody');
  10463. if (!tbody) return;
  10464. const empty = document.getElementById('rf-rules-empty');
  10465. const statusCount = document.getElementById('rf-status-count');
  10466. let list = (state.routingFilters || []).slice();
  10467. if (state.filterChainSelected && state.filterChainSelected !== 'all') {
  10468. list = list.filter(r => r.chain === state.filterChainSelected);
  10469. }
  10470. const q = state.rfSearchQuery;
  10471. if (q) {
  10472. list = list.filter(r =>
  10473. (r.chain && r.chain.toLowerCase().includes(q)) ||
  10474. (r.rule && r.rule.toLowerCase().includes(q)) ||
  10475. (r.prefix && r.prefix.toLowerCase().includes(q)) ||
  10476. (r.comment && r.comment.toLowerCase().includes(q))
  10477. );
  10478. }
  10479. if (!state.rfSort?.['rules']) {
  10480. list.sort((a, b) => {
  10481. if (a.chain !== b.chain) return (a.chain || '').localeCompare(b.chain || '');
  10482. return (a.rule_order || 0) - (b.rule_order || 0);
  10483. });
  10484. }
  10485. if (statusCount && (state.activeRoutingFilterTab === 'rules' || !state.activeRoutingFilterTab)) {
  10486. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  10487. }
  10488. if (list.length === 0) {
  10489. tbody.innerHTML = '';
  10490. if (empty) empty.classList.remove('hidden');
  10491. return;
  10492. }
  10493. if (empty) empty.classList.add('hidden');
  10494. tbody.innerHTML = list.map(r => {
  10495. const isSelected = state.selectedFilterRow?.['rules'] === r.id;
  10496. const flagA = !r.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  10497. const flagX = r.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  10498. const flagC = r.comment ? '<span class="text-amber-400 font-bold ml-1" title="Comment">C</span>' : '';
  10499. let ruleDisplay = '';
  10500. if (r.rule && r.rule.trim() !== '') {
  10501. ruleDisplay = `<span class="text-emerald-400 font-mono font-medium">${escapeHtml(r.rule)}</span>`;
  10502. } else {
  10503. let conds = [];
  10504. if (r.prefix) conds.push(`dst in ${escapeHtml(r.prefix)}`);
  10505. if (r.match_protocol && r.match_protocol !== 'any') conds.push(`protocol ${escapeHtml(r.match_protocol)}`);
  10506. let act = r.action || 'accept';
  10507. ruleDisplay = `<span class="text-slate-300 font-mono">if (${conds.length ? conds.join(' && ') : 'true'}) { ${escapeHtml(act)}; }</span>`;
  10508. }
  10509. return `
  10510. <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'}">
  10511. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}${flagC}</td>
  10512. <td class="py-2 px-2 font-mono text-slate-400 font-bold">${r.rule_order || 10}</td>
  10513. <td class="py-2 px-3">
  10514. <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>
  10515. </td>
  10516. <td class="py-2 px-3 break-all max-w-xl">${ruleDisplay}</td>
  10517. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(r.comment || '')}</td>
  10518. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  10519. <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>
  10520. <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>
  10521. <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'}">
  10522. ${r.disabled ? 'Enable' : 'Disable'}
  10523. </button>
  10524. <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">
  10525. Edit
  10526. </button>
  10527. <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">
  10528. ✕
  10529. </button>
  10530. </td>
  10531. </tr>
  10532. `;
  10533. }).join('');
  10534. }
  10535. // -------------------------------------------------------------
  10536. // TAB 2: SELECT RULES (/routing filter select-rule)
  10537. // -------------------------------------------------------------
  10538. function renderRoutingFilterSelectRules() {
  10539. const tbody = document.getElementById('routing-filter-select-rules-tbody');
  10540. if (!tbody) return;
  10541. const empty = document.getElementById('rf-select-rules-empty');
  10542. const statusCount = document.getElementById('rf-status-count');
  10543. let list = (state.routingSelectRules || []).slice();
  10544. if (state.filterChainSelected && state.filterChainSelected !== 'all') {
  10545. list = list.filter(r => r.chain === state.filterChainSelected);
  10546. }
  10547. const q = state.rfSearchQuery;
  10548. if (q) {
  10549. list = list.filter(r =>
  10550. (r.chain && r.chain.toLowerCase().includes(q)) ||
  10551. (r.rule && r.rule.toLowerCase().includes(q)) ||
  10552. (r.comment && r.comment.toLowerCase().includes(q))
  10553. );
  10554. }
  10555. if (statusCount && state.activeRoutingFilterTab === 'select-rules') {
  10556. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  10557. }
  10558. if (list.length === 0) {
  10559. tbody.innerHTML = '';
  10560. if (empty) empty.classList.remove('hidden');
  10561. return;
  10562. }
  10563. if (empty) empty.classList.add('hidden');
  10564. tbody.innerHTML = list.map(r => {
  10565. const isSelected = state.selectedFilterRow?.['select-rules'] === r.id;
  10566. const flagA = !r.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  10567. const flagX = r.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  10568. return `
  10569. <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'}">
  10570. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  10571. <td class="py-2 px-2 font-mono text-slate-400 font-bold">${r.rule_order || 10}</td>
  10572. <td class="py-2 px-3">
  10573. <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>
  10574. </td>
  10575. <td class="py-2 px-3 break-all max-w-xl font-mono text-emerald-400">${escapeHtml(r.rule || '')}</td>
  10576. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(r.comment || '')}</td>
  10577. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  10578. <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'}">
  10579. ${r.disabled ? 'Enable' : 'Disable'}
  10580. </button>
  10581. <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">
  10582. Edit
  10583. </button>
  10584. <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">
  10585. ✕
  10586. </button>
  10587. </td>
  10588. </tr>
  10589. `;
  10590. }).join('');
  10591. }
  10592. // -------------------------------------------------------------
  10593. // TAB 3: COMMUNITY LISTS (/routing filter community-list)
  10594. // -------------------------------------------------------------
  10595. function renderRoutingFilterCommunityLists() {
  10596. const tbody = document.getElementById('routing-filter-comm-lists-tbody');
  10597. if (!tbody) return;
  10598. const empty = document.getElementById('rf-comm-lists-empty');
  10599. const statusCount = document.getElementById('rf-status-count');
  10600. let list = (state.routingCommunityLists || []).slice();
  10601. const q = state.rfSearchQuery;
  10602. if (q) {
  10603. list = list.filter(cl =>
  10604. (cl.name && cl.name.toLowerCase().includes(q)) ||
  10605. (cl.comment && cl.comment.toLowerCase().includes(q)) ||
  10606. (cl.communities && cl.communities.some(c => c.toLowerCase().includes(q)))
  10607. );
  10608. }
  10609. if (statusCount && state.activeRoutingFilterTab === 'community-lists') {
  10610. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  10611. }
  10612. if (list.length === 0) {
  10613. tbody.innerHTML = '';
  10614. if (empty) empty.classList.remove('hidden');
  10615. return;
  10616. }
  10617. if (empty) empty.classList.add('hidden');
  10618. tbody.innerHTML = list.map(cl => {
  10619. const isSelected = state.selectedFilterRow?.['community-lists'] === cl.id;
  10620. const flagA = !cl.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  10621. const flagX = cl.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  10622. const commBadges = (cl.communities || []).map(c =>
  10623. `<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>`
  10624. ).join(' ');
  10625. return `
  10626. <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'}">
  10627. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  10628. <td class="py-2 px-3 font-mono font-bold text-white">${escapeHtml(cl.name)}</td>
  10629. <td class="py-2 px-3 space-x-1">${commBadges || '<span class="text-slate-600">-</span>'}</td>
  10630. <td class="py-2 px-3 font-mono text-slate-400">${escapeHtml(cl.regexp || '-')}</td>
  10631. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(cl.comment || '')}</td>
  10632. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  10633. <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'}">
  10634. ${cl.disabled ? 'Enable' : 'Disable'}
  10635. </button>
  10636. <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">
  10637. Edit
  10638. </button>
  10639. <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">
  10640. ✕
  10641. </button>
  10642. </td>
  10643. </tr>
  10644. `;
  10645. }).join('');
  10646. }
  10647. // -------------------------------------------------------------
  10648. // TAB 4: AS LISTS (/routing filter num-list)
  10649. // -------------------------------------------------------------
  10650. function renderRoutingFilterASLists() {
  10651. const tbody = document.getElementById('routing-filter-as-lists-tbody');
  10652. if (!tbody) return;
  10653. const empty = document.getElementById('rf-as-lists-empty');
  10654. const statusCount = document.getElementById('rf-status-count');
  10655. let list = (state.routingASLists || []).slice();
  10656. const q = state.rfSearchQuery;
  10657. if (q) {
  10658. list = list.filter(al =>
  10659. (al.name && al.name.toLowerCase().includes(q)) ||
  10660. (al.range && al.range.toLowerCase().includes(q)) ||
  10661. (al.comment && al.comment.toLowerCase().includes(q))
  10662. );
  10663. }
  10664. if (statusCount && state.activeRoutingFilterTab === 'as-lists') {
  10665. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  10666. }
  10667. if (list.length === 0) {
  10668. tbody.innerHTML = '';
  10669. if (empty) empty.classList.remove('hidden');
  10670. return;
  10671. }
  10672. if (empty) empty.classList.add('hidden');
  10673. tbody.innerHTML = list.map(al => {
  10674. const isSelected = state.selectedFilterRow?.['as-lists'] === al.id;
  10675. const flagA = !al.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  10676. const flagX = al.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  10677. return `
  10678. <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'}">
  10679. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  10680. <td class="py-2 px-3 font-mono font-bold text-white">${escapeHtml(al.name)}</td>
  10681. <td class="py-2 px-3 font-mono text-purple-300">${escapeHtml(al.range)}</td>
  10682. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(al.comment || '')}</td>
  10683. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  10684. <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'}">
  10685. ${al.disabled ? 'Enable' : 'Disable'}
  10686. </button>
  10687. <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">
  10688. Edit
  10689. </button>
  10690. <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">
  10691. ✕
  10692. </button>
  10693. </td>
  10694. </tr>
  10695. `;
  10696. }).join('');
  10697. }
  10698. // -------------------------------------------------------------
  10699. // SNIPPETS & WIZARD HELPERS
  10700. // -------------------------------------------------------------
  10701. function insertRuleSnippet(type) {
  10702. const textarea = document.getElementById('modal-rf-rule');
  10703. if (!textarea) return;
  10704. let snippet = '';
  10705. switch (type) {
  10706. case 'accept-default':
  10707. snippet = 'if (dst in 0.0.0.0/0) { accept; }';
  10708. break;
  10709. case 'drop-rfc1918':
  10710. snippet = 'if (dst in 10.0.0.0/8 || dst in 172.16.0.0/12 || dst in 192.168.0.0/16) { reject; }';
  10711. break;
  10712. case 'len-24':
  10713. snippet = 'if (dst-len > 24) { reject; }';
  10714. break;
  10715. case 'local-pref-150':
  10716. snippet = 'if (dst in 10.0.0.0/8) { set bgp-local-pref 150; accept; }';
  10717. break;
  10718. case 'as-prepend-2':
  10719. snippet = 'set bgp-path-prepend 2; accept;';
  10720. break;
  10721. case 'set-comm':
  10722. snippet = 'set bgp-communities.add 65000:100; accept;';
  10723. break;
  10724. case 'match-comm':
  10725. snippet = 'if (bgp-communities includes 65000:100) { accept; }';
  10726. break;
  10727. case 'reject-all':
  10728. snippet = 'reject;';
  10729. break;
  10730. }
  10731. if (!snippet) return;
  10732. if (!textarea.value.trim()) {
  10733. textarea.value = snippet;
  10734. } else {
  10735. textarea.value = textarea.value.trim() + '\n' + snippet;
  10736. }
  10737. }
  10738. function generateScriptFromWizard() {
  10739. const pfx = (document.getElementById('modal-rf-prefix')?.value || '').trim();
  10740. const pfxLen = (document.getElementById('modal-rf-prefix-len')?.value || '').trim();
  10741. const proto = document.getElementById('modal-rf-protocol')?.value || 'any';
  10742. const asp = (document.getElementById('modal-rf-as-path')?.value || '').trim();
  10743. const comm = (document.getElementById('modal-rf-community')?.value || '').trim();
  10744. const act = document.getElementById('modal-rf-action')?.value || 'accept';
  10745. const lp = parseInt(document.getElementById('modal-rf-set-local-pref')?.value, 10) || 0;
  10746. const prep = parseInt(document.getElementById('modal-rf-set-as-prepend')?.value, 10) || 0;
  10747. const conds = [];
  10748. if (pfx) {
  10749. if (pfxLen) {
  10750. if (pfxLen.includes('-')) {
  10751. const parts = pfxLen.split('-');
  10752. conds.push(`dst in ${pfx}{${parts[0].trim()},${parts[1].trim()}}`);
  10753. } else {
  10754. conds.push(`dst in ${pfx} && dst-len >= ${pfxLen}`);
  10755. }
  10756. } else {
  10757. conds.push(`dst in ${pfx}`);
  10758. }
  10759. }
  10760. if (proto && proto !== 'any') {
  10761. conds.push(`protocol ${proto}`);
  10762. }
  10763. if (asp) {
  10764. conds.push(`bgp-as-path "${asp}"`);
  10765. }
  10766. if (comm) {
  10767. conds.push(`bgp-communities includes ${comm}`);
  10768. }
  10769. const actions = [];
  10770. if (lp > 0) actions.push(`set bgp-local-pref ${lp};`);
  10771. if (prep > 0) actions.push(`set bgp-path-prepend ${prep};`);
  10772. actions.push(`${act};`);
  10773. let code = '';
  10774. if (conds.length > 0) {
  10775. code = `if (${conds.join(' && ')}) {\n ${actions.join(' ')}\n}`;
  10776. } else {
  10777. code = actions.join(' ');
  10778. }
  10779. const textarea = document.getElementById('modal-rf-rule');
  10780. if (textarea) textarea.value = code;
  10781. }
  10782. // -------------------------------------------------------------
  10783. // MODAL CRUD: RULES (/routing filter rule)
  10784. // -------------------------------------------------------------
  10785. function openAddRoutingFilterModal(defaultChain = '') {
  10786. const form = document.getElementById('routing-filter-form');
  10787. if (form) form.reset();
  10788. const idEl = document.getElementById('modal-rf-id');
  10789. if (idEl) idEl.value = '';
  10790. const titleEl = document.getElementById('modal-rf-title');
  10791. if (titleEl) titleEl.innerText = 'Add Routing Filter Rule';
  10792. const chainEl = document.getElementById('modal-rf-chain');
  10793. if (chainEl) chainEl.value = defaultChain || (state.filterChainSelected && state.filterChainSelected !== 'all' ? state.filterChainSelected : 'bgp-in');
  10794. const orderEl = document.getElementById('modal-rf-order');
  10795. if (orderEl) orderEl.value = ((state.routingFilters || []).length + 1) * 10;
  10796. const ruleEl = document.getElementById('modal-rf-rule');
  10797. if (ruleEl) ruleEl.value = 'if (dst in 10.0.0.0/8) { set bgp-local-pref 150; accept; }';
  10798. const disEl = document.getElementById('modal-rf-disabled');
  10799. if (disEl) disEl.checked = false;
  10800. const modal = document.getElementById('modal-routing-filter');
  10801. if (modal) modal.classList.remove('hidden');
  10802. }
  10803. function openEditRoutingFilterModal(id) {
  10804. const r = (state.routingFilters || []).find(item => item.id === id);
  10805. if (!r) return;
  10806. const idEl = document.getElementById('modal-rf-id');
  10807. if (idEl) idEl.value = r.id;
  10808. const titleEl = document.getElementById('modal-rf-title');
  10809. if (titleEl) titleEl.innerText = 'Edit Routing Filter Rule';
  10810. const chainEl = document.getElementById('modal-rf-chain');
  10811. if (chainEl) chainEl.value = r.chain || '';
  10812. const orderEl = document.getElementById('modal-rf-order');
  10813. if (orderEl) orderEl.value = r.rule_order || 10;
  10814. const ruleEl = document.getElementById('modal-rf-rule');
  10815. if (ruleEl) {
  10816. if (r.rule) {
  10817. ruleEl.value = r.rule;
  10818. } else {
  10819. let conds = [];
  10820. if (r.prefix) conds.push(`dst in ${r.prefix}`);
  10821. if (r.match_protocol && r.match_protocol !== 'any') conds.push(`protocol ${r.match_protocol}`);
  10822. let act = r.action || 'accept';
  10823. ruleEl.value = `if (${conds.length ? conds.join(' && ') : 'true'}) { ${act}; }`;
  10824. }
  10825. }
  10826. const comEl = document.getElementById('modal-rf-comment');
  10827. if (comEl) comEl.value = r.comment || '';
  10828. const disEl = document.getElementById('modal-rf-disabled');
  10829. if (disEl) disEl.checked = !!r.disabled;
  10830. const modal = document.getElementById('modal-routing-filter');
  10831. if (modal) modal.classList.remove('hidden');
  10832. }
  10833. function closeRoutingFilterModal() {
  10834. const modal = document.getElementById('modal-routing-filter');
  10835. if (modal) modal.classList.add('hidden');
  10836. }
  10837. async function submitRoutingFilter(e) {
  10838. if (e) e.preventDefault();
  10839. const payload = {
  10840. id: document.getElementById('modal-rf-id').value,
  10841. chain: document.getElementById('modal-rf-chain').value.trim(),
  10842. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  10843. rule: document.getElementById('modal-rf-rule').value.trim(),
  10844. comment: document.getElementById('modal-rf-comment').value.trim(),
  10845. disabled: document.getElementById('modal-rf-disabled').checked
  10846. };
  10847. try {
  10848. const res = await fetch(`${API_BASE}/routing/filters`, {
  10849. method: 'POST',
  10850. headers: { 'Content-Type': 'application/json' },
  10851. body: JSON.stringify(payload)
  10852. });
  10853. if (res.ok) {
  10854. closeRoutingFilterModal();
  10855. showToast('Success', 'Routing filter rule saved', 'success');
  10856. loadDynamicRouting();
  10857. } else {
  10858. const err = await res.json();
  10859. showToast('Error', err.error || 'Failed to save filter rule', 'error');
  10860. }
  10861. } catch (err) {
  10862. showToast('Error', err.message, 'error');
  10863. }
  10864. }
  10865. async function applyRoutingFilterForm() {
  10866. const payload = {
  10867. id: document.getElementById('modal-rf-id').value,
  10868. chain: document.getElementById('modal-rf-chain').value.trim(),
  10869. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  10870. rule: document.getElementById('modal-rf-rule').value.trim(),
  10871. comment: document.getElementById('modal-rf-comment').value.trim(),
  10872. disabled: document.getElementById('modal-rf-disabled').checked
  10873. };
  10874. try {
  10875. const res = await fetch(`${API_BASE}/routing/filters`, {
  10876. method: 'POST',
  10877. headers: { 'Content-Type': 'application/json' },
  10878. body: JSON.stringify(payload)
  10879. });
  10880. if (res.ok) {
  10881. const data = await res.json();
  10882. if (data.id) document.getElementById('modal-rf-id').value = data.id;
  10883. showToast('Applied', 'Routing filter configuration applied', 'success');
  10884. loadDynamicRouting();
  10885. } else {
  10886. const err = await res.json();
  10887. showToast('Error', err.error || 'Failed to apply filter rule', 'error');
  10888. }
  10889. } catch (err) {
  10890. showToast('Error', err.message, 'error');
  10891. }
  10892. }
  10893. async function moveRoutingFilterOrder(id, delta) {
  10894. const list = state.routingFilters || [];
  10895. const idx = list.findIndex(r => r.id === id);
  10896. if (idx < 0) return;
  10897. const targetIdx = idx + delta;
  10898. if (targetIdx < 0 || targetIdx >= list.length) return;
  10899. const currentOrder = list[idx].rule_order || 10;
  10900. const targetOrder = list[targetIdx].rule_order || 20;
  10901. list[idx].rule_order = targetOrder;
  10902. list[targetIdx].rule_order = currentOrder;
  10903. try {
  10904. await fetch(`${API_BASE}/routing/filters`, {
  10905. method: 'POST',
  10906. headers: { 'Content-Type': 'application/json' },
  10907. body: JSON.stringify(list[idx])
  10908. });
  10909. await fetch(`${API_BASE}/routing/filters`, {
  10910. method: 'POST',
  10911. headers: { 'Content-Type': 'application/json' },
  10912. body: JSON.stringify(list[targetIdx])
  10913. });
  10914. loadDynamicRouting();
  10915. } catch (e) {
  10916. console.error('Reorder error:', e);
  10917. }
  10918. }
  10919. async function deleteRoutingFilter(id) {
  10920. if (!confirm('Are you sure you want to delete this routing filter rule?')) return;
  10921. try {
  10922. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10923. if (res.ok) {
  10924. showToast('Deleted', 'Routing filter rule removed', 'info');
  10925. loadDynamicRouting();
  10926. } else {
  10927. const err = await res.json();
  10928. showToast('Error', err.error || 'Failed to delete rule', 'error');
  10929. }
  10930. } catch (err) {
  10931. showToast('Error', err.message, 'error');
  10932. }
  10933. }
  10934. async function toggleRoutingFilterState(id, disabled) {
  10935. try {
  10936. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}/state`, {
  10937. method: 'POST',
  10938. headers: { 'Content-Type': 'application/json' },
  10939. body: JSON.stringify({ disabled })
  10940. });
  10941. if (res.ok) {
  10942. showToast('Status Updated', `Rule ${disabled ? 'disabled' : 'enabled'}`, 'info');
  10943. loadDynamicRouting();
  10944. } else {
  10945. const err = await res.json();
  10946. showToast('Error', err.error || 'Failed to toggle rule state', 'error');
  10947. }
  10948. } catch (err) {
  10949. showToast('Error', err.message, 'error');
  10950. }
  10951. }
  10952. // -------------------------------------------------------------
  10953. // MODAL CRUD: SELECT RULES (/routing filter select-rule)
  10954. // -------------------------------------------------------------
  10955. function openAddSelectRuleModal() {
  10956. document.getElementById('modal-rf-sr-id').value = '';
  10957. document.getElementById('modal-rf-sr-title').innerText = 'Add Routing Select Rule';
  10958. document.getElementById('modal-rf-sr-chain').value = state.filterChainSelected && state.filterChainSelected !== 'all' ? state.filterChainSelected : 'bgp-out';
  10959. document.getElementById('modal-rf-sr-order').value = ((state.routingSelectRules || []).length + 1) * 10;
  10960. document.getElementById('modal-rf-sr-rule').value = 'if (protocol bgp && dst in 10.0.0.0/8) { accept; }';
  10961. document.getElementById('modal-rf-sr-comment').value = '';
  10962. document.getElementById('modal-rf-sr-disabled').checked = false;
  10963. document.getElementById('modal-rf-select-rule').classList.remove('hidden');
  10964. }
  10965. function openEditSelectRuleModal(id) {
  10966. const r = (state.routingSelectRules || []).find(item => item.id === id);
  10967. if (!r) return;
  10968. document.getElementById('modal-rf-sr-id').value = r.id;
  10969. document.getElementById('modal-rf-sr-title').innerText = 'Edit Routing Select Rule';
  10970. document.getElementById('modal-rf-sr-chain').value = r.chain || '';
  10971. document.getElementById('modal-rf-sr-order').value = r.rule_order || 10;
  10972. document.getElementById('modal-rf-sr-rule').value = r.rule || '';
  10973. document.getElementById('modal-rf-sr-comment').value = r.comment || '';
  10974. document.getElementById('modal-rf-sr-disabled').checked = !!r.disabled;
  10975. document.getElementById('modal-rf-select-rule').classList.remove('hidden');
  10976. }
  10977. function closeSelectRuleModal() {
  10978. document.getElementById('modal-rf-select-rule').classList.add('hidden');
  10979. }
  10980. async function submitSelectRule(e) {
  10981. e.preventDefault();
  10982. const payload = {
  10983. id: document.getElementById('modal-rf-sr-id').value,
  10984. chain: document.getElementById('modal-rf-sr-chain').value.trim(),
  10985. rule_order: parseInt(document.getElementById('modal-rf-sr-order').value, 10) || 10,
  10986. rule: document.getElementById('modal-rf-sr-rule').value.trim(),
  10987. comment: document.getElementById('modal-rf-sr-comment').value.trim(),
  10988. disabled: document.getElementById('modal-rf-sr-disabled').checked
  10989. };
  10990. try {
  10991. const res = await fetch(`${API_BASE}/routing/filters/select-rules`, {
  10992. method: 'POST',
  10993. headers: { 'Content-Type': 'application/json' },
  10994. body: JSON.stringify(payload)
  10995. });
  10996. if (res.ok) {
  10997. closeSelectRuleModal();
  10998. showToast('Success', 'Select rule saved', 'success');
  10999. loadDynamicRouting();
  11000. } else {
  11001. const err = await res.json();
  11002. showToast('Error', err.error || 'Failed to save select rule', 'error');
  11003. }
  11004. } catch (err) {
  11005. showToast('Error', err.message, 'error');
  11006. }
  11007. }
  11008. async function deleteSelectRule(id) {
  11009. if (!confirm('Are you sure you want to delete this select rule?')) return;
  11010. try {
  11011. const res = await fetch(`${API_BASE}/routing/filters/select-rules/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11012. if (res.ok) {
  11013. showToast('Deleted', 'Select rule removed', 'info');
  11014. loadDynamicRouting();
  11015. } else {
  11016. const err = await res.json();
  11017. showToast('Error', err.error || 'Failed to delete select rule', 'error');
  11018. }
  11019. } catch (err) {
  11020. showToast('Error', err.message, 'error');
  11021. }
  11022. }
  11023. async function toggleSelectRuleState(id, disabled) {
  11024. try {
  11025. const res = await fetch(`${API_BASE}/routing/filters/select-rules/${encodeURIComponent(id)}/state`, {
  11026. method: 'POST',
  11027. headers: { 'Content-Type': 'application/json' },
  11028. body: JSON.stringify({ disabled })
  11029. });
  11030. if (res.ok) {
  11031. showToast('Status Updated', `Select rule ${disabled ? 'disabled' : 'enabled'}`, 'info');
  11032. loadDynamicRouting();
  11033. } else {
  11034. const err = await res.json();
  11035. showToast('Error', err.error || 'Failed to update select rule state', 'error');
  11036. }
  11037. } catch (err) {
  11038. showToast('Error', err.message, 'error');
  11039. }
  11040. }
  11041. // -------------------------------------------------------------
  11042. // MODAL CRUD: COMMUNITY LISTS (/routing filter community-list)
  11043. // -------------------------------------------------------------
  11044. function openAddCommunityListModal() {
  11045. document.getElementById('modal-rf-cl-id').value = '';
  11046. document.getElementById('modal-rf-cl-title').innerText = 'Add BGP Community List';
  11047. document.getElementById('modal-rf-cl-name').value = '';
  11048. document.getElementById('modal-rf-cl-communities').value = '';
  11049. document.getElementById('modal-rf-cl-regexp').value = '';
  11050. document.getElementById('modal-rf-cl-comment').value = '';
  11051. document.getElementById('modal-rf-cl-disabled').checked = false;
  11052. document.getElementById('modal-rf-community-list').classList.remove('hidden');
  11053. }
  11054. function openEditCommunityListModal(id) {
  11055. const cl = (state.routingCommunityLists || []).find(item => item.id === id);
  11056. if (!cl) return;
  11057. document.getElementById('modal-rf-cl-id').value = cl.id;
  11058. document.getElementById('modal-rf-cl-title').innerText = 'Edit BGP Community List';
  11059. document.getElementById('modal-rf-cl-name').value = cl.name || '';
  11060. document.getElementById('modal-rf-cl-communities').value = (cl.communities || []).join(', ');
  11061. document.getElementById('modal-rf-cl-regexp').value = cl.regexp || '';
  11062. document.getElementById('modal-rf-cl-comment').value = cl.comment || '';
  11063. document.getElementById('modal-rf-cl-disabled').checked = !!cl.disabled;
  11064. document.getElementById('modal-rf-community-list').classList.remove('hidden');
  11065. }
  11066. function closeCommunityListModal() {
  11067. document.getElementById('modal-rf-community-list').classList.add('hidden');
  11068. }
  11069. async function submitCommunityList(e) {
  11070. e.preventDefault();
  11071. const rawComms = document.getElementById('modal-rf-cl-communities').value;
  11072. const comms = rawComms.split(',').map(c => c.trim()).filter(Boolean);
  11073. const payload = {
  11074. id: document.getElementById('modal-rf-cl-id').value,
  11075. name: document.getElementById('modal-rf-cl-name').value.trim(),
  11076. communities: comms,
  11077. regexp: document.getElementById('modal-rf-cl-regexp').value.trim(),
  11078. comment: document.getElementById('modal-rf-cl-comment').value.trim(),
  11079. disabled: document.getElementById('modal-rf-cl-disabled').checked
  11080. };
  11081. try {
  11082. const res = await fetch(`${API_BASE}/routing/filters/community-lists`, {
  11083. method: 'POST',
  11084. headers: { 'Content-Type': 'application/json' },
  11085. body: JSON.stringify(payload)
  11086. });
  11087. if (res.ok) {
  11088. closeCommunityListModal();
  11089. showToast('Success', 'Community list saved', 'success');
  11090. loadDynamicRouting();
  11091. } else {
  11092. const err = await res.json();
  11093. showToast('Error', err.error || 'Failed to save community list', 'error');
  11094. }
  11095. } catch (err) {
  11096. showToast('Error', err.message, 'error');
  11097. }
  11098. }
  11099. async function deleteCommunityList(id) {
  11100. if (!confirm('Are you sure you want to delete this community list?')) return;
  11101. try {
  11102. const res = await fetch(`${API_BASE}/routing/filters/community-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11103. if (res.ok) {
  11104. showToast('Deleted', 'Community list removed', 'info');
  11105. loadDynamicRouting();
  11106. } else {
  11107. const err = await res.json();
  11108. showToast('Error', err.error || 'Failed to delete community list', 'error');
  11109. }
  11110. } catch (err) {
  11111. showToast('Error', err.message, 'error');
  11112. }
  11113. }
  11114. async function toggleCommunityListState(id, disabled) {
  11115. try {
  11116. const res = await fetch(`${API_BASE}/routing/filters/community-lists/${encodeURIComponent(id)}/state`, {
  11117. method: 'POST',
  11118. headers: { 'Content-Type': 'application/json' },
  11119. body: JSON.stringify({ disabled })
  11120. });
  11121. if (res.ok) {
  11122. showToast('Status Updated', `Community list ${disabled ? 'disabled' : 'enabled'}`, 'info');
  11123. loadDynamicRouting();
  11124. } else {
  11125. const err = await res.json();
  11126. showToast('Error', err.error || 'Failed to update community list state', 'error');
  11127. }
  11128. } catch (err) {
  11129. showToast('Error', err.message, 'error');
  11130. }
  11131. }
  11132. // -------------------------------------------------------------
  11133. // MODAL CRUD: AS LISTS (/routing filter num-list)
  11134. // -------------------------------------------------------------
  11135. function openAddASListModal() {
  11136. document.getElementById('modal-rf-al-id').value = '';
  11137. document.getElementById('modal-rf-al-title').innerText = 'Add AS Number List';
  11138. document.getElementById('modal-rf-al-name').value = '';
  11139. document.getElementById('modal-rf-al-range').value = '';
  11140. document.getElementById('modal-rf-al-comment').value = '';
  11141. document.getElementById('modal-rf-al-disabled').checked = false;
  11142. document.getElementById('modal-rf-as-list').classList.remove('hidden');
  11143. }
  11144. function openEditASListModal(id) {
  11145. const al = (state.routingASLists || []).find(item => item.id === id);
  11146. if (!al) return;
  11147. document.getElementById('modal-rf-al-id').value = al.id;
  11148. document.getElementById('modal-rf-al-title').innerText = 'Edit AS Number List';
  11149. document.getElementById('modal-rf-al-name').value = al.name || '';
  11150. document.getElementById('modal-rf-al-range').value = al.range || '';
  11151. document.getElementById('modal-rf-al-comment').value = al.comment || '';
  11152. document.getElementById('modal-rf-al-disabled').checked = !!al.disabled;
  11153. document.getElementById('modal-rf-as-list').classList.remove('hidden');
  11154. }
  11155. function closeASListModal() {
  11156. document.getElementById('modal-rf-as-list').classList.add('hidden');
  11157. }
  11158. async function submitASList(e) {
  11159. e.preventDefault();
  11160. const payload = {
  11161. id: document.getElementById('modal-rf-al-id').value,
  11162. name: document.getElementById('modal-rf-al-name').value.trim(),
  11163. range: document.getElementById('modal-rf-al-range').value.trim(),
  11164. comment: document.getElementById('modal-rf-al-comment').value.trim(),
  11165. disabled: document.getElementById('modal-rf-al-disabled').checked
  11166. };
  11167. try {
  11168. const res = await fetch(`${API_BASE}/routing/filters/as-lists`, {
  11169. method: 'POST',
  11170. headers: { 'Content-Type': 'application/json' },
  11171. body: JSON.stringify(payload)
  11172. });
  11173. if (res.ok) {
  11174. closeASListModal();
  11175. showToast('Success', 'AS number list saved', 'success');
  11176. loadDynamicRouting();
  11177. } else {
  11178. const err = await res.json();
  11179. showToast('Error', err.error || 'Failed to save AS list', 'error');
  11180. }
  11181. } catch (err) {
  11182. showToast('Error', err.message, 'error');
  11183. }
  11184. }
  11185. async function deleteASList(id) {
  11186. if (!confirm('Are you sure you want to delete this AS list?')) return;
  11187. try {
  11188. const res = await fetch(`${API_BASE}/routing/filters/as-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11189. if (res.ok) {
  11190. showToast('Deleted', 'AS list removed', 'info');
  11191. loadDynamicRouting();
  11192. } else {
  11193. const err = await res.json();
  11194. showToast('Error', err.error || 'Failed to delete AS list', 'error');
  11195. }
  11196. } catch (err) {
  11197. showToast('Error', err.message, 'error');
  11198. }
  11199. }
  11200. async function toggleASListState(id, disabled) {
  11201. try {
  11202. const res = await fetch(`${API_BASE}/routing/filters/as-lists/${encodeURIComponent(id)}/state`, {
  11203. method: 'POST',
  11204. headers: { 'Content-Type': 'application/json' },
  11205. body: JSON.stringify({ disabled })
  11206. });
  11207. if (res.ok) {
  11208. showToast('Status Updated', `AS list ${disabled ? 'disabled' : 'enabled'}`, 'info');
  11209. loadDynamicRouting();
  11210. } else {
  11211. const err = await res.json();
  11212. showToast('Error', err.error || 'Failed to update AS list state', 'error');
  11213. }
  11214. } catch (err) {
  11215. showToast('Error', err.message, 'error');
  11216. }
  11217. }
  11218. // ==========================================
  11219. // TROUBLESHOOT & DIAGNOSTIC TOOLS (/tool)
  11220. // ==========================================
  11221. function loadToolsView() {
  11222. populateToolsInterfaces();
  11223. switchToolsSubTab(state.activeToolsSubTab || 'ping');
  11224. }
  11225. function populateToolsInterfaces() {
  11226. const pingSel = document.getElementById('tools-ping-iface');
  11227. const traceSel = document.getElementById('tools-tr-iface');
  11228. let opts = '<option value="">Auto (Default Route)</option>';
  11229. if (Array.isArray(state.interfaces)) {
  11230. state.interfaces.forEach(iface => {
  11231. if (iface.name) {
  11232. opts += `<option value="${escapeHtml(iface.name)}">${escapeHtml(iface.name)}${iface.ip_address ? ' (' + escapeHtml(iface.ip_address) + ')' : ''}</option>`;
  11233. }
  11234. });
  11235. }
  11236. if (pingSel) {
  11237. const cur = pingSel.value;
  11238. pingSel.innerHTML = opts;
  11239. if (cur) pingSel.value = cur;
  11240. }
  11241. if (traceSel) {
  11242. const cur = traceSel.value;
  11243. traceSel.innerHTML = opts;
  11244. if (cur) traceSel.value = cur;
  11245. }
  11246. }
  11247. function switchToolsSubTab(subTab) {
  11248. state.activeToolsSubTab = subTab;
  11249. const tabs = ['ping', 'traceroute', 'mtr', 'dns', 'port'];
  11250. tabs.forEach(t => {
  11251. const btn = document.getElementById(`tools-subtab-btn-${t}`);
  11252. const view = document.getElementById(`tools-view-${t}`);
  11253. if (btn) {
  11254. if (t === subTab) {
  11255. 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';
  11256. } else {
  11257. 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';
  11258. }
  11259. }
  11260. if (view) {
  11261. if (t === subTab) {
  11262. view.classList.remove('hidden');
  11263. } else {
  11264. view.classList.add('hidden');
  11265. }
  11266. }
  11267. });
  11268. }
  11269. function setPortPreset(port) {
  11270. const input = document.getElementById('tools-port-num');
  11271. if (input) input.value = port;
  11272. }
  11273. let pingAbortController = null;
  11274. let tracerouteAbortController = null;
  11275. function clearPingTable() {
  11276. const tbody = document.getElementById('tools-ping-tbody');
  11277. if (tbody) tbody.innerHTML = '';
  11278. const rawEl = document.getElementById('tools-ping-raw');
  11279. if (rawEl) rawEl.innerText = '';
  11280. const sentEl = document.getElementById('tools-ping-stat-sent');
  11281. if (sentEl) sentEl.innerText = '0';
  11282. const recvEl = document.getElementById('tools-ping-stat-recv');
  11283. if (recvEl) recvEl.innerText = '0';
  11284. const lossEl = document.getElementById('tools-ping-stat-loss');
  11285. if (lossEl) lossEl.innerText = '0%';
  11286. const avgEl = document.getElementById('tools-ping-stat-avg');
  11287. if (avgEl) avgEl.innerText = '0 ms';
  11288. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  11289. if (minMaxEl) minMaxEl.innerText = '-';
  11290. const badge = document.getElementById('tools-ping-status-badge');
  11291. if (badge) {
  11292. badge.className = '';
  11293. badge.innerText = '';
  11294. }
  11295. }
  11296. function clearTracerouteTable() {
  11297. const tbody = document.getElementById('tools-tr-tbody');
  11298. if (tbody) tbody.innerHTML = '';
  11299. const rawEl = document.getElementById('tools-tr-raw');
  11300. if (rawEl) rawEl.innerText = '';
  11301. const statHops = document.getElementById('tools-tr-hops-count');
  11302. if (statHops) statHops.innerText = '0 Hops';
  11303. }
  11304. function resetPingButton() {
  11305. const btn = document.getElementById('tools-ping-btn');
  11306. const btnText = document.getElementById('tools-ping-btn-text');
  11307. const spinner = document.getElementById('tools-ping-spinner');
  11308. if (btn) {
  11309. btn.disabled = false;
  11310. 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';
  11311. }
  11312. if (btnText) btnText.innerText = 'Start Ping';
  11313. if (spinner) spinner.classList.add('hidden');
  11314. }
  11315. function setPingRunningButton() {
  11316. const btn = document.getElementById('tools-ping-btn');
  11317. const btnText = document.getElementById('tools-ping-btn-text');
  11318. const spinner = document.getElementById('tools-ping-spinner');
  11319. if (btn) {
  11320. btn.disabled = false;
  11321. 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';
  11322. }
  11323. if (btnText) btnText.innerText = 'Stop Ping';
  11324. if (spinner) spinner.classList.remove('hidden');
  11325. }
  11326. function resetTracerouteButton() {
  11327. const btn = document.getElementById('tools-tr-btn');
  11328. const btnText = document.getElementById('tools-tr-btn-text');
  11329. const spinner = document.getElementById('tools-tr-spinner');
  11330. if (btn) {
  11331. btn.disabled = false;
  11332. 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';
  11333. }
  11334. if (btnText) btnText.innerText = 'Start Traceroute';
  11335. if (spinner) spinner.classList.add('hidden');
  11336. }
  11337. function setTracerouteRunningButton() {
  11338. const btn = document.getElementById('tools-tr-btn');
  11339. const btnText = document.getElementById('tools-tr-btn-text');
  11340. const spinner = document.getElementById('tools-tr-spinner');
  11341. if (btn) {
  11342. btn.disabled = false;
  11343. 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';
  11344. }
  11345. if (btnText) btnText.innerText = 'Stop Traceroute';
  11346. if (spinner) spinner.classList.remove('hidden');
  11347. }
  11348. async function executePing(e) {
  11349. if (e) e.preventDefault();
  11350. // If already running, clicking the button stops the stream!
  11351. if (pingAbortController) {
  11352. pingAbortController.abort();
  11353. pingAbortController = null;
  11354. resetPingButton();
  11355. showToast('Ping Stopped', 'Live ping stopped by user', 'info');
  11356. return;
  11357. }
  11358. const target = document.getElementById('tools-ping-target')?.value?.trim();
  11359. const count = parseInt(document.getElementById('tools-ping-count')?.value || '4', 10);
  11360. const size = parseInt(document.getElementById('tools-ping-size')?.value || '56', 10);
  11361. const timeout = parseInt(document.getElementById('tools-ping-timeout')?.value || '3', 10);
  11362. const iface = document.getElementById('tools-ping-iface')?.value || '';
  11363. const dontFrag = document.getElementById('tools-ping-df')?.checked || false;
  11364. if (!target) {
  11365. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  11366. return;
  11367. }
  11368. clearPingTable();
  11369. const resCard = document.getElementById('tools-ping-results');
  11370. if (resCard) resCard.classList.remove('hidden');
  11371. pingAbortController = new AbortController();
  11372. setPingRunningButton();
  11373. try {
  11374. const res = await fetch(`${API_BASE}/tools/ping/stream`, {
  11375. method: 'POST',
  11376. headers: { 'Content-Type': 'application/json' },
  11377. body: JSON.stringify({
  11378. target,
  11379. count,
  11380. size,
  11381. timeout,
  11382. interface: iface,
  11383. dont_frag: dontFrag
  11384. }),
  11385. signal: pingAbortController.signal
  11386. });
  11387. if (!res.ok) {
  11388. const errText = await res.text();
  11389. showToast('Ping Error', errText || 'Failed to start live ping', 'error');
  11390. resetPingButton();
  11391. pingAbortController = null;
  11392. return;
  11393. }
  11394. const reader = res.body.getReader();
  11395. const decoder = new TextDecoder('utf-8');
  11396. let buffer = '';
  11397. while (true) {
  11398. const { done, value } = await reader.read();
  11399. if (done) break;
  11400. buffer += decoder.decode(value, { stream: true });
  11401. const blocks = buffer.split('\n\n');
  11402. buffer = blocks.pop() || '';
  11403. for (const block of blocks) {
  11404. const trimmed = block.trim();
  11405. if (!trimmed) continue;
  11406. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  11407. try {
  11408. const evt = JSON.parse(line);
  11409. handleLivePingEvent(evt);
  11410. } catch (parseErr) {
  11411. console.warn('Ping SSE parse error:', parseErr, line);
  11412. }
  11413. }
  11414. }
  11415. } catch (err) {
  11416. if (err.name === 'AbortError') {
  11417. // User aborted normally
  11418. } else {
  11419. showToast('Ping Error', err.message, 'error');
  11420. }
  11421. } finally {
  11422. pingAbortController = null;
  11423. resetPingButton();
  11424. }
  11425. }
  11426. function handleLivePingEvent(evt) {
  11427. const sentEl = document.getElementById('tools-ping-stat-sent');
  11428. const recvEl = document.getElementById('tools-ping-stat-recv');
  11429. const lossEl = document.getElementById('tools-ping-stat-loss');
  11430. const avgEl = document.getElementById('tools-ping-stat-avg');
  11431. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  11432. const badge = document.getElementById('tools-ping-status-badge');
  11433. const tbody = document.getElementById('tools-ping-tbody');
  11434. const rawEl = document.getElementById('tools-ping-raw');
  11435. if (evt.raw && rawEl) {
  11436. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  11437. rawEl.scrollTop = rawEl.scrollHeight;
  11438. }
  11439. if (evt.type === 'reply') {
  11440. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  11441. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  11442. if (lossEl && evt.packet_loss_pct !== undefined) {
  11443. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  11444. lossEl.className = evt.packet_loss_pct === 0
  11445. ? 'text-base font-bold font-mono text-emerald-400 mt-1'
  11446. : (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');
  11447. }
  11448. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  11449. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  11450. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  11451. }
  11452. if (badge) {
  11453. if (evt.packet_loss_pct === 0) {
  11454. 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';
  11455. badge.innerText = '100% OK';
  11456. } else {
  11457. 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';
  11458. badge.innerText = `${evt.packet_loss_pct.toFixed(0)}% LOSS`;
  11459. }
  11460. }
  11461. if (tbody) {
  11462. const tr = document.createElement('tr');
  11463. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  11464. tr.innerHTML = `
  11465. <td class="py-2 px-3 text-slate-300">#${evt.seq}</td>
  11466. <td class="py-2 px-3 font-semibold text-white">${escapeHtml(evt.from)}</td>
  11467. <td class="py-2 px-3 text-slate-400">${evt.bytes} bytes</td>
  11468. <td class="py-2 px-3 text-slate-300">${evt.ttl}</td>
  11469. <td class="py-2 px-3 font-bold text-amber-300">${evt.time_ms.toFixed(2)} ms</td>
  11470. <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>
  11471. `;
  11472. tbody.appendChild(tr);
  11473. }
  11474. } else if (evt.type === 'timeout') {
  11475. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  11476. if (lossEl && evt.packet_loss_pct !== undefined) {
  11477. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  11478. 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';
  11479. }
  11480. if (badge) {
  11481. 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';
  11482. badge.innerText = `${evt.packet_loss_pct?.toFixed(0) || 100}% LOSS`;
  11483. }
  11484. if (tbody) {
  11485. const tr = document.createElement('tr');
  11486. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs opacity-75';
  11487. tr.innerHTML = `
  11488. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  11489. <td class="py-2 px-3 font-semibold text-slate-500 italic">Request timed out</td>
  11490. <td class="py-2 px-3 text-slate-600">--</td>
  11491. <td class="py-2 px-3 text-slate-600">--</td>
  11492. <td class="py-2 px-3 font-bold text-slate-500">* * *</td>
  11493. <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>
  11494. `;
  11495. tbody.appendChild(tr);
  11496. }
  11497. } else if (evt.type === 'unreach') {
  11498. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  11499. if (lossEl && evt.packet_loss_pct !== undefined) {
  11500. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  11501. lossEl.className = 'text-base font-bold font-mono text-rose-400 mt-1';
  11502. }
  11503. if (badge) {
  11504. 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';
  11505. badge.innerText = 'UNREACHABLE';
  11506. }
  11507. if (tbody) {
  11508. const tr = document.createElement('tr');
  11509. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  11510. tr.innerHTML = `
  11511. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  11512. <td class="py-2 px-3 font-semibold text-rose-400">${escapeHtml(evt.from || 'Gateway')}</td>
  11513. <td class="py-2 px-3 text-slate-600">--</td>
  11514. <td class="py-2 px-3 text-slate-600">--</td>
  11515. <td class="py-2 px-3 font-bold text-rose-400 text-xs">${escapeHtml(evt.message || 'Unreachable')}</td>
  11516. <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>
  11517. `;
  11518. tbody.appendChild(tr);
  11519. }
  11520. } else if (evt.type === 'stats') {
  11521. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  11522. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  11523. if (lossEl && evt.packet_loss_pct !== undefined) lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  11524. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  11525. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  11526. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  11527. }
  11528. } else if (evt.type === 'done') {
  11529. 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');
  11530. }
  11531. }
  11532. async function executeTraceroute(e) {
  11533. if (e) e.preventDefault();
  11534. if (tracerouteAbortController) {
  11535. tracerouteAbortController.abort();
  11536. tracerouteAbortController = null;
  11537. resetTracerouteButton();
  11538. showToast('Traceroute Stopped', 'Traceroute stopped by user', 'info');
  11539. return;
  11540. }
  11541. const target = document.getElementById('tools-tr-target')?.value?.trim();
  11542. const maxHops = parseInt(document.getElementById('tools-tr-maxhops')?.value || '15', 10);
  11543. const protocol = document.getElementById('tools-tr-proto')?.value || 'icmp';
  11544. const iface = document.getElementById('tools-tr-iface')?.value || '';
  11545. const resolve = document.getElementById('tools-tr-resolve')?.checked || false;
  11546. if (!target) {
  11547. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  11548. return;
  11549. }
  11550. clearTracerouteTable();
  11551. const resCard = document.getElementById('tools-tr-results');
  11552. if (resCard) resCard.classList.remove('hidden');
  11553. tracerouteAbortController = new AbortController();
  11554. setTracerouteRunningButton();
  11555. try {
  11556. const res = await fetch(`${API_BASE}/tools/traceroute/stream`, {
  11557. method: 'POST',
  11558. headers: { 'Content-Type': 'application/json' },
  11559. body: JSON.stringify({
  11560. target,
  11561. max_hops: maxHops,
  11562. protocol,
  11563. interface: iface,
  11564. resolve
  11565. }),
  11566. signal: tracerouteAbortController.signal
  11567. });
  11568. if (!res.ok) {
  11569. const errText = await res.text();
  11570. showToast('Traceroute Error', errText || 'Failed to start traceroute', 'error');
  11571. resetTracerouteButton();
  11572. tracerouteAbortController = null;
  11573. return;
  11574. }
  11575. const reader = res.body.getReader();
  11576. const decoder = new TextDecoder('utf-8');
  11577. let buffer = '';
  11578. while (true) {
  11579. const { done, value } = await reader.read();
  11580. if (done) break;
  11581. buffer += decoder.decode(value, { stream: true });
  11582. const blocks = buffer.split('\n\n');
  11583. buffer = blocks.pop() || '';
  11584. for (const block of blocks) {
  11585. const trimmed = block.trim();
  11586. if (!trimmed) continue;
  11587. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  11588. try {
  11589. const evt = JSON.parse(line);
  11590. handleLiveTracerouteEvent(evt);
  11591. } catch (parseErr) {
  11592. console.warn('Traceroute SSE parse error:', parseErr, line);
  11593. }
  11594. }
  11595. }
  11596. } catch (err) {
  11597. if (err.name === 'AbortError') {
  11598. // User aborted normally
  11599. } else {
  11600. showToast('Traceroute Error', err.message, 'error');
  11601. }
  11602. } finally {
  11603. tracerouteAbortController = null;
  11604. resetTracerouteButton();
  11605. }
  11606. }
  11607. function handleLiveTracerouteEvent(evt) {
  11608. const statHops = document.getElementById('tools-tr-hops-count');
  11609. const tbody = document.getElementById('tools-tr-tbody');
  11610. const rawEl = document.getElementById('tools-tr-raw');
  11611. if (evt.raw && rawEl) {
  11612. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  11613. rawEl.scrollTop = rawEl.scrollHeight;
  11614. }
  11615. if (evt.hops_count !== undefined && statHops) {
  11616. statHops.innerText = `${evt.hops_count} Hops`;
  11617. }
  11618. if (evt.type === 'hop' && evt.hop && tbody) {
  11619. const h = evt.hop;
  11620. const isTimeout = h.status === 'timeout' || (!h.ip && !h.host);
  11621. const rtt1 = Array.isArray(h.times_ms) && h.times_ms[0] ? `${h.times_ms[0]} ms` : (isTimeout ? '*' : '--');
  11622. const rtt2 = Array.isArray(h.times_ms) && h.times_ms[1] ? `${h.times_ms[1]} ms` : (isTimeout ? '*' : '--');
  11623. const displayHost = h.host && h.host !== h.ip ? `${escapeHtml(h.host)} (${escapeHtml(h.ip || '')})` : escapeHtml(h.ip || (isTimeout ? 'Request timed out' : '--'));
  11624. const tr = document.createElement('tr');
  11625. tr.className = `hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs ${isTimeout ? 'opacity-60' : ''}`;
  11626. tr.innerHTML = `
  11627. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  11628. <td class="py-2.5 px-3 font-semibold ${isTimeout ? 'text-slate-500 italic' : 'text-cyan-300'}">${displayHost}</td>
  11629. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt1)}</td>
  11630. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt2)}</td>
  11631. <td class="py-2.5 px-3 text-right">
  11632. ${isTimeout
  11633. ? '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-slate-800 text-slate-400 border border-slate-700">TIMEOUT</span>'
  11634. : '<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>'}
  11635. </td>
  11636. `;
  11637. tbody.appendChild(tr);
  11638. } else if (evt.type === 'done') {
  11639. showToast('Traceroute Finished', `Traced ${evt.hops_count || 0} hops`, 'info');
  11640. }
  11641. }
  11642. async function executeMTR(e) {
  11643. if (e) e.preventDefault();
  11644. const target = document.getElementById('tools-mtr-target')?.value?.trim();
  11645. const cycles = parseInt(document.getElementById('tools-mtr-count')?.value || '3', 10);
  11646. if (!target) {
  11647. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  11648. return;
  11649. }
  11650. const btn = document.getElementById('tools-mtr-btn');
  11651. const spinner = document.getElementById('tools-mtr-spinner');
  11652. if (btn) btn.disabled = true;
  11653. if (spinner) spinner.classList.remove('hidden');
  11654. try {
  11655. const res = await fetch(`${API_BASE}/tools/mtr`, {
  11656. method: 'POST',
  11657. headers: { 'Content-Type': 'application/json' },
  11658. body: JSON.stringify({ target, count: cycles })
  11659. });
  11660. const data = await res.json();
  11661. if (!res.ok) {
  11662. showToast('MTR Error', data.error || 'Failed to execute MTR', 'error');
  11663. return;
  11664. }
  11665. const resCard = document.getElementById('tools-mtr-results');
  11666. if (resCard) resCard.classList.remove('hidden');
  11667. const hopsCount = Array.isArray(data.hops) ? data.hops.length : 0;
  11668. const statHops = document.getElementById('tools-mtr-hops-count');
  11669. if (statHops) statHops.innerText = `${hopsCount} Hops`;
  11670. const tbody = document.getElementById('tools-mtr-tbody');
  11671. if (tbody) {
  11672. if (hopsCount > 0) {
  11673. tbody.innerHTML = data.hops.map(h => {
  11674. 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');
  11675. return `
  11676. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  11677. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  11678. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(h.host || '--')}</td>
  11679. <td class="py-2.5 px-3 ${lossClass}">${h.loss_pct.toFixed(1)}%</td>
  11680. <td class="py-2.5 px-3 text-slate-300">${h.sent}</td>
  11681. <td class="py-2.5 px-3 text-slate-300">${h.last_ms.toFixed(1)}</td>
  11682. <td class="py-2.5 px-3 font-bold text-amber-300">${h.avg_ms.toFixed(1)}</td>
  11683. <td class="py-2.5 px-3 text-emerald-400">${h.best_ms.toFixed(1)}</td>
  11684. <td class="py-2.5 px-3 text-rose-400">${h.wrst_ms.toFixed(1)}</td>
  11685. <td class="py-2.5 px-3 text-slate-400">${h.stdev_ms.toFixed(1)}</td>
  11686. </tr>
  11687. `;
  11688. }).join('');
  11689. } else {
  11690. tbody.innerHTML = `<tr><td colspan="9" class="p-4 text-center text-xs text-rose-400 font-mono">No MTR data collected</td></tr>`;
  11691. }
  11692. }
  11693. const rawEl = document.getElementById('tools-mtr-raw');
  11694. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  11695. showToast('MTR Finished', `Report completed (${hopsCount} hops discovered)`, 'info');
  11696. } catch (err) {
  11697. showToast('MTR Error', err.message, 'error');
  11698. } finally {
  11699. if (btn) btn.disabled = false;
  11700. if (spinner) spinner.classList.add('hidden');
  11701. }
  11702. }
  11703. async function executeDNS(e) {
  11704. if (e) e.preventDefault();
  11705. const domain = document.getElementById('tools-dns-domain')?.value?.trim();
  11706. const type = document.getElementById('tools-dns-type')?.value || 'A';
  11707. const server = document.getElementById('tools-dns-server')?.value?.trim() || '';
  11708. if (!domain) {
  11709. showToast('Input Required', 'Please enter a hostname or domain', 'warning');
  11710. return;
  11711. }
  11712. const btn = document.getElementById('tools-dns-btn');
  11713. const spinner = document.getElementById('tools-dns-spinner');
  11714. if (btn) btn.disabled = true;
  11715. if (spinner) spinner.classList.remove('hidden');
  11716. try {
  11717. const res = await fetch(`${API_BASE}/tools/dns`, {
  11718. method: 'POST',
  11719. headers: { 'Content-Type': 'application/json' },
  11720. body: JSON.stringify({ domain, type, server })
  11721. });
  11722. const data = await res.json();
  11723. if (!res.ok) {
  11724. showToast('DNS Error', data.error || 'Failed to resolve DNS query', 'error');
  11725. return;
  11726. }
  11727. const resCard = document.getElementById('tools-dns-results');
  11728. if (resCard) resCard.classList.remove('hidden');
  11729. const metaEl = document.getElementById('tools-dns-meta');
  11730. if (metaEl) metaEl.innerText = `Resolved in ${data.query_time_ms ?? 0} ms via ${escapeHtml(data.server || 'System DNS')}`;
  11731. const tbody = document.getElementById('tools-dns-tbody');
  11732. if (tbody) {
  11733. if (Array.isArray(data.records) && data.records.length > 0) {
  11734. tbody.innerHTML = data.records.map(r => `
  11735. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  11736. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.name)}</td>
  11737. <td class="py-2.5 px-3 text-slate-400">${r.ttl}s</td>
  11738. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.class || 'IN')}</td>
  11739. <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>
  11740. <td class="py-2.5 px-3 font-bold text-amber-300 break-all">${escapeHtml(r.value)}</td>
  11741. </tr>
  11742. `).join('');
  11743. } else {
  11744. 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>`;
  11745. }
  11746. }
  11747. const rawEl = document.getElementById('tools-dns-raw');
  11748. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  11749. showToast('DNS Lookup Done', `Resolved ${domain} in ${data.query_time_ms} ms`, 'success');
  11750. } catch (err) {
  11751. showToast('DNS Error', err.message, 'error');
  11752. } finally {
  11753. if (btn) btn.disabled = false;
  11754. if (spinner) spinner.classList.add('hidden');
  11755. }
  11756. }
  11757. async function executePortProbe(e) {
  11758. if (e) e.preventDefault();
  11759. const target = document.getElementById('tools-port-target')?.value?.trim();
  11760. const port = parseInt(document.getElementById('tools-port-num')?.value || '80', 10);
  11761. const timeout = parseInt(document.getElementById('tools-port-timeout')?.value || '3', 10);
  11762. if (!target || !port) {
  11763. showToast('Input Required', 'Please enter a target host and TCP port', 'warning');
  11764. return;
  11765. }
  11766. const btn = document.getElementById('tools-port-btn');
  11767. const spinner = document.getElementById('tools-port-spinner');
  11768. if (btn) btn.disabled = true;
  11769. if (spinner) spinner.classList.remove('hidden');
  11770. try {
  11771. const res = await fetch(`${API_BASE}/tools/port-probe`, {
  11772. method: 'POST',
  11773. headers: { 'Content-Type': 'application/json' },
  11774. body: JSON.stringify({ target, port, timeout })
  11775. });
  11776. const data = await res.json();
  11777. if (!res.ok) {
  11778. showToast('Probe Error', data.error || 'Failed to probe TCP port', 'error');
  11779. return;
  11780. }
  11781. const resCard = document.getElementById('tools-port-results');
  11782. if (resCard) resCard.classList.remove('hidden');
  11783. const banner = document.getElementById('tools-port-banner');
  11784. const icon = document.getElementById('tools-port-icon');
  11785. const title = document.getElementById('tools-port-title');
  11786. const sub = document.getElementById('tools-port-sub');
  11787. const latency = document.getElementById('tools-port-latency');
  11788. if (data.open) {
  11789. if (banner) banner.className = 'rounded-xl p-5 border bg-emerald-950/30 border-emerald-800/50 flex items-center justify-between';
  11790. if (icon) {
  11791. 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';
  11792. icon.innerText = '✓';
  11793. }
  11794. if (title) {
  11795. title.className = 'text-sm font-bold text-emerald-300';
  11796. title.innerText = `PORT ${port} OPEN / LISTENING`;
  11797. }
  11798. if (sub) {
  11799. sub.className = 'text-xs mt-0.5 font-mono text-emerald-400/80';
  11800. sub.innerText = `TCP 3-way handshake established with ${escapeHtml(target)}:${port}${data.service ? ' (' + escapeHtml(data.service) + ')' : ''}`;
  11801. }
  11802. if (latency) {
  11803. latency.className = 'text-base font-bold font-mono text-emerald-300';
  11804. latency.innerText = `${data.latency_ms.toFixed(2)} ms`;
  11805. }
  11806. } else {
  11807. if (banner) banner.className = 'rounded-xl p-5 border bg-rose-950/30 border-rose-800/50 flex items-center justify-between';
  11808. if (icon) {
  11809. 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';
  11810. icon.innerText = '✕';
  11811. }
  11812. if (title) {
  11813. title.className = 'text-sm font-bold text-rose-300';
  11814. title.innerText = `PORT ${port} CLOSED / FILTERED`;
  11815. }
  11816. if (sub) {
  11817. sub.className = 'text-xs mt-0.5 font-mono text-rose-400/80';
  11818. sub.innerText = `Connection failed or timed out to ${escapeHtml(target)}:${port}`;
  11819. }
  11820. if (latency) {
  11821. latency.className = 'text-base font-bold font-mono text-slate-500';
  11822. latency.innerText = '--';
  11823. }
  11824. }
  11825. const rawEl = document.getElementById('tools-port-raw');
  11826. 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'}`);
  11827. showToast('Probe Complete', `Port ${port} is ${data.open ? 'OPEN' : 'CLOSED'}`, data.open ? 'success' : 'warning');
  11828. } catch (err) {
  11829. showToast('Probe Error', err.message, 'error');
  11830. } finally {
  11831. if (btn) btn.disabled = false;
  11832. if (spinner) spinner.classList.add('hidden');
  11833. }
  11834. }
  11835. // ==========================================
  11836. // DHCP CLIENT (/ip dhcp-client) CONTROLLER
  11837. // ==========================================
  11838. async function loadDHCPClients(showToastMsg = false) {
  11839. try {
  11840. const [clientsRes, sumRes] = await Promise.all([
  11841. fetch(`${API_BASE}/dhcp/clients`),
  11842. fetch(`${API_BASE}/dhcp/clients/summary`)
  11843. ]);
  11844. if (clientsRes.ok) {
  11845. state.dhcpClients = await clientsRes.json();
  11846. }
  11847. if (sumRes.ok) {
  11848. state.dhcpSummary = await sumRes.json();
  11849. }
  11850. renderDHCPClients();
  11851. updateDHCPSummaryCards();
  11852. const bDhcp = document.getElementById('badge-dhcp-client-count');
  11853. if (bDhcp && state.dhcpSummary) {
  11854. bDhcp.innerText = state.dhcpSummary.total_clients || 0;
  11855. }
  11856. if (showToastMsg) {
  11857. showToast('Refreshed', 'DHCP Client telemetry updated', 'info');
  11858. }
  11859. } catch (err) {
  11860. console.error('Failed to load DHCP clients:', err);
  11861. if (showToastMsg) {
  11862. showToast('Notice', 'Unable to fetch DHCP client status', 'warning');
  11863. }
  11864. }
  11865. }
  11866. function updateDHCPSummaryCards() {
  11867. const sum = state.dhcpSummary || {
  11868. total_clients: (state.dhcpClients || []).length,
  11869. bound_clients: (state.dhcpClients || []).filter(c => c.status === 'bound').length,
  11870. searching_clients: (state.dhcpClients || []).filter(c => c.status === 'searching').length,
  11871. disabled_clients: (state.dhcpClients || []).filter(c => !c.enabled).length
  11872. };
  11873. const totalEl = document.getElementById('dhcp-stat-total');
  11874. const boundEl = document.getElementById('dhcp-stat-bound');
  11875. const searchEl = document.getElementById('dhcp-stat-searching');
  11876. const disEl = document.getElementById('dhcp-stat-disabled');
  11877. if (totalEl) totalEl.innerText = sum.total_clients ?? 0;
  11878. if (boundEl) boundEl.innerText = sum.bound_clients ?? 0;
  11879. if (searchEl) searchEl.innerText = sum.searching_clients ?? 0;
  11880. if (disEl) disEl.innerText = sum.disabled_clients ?? 0;
  11881. }
  11882. function renderDHCPClients() {
  11883. const tbody = document.getElementById('dhcp-clients-tbody');
  11884. const emptyState = document.getElementById('dhcp-clients-empty');
  11885. if (!tbody) return;
  11886. const clients = Array.isArray(state.dhcpClients) ? state.dhcpClients : [];
  11887. if (clients.length === 0) {
  11888. tbody.innerHTML = '';
  11889. if (emptyState) emptyState.classList.remove('hidden');
  11890. return;
  11891. }
  11892. if (emptyState) emptyState.classList.add('hidden');
  11893. const sig = clients.map(c => `${c.id}:${c.status}:${c.ip_address}:${c.gateway}:${c.enabled}`).join(';');
  11894. if (tbody.dataset.sig === sig) return;
  11895. tbody.dataset.sig = sig;
  11896. tbody.innerHTML = clients.map(c => {
  11897. let statusBadge = '';
  11898. if (!c.enabled) {
  11899. 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>';
  11900. } else if (c.status === 'bound') {
  11901. 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>';
  11902. } else if (c.status === 'searching') {
  11903. 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>';
  11904. } else if (c.status === 'stopped') {
  11905. 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>';
  11906. } else {
  11907. 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>`;
  11908. }
  11909. 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>';
  11910. const gwDisplay = c.gateway ? `<span class="text-slate-300">${escapeHtml(c.gateway)}</span>` : '<span class="text-slate-600">--</span>';
  11911. const srvDisplay = c.dhcp_server ? `<span class="text-slate-300">${escapeHtml(c.dhcp_server)}</span>` : '<span class="text-slate-600">--</span>';
  11912. 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>';
  11913. const expDisplay = c.expires_in ? `<span class="text-purple-300">${escapeHtml(c.expires_in)}</span>` : '<span class="text-slate-600">--</span>';
  11914. // Option flags
  11915. const flags = [];
  11916. 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>');
  11917. 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>');
  11918. 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>');
  11919. 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>`);
  11920. return `
  11921. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 text-xs transition">
  11922. <td class="py-3 px-4">
  11923. <div class="flex items-center gap-2">
  11924. <span class="font-bold text-white text-sm">${escapeHtml(c.interface)}</span>
  11925. ${c.comment ? `<span class="text-[11px] text-slate-400 font-sans italic">(${escapeHtml(c.comment)})</span>` : ''}
  11926. </div>
  11927. </td>
  11928. <td class="py-3 px-4">${statusBadge}</td>
  11929. <td class="py-3 px-4 font-mono">${ipDisplay}</td>
  11930. <td class="py-3 px-4 font-mono">${gwDisplay}</td>
  11931. <td class="py-3 px-4 font-mono">${srvDisplay}</td>
  11932. <td class="py-3 px-4 font-mono text-[11px]">${dnsDisplay}</td>
  11933. <td class="py-3 px-4 font-mono text-[11px]">${expDisplay}</td>
  11934. <td class="py-3 px-4">
  11935. <div class="flex flex-wrap gap-1 font-mono">${flags.join('')}</div>
  11936. </td>
  11937. <td class="py-3 px-4 text-right space-x-1.5 font-sans whitespace-nowrap">
  11938. ${c.enabled ? `
  11939. <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>
  11940. <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>
  11941. <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>
  11942. ` : `
  11943. <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>
  11944. `}
  11945. <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>
  11946. <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>
  11947. </td>
  11948. </tr>
  11949. `;
  11950. }).join('');
  11951. }
  11952. function openDHCPClientModal(clientId = null) {
  11953. const modal = document.getElementById('modal-dhcp-client');
  11954. if (!modal) return;
  11955. const title = document.getElementById('modal-dhcp-title');
  11956. const idInput = document.getElementById('modal-dhcp-id');
  11957. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  11958. const distInput = document.getElementById('modal-dhcp-distance');
  11959. const commentInput = document.getElementById('modal-dhcp-comment');
  11960. const defRouteCheck = document.getElementById('modal-dhcp-def-route');
  11961. const peerDnsCheck = document.getElementById('modal-dhcp-peer-dns');
  11962. const peerNtpCheck = document.getElementById('modal-dhcp-peer-ntp');
  11963. const enabledCheck = document.getElementById('modal-dhcp-enabled');
  11964. // Populate interfaces
  11965. if (ifaceSelect) {
  11966. let opts = '<option value="">Select interface...</option>';
  11967. const allIfaces = state.interfaces || [];
  11968. const allVlans = state.vlans || [];
  11969. const usedIfaces = new Set((state.dhcpClients || []).map(c => c.interface));
  11970. // Group 1: Physical & Bridge Interfaces
  11971. opts += '<optgroup label="Physical & Bridge Interfaces">';
  11972. allIfaces.filter(i => supportsDHCPClient(i)).forEach(i => {
  11973. const isConfigured = usedIfaces.has(i.name) ? ' (Configured)' : '';
  11974. opts += `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)} [${escapeHtml(i.role || i.type)}]${isConfigured}</option>`;
  11975. });
  11976. opts += '</optgroup>';
  11977. // Group 2: VLAN Interfaces
  11978. if (allVlans.length > 0) {
  11979. opts += '<optgroup label="802.1Q VLAN Sub-interfaces">';
  11980. allVlans.forEach(v => {
  11981. const isConfigured = usedIfaces.has(v.name) ? ' (Configured)' : '';
  11982. opts += `<option value="${escapeHtml(v.name)}">${escapeHtml(v.name)} (VLAN ${v.vlan_id})${isConfigured}</option>`;
  11983. });
  11984. opts += '</optgroup>';
  11985. }
  11986. ifaceSelect.innerHTML = opts;
  11987. }
  11988. if (clientId) {
  11989. const client = (state.dhcpClients || []).find(c => c.id === clientId);
  11990. if (client) {
  11991. if (title) title.innerText = `Edit DHCP Client: ${client.interface}`;
  11992. if (idInput) idInput.value = client.id;
  11993. if (ifaceSelect) {
  11994. ifaceSelect.value = client.interface;
  11995. ifaceSelect.disabled = true; // interface cannot be changed on edit
  11996. }
  11997. if (distInput) distInput.value = client.default_route_distance || 1;
  11998. if (commentInput) commentInput.value = client.comment || '';
  11999. if (defRouteCheck) defRouteCheck.checked = client.add_default_route !== false;
  12000. if (peerDnsCheck) peerDnsCheck.checked = client.use_peer_dns !== false;
  12001. if (peerNtpCheck) peerNtpCheck.checked = client.use_peer_ntp !== false;
  12002. if (enabledCheck) enabledCheck.checked = client.enabled !== false;
  12003. }
  12004. } else {
  12005. if (title) title.innerText = 'Add DHCP Client';
  12006. if (idInput) idInput.value = '';
  12007. if (ifaceSelect) {
  12008. ifaceSelect.value = '';
  12009. ifaceSelect.disabled = false;
  12010. }
  12011. if (distInput) distInput.value = 1;
  12012. if (commentInput) commentInput.value = '';
  12013. if (defRouteCheck) defRouteCheck.checked = true;
  12014. if (peerDnsCheck) peerDnsCheck.checked = true;
  12015. if (peerNtpCheck) peerNtpCheck.checked = true;
  12016. if (enabledCheck) enabledCheck.checked = true;
  12017. }
  12018. modal.classList.remove('hidden');
  12019. }
  12020. function openDHCPClientModalForIface(ifaceName) {
  12021. openDHCPClientModal();
  12022. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  12023. if (ifaceSelect && ifaceName) {
  12024. ifaceSelect.value = ifaceName;
  12025. }
  12026. }
  12027. function closeDHCPClientModal() {
  12028. const modal = document.getElementById('modal-dhcp-client');
  12029. if (modal) modal.classList.add('hidden');
  12030. }
  12031. async function submitSaveDHCPClient(e) {
  12032. if (e) e.preventDefault();
  12033. const id = document.getElementById('modal-dhcp-id')?.value;
  12034. const iface = document.getElementById('modal-dhcp-iface')?.value?.trim();
  12035. const distance = parseInt(document.getElementById('modal-dhcp-distance')?.value || '1', 10);
  12036. const comment = document.getElementById('modal-dhcp-comment')?.value?.trim() || '';
  12037. const defRoute = document.getElementById('modal-dhcp-def-route')?.checked ?? true;
  12038. const peerDns = document.getElementById('modal-dhcp-peer-dns')?.checked ?? true;
  12039. const peerNtp = document.getElementById('modal-dhcp-peer-ntp')?.checked ?? true;
  12040. const enabled = document.getElementById('modal-dhcp-enabled')?.checked ?? true;
  12041. if (!id && !iface) {
  12042. showToast('Input Required', 'Please select an interface for the DHCP client', 'warning');
  12043. return;
  12044. }
  12045. try {
  12046. let res;
  12047. if (id) {
  12048. // PUT update
  12049. res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  12050. method: 'PUT',
  12051. headers: { 'Content-Type': 'application/json' },
  12052. body: JSON.stringify({
  12053. enabled,
  12054. add_default_route: defRoute,
  12055. default_route_distance: distance,
  12056. use_peer_dns: peerDns,
  12057. use_peer_ntp: peerNtp,
  12058. comment
  12059. })
  12060. });
  12061. } else {
  12062. // POST create
  12063. res = await fetch(`${API_BASE}/dhcp/clients`, {
  12064. method: 'POST',
  12065. headers: { 'Content-Type': 'application/json' },
  12066. body: JSON.stringify({
  12067. interface: iface,
  12068. enabled,
  12069. add_default_route: defRoute,
  12070. default_route_distance: distance,
  12071. use_peer_dns: peerDns,
  12072. use_peer_ntp: peerNtp,
  12073. comment
  12074. })
  12075. });
  12076. }
  12077. const data = await res.json();
  12078. if (!res.ok) {
  12079. showToast('Error', data.error || 'Failed to save DHCP client', 'error');
  12080. return;
  12081. }
  12082. closeDHCPClientModal();
  12083. showToast('Success', id ? 'DHCP Client updated successfully' : `DHCP Client activated on ${iface}`, 'success');
  12084. await loadDHCPClients();
  12085. fetchData(); // refresh interfaces list with new lease/status
  12086. } catch (err) {
  12087. showToast('Error', err.message, 'error');
  12088. }
  12089. }
  12090. async function toggleDHCPClientState(id, enabled) {
  12091. try {
  12092. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/state`, {
  12093. method: 'POST',
  12094. headers: { 'Content-Type': 'application/json' },
  12095. body: JSON.stringify({ enabled })
  12096. });
  12097. const data = await res.json();
  12098. if (!res.ok) {
  12099. showToast('Error', data.error || 'Failed to toggle client state', 'error');
  12100. return;
  12101. }
  12102. showToast('Updated', `DHCP client ${enabled ? 'enabled' : 'disabled'}`, 'info');
  12103. await loadDHCPClients();
  12104. fetchData();
  12105. } catch (err) {
  12106. showToast('Error', err.message, 'error');
  12107. }
  12108. }
  12109. async function renewDHCPClient(id) {
  12110. try {
  12111. showToast('Renewing...', 'Requesting DHCP lease renewal from upstream server', 'info');
  12112. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/renew`, {
  12113. method: 'POST'
  12114. });
  12115. const data = await res.json();
  12116. if (!res.ok) {
  12117. showToast('Error', data.error || 'Failed to renew lease', 'error');
  12118. return;
  12119. }
  12120. showToast('Lease Renewed', 'DHCP renewal signal sent successfully', 'success');
  12121. setTimeout(() => {
  12122. loadDHCPClients();
  12123. fetchData();
  12124. }, 1500);
  12125. } catch (err) {
  12126. showToast('Error', err.message, 'error');
  12127. }
  12128. }
  12129. async function releaseDHCPClient(id) {
  12130. try {
  12131. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/release`, {
  12132. method: 'POST'
  12133. });
  12134. const data = await res.json();
  12135. if (!res.ok) {
  12136. showToast('Error', data.error || 'Failed to release lease', 'error');
  12137. return;
  12138. }
  12139. showToast('Lease Released', 'DHCP lease released from upstream server', 'info');
  12140. await loadDHCPClients();
  12141. fetchData();
  12142. } catch (err) {
  12143. showToast('Error', err.message, 'error');
  12144. }
  12145. }
  12146. async function deleteDHCPClient(id, ifaceName) {
  12147. if (!confirm(`Are you sure you want to remove the DHCP Client on ${ifaceName}? The interface will release its dynamic IP.`)) {
  12148. return;
  12149. }
  12150. try {
  12151. const res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  12152. method: 'DELETE'
  12153. });
  12154. const data = await res.json();
  12155. if (!res.ok) {
  12156. showToast('Error', data.error || 'Failed to delete DHCP client', 'error');
  12157. return;
  12158. }
  12159. showToast('Deleted', `DHCP client removed from ${ifaceName}`, 'info');
  12160. await loadDHCPClients();
  12161. fetchData();
  12162. } catch (err) {
  12163. showToast('Error', err.message, 'error');
  12164. }
  12165. }
  12166. // ==================== DHCP SERVER (/ip dhcp-server) ====================
  12167. async function loadDHCPServer(populate = true) {
  12168. try {
  12169. const [sumRes, srvRes, netRes, leaseRes, optRes] = await Promise.all([
  12170. fetch(`${API_BASE}/dhcp-server/summary`),
  12171. fetch(`${API_BASE}/dhcp-server/servers`),
  12172. fetch(`${API_BASE}/dhcp-server/networks`),
  12173. fetch(`${API_BASE}/dhcp-server/leases`),
  12174. fetch(`${API_BASE}/dhcp-server/options`)
  12175. ]);
  12176. if (sumRes.ok) state.dhcpServerSummary = await sumRes.json();
  12177. if (srvRes.ok) state.dhcpServers = await srvRes.json();
  12178. if (netRes.ok) state.dhcpNetworks = await netRes.json();
  12179. if (leaseRes.ok) state.dhcpLeases = await leaseRes.json();
  12180. if (optRes.ok) state.dhcpOptions = await optRes.json();
  12181. const sum = state.dhcpServerSummary || {};
  12182. const srvs = state.dhcpServers || [];
  12183. const nets = state.dhcpNetworks || [];
  12184. const leases = state.dhcpLeases || [];
  12185. const opts = state.dhcpOptions || [];
  12186. // KPI Cards
  12187. const statActive = document.getElementById('dhcp-server-stat-active');
  12188. if (statActive) {
  12189. const activeCount = srvs.filter(s => s.running).length;
  12190. statActive.innerText = `${activeCount} / ${srvs.length}`;
  12191. }
  12192. const statLeases = document.getElementById('dhcp-server-stat-leases');
  12193. if (statLeases) {
  12194. statLeases.innerText = leases.length;
  12195. }
  12196. const statLeasesSub = document.getElementById('dhcp-server-stat-leases-sub');
  12197. if (statLeasesSub) {
  12198. const dyn = leases.filter(l => l.dynamic).length;
  12199. const st = leases.filter(l => !l.dynamic).length;
  12200. statLeasesSub.innerText = `${dyn} dynamic, ${st} static`;
  12201. }
  12202. const statNetworks = document.getElementById('dhcp-server-stat-networks');
  12203. if (statNetworks) {
  12204. statNetworks.innerText = nets.length;
  12205. }
  12206. // Subtab Badges
  12207. const bSrv = document.getElementById('dhcp-server-tab-badge-servers');
  12208. if (bSrv) bSrv.innerText = srvs.length;
  12209. const bNet = document.getElementById('dhcp-server-tab-badge-networks');
  12210. if (bNet) bNet.innerText = nets.length;
  12211. const bLease = document.getElementById('dhcp-server-tab-badge-leases');
  12212. if (bLease) bLease.innerText = leases.length;
  12213. const bOpt = document.getElementById('dhcp-server-tab-badge-options');
  12214. if (bOpt) bOpt.innerText = opts.length;
  12215. // Sidebar Badge
  12216. const sideBadge = document.getElementById('badge-dhcp-server-count');
  12217. if (sideBadge) sideBadge.innerText = leases.length || srvs.length;
  12218. renderCurrentDHCPServerTab();
  12219. } catch (err) {
  12220. console.error('Failed to load DHCP Server:', err);
  12221. }
  12222. }
  12223. function switchDHCPServerTab(tab) {
  12224. state.dhcpServerTab = tab;
  12225. const tabs = ['servers', 'networks', 'leases', 'options'];
  12226. tabs.forEach(t => {
  12227. const panel = document.getElementById(`dhcp-server-subtab-${t}`);
  12228. const btn = document.getElementById(`dhcp-server-tab-btn-${t}`);
  12229. if (panel) {
  12230. if (t === tab) panel.classList.remove('hidden');
  12231. else panel.classList.add('hidden');
  12232. }
  12233. if (btn) {
  12234. if (t === tab) {
  12235. 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';
  12236. } else {
  12237. 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';
  12238. }
  12239. }
  12240. });
  12241. const addBtn = document.getElementById('dhcp-server-primary-add-btn');
  12242. if (addBtn) {
  12243. if (tab === 'servers') addBtn.innerHTML = '<span>+ Add Server</span>';
  12244. else if (tab === 'networks') addBtn.innerHTML = '<span>+ Add Network</span>';
  12245. else if (tab === 'leases') addBtn.innerHTML = '<span>+ Add Static Lease</span>';
  12246. else if (tab === 'options') addBtn.innerHTML = '<span>+ Add Option</span>';
  12247. }
  12248. renderCurrentDHCPServerTab();
  12249. }
  12250. function handleDHCPServerPrimaryAdd() {
  12251. const tab = state.dhcpServerTab || 'servers';
  12252. if (tab === 'servers') openAddDHCPServerModal();
  12253. else if (tab === 'networks') openAddDHCPNetworkModal();
  12254. else if (tab === 'leases') openAddDHCPStaticLeaseModal();
  12255. else if (tab === 'options') openAddDHCPOptionModal();
  12256. }
  12257. function renderCurrentDHCPServerTab() {
  12258. const tab = state.dhcpServerTab || 'servers';
  12259. if (tab === 'servers') renderDHCPServers();
  12260. else if (tab === 'networks') renderDHCPNetworks();
  12261. else if (tab === 'leases') renderDHCPLeases();
  12262. else if (tab === 'options') renderDHCPOptions();
  12263. }
  12264. function renderDHCPServers() {
  12265. const tbody = document.getElementById('dhcp-server-tbody');
  12266. const empty = document.getElementById('dhcp-server-empty');
  12267. if (!tbody) return;
  12268. const servers = state.dhcpServers || [];
  12269. if (servers.length === 0) {
  12270. tbody.innerHTML = '';
  12271. empty?.classList.remove('hidden');
  12272. return;
  12273. }
  12274. empty?.classList.add('hidden');
  12275. const sig = servers.map(s => `${s.id}:${s.running}:${s.disabled}:${s.active_leases}:${s.interface}`).join(';');
  12276. if (tbody.dataset.sig === sig) return;
  12277. tbody.dataset.sig = sig;
  12278. tbody.innerHTML = '';
  12279. servers.forEach(s => {
  12280. const tr = document.createElement('tr');
  12281. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  12282. tr.innerHTML = `
  12283. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(s.running, s.disabled)}</td>
  12284. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(s.name)}</td>
  12285. <td class="py-2.5 px-3 font-mono text-cyan-400 font-semibold">${escapeHtml(s.interface)}</td>
  12286. <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>
  12287. <td class="py-2.5 px-3 font-mono text-emerald-400">${escapeHtml(s.address_pool)}</td>
  12288. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(s.lease_time || '12h')}</td>
  12289. <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>
  12290. <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>
  12291. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]" title="${escapeHtml(s.comment || '')}">${escapeHtml(s.comment || '-')}</td>
  12292. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  12293. <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>
  12294. <button onclick="openEditDHCPServerModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  12295. <button onclick="deleteDHCPServer('${s.id}', '${escapeHtml(s.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  12296. </td>
  12297. `;
  12298. tbody.appendChild(tr);
  12299. });
  12300. }
  12301. function renderDHCPNetworks() {
  12302. const tbody = document.getElementById('dhcp-networks-tbody');
  12303. const empty = document.getElementById('dhcp-networks-empty');
  12304. if (!tbody) return;
  12305. tbody.innerHTML = '';
  12306. const networks = state.dhcpNetworks || [];
  12307. if (networks.length === 0) {
  12308. empty?.classList.remove('hidden');
  12309. return;
  12310. }
  12311. empty?.classList.add('hidden');
  12312. networks.forEach(n => {
  12313. const tr = document.createElement('tr');
  12314. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  12315. const dnsStr = (n.dns_servers || []).join(', ') || '-';
  12316. const optionsChips = (n.dhcp_options || []).map(optId => {
  12317. const opt = (state.dhcpOptions || []).find(o => o.id === optId);
  12318. if (!opt) return '';
  12319. return `<span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 text-cyan-300 border border-slate-700 inline-block mr-1 mb-0.5" title="${escapeHtml(opt.name)}: ${escapeHtml(opt.value)}">#${opt.code} ${escapeHtml(opt.name)}</span>`;
  12320. }).filter(Boolean).join('');
  12321. tr.innerHTML = `
  12322. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${escapeHtml(n.address)}</td>
  12323. <td class="py-2.5 px-3 font-mono text-cyan-300 font-semibold">${escapeHtml(n.gateway || '-')}</td>
  12324. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(n.netmask || '-')}</td>
  12325. <td class="py-2.5 px-3 font-mono text-slate-300 truncate max-w-[140px]" title="${escapeHtml(dnsStr)}">${escapeHtml(dnsStr)}</td>
  12326. <td class="py-2.5 px-3 font-mono text-slate-400">${escapeHtml(n.domain || '-')}</td>
  12327. <td class="py-2.5 px-3 font-mono">${optionsChips || '<span class="text-slate-600 font-sans">-</span>'}</td>
  12328. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(n.comment || '')}">${escapeHtml(n.comment || '-')}</td>
  12329. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  12330. <button onclick="openEditDHCPNetworkModal('${n.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  12331. <button onclick="deleteDHCPNetwork('${n.id}', '${escapeHtml(n.address)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  12332. </td>
  12333. `;
  12334. tbody.appendChild(tr);
  12335. });
  12336. }
  12337. function renderDHCPLeases() {
  12338. const tbody = document.getElementById('dhcp-leases-tbody');
  12339. const empty = document.getElementById('dhcp-leases-empty');
  12340. if (!tbody) return;
  12341. tbody.innerHTML = '';
  12342. const leases = state.dhcpLeases || [];
  12343. if (leases.length === 0) {
  12344. empty?.classList.remove('hidden');
  12345. return;
  12346. }
  12347. empty?.classList.add('hidden');
  12348. leases.forEach(l => {
  12349. const tr = document.createElement('tr');
  12350. tr.className = `hover:bg-slate-800/40 transition text-xs ${l.disabled ? 'opacity-50' : ''}`;
  12351. 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>';
  12352. const statusBadge = l.status === 'bound'
  12353. ? '<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>'
  12354. : l.status === 'static'
  12355. ? '<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>'
  12356. : '<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>';
  12357. const makeStaticBtn = l.dynamic
  12358. ? `<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>`
  12359. : `<button onclick="deleteDHCPStaticLease('${l.id}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Remove</button>`;
  12360. tr.innerHTML = `
  12361. <td class="py-2.5 px-3 text-center">${flag}</td>
  12362. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(l.address)}</td>
  12363. <td class="py-2.5 px-3 font-mono text-cyan-300">${escapeHtml(l.mac_address)}</td>
  12364. <td class="py-2.5 px-3 font-sans text-slate-200 font-medium">${escapeHtml(l.hostname || '*')}</td>
  12365. <td class="py-2.5 px-3 font-mono text-slate-400">${escapeHtml(l.server || 'all')}</td>
  12366. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(l.expires_in || 'never')}</td>
  12367. <td class="py-2.5 px-3">${statusBadge}</td>
  12368. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(l.comment || '')}">${escapeHtml(l.comment || '-')}</td>
  12369. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  12370. ${makeStaticBtn}
  12371. </td>
  12372. `;
  12373. tbody.appendChild(tr);
  12374. });
  12375. }
  12376. function renderDHCPOptions() {
  12377. const tbody = document.getElementById('dhcp-options-tbody');
  12378. const empty = document.getElementById('dhcp-options-empty');
  12379. if (!tbody) return;
  12380. tbody.innerHTML = '';
  12381. const options = state.dhcpOptions || [];
  12382. if (options.length === 0) {
  12383. empty?.classList.remove('hidden');
  12384. return;
  12385. }
  12386. empty?.classList.add('hidden');
  12387. options.forEach(o => {
  12388. const tr = document.createElement('tr');
  12389. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  12390. tr.innerHTML = `
  12391. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(o.name)}</td>
  12392. <td class="py-2.5 px-3 font-bold text-cyan-400 font-mono">${o.code}</td>
  12393. <td class="py-2.5 px-3 font-mono text-emerald-400 break-all max-w-xs">${escapeHtml(o.value)}</td>
  12394. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-xs" title="${escapeHtml(o.comment || '')}">${escapeHtml(o.comment || '-')}</td>
  12395. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  12396. <button onclick="openEditDHCPOptionModal('${o.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  12397. <button onclick="deleteDHCPOption('${o.id}', '${escapeHtml(o.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  12398. </td>
  12399. `;
  12400. tbody.appendChild(tr);
  12401. });
  12402. }
  12403. // ==================== MODALS & ACTIONS: SERVER ====================
  12404. function populateDHCPNetworkSelect(elemId, selectedVal) {
  12405. const sel = document.getElementById(elemId);
  12406. if (!sel) return;
  12407. sel.innerHTML = '<option value="">Select network subnet...</option>';
  12408. const networks = state.dhcpNetworks || [];
  12409. networks.forEach(n => {
  12410. const opt = document.createElement('option');
  12411. opt.value = n.address;
  12412. opt.innerText = `${n.address} (Gateway: ${n.gateway || 'None'}${n.comment ? ' - ' + n.comment : ''})`;
  12413. if (selectedVal && (selectedVal === n.address || selectedVal === n.id)) {
  12414. opt.selected = true;
  12415. }
  12416. sel.appendChild(opt);
  12417. });
  12418. }
  12419. function onDHCPServerNetworkChange() {
  12420. const netSel = document.getElementById('dhcp-server-modal-network');
  12421. if (!netSel) return;
  12422. const netVal = netSel.value;
  12423. if (!netVal) return;
  12424. const poolInput = document.getElementById('dhcp-server-modal-pool');
  12425. if (!poolInput) return;
  12426. // Auto-calculate suggested address pool based on subnet CIDR
  12427. const parts = netVal.split('/');
  12428. const ip = parts[0];
  12429. const cidr = parseInt(parts[1] || '24', 10);
  12430. if (cidr === 24) {
  12431. const octets = ip.split('.');
  12432. if (octets.length === 4) {
  12433. const base = `${octets[0]}.${octets[1]}.${octets[2]}`;
  12434. poolInput.value = `${base}.10-${base}.254`;
  12435. }
  12436. }
  12437. }
  12438. function openAddDHCPServerModal() {
  12439. document.getElementById('dhcp-server-modal-title').innerText = 'Add DHCP Server';
  12440. document.getElementById('dhcp-server-modal-id').value = '';
  12441. document.getElementById('dhcp-server-modal-name').value = `dhcp${(state.dhcpServers || []).length + 1}`;
  12442. document.getElementById('dhcp-server-modal-pool').value = '192.168.88.10-192.168.88.254';
  12443. document.getElementById('dhcp-server-modal-leasetime').value = '12h';
  12444. document.getElementById('dhcp-server-modal-comment').value = '';
  12445. document.getElementById('dhcp-server-modal-authoritative').checked = true;
  12446. document.getElementById('dhcp-server-modal-disabled').checked = false;
  12447. populateDHCPIfaceSelect('dhcp-server-modal-iface', '');
  12448. const networks = state.dhcpNetworks || [];
  12449. const defaultNet = networks.length > 0 ? networks[0].address : '';
  12450. populateDHCPNetworkSelect('dhcp-server-modal-network', defaultNet);
  12451. if (defaultNet) {
  12452. onDHCPServerNetworkChange();
  12453. }
  12454. document.getElementById('dhcp-server-instance-modal').classList.remove('hidden');
  12455. }
  12456. function openEditDHCPServerModal(id) {
  12457. const s = (state.dhcpServers || []).find(item => item.id === id);
  12458. if (!s) return;
  12459. document.getElementById('dhcp-server-modal-title').innerText = `Edit DHCP Server (${s.name})`;
  12460. document.getElementById('dhcp-server-modal-id').value = s.id;
  12461. document.getElementById('dhcp-server-modal-name').value = s.name;
  12462. document.getElementById('dhcp-server-modal-pool').value = s.address_pool;
  12463. document.getElementById('dhcp-server-modal-leasetime').value = s.lease_time || '12h';
  12464. document.getElementById('dhcp-server-modal-comment').value = s.comment || '';
  12465. document.getElementById('dhcp-server-modal-authoritative').checked = s.authoritative !== false;
  12466. document.getElementById('dhcp-server-modal-disabled').checked = !!s.disabled;
  12467. populateDHCPIfaceSelect('dhcp-server-modal-iface', s.interface);
  12468. populateDHCPNetworkSelect('dhcp-server-modal-network', s.network || '');
  12469. document.getElementById('dhcp-server-instance-modal').classList.remove('hidden');
  12470. }
  12471. function closeDHCPServerModal() {
  12472. document.getElementById('dhcp-server-instance-modal').classList.add('hidden');
  12473. }
  12474. async function submitSaveDHCPServer(e) {
  12475. e.preventDefault();
  12476. const id = document.getElementById('dhcp-server-modal-id').value;
  12477. const name = document.getElementById('dhcp-server-modal-name').value.trim();
  12478. const iface = document.getElementById('dhcp-server-modal-iface').value;
  12479. const network = document.getElementById('dhcp-server-modal-network').value.trim();
  12480. const pool = document.getElementById('dhcp-server-modal-pool').value.trim();
  12481. const leaseTime = document.getElementById('dhcp-server-modal-leasetime').value.trim() || '12h';
  12482. const comment = document.getElementById('dhcp-server-modal-comment').value.trim();
  12483. const authoritative = document.getElementById('dhcp-server-modal-authoritative').checked;
  12484. const disabled = document.getElementById('dhcp-server-modal-disabled').checked;
  12485. try {
  12486. const res = await fetch(`${API_BASE}/dhcp-server/servers`, {
  12487. method: 'POST',
  12488. headers: { 'Content-Type': 'application/json' },
  12489. body: JSON.stringify({
  12490. id,
  12491. name,
  12492. interface: iface,
  12493. network,
  12494. address_pool: pool,
  12495. lease_time: leaseTime,
  12496. authoritative,
  12497. disabled,
  12498. comment
  12499. })
  12500. });
  12501. if (res.ok) {
  12502. showToast('DHCP Server Saved', `Server ${name} configured successfully`, 'success');
  12503. closeDHCPServerModal();
  12504. loadDHCPServer(false);
  12505. fetchData(false);
  12506. } else {
  12507. const err = await res.text();
  12508. showToast('Error', err, 'error');
  12509. }
  12510. } catch (err) {
  12511. showToast('Error', err.message, 'error');
  12512. }
  12513. }
  12514. async function toggleDHCPServerState(id, disabled) {
  12515. try {
  12516. const res = await fetch(`${API_BASE}/dhcp-server/servers/${encodeURIComponent(id)}/state`, {
  12517. method: 'POST',
  12518. headers: { 'Content-Type': 'application/json' },
  12519. body: JSON.stringify({ disabled })
  12520. });
  12521. if (res.ok) {
  12522. showToast('State Updated', disabled ? 'Server disabled' : 'Server enabled', 'info');
  12523. loadDHCPServer(false);
  12524. fetchData(false);
  12525. }
  12526. } catch (err) {
  12527. showToast('Error', err.message, 'error');
  12528. }
  12529. }
  12530. async function deleteDHCPServer(id, name) {
  12531. if (!confirm(`Are you sure you want to delete DHCP Server "${name}"?`)) return;
  12532. try {
  12533. const res = await fetch(`${API_BASE}/dhcp-server/servers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12534. if (res.ok) {
  12535. showToast('Deleted', `DHCP Server ${name} removed`, 'success');
  12536. loadDHCPServer(false);
  12537. fetchData(false);
  12538. }
  12539. } catch (err) {
  12540. showToast('Error', err.message, 'error');
  12541. }
  12542. }
  12543. // ==================== MODALS & ACTIONS: NETWORKS ====================
  12544. function openAddDHCPNetworkModal() {
  12545. document.getElementById('dhcp-network-modal-title').innerText = 'Add DHCP Network';
  12546. document.getElementById('dhcp-network-modal-id').value = '';
  12547. document.getElementById('dhcp-network-modal-address').value = '192.168.88.0/24';
  12548. document.getElementById('dhcp-network-modal-gateway').value = '192.168.88.1';
  12549. document.getElementById('dhcp-network-modal-dns').value = '192.168.88.1, 1.1.1.1, 8.8.8.8';
  12550. document.getElementById('dhcp-network-modal-domain').value = 'lan';
  12551. document.getElementById('dhcp-network-modal-netmask').value = '';
  12552. document.getElementById('dhcp-network-modal-comment').value = '';
  12553. renderDHCPNetworkOptionsCheckboxes([]);
  12554. document.getElementById('dhcp-network-modal').classList.remove('hidden');
  12555. }
  12556. function openEditDHCPNetworkModal(id) {
  12557. const n = (state.dhcpNetworks || []).find(item => item.id === id);
  12558. if (!n) return;
  12559. document.getElementById('dhcp-network-modal-title').innerText = `Edit DHCP Network (${n.address})`;
  12560. document.getElementById('dhcp-network-modal-id').value = n.id;
  12561. document.getElementById('dhcp-network-modal-address').value = n.address;
  12562. document.getElementById('dhcp-network-modal-gateway').value = n.gateway || '';
  12563. document.getElementById('dhcp-network-modal-dns').value = (n.dns_servers || []).join(', ');
  12564. document.getElementById('dhcp-network-modal-domain').value = n.domain || '';
  12565. document.getElementById('dhcp-network-modal-netmask').value = n.netmask || '';
  12566. document.getElementById('dhcp-network-modal-comment').value = n.comment || '';
  12567. renderDHCPNetworkOptionsCheckboxes(n.dhcp_options || []);
  12568. document.getElementById('dhcp-network-modal').classList.remove('hidden');
  12569. }
  12570. function renderDHCPNetworkOptionsCheckboxes(selectedIds) {
  12571. const container = document.getElementById('dhcp-network-modal-options-list');
  12572. if (!container) return;
  12573. container.innerHTML = '';
  12574. const opts = state.dhcpOptions || [];
  12575. if (opts.length === 0) {
  12576. container.innerHTML = '<span class="text-slate-500 text-[11px] col-span-2">No custom options configured. Add some in the "Options" tab.</span>';
  12577. return;
  12578. }
  12579. opts.forEach(o => {
  12580. const isChecked = selectedIds.includes(o.id);
  12581. const label = document.createElement('label');
  12582. label.className = 'flex items-center space-x-2 text-slate-300 hover:text-white cursor-pointer';
  12583. label.innerHTML = `
  12584. <input type="checkbox" name="dhcp-net-opt" value="${o.id}" ${isChecked ? 'checked' : ''} class="rounded bg-slate-800 border-slate-700 text-emerald-600">
  12585. <span class="truncate" title="${escapeHtml(o.name)} (Code ${o.code})">${escapeHtml(o.name)} <span class="text-cyan-400">#${o.code}</span></span>
  12586. `;
  12587. container.appendChild(label);
  12588. });
  12589. }
  12590. function closeDHCPNetworkModal() {
  12591. document.getElementById('dhcp-network-modal').classList.add('hidden');
  12592. }
  12593. async function submitSaveDHCPNetwork(e) {
  12594. e.preventDefault();
  12595. const id = document.getElementById('dhcp-network-modal-id').value;
  12596. const address = document.getElementById('dhcp-network-modal-address').value.trim();
  12597. const gateway = document.getElementById('dhcp-network-modal-gateway').value.trim();
  12598. const dnsStr = document.getElementById('dhcp-network-modal-dns').value.trim();
  12599. const domain = document.getElementById('dhcp-network-modal-domain').value.trim();
  12600. const netmask = document.getElementById('dhcp-network-modal-netmask').value.trim();
  12601. const comment = document.getElementById('dhcp-network-modal-comment').value.trim();
  12602. const selectedOpts = [];
  12603. document.querySelectorAll('input[name="dhcp-net-opt"]:checked').forEach(cb => selectedOpts.push(cb.value));
  12604. const dnsServers = dnsStr ? dnsStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  12605. try {
  12606. const res = await fetch(`${API_BASE}/dhcp-server/networks`, {
  12607. method: 'POST',
  12608. headers: { 'Content-Type': 'application/json' },
  12609. body: JSON.stringify({
  12610. id,
  12611. address,
  12612. gateway,
  12613. netmask,
  12614. dns_servers: dnsServers,
  12615. domain,
  12616. dhcp_options: selectedOpts,
  12617. comment
  12618. })
  12619. });
  12620. if (res.ok) {
  12621. showToast('Network Saved', `Subnet ${address} configured successfully`, 'success');
  12622. closeDHCPNetworkModal();
  12623. loadDHCPServer(false);
  12624. fetchData(false);
  12625. } else {
  12626. const err = await res.text();
  12627. showToast('Error', err, 'error');
  12628. }
  12629. } catch (err) {
  12630. showToast('Error', err.message, 'error');
  12631. }
  12632. }
  12633. async function deleteDHCPNetwork(id, addr) {
  12634. if (!confirm(`Are you sure you want to delete DHCP Network "${addr}"?`)) return;
  12635. try {
  12636. const res = await fetch(`${API_BASE}/dhcp-server/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12637. if (res.ok) {
  12638. showToast('Deleted', `Network ${addr} removed`, 'success');
  12639. loadDHCPServer(false);
  12640. fetchData(false);
  12641. }
  12642. } catch (err) {
  12643. showToast('Error', err.message, 'error');
  12644. }
  12645. }
  12646. // ==================== MODALS & ACTIONS: LEASES ====================
  12647. function openAddDHCPStaticLeaseModal() {
  12648. document.getElementById('dhcp-static-lease-modal-title').innerText = 'Add Static Lease Reservation';
  12649. document.getElementById('dhcp-static-lease-modal-id').value = '';
  12650. document.getElementById('dhcp-static-lease-modal-mac').value = '';
  12651. document.getElementById('dhcp-static-lease-modal-ip').value = '';
  12652. document.getElementById('dhcp-static-lease-modal-hostname').value = '';
  12653. document.getElementById('dhcp-static-lease-modal-server').value = 'all';
  12654. document.getElementById('dhcp-static-lease-modal-comment').value = '';
  12655. document.getElementById('dhcp-static-lease-modal-disabled').checked = false;
  12656. document.getElementById('dhcp-static-lease-modal').classList.remove('hidden');
  12657. }
  12658. function closeDHCPStaticLeaseModal() {
  12659. document.getElementById('dhcp-static-lease-modal').classList.add('hidden');
  12660. }
  12661. async function submitSaveDHCPStaticLease(e) {
  12662. e.preventDefault();
  12663. const id = document.getElementById('dhcp-static-lease-modal-id').value;
  12664. const mac = document.getElementById('dhcp-static-lease-modal-mac').value.trim();
  12665. const ip = document.getElementById('dhcp-static-lease-modal-ip').value.trim();
  12666. const hostname = document.getElementById('dhcp-static-lease-modal-hostname').value.trim();
  12667. const server = document.getElementById('dhcp-static-lease-modal-server').value.trim() || 'all';
  12668. const comment = document.getElementById('dhcp-static-lease-modal-comment').value.trim();
  12669. const disabled = document.getElementById('dhcp-static-lease-modal-disabled').checked;
  12670. try {
  12671. const res = await fetch(`${API_BASE}/dhcp-server/leases/static`, {
  12672. method: 'POST',
  12673. headers: { 'Content-Type': 'application/json' },
  12674. body: JSON.stringify({
  12675. id,
  12676. mac_address: mac,
  12677. address: ip,
  12678. hostname,
  12679. server,
  12680. comment,
  12681. disabled
  12682. })
  12683. });
  12684. if (res.ok) {
  12685. showToast('Static Lease Saved', `IP ${ip} reserved for ${mac}`, 'success');
  12686. closeDHCPStaticLeaseModal();
  12687. loadDHCPServer(false);
  12688. fetchData(false);
  12689. } else {
  12690. const err = await res.text();
  12691. showToast('Error', err, 'error');
  12692. }
  12693. } catch (err) {
  12694. showToast('Error', err.message, 'error');
  12695. }
  12696. }
  12697. async function deleteDHCPStaticLease(id) {
  12698. if (!confirm('Are you sure you want to remove this static reservation?')) return;
  12699. try {
  12700. const res = await fetch(`${API_BASE}/dhcp-server/leases/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12701. if (res.ok) {
  12702. showToast('Deleted', 'Static lease removed', 'success');
  12703. loadDHCPServer(false);
  12704. fetchData(false);
  12705. }
  12706. } catch (err) {
  12707. showToast('Error', err.message, 'error');
  12708. }
  12709. }
  12710. async function makeDHCPLeaseStatic(mac, ip, hostname, comment) {
  12711. try {
  12712. const res = await fetch(`${API_BASE}/dhcp-server/leases/make-static`, {
  12713. method: 'POST',
  12714. headers: { 'Content-Type': 'application/json' },
  12715. body: JSON.stringify({
  12716. mac_address: mac,
  12717. address: ip,
  12718. hostname,
  12719. comment: comment || 'Converted to static'
  12720. })
  12721. });
  12722. if (res.ok) {
  12723. showToast('Lease Made Static', `IP ${ip} permanently reserved for ${mac}`, 'success');
  12724. loadDHCPServer(false);
  12725. fetchData(false);
  12726. } else {
  12727. const err = await res.text();
  12728. showToast('Error', err, 'error');
  12729. }
  12730. } catch (err) {
  12731. showToast('Error', err.message, 'error');
  12732. }
  12733. }
  12734. // ==================== MODALS & ACTIONS: OPTIONS ====================
  12735. function openAddDHCPOptionModal() {
  12736. document.getElementById('dhcp-option-modal-title').innerText = 'Add DHCP Option';
  12737. document.getElementById('dhcp-option-modal-id').value = '';
  12738. document.getElementById('dhcp-option-modal-name').value = '';
  12739. document.getElementById('dhcp-option-modal-code').value = '';
  12740. document.getElementById('dhcp-option-modal-value').value = '';
  12741. document.getElementById('dhcp-option-modal-comment').value = '';
  12742. document.getElementById('dhcp-option-modal').classList.remove('hidden');
  12743. }
  12744. function openEditDHCPOptionModal(id) {
  12745. const o = (state.dhcpOptions || []).find(item => item.id === id);
  12746. if (!o) return;
  12747. document.getElementById('dhcp-option-modal-title').innerText = `Edit DHCP Option (${o.name})`;
  12748. document.getElementById('dhcp-option-modal-id').value = o.id;
  12749. document.getElementById('dhcp-option-modal-name').value = o.name;
  12750. document.getElementById('dhcp-option-modal-code').value = o.code;
  12751. document.getElementById('dhcp-option-modal-value').value = o.value;
  12752. document.getElementById('dhcp-option-modal-comment').value = o.comment || '';
  12753. document.getElementById('dhcp-option-modal').classList.remove('hidden');
  12754. }
  12755. function closeDHCPOptionModal() {
  12756. document.getElementById('dhcp-option-modal').classList.add('hidden');
  12757. }
  12758. async function submitSaveDHCPOption(e) {
  12759. e.preventDefault();
  12760. const id = document.getElementById('dhcp-option-modal-id').value;
  12761. const name = document.getElementById('dhcp-option-modal-name').value.trim();
  12762. const code = parseInt(document.getElementById('dhcp-option-modal-code').value);
  12763. const value = document.getElementById('dhcp-option-modal-value').value.trim();
  12764. const comment = document.getElementById('dhcp-option-modal-comment').value.trim();
  12765. try {
  12766. const res = await fetch(`${API_BASE}/dhcp-server/options`, {
  12767. method: 'POST',
  12768. headers: { 'Content-Type': 'application/json' },
  12769. body: JSON.stringify({ id, name, code, value, comment })
  12770. });
  12771. if (res.ok) {
  12772. showToast('Option Saved', `DHCP option ${name} (#${code}) configured`, 'success');
  12773. closeDHCPOptionModal();
  12774. loadDHCPServer(false);
  12775. fetchData(false);
  12776. } else {
  12777. const err = await res.text();
  12778. showToast('Error', err, 'error');
  12779. }
  12780. } catch (err) {
  12781. showToast('Error', err.message, 'error');
  12782. }
  12783. }
  12784. async function deleteDHCPOption(id, name) {
  12785. if (!confirm(`Are you sure you want to delete DHCP Option "${name}"?`)) return;
  12786. try {
  12787. const res = await fetch(`${API_BASE}/dhcp-server/options/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12788. if (res.ok) {
  12789. showToast('Deleted', `Option ${name} removed`, 'success');
  12790. loadDHCPServer(false);
  12791. fetchData(false);
  12792. }
  12793. } catch (err) {
  12794. showToast('Error', err.message, 'error');
  12795. }
  12796. }
  12797. // ==================== WIZARD: DHCP SETUP (MikroTik style) ====================
  12798. function openDHCPServerSetupModal() {
  12799. populateDHCPIfaceSelect('dhcp-wizard-iface', '');
  12800. onDHCPWizardIfaceChange();
  12801. document.getElementById('dhcp-setup-wizard-modal').classList.remove('hidden');
  12802. }
  12803. function closeDHCPServerSetupModal() {
  12804. document.getElementById('dhcp-setup-wizard-modal').classList.add('hidden');
  12805. }
  12806. function onDHCPWizardIfaceChange() {
  12807. const ifaceName = document.getElementById('dhcp-wizard-iface').value;
  12808. const iface = (state.interfaces || []).find(i => i.name === ifaceName);
  12809. let ip = '192.168.88.1';
  12810. let prefix = '24';
  12811. if (iface && iface.ip_address) {
  12812. const parts = iface.ip_address.split('/');
  12813. ip = parts[0];
  12814. if (parts.length > 1) prefix = parts[1];
  12815. }
  12816. // Calculate subnet base (e.g. 192.168.88.0/24)
  12817. const ipParts = ip.split('.');
  12818. if (ipParts.length === 4) {
  12819. const baseSpace = `${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.0/${prefix}`;
  12820. const pool = `${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.10-${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.254`;
  12821. document.getElementById('dhcp-wizard-space').value = baseSpace;
  12822. document.getElementById('dhcp-wizard-gateway').value = ip;
  12823. document.getElementById('dhcp-wizard-pool').value = pool;
  12824. document.getElementById('dhcp-wizard-dns').value = `${ip}, 1.1.1.1, 8.8.8.8`;
  12825. document.getElementById('dhcp-wizard-ntp').value = `${ip}`;
  12826. }
  12827. }
  12828. async function submitDHCPServerSetupWizard(e) {
  12829. e.preventDefault();
  12830. const iface = document.getElementById('dhcp-wizard-iface').value;
  12831. const space = document.getElementById('dhcp-wizard-space').value.trim();
  12832. const gw = document.getElementById('dhcp-wizard-gateway').value.trim();
  12833. const pool = document.getElementById('dhcp-wizard-pool').value.trim();
  12834. const dnsStr = document.getElementById('dhcp-wizard-dns').value.trim();
  12835. const leaseTime = document.getElementById('dhcp-wizard-leasetime').value.trim() || '12h';
  12836. const ntpStr = document.getElementById('dhcp-wizard-ntp').value.trim();
  12837. const tftp = document.getElementById('dhcp-wizard-tftp').value.trim();
  12838. const dnsServers = dnsStr ? dnsStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  12839. const ntpServers = ntpStr ? ntpStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  12840. try {
  12841. const res = await fetch(`${API_BASE}/dhcp-server/setup`, {
  12842. method: 'POST',
  12843. headers: { 'Content-Type': 'application/json' },
  12844. body: JSON.stringify({
  12845. interface: iface,
  12846. address_space: space,
  12847. gateway: gw,
  12848. address_pool: pool,
  12849. dns_servers: dnsServers,
  12850. lease_time: leaseTime,
  12851. ntp_servers: ntpServers,
  12852. next_server: tftp
  12853. })
  12854. });
  12855. if (res.ok) {
  12856. showToast('DHCP Setup Complete', `DHCP Server setup finished on ${iface}`, 'success');
  12857. closeDHCPServerSetupModal();
  12858. loadDHCPServer(false);
  12859. fetchData(false);
  12860. } else {
  12861. const err = await res.text();
  12862. showToast('Error', err, 'error');
  12863. }
  12864. } catch (err) {
  12865. showToast('Error', err.message, 'error');
  12866. }
  12867. }
  12868. function populateDHCPIfaceSelect(elemId, selectedVal) {
  12869. const sel = document.getElementById(elemId);
  12870. if (!sel) return;
  12871. sel.innerHTML = '<option value="">Select interface...</option>';
  12872. const ifaces = state.interfaces || [];
  12873. ifaces.forEach(i => {
  12874. if (i.name === 'lo') return;
  12875. const opt = document.createElement('option');
  12876. opt.value = i.name;
  12877. const ipStr = i.ip_address ? ` (${i.ip_address})` : '';
  12878. opt.textContent = `${i.name}${ipStr} [${i.role || i.type || 'interface'}]`;
  12879. if (i.name === selectedVal) opt.selected = true;
  12880. sel.appendChild(opt);
  12881. });
  12882. }
  12883. // ==================== UNIVERSAL TABLE ORDERING / SORTING (WINBOX / WEBFIG STYLE) ====================
  12884. function initTableSorting() {
  12885. document.querySelectorAll('table').forEach(setupSortableTable);
  12886. }
  12887. function setupSortableTable(table) {
  12888. const thead = table.querySelector('thead');
  12889. const tbody = table.querySelector('tbody');
  12890. if (!thead || !tbody) return;
  12891. const headerRows = thead.querySelectorAll('tr');
  12892. if (headerRows.length === 0) return;
  12893. const ths = headerRows[headerRows.length - 1].querySelectorAll('th');
  12894. ths.forEach((th, colIdx) => {
  12895. if (th._sortBound) return;
  12896. th._sortBound = true;
  12897. const rawText = th.innerText.trim().toLowerCase();
  12898. const isActionsCol = rawText === 'actions' || (rawText === 'action' && th.classList.contains('text-right'));
  12899. const isCheckboxCol = !!th.querySelector('input[type="checkbox"]');
  12900. const isExpandCol = (th.classList.contains('w-8') || th.classList.contains('w-6')) && !rawText;
  12901. const isExplicitNoSort = th.classList.contains('no-sort') || th.getAttribute('data-sortable') === 'false';
  12902. if (isActionsCol || isCheckboxCol || isExpandCol || isExplicitNoSort) {
  12903. return;
  12904. }
  12905. th.classList.add('table-sortable', 'group');
  12906. if (!th.title) th.title = 'Click to sort (Ascending / Descending / Default)';
  12907. let icon = th.querySelector('.table-sort-icon');
  12908. if (!icon) {
  12909. icon = document.createElement('span');
  12910. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  12911. icon.innerHTML = '⇅';
  12912. th.appendChild(icon);
  12913. }
  12914. th.addEventListener('click', (e) => {
  12915. if (e.target.tagName === 'INPUT' || e.target.tagName === 'BUTTON' || e.target.closest('button, input')) return;
  12916. handleHeaderClick(table, th, colIdx);
  12917. });
  12918. });
  12919. if (!tbody._sortObserved) {
  12920. tbody._sortObserved = true;
  12921. let sortDebounceTimer = null;
  12922. const observer = new MutationObserver((mutations) => {
  12923. if (tbody._isSorting) return;
  12924. const hasChildChanges = mutations.some(m => m.type === 'childList' && m.addedNodes.length > 0);
  12925. if (!hasChildChanges) return;
  12926. clearTimeout(sortDebounceTimer);
  12927. sortDebounceTimer = setTimeout(() => {
  12928. if (tbody._isSorting) return;
  12929. if (table._activeSort && table._activeSort.dir !== 'none') {
  12930. applyTableSort(table, table._activeSort.colIdx, table._activeSort.dir, false);
  12931. } else {
  12932. tagOriginalRowOrder(tbody);
  12933. }
  12934. }, 50);
  12935. });
  12936. tbody._sortObserver = observer;
  12937. observer.observe(tbody, { childList: true });
  12938. }
  12939. tagOriginalRowOrder(tbody);
  12940. }
  12941. function tagOriginalRowOrder(tbody) {
  12942. let idx = 0;
  12943. Array.from(tbody.children).forEach(tr => {
  12944. if (!tr.querySelector('td[colspan]')) {
  12945. if (!tr.hasAttribute('data-orig-idx')) {
  12946. tr.setAttribute('data-orig-idx', idx++);
  12947. }
  12948. }
  12949. });
  12950. }
  12951. function handleHeaderClick(table, th, colIdx) {
  12952. const currentSort = table._activeSort || { colIdx: -1, dir: 'none' };
  12953. let newDir = 'asc';
  12954. if (currentSort.colIdx === colIdx) {
  12955. if (currentSort.dir === 'asc') newDir = 'desc';
  12956. else if (currentSort.dir === 'desc') newDir = 'none';
  12957. else newDir = 'asc';
  12958. } else {
  12959. newDir = 'asc';
  12960. }
  12961. table._activeSort = { colIdx, dir: newDir };
  12962. updateHeaderIcons(table, colIdx, newDir);
  12963. applyTableSort(table, colIdx, newDir, true);
  12964. }
  12965. function updateHeaderIcons(table, activeColIdx, dir) {
  12966. const thead = table.querySelector('thead');
  12967. if (!thead) return;
  12968. const ths = thead.querySelectorAll('th');
  12969. ths.forEach((th, idx) => {
  12970. const icon = th.querySelector('.table-sort-icon');
  12971. if (!icon) return;
  12972. if (idx === activeColIdx && dir !== 'none') {
  12973. icon.innerHTML = dir === 'asc' ? '▲' : '▼';
  12974. icon.className = 'table-sort-icon text-cyan-400 font-bold opacity-100';
  12975. th.classList.add('table-sorted-active');
  12976. } else {
  12977. icon.innerHTML = '⇅';
  12978. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  12979. th.classList.remove('table-sorted-active');
  12980. }
  12981. });
  12982. }
  12983. function applyTableSort(table, colIdx, dir, userInitiated) {
  12984. const tbody = table.querySelector('tbody');
  12985. if (!tbody || tbody.children.length <= 1) return;
  12986. tbody._isSorting = true;
  12987. tagOriginalRowOrder(tbody);
  12988. // Group parent rows and any attached drawer/sub-rows
  12989. const groups = [];
  12990. let currentGroup = null;
  12991. Array.from(tbody.children).forEach(tr => {
  12992. if (tr.querySelector('td[colspan]')) {
  12993. if (currentGroup) {
  12994. currentGroup.subRows.push(tr);
  12995. } else {
  12996. groups.push({ mainRow: tr, subRows: [] });
  12997. }
  12998. } else {
  12999. currentGroup = { mainRow: tr, subRows: [] };
  13000. groups.push(currentGroup);
  13001. }
  13002. });
  13003. if (dir === 'none') {
  13004. groups.sort((a, b) => {
  13005. const idxA = parseInt(a.mainRow.getAttribute('data-orig-idx') || '0', 10);
  13006. const idxB = parseInt(b.mainRow.getAttribute('data-orig-idx') || '0', 10);
  13007. return idxA - idxB;
  13008. });
  13009. } else {
  13010. groups.sort((a, b) => {
  13011. const cellA = a.mainRow.children[colIdx];
  13012. const cellB = b.mainRow.children[colIdx];
  13013. const res = compareTableCells(cellA, cellB);
  13014. return dir === 'asc' ? res : -res;
  13015. });
  13016. }
  13017. // Check if rows are already in correct order to avoid modifying DOM
  13018. let alreadyOrdered = true;
  13019. let childIdx = 0;
  13020. for (const g of groups) {
  13021. if (tbody.children[childIdx] !== g.mainRow) {
  13022. alreadyOrdered = false;
  13023. break;
  13024. }
  13025. childIdx++;
  13026. for (const sub of g.subRows) {
  13027. if (tbody.children[childIdx] !== sub) {
  13028. alreadyOrdered = false;
  13029. break;
  13030. }
  13031. childIdx++;
  13032. }
  13033. }
  13034. if (alreadyOrdered) {
  13035. tbody._isSorting = false;
  13036. return;
  13037. }
  13038. // Disconnect observer while re-ordering to prevent recursion and thrashing
  13039. if (tbody._sortObserver) {
  13040. tbody._sortObserver.disconnect();
  13041. }
  13042. // Re-append rows in sorted order
  13043. groups.forEach(g => {
  13044. tbody.appendChild(g.mainRow);
  13045. g.subRows.forEach(sub => tbody.appendChild(sub));
  13046. });
  13047. // Drain any queued mutations and re-connect observer
  13048. if (tbody._sortObserver) {
  13049. tbody._sortObserver.takeRecords();
  13050. tbody._sortObserver.observe(tbody, { childList: true });
  13051. }
  13052. tbody._isSorting = false;
  13053. }
  13054. function getCellRawText(cell) {
  13055. if (!cell) return '';
  13056. if (cell.hasAttribute('data-sort-value')) return cell.getAttribute('data-sort-value');
  13057. const input = cell.querySelector('input, select');
  13058. if (input) {
  13059. if (input.type === 'checkbox') return input.checked ? '1' : '0';
  13060. return input.value;
  13061. }
  13062. return cell.innerText.trim();
  13063. }
  13064. function parseTrafficToNumber(str) {
  13065. const m = str.match(/^([\d.,]+)\s*([KMGTkmgt]?[iI]?[Bb](?:ps|\/s)?)/);
  13066. if (!m) return null;
  13067. const num = parseFloat(m[1].replace(/,/g, ''));
  13068. if (isNaN(num)) return null;
  13069. const unit = m[2].toUpperCase();
  13070. let mult = 1;
  13071. if (unit.startsWith('K')) mult = 1024;
  13072. else if (unit.startsWith('M')) mult = 1024 * 1024;
  13073. else if (unit.startsWith('G')) mult = 1024 * 1024 * 1024;
  13074. else if (unit.startsWith('T')) mult = 1024 * 1024 * 1024 * 1024;
  13075. return num * mult;
  13076. }
  13077. function parseIpToNumber(str) {
  13078. const clean = str.replace(/^[!~]/, '').trim();
  13079. const m = clean.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(?:\/(\d{1,2}))?/);
  13080. if (!m) return null;
  13081. const o1 = parseInt(m[1], 10);
  13082. const o2 = parseInt(m[2], 10);
  13083. const o3 = parseInt(m[3], 10);
  13084. const o4 = parseInt(m[4], 10);
  13085. if (o1 > 255 || o2 > 255 || o3 > 255 || o4 > 255) return null;
  13086. return ((o1 * 256 + o2) * 256 + o3) * 256 + o4;
  13087. }
  13088. function parseCompoundPackets(str) {
  13089. const m = str.match(/^([\d,]+)p/);
  13090. if (!m) return null;
  13091. return parseInt(m[1].replace(/,/g, ''), 10);
  13092. }
  13093. function compareTableCells(cellA, cellB) {
  13094. const a = getCellRawText(cellA);
  13095. const b = getCellRawText(cellB);
  13096. if (a === '' && b !== '') return 1;
  13097. if (b === '' && a !== '') return -1;
  13098. if (a === b) return 0;
  13099. // 1. IP Addresses / CIDR
  13100. const ipA = parseIpToNumber(a);
  13101. const ipB = parseIpToNumber(b);
  13102. if (ipA !== null && ipB !== null) return ipA - ipB;
  13103. // 2. Packet counts (e.g. "1,250p / 45 KB")
  13104. const pktA = parseCompoundPackets(a);
  13105. const pktB = parseCompoundPackets(b);
  13106. if (pktA !== null && pktB !== null) return pktA - pktB;
  13107. // 3. Traffic / Throughput / Bytes (e.g. "1.2 MB", "500 KiB", "10 Gbps")
  13108. const trafA = parseTrafficToNumber(a);
  13109. const trafB = parseTrafficToNumber(b);
  13110. if (trafA !== null && trafB !== null) return trafA - trafB;
  13111. // 4. Numbers with '#' or formatted with commas (e.g. "#1", "24", "1,200")
  13112. const cleanNumA = a.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  13113. const cleanNumB = b.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  13114. const numA = Number(cleanNumA);
  13115. const numB = Number(cleanNumB);
  13116. if (!isNaN(numA) && !isNaN(numB) && cleanNumA !== '' && cleanNumB !== '') {
  13117. return numA - numB;
  13118. }
  13119. // 5. Natural case-insensitive string compare
  13120. return a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' });
  13121. }
  13122. // ==================== VRRP HIGH AVAILABILITY CONTROLLER ====================
  13123. async function loadVRRP(showToastNotification = false) {
  13124. try {
  13125. const [instRes, sumRes] = await Promise.all([
  13126. fetch(`${API_BASE}/vrrp/instances`),
  13127. fetch(`${API_BASE}/vrrp/summary`)
  13128. ]);
  13129. if (instRes.ok) {
  13130. state.vrrpInstances = await instRes.json();
  13131. renderVRRP();
  13132. }
  13133. if (sumRes.ok) {
  13134. state.vrrpSummary = await sumRes.json();
  13135. renderVRRPSummary();
  13136. }
  13137. if (showToastNotification) {
  13138. showToast('Refreshed', 'VRRP telemetry refreshed', 'info');
  13139. }
  13140. } catch (err) {
  13141. console.error('Failed to load VRRP:', err);
  13142. }
  13143. }
  13144. function renderVRRPSummary() {
  13145. const s = state.vrrpSummary || { total_instances: 0, master_instances: 0, backup_instances: 0 };
  13146. const elTotal = document.getElementById('vrrp-stat-total');
  13147. if (elTotal) elTotal.innerText = s.total_instances || 0;
  13148. const elMaster = document.getElementById('vrrp-stat-master');
  13149. if (elMaster) elMaster.innerText = s.master_instances || 0;
  13150. const elBackup = document.getElementById('vrrp-stat-backup');
  13151. if (elBackup) elBackup.innerText = s.backup_instances || 0;
  13152. const bCount = document.getElementById('badge-vrrp-count');
  13153. if (bCount) bCount.innerText = s.total_instances || 0;
  13154. const dot = document.getElementById('badge-vrrp-dot');
  13155. if (dot) {
  13156. if (s.master_instances > 0) {
  13157. dot.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  13158. } else if (s.backup_instances > 0) {
  13159. dot.className = 'w-2 h-2 rounded-full bg-sky-400';
  13160. } else {
  13161. dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  13162. }
  13163. }
  13164. }
  13165. function renderVRRP() {
  13166. const tbody = document.getElementById('vrrp-table-tbody');
  13167. const empty = document.getElementById('vrrp-table-empty');
  13168. if (!tbody) return;
  13169. tbody.innerHTML = '';
  13170. const instances = state.vrrpInstances || [];
  13171. if (instances.length === 0) {
  13172. empty?.classList.remove('hidden');
  13173. return;
  13174. }
  13175. empty?.classList.add('hidden');
  13176. instances.forEach(inst => {
  13177. const tr = document.createElement('tr');
  13178. tr.className = `hover:bg-slate-800/40 transition text-xs ${inst.disabled ? 'opacity-50' : ''}`;
  13179. // Render Flag: M (Master), B (Backup), F (Fault), X (Disabled)
  13180. 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>`;
  13181. if (inst.disabled) {
  13182. 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>`;
  13183. } else if (inst.state === 'MASTER') {
  13184. 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>`;
  13185. } else if (inst.state === 'BACKUP') {
  13186. 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>`;
  13187. } else if (inst.state === 'FAULT') {
  13188. 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>`;
  13189. }
  13190. // Render State Badge
  13191. let stateBadge = `<span class="px-2 py-0.5 rounded text-[10px] bg-slate-800 text-slate-400 border border-slate-700">DISABLED</span>`;
  13192. if (!inst.disabled) {
  13193. if (inst.state === 'MASTER') {
  13194. 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>`;
  13195. } else if (inst.state === 'BACKUP') {
  13196. 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>`;
  13197. } else if (inst.state === 'FAULT') {
  13198. 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>`;
  13199. }
  13200. }
  13201. const vipsStr = (inst.virtual_ips || []).join(', ') || '-';
  13202. tr.innerHTML = `
  13203. <td class="py-2.5 px-3 text-center">${flagHtml}</td>
  13204. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(inst.name)}</td>
  13205. <td class="py-2.5 px-3 font-mono text-cyan-400 font-semibold">${escapeHtml(inst.interface)}</td>
  13206. <td class="py-2.5 px-3 font-mono font-bold text-center text-white">${inst.vrid}</td>
  13207. <td class="py-2.5 px-3 font-mono text-center text-slate-300 font-semibold">${inst.priority}</td>
  13208. <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>
  13209. <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>
  13210. <td class="py-2.5 px-3 font-mono text-slate-400 text-[11px]">${escapeHtml(inst.virtual_mac || '-')}</td>
  13211. <td class="py-2.5 px-3 text-center">${stateBadge}</td>
  13212. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]" title="${escapeHtml(inst.comment || '')}">${escapeHtml(inst.comment || '-')}</td>
  13213. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  13214. <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>
  13215. <button onclick="openEditVRRPModal('${inst.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  13216. <button onclick="deleteVRRP('${inst.id}', '${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  13217. </td>
  13218. `;
  13219. tbody.appendChild(tr);
  13220. });
  13221. }
  13222. function populateVRRPIfaceSelect(elemId, selectedIface) {
  13223. const sel = document.getElementById(elemId);
  13224. if (!sel) return;
  13225. sel.innerHTML = '<option value="">Select interface...</option>';
  13226. const ifaces = state.interfaces || [];
  13227. ifaces.forEach(i => {
  13228. const opt = document.createElement('option');
  13229. opt.value = i.name;
  13230. opt.innerText = `${i.name} (${i.type || 'net'}${i.ip ? ' - ' + i.ip : ''})`;
  13231. if (selectedIface && selectedIface === i.name) opt.selected = true;
  13232. sel.appendChild(opt);
  13233. });
  13234. }
  13235. function openAddVRRPModal() {
  13236. document.getElementById('modal-vrrp-title').innerText = 'Add VRRP Instance';
  13237. document.getElementById('modal-vrrp-id').value = '';
  13238. document.getElementById('modal-vrrp-name').value = `vrrp${(state.vrrpInstances || []).length + 1}`;
  13239. document.getElementById('modal-vrrp-vrid').value = 10 + (state.vrrpInstances || []).length;
  13240. document.getElementById('modal-vrrp-priority').value = 100;
  13241. document.getElementById('modal-vrrp-vip').value = '192.168.88.254/24';
  13242. document.getElementById('modal-vrrp-version').value = '3';
  13243. document.getElementById('modal-vrrp-interval').value = 1;
  13244. document.getElementById('modal-vrrp-authtype').value = 'none';
  13245. document.getElementById('modal-vrrp-authpass').value = '';
  13246. document.getElementById('modal-vrrp-comment').value = '';
  13247. document.getElementById('modal-vrrp-preempt').checked = true;
  13248. document.getElementById('modal-vrrp-disabled').checked = false;
  13249. populateVRRPIfaceSelect('modal-vrrp-iface', '');
  13250. document.getElementById('modal-vrrp-instance').classList.remove('hidden');
  13251. }
  13252. function openEditVRRPModal(id) {
  13253. const inst = (state.vrrpInstances || []).find(item => item.id === id);
  13254. if (!inst) return;
  13255. document.getElementById('modal-vrrp-title').innerText = `Edit VRRP Instance (${inst.name})`;
  13256. document.getElementById('modal-vrrp-id').value = inst.id;
  13257. document.getElementById('modal-vrrp-name').value = inst.name;
  13258. document.getElementById('modal-vrrp-vrid').value = inst.vrid;
  13259. document.getElementById('modal-vrrp-priority').value = inst.priority;
  13260. document.getElementById('modal-vrrp-vip').value = (inst.virtual_ips || []).join(', ');
  13261. document.getElementById('modal-vrrp-version').value = String(inst.version || 3);
  13262. document.getElementById('modal-vrrp-interval').value = inst.interval || 1;
  13263. document.getElementById('modal-vrrp-authtype').value = inst.auth_type || 'none';
  13264. document.getElementById('modal-vrrp-authpass').value = inst.auth_password || '';
  13265. document.getElementById('modal-vrrp-comment').value = inst.comment || '';
  13266. document.getElementById('modal-vrrp-preempt').checked = inst.preempt !== false;
  13267. document.getElementById('modal-vrrp-disabled').checked = !!inst.disabled;
  13268. populateVRRPIfaceSelect('modal-vrrp-iface', inst.interface);
  13269. document.getElementById('modal-vrrp-instance').classList.remove('hidden');
  13270. }
  13271. function closeVRRPModal() {
  13272. document.getElementById('modal-vrrp-instance').classList.add('hidden');
  13273. }
  13274. async function submitSaveVRRP(e) {
  13275. e.preventDefault();
  13276. const id = document.getElementById('modal-vrrp-id').value;
  13277. const name = document.getElementById('modal-vrrp-name').value.trim();
  13278. const iface = document.getElementById('modal-vrrp-iface').value;
  13279. const vrid = parseInt(document.getElementById('modal-vrrp-vrid').value, 10) || 1;
  13280. const priority = parseInt(document.getElementById('modal-vrrp-priority').value, 10) || 100;
  13281. const vipRaw = document.getElementById('modal-vrrp-vip').value.trim();
  13282. const version = parseInt(document.getElementById('modal-vrrp-version').value, 10) || 3;
  13283. const interval = parseInt(document.getElementById('modal-vrrp-interval').value, 10) || 1;
  13284. const authType = document.getElementById('modal-vrrp-authtype').value;
  13285. const authPass = document.getElementById('modal-vrrp-authpass').value.trim();
  13286. const comment = document.getElementById('modal-vrrp-comment').value.trim();
  13287. const preempt = document.getElementById('modal-vrrp-preempt').checked;
  13288. const disabled = document.getElementById('modal-vrrp-disabled').checked;
  13289. const vips = vipRaw.split(',').map(s => s.trim()).filter(Boolean);
  13290. try {
  13291. const res = await fetch(`${API_BASE}/vrrp/instances`, {
  13292. method: 'POST',
  13293. headers: { 'Content-Type': 'application/json' },
  13294. body: JSON.stringify({
  13295. id,
  13296. name,
  13297. interface: iface,
  13298. vrid,
  13299. priority,
  13300. virtual_ips: vips,
  13301. version,
  13302. interval,
  13303. auth_type: authType,
  13304. auth_password: authPass,
  13305. comment,
  13306. preempt,
  13307. disabled
  13308. })
  13309. });
  13310. if (res.ok) {
  13311. showToast('VRRP Saved', `VRRP instance ${name} configured`, 'success');
  13312. closeVRRPModal();
  13313. loadVRRP(false);
  13314. fetchData(false);
  13315. } else {
  13316. const err = await res.text();
  13317. showToast('Error', err, 'error');
  13318. }
  13319. } catch (err) {
  13320. showToast('Error', err.message, 'error');
  13321. }
  13322. }
  13323. async function deleteVRRP(id, name) {
  13324. if (!confirm(`Delete VRRP instance "${name}"?`)) return;
  13325. try {
  13326. const res = await fetch(`${API_BASE}/vrrp/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  13327. if (res.ok) {
  13328. showToast('Deleted', `VRRP instance ${name} removed`, 'info');
  13329. loadVRRP(false);
  13330. fetchData(false);
  13331. } else {
  13332. const err = await res.text();
  13333. showToast('Error', err, 'error');
  13334. }
  13335. } catch (err) {
  13336. showToast('Error', err.message, 'error');
  13337. }
  13338. }
  13339. async function toggleVRRPState(id, disabled) {
  13340. try {
  13341. const res = await fetch(`${API_BASE}/vrrp/instances/${encodeURIComponent(id)}/state`, {
  13342. method: 'POST',
  13343. headers: { 'Content-Type': 'application/json' },
  13344. body: JSON.stringify({ disabled })
  13345. });
  13346. if (res.ok) {
  13347. showToast('State Updated', disabled ? 'VRRP disabled' : 'VRRP enabled', 'info');
  13348. loadVRRP(false);
  13349. fetchData(false);
  13350. } else {
  13351. const err = await res.text();
  13352. showToast('Error', err, 'error');
  13353. }
  13354. } catch (err) {
  13355. showToast('Error', err.message, 'error');
  13356. }
  13357. }
  13358. // Global observer for dynamically injected tables (e.g. inside modals or drawers)
  13359. if (typeof MutationObserver !== 'undefined' && typeof document !== 'undefined') {
  13360. let docSortDebounce = null;
  13361. const docTableObserver = new MutationObserver((mutations) => {
  13362. let needsInit = false;
  13363. for (const m of mutations) {
  13364. for (const node of m.addedNodes) {
  13365. if (node.nodeType === 1) {
  13366. if (node.tagName === 'TABLE' && !node.closest('tbody, thead')) {
  13367. needsInit = true;
  13368. break;
  13369. } else if (node.querySelector && !node.closest('table') && node.querySelector('table')) {
  13370. needsInit = true;
  13371. break;
  13372. }
  13373. }
  13374. }
  13375. if (needsInit) break;
  13376. }
  13377. if (needsInit) {
  13378. clearTimeout(docSortDebounce);
  13379. docSortDebounce = setTimeout(initTableSorting, 100);
  13380. }
  13381. });
  13382. docTableObserver.observe(document.body || document.documentElement, { childList: true, subtree: true });
  13383. }
  13384. // =========================================================================
  13385. // BANDWIDTH TEST (BwTest) BENCHMARK ENGINE
  13386. // =========================================================================
  13387. const bwtestState = {
  13388. running: false,
  13389. pollTimer: null,
  13390. eventSource: null,
  13391. chartPoints: [],
  13392. maxChartPoints: 60,
  13393. serverConfig: null,
  13394. peakTx: 0,
  13395. peakRx: 0,
  13396. targetDuration: 10,
  13397. lastSampleIndex: 0
  13398. };
  13399. async function loadBwTestView() {
  13400. fetchBwTestServerStatus();
  13401. loadBwTestHistory();
  13402. resizeBwTestCanvas();
  13403. checkActiveBwTest();
  13404. }
  13405. async function fetchBwTestServerStatus() {
  13406. try {
  13407. const res = await fetch(`${API_BASE}/tools/bwtest/server`);
  13408. if (!res.ok) return;
  13409. const s = await res.json();
  13410. bwtestState.serverConfig = s;
  13411. // Update indicator and badges
  13412. const indicator = document.getElementById('bwtest-server-indicator');
  13413. const badge = document.getElementById('bwtest-server-badge');
  13414. const sideBadge = document.getElementById('badge-bwtest-server');
  13415. if (s.enabled && s.running) {
  13416. if (indicator) indicator.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  13417. if (badge) {
  13418. badge.innerText = `Port ${s.port} (Active)`;
  13419. badge.className = 'text-emerald-400 font-bold';
  13420. }
  13421. if (sideBadge) {
  13422. sideBadge.innerText = s.port;
  13423. 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';
  13424. }
  13425. } else {
  13426. if (indicator) indicator.className = 'w-2 h-2 rounded-full bg-slate-600';
  13427. if (badge) {
  13428. badge.innerText = `Disabled`;
  13429. badge.className = 'text-slate-500 font-bold';
  13430. }
  13431. if (sideBadge) {
  13432. sideBadge.innerText = 'Off';
  13433. sideBadge.className = 'text-[10px] bg-slate-800 text-slate-500 border border-slate-700 px-1.5 py-0.2 rounded-full font-mono';
  13434. }
  13435. }
  13436. // Modal fields
  13437. const toggle = document.getElementById('bwtest-server-enable-toggle');
  13438. if (toggle) toggle.checked = !!s.enabled;
  13439. const portInp = document.getElementById('bwtest-server-port-input');
  13440. if (portInp) portInp.value = s.port || 2000;
  13441. const actSess = document.getElementById('bwtest-modal-active-sessions');
  13442. if (actSess) actSess.innerText = s.active_sessions || 0;
  13443. const totServ = document.getElementById('bwtest-modal-total-served');
  13444. if (totServ) totServ.innerText = s.total_sessions_served || 0;
  13445. const totBytes = document.getElementById('bwtest-modal-total-bytes');
  13446. if (totBytes) totBytes.innerText = formatBytes(s.total_bytes_processed || 0);
  13447. } catch (err) {
  13448. console.error('Failed to fetch BwTest server status:', err);
  13449. }
  13450. }
  13451. function openBwTestServerModal() {
  13452. fetchBwTestServerStatus();
  13453. document.getElementById('modal-bwtest-server')?.classList.remove('hidden');
  13454. }
  13455. function closeBwTestServerModal() {
  13456. document.getElementById('modal-bwtest-server')?.classList.add('hidden');
  13457. }
  13458. async function submitBwTestServerSettings(e) {
  13459. e.preventDefault();
  13460. const enabled = document.getElementById('bwtest-server-enable-toggle').checked;
  13461. const port = parseInt(document.getElementById('bwtest-server-port-input').value, 10) || 2000;
  13462. try {
  13463. const res = await fetch(`${API_BASE}/tools/bwtest/server`, {
  13464. method: 'POST',
  13465. headers: { 'Content-Type': 'application/json' },
  13466. body: JSON.stringify({ enabled, port, listen_addr: '0.0.0.0', allow_anonymous: true })
  13467. });
  13468. if (!res.ok) {
  13469. const err = await res.json();
  13470. throw new Error(err.error || 'Failed to update server configuration');
  13471. }
  13472. showToast('BwTest Server', `Bandwidth Test server updated (Port ${port})`, 'success');
  13473. closeBwTestServerModal();
  13474. fetchBwTestServerStatus();
  13475. } catch (err) {
  13476. showToast('Server Configuration Error', err.message, 'error');
  13477. }
  13478. }
  13479. function setBwTestTarget(target) {
  13480. const inp = document.getElementById('bwtest-input-target');
  13481. if (inp) inp.value = target;
  13482. }
  13483. function setBwTestProtocol(proto) {
  13484. const hiddenInp = document.getElementById('bwtest-input-protocol');
  13485. if (hiddenInp) hiddenInp.value = proto;
  13486. const btnUdp = document.getElementById('bwtest-proto-udp');
  13487. const btnTcp = document.getElementById('bwtest-proto-tcp');
  13488. const badge = document.getElementById('bwtest-proto-badge');
  13489. const pktField = document.getElementById('bwtest-field-pktsize');
  13490. 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';
  13491. 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';
  13492. 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';
  13493. if (proto === 'udp') {
  13494. if (btnUdp) {
  13495. btnUdp.className = activeUdpCls;
  13496. const dot = btnUdp.querySelector('span');
  13497. if (dot) dot.className = 'w-2 h-2 rounded-full bg-emerald-400';
  13498. }
  13499. if (btnTcp) {
  13500. btnTcp.className = inactiveCls;
  13501. const dot = btnTcp.querySelector('span');
  13502. if (dot) dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  13503. }
  13504. if (badge) {
  13505. badge.innerText = 'UDP Mode (RFC 3550 Jitter + Loss %)';
  13506. badge.className = 'text-[10px] font-mono text-emerald-400 bg-emerald-500/10 px-2 py-0.5 rounded border border-emerald-500/20';
  13507. }
  13508. if (pktField) pktField.classList.remove('opacity-40');
  13509. } else {
  13510. if (btnUdp) {
  13511. btnUdp.className = inactiveCls;
  13512. const dot = btnUdp.querySelector('span');
  13513. if (dot) dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  13514. }
  13515. if (btnTcp) {
  13516. btnTcp.className = activeTcpCls;
  13517. const dot = btnTcp.querySelector('span');
  13518. if (dot) dot.className = 'w-2 h-2 rounded-full bg-blue-400';
  13519. }
  13520. if (badge) {
  13521. badge.innerText = 'TCP Mode (Sliding Window Throughput)';
  13522. badge.className = 'text-[10px] font-mono text-blue-400 bg-blue-500/10 px-2 py-0.5 rounded border border-blue-500/20';
  13523. }
  13524. if (pktField) pktField.classList.add('opacity-40');
  13525. }
  13526. }
  13527. function setBwTestDirection(dir) {
  13528. const hiddenInp = document.getElementById('bwtest-input-direction');
  13529. if (hiddenInp) hiddenInp.value = dir;
  13530. const btnBoth = document.getElementById('bwtest-dir-both');
  13531. const btnTx = document.getElementById('bwtest-dir-tx');
  13532. const btnRx = document.getElementById('bwtest-dir-rx');
  13533. 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';
  13534. 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';
  13535. if (btnBoth) btnBoth.className = dir === 'both' ? activeCls : inactiveCls;
  13536. if (btnTx) btnTx.className = dir === 'tx' ? activeCls : inactiveCls;
  13537. if (btnRx) btnRx.className = dir === 'rx' ? activeCls : inactiveCls;
  13538. }
  13539. function setBwTestLimit(bps) {
  13540. const sel = document.getElementById('bwtest-input-limit');
  13541. if (sel) sel.value = String(bps);
  13542. }
  13543. async function checkActiveBwTest() {
  13544. try {
  13545. const res = await fetch(`${API_BASE}/tools/bwtest/status`);
  13546. if (!res.ok) return;
  13547. const st = await res.json();
  13548. if (st.running) {
  13549. setBwTestRunningUI(true);
  13550. if (st.current_sample) handleBwTestSample(st.current_sample);
  13551. startBwTestTelemetry();
  13552. }
  13553. } catch (err) {
  13554. console.error('Failed to check active BwTest:', err);
  13555. }
  13556. }
  13557. async function startBwTest(e) {
  13558. if (e && e.preventDefault) e.preventDefault();
  13559. const target = document.getElementById('bwtest-input-target').value.trim() || '127.0.0.1';
  13560. const port = parseInt(document.getElementById('bwtest-input-port').value, 10) || 2000;
  13561. const direction = document.getElementById('bwtest-input-direction').value || 'both';
  13562. const protocol = document.getElementById('bwtest-input-protocol').value || 'udp';
  13563. const bandwidth_limit = parseInt(document.getElementById('bwtest-input-limit').value, 10) || 0;
  13564. const packet_size = parseInt(document.getElementById('bwtest-input-pktsize').value, 10) || 1472;
  13565. const streams = parseInt(document.getElementById('bwtest-input-streams').value, 10) || 1;
  13566. const duration = parseInt(document.getElementById('bwtest-input-duration').value, 10);
  13567. bwtestState.targetDuration = duration;
  13568. bwtestState.chartPoints = [];
  13569. bwtestState.peakTx = 0;
  13570. bwtestState.peakRx = 0;
  13571. bwtestState.lastSampleIndex = 0;
  13572. // Clear UI elements
  13573. document.getElementById('bwtest-stat-tx-mbps').innerText = '0.00';
  13574. document.getElementById('bwtest-stat-tx-peak').innerText = '0.00 Mbps';
  13575. document.getElementById('bwtest-stat-tx-pkts').innerText = '0';
  13576. document.getElementById('bwtest-stat-rx-mbps').innerText = '0.00';
  13577. document.getElementById('bwtest-stat-rx-peak').innerText = '0.00 Mbps';
  13578. document.getElementById('bwtest-stat-rx-pkts').innerText = '0';
  13579. document.getElementById('bwtest-stat-loss').innerText = '0.0%';
  13580. document.getElementById('bwtest-stat-jitter').innerText = '0.00 ms';
  13581. document.getElementById('bwtest-stat-time').innerText = '0.0s';
  13582. document.getElementById('bwtest-stat-data').innerText = '0.0 MB';
  13583. document.getElementById('bwtest-stat-target-dur').innerText = duration > 0 ? `/ ${duration}s` : '/ ∞';
  13584. const tbody = document.getElementById('bwtest-samples-tbody');
  13585. if (tbody) tbody.innerHTML = '';
  13586. document.getElementById('bwtest-sample-count').innerText = '0 samples';
  13587. setBwTestRunningUI(true);
  13588. try {
  13589. const res = await fetch(`${API_BASE}/tools/bwtest/start`, {
  13590. method: 'POST',
  13591. headers: { 'Content-Type': 'application/json' },
  13592. body: JSON.stringify({
  13593. target,
  13594. port,
  13595. direction,
  13596. protocol,
  13597. bandwidth_limit,
  13598. packet_size,
  13599. streams,
  13600. duration
  13601. })
  13602. });
  13603. if (!res.ok) {
  13604. const err = await res.json();
  13605. throw new Error(err.error || 'Failed to start bandwidth test');
  13606. }
  13607. showToast('Benchmark Started', `Target: ${target}:${port} (${direction.toUpperCase()}, ${protocol.toUpperCase()})`, 'info');
  13608. startBwTestTelemetry();
  13609. } catch (err) {
  13610. setBwTestRunningUI(false);
  13611. showToast('Start Failed', err.message, 'error');
  13612. }
  13613. }
  13614. function setBwTestRunningUI(running) {
  13615. bwtestState.running = running;
  13616. const startBtn = document.getElementById('bwtest-btn-start');
  13617. const stopBtn = document.getElementById('bwtest-btn-stop');
  13618. const badge = document.getElementById('bwtest-run-status-badge');
  13619. const ph = document.getElementById('bwtest-chart-placeholder');
  13620. if (running) {
  13621. if (startBtn) {
  13622. startBtn.disabled = true;
  13623. startBtn.classList.add('opacity-50', 'cursor-not-allowed');
  13624. }
  13625. if (stopBtn) {
  13626. stopBtn.disabled = false;
  13627. stopBtn.classList.remove('opacity-40');
  13628. }
  13629. if (badge) {
  13630. badge.innerText = 'TESTING...';
  13631. 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';
  13632. }
  13633. if (ph) ph.style.display = 'none';
  13634. } else {
  13635. if (startBtn) {
  13636. startBtn.disabled = false;
  13637. startBtn.classList.remove('opacity-50', 'cursor-not-allowed');
  13638. }
  13639. if (stopBtn) {
  13640. stopBtn.disabled = true;
  13641. stopBtn.classList.add('opacity-40');
  13642. }
  13643. if (badge) {
  13644. badge.innerText = 'IDLE';
  13645. badge.className = 'px-2 py-0.5 rounded text-[10px] font-mono bg-slate-800 text-slate-400 border border-slate-700 font-semibold';
  13646. }
  13647. }
  13648. }
  13649. async function stopBwTest() {
  13650. try {
  13651. await fetch(`${API_BASE}/tools/bwtest/stop`, { method: 'POST' });
  13652. showToast('Test Stopped', 'Bandwidth test terminated by user', 'info');
  13653. } catch (err) {
  13654. console.error('Failed to stop test:', err);
  13655. }
  13656. }
  13657. function startBwTestTelemetry() {
  13658. if (bwtestState.pollTimer) clearInterval(bwtestState.pollTimer);
  13659. bwtestState.pollTimer = setInterval(async () => {
  13660. try {
  13661. const res = await fetch(`${API_BASE}/tools/bwtest/status`);
  13662. if (!res.ok) return;
  13663. const st = await res.json();
  13664. if (st.recent_samples && st.recent_samples.length > 0) {
  13665. // Process new samples
  13666. const newSamples = st.recent_samples.slice(bwtestState.lastSampleIndex);
  13667. newSamples.forEach(s => handleBwTestSample(s));
  13668. bwtestState.lastSampleIndex = st.recent_samples.length;
  13669. }
  13670. if (!st.running) {
  13671. clearInterval(bwtestState.pollTimer);
  13672. bwtestState.pollTimer = null;
  13673. setBwTestRunningUI(false);
  13674. handleBwTestFinish(st.summary, st.error);
  13675. }
  13676. } catch (err) {
  13677. console.error('BwTest polling error:', err);
  13678. }
  13679. }, 400);
  13680. }
  13681. function handleBwTestSample(s) {
  13682. if (!s) return;
  13683. const txMbps = s.tx_mbps || 0;
  13684. const rxMbps = s.rx_mbps || 0;
  13685. if (txMbps > bwtestState.peakTx) bwtestState.peakTx = txMbps;
  13686. if (rxMbps > bwtestState.peakRx) bwtestState.peakRx = rxMbps;
  13687. // KPI updates
  13688. const elTx = document.getElementById('bwtest-stat-tx-mbps');
  13689. if (elTx) elTx.innerText = txMbps.toFixed(2);
  13690. const elTxPeak = document.getElementById('bwtest-stat-tx-peak');
  13691. if (elTxPeak) elTxPeak.innerText = `${bwtestState.peakTx.toFixed(2)} Mbps`;
  13692. const elTxPkts = document.getElementById('bwtest-stat-tx-pkts');
  13693. if (elTxPkts) elTxPkts.innerText = s.tx_packets || 0;
  13694. const elRx = document.getElementById('bwtest-stat-rx-mbps');
  13695. if (elRx) elRx.innerText = rxMbps.toFixed(2);
  13696. const elRxPeak = document.getElementById('bwtest-stat-rx-peak');
  13697. if (elRxPeak) elRxPeak.innerText = `${bwtestState.peakRx.toFixed(2)} Mbps`;
  13698. const elRxPkts = document.getElementById('bwtest-stat-rx-pkts');
  13699. if (elRxPkts) elRxPkts.innerText = s.rx_packets || 0;
  13700. const elLoss = document.getElementById('bwtest-stat-loss');
  13701. if (elLoss) {
  13702. elLoss.innerText = `${(s.loss_pct || 0).toFixed(1)}%`;
  13703. elLoss.className = (s.loss_pct > 1.0) ? 'text-2xl font-bold text-rose-400' : 'text-2xl font-bold text-emerald-400';
  13704. }
  13705. const elLostPkts = document.getElementById('bwtest-stat-lost-pkts');
  13706. if (elLostPkts) elLostPkts.innerText = s.lost_packets || 0;
  13707. const elJitter = document.getElementById('bwtest-stat-jitter');
  13708. if (elJitter) elJitter.innerText = `${(s.jitter_ms || 0).toFixed(2)} ms`;
  13709. const elTime = document.getElementById('bwtest-stat-time');
  13710. if (elTime) elTime.innerText = `${(s.elapsed_sec || 0).toFixed(1)}s`;
  13711. const elData = document.getElementById('bwtest-stat-data');
  13712. if (elData) elData.innerText = formatBytes((s.tx_bytes || 0) + (s.rx_bytes || 0));
  13713. const elGraphRate = document.getElementById('bwtest-graph-rate');
  13714. if (elGraphRate) elGraphRate.innerText = `TX: ${txMbps.toFixed(1)} Mbps • RX: ${rxMbps.toFixed(1)} Mbps`;
  13715. // Append point to chart buffer
  13716. bwtestState.chartPoints.push({
  13717. elapsed: s.elapsed_sec || 0,
  13718. tx: txMbps,
  13719. rx: rxMbps
  13720. });
  13721. if (bwtestState.chartPoints.length > bwtestState.maxChartPoints) {
  13722. bwtestState.chartPoints.shift();
  13723. }
  13724. drawBwTestChart();
  13725. // Add row to breakdown table
  13726. const tbody = document.getElementById('bwtest-samples-tbody');
  13727. if (tbody) {
  13728. const tr = document.createElement('tr');
  13729. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  13730. tr.innerHTML = `
  13731. <td class="py-1.5 px-3 font-semibold text-white">${(s.elapsed_sec || 0).toFixed(1)}s</td>
  13732. <td class="py-1.5 px-3 font-bold text-cyan-400">${txMbps.toFixed(2)} Mbps</td>
  13733. <td class="py-1.5 px-3 font-bold text-purple-400">${rxMbps.toFixed(2)} Mbps</td>
  13734. <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>
  13735. <td class="py-1.5 px-3 text-slate-300">${(s.jitter_ms || 0).toFixed(2)} ms</td>
  13736. <td class="py-1.5 px-3 text-slate-400">${formatBytes((s.tx_bytes || 0) + (s.rx_bytes || 0))}</td>
  13737. `;
  13738. tbody.insertBefore(tr, tbody.firstChild);
  13739. const countEl = document.getElementById('bwtest-sample-count');
  13740. if (countEl) countEl.innerText = `${tbody.children.length} samples`;
  13741. }
  13742. }
  13743. function handleBwTestFinish(summary, error) {
  13744. const badge = document.getElementById('bwtest-run-status-badge');
  13745. if (error) {
  13746. showToast('Benchmark Error', error, 'error');
  13747. if (badge) {
  13748. badge.innerText = 'ERROR';
  13749. 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';
  13750. }
  13751. } else if (summary) {
  13752. const avgTx = summary.avg_tx_mbps.toFixed(1);
  13753. const avgRx = summary.avg_rx_mbps.toFixed(1);
  13754. showToast('Benchmark Complete', `Average TX: ${avgTx} Mbps | RX: ${avgRx} Mbps (Loss: ${summary.avg_loss_pct.toFixed(1)}%)`, 'success');
  13755. if (badge) {
  13756. badge.innerText = 'COMPLETED';
  13757. 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';
  13758. }
  13759. }
  13760. loadBwTestHistory();
  13761. fetchBwTestServerStatus();
  13762. }
  13763. function resizeBwTestCanvas() {
  13764. const canvas = document.getElementById('bwtest-chart');
  13765. if (!canvas || !canvas.parentElement) return;
  13766. const rect = canvas.parentElement.getBoundingClientRect();
  13767. const dpr = window.devicePixelRatio || 1;
  13768. canvas.width = rect.width * dpr;
  13769. canvas.height = rect.height * dpr;
  13770. const ctx = canvas.getContext('2d');
  13771. ctx.scale(dpr, dpr);
  13772. drawBwTestChart();
  13773. }
  13774. window.addEventListener('resize', () => {
  13775. if (state.activeTab === 'bwtest') resizeBwTestCanvas();
  13776. });
  13777. function drawBwTestChart() {
  13778. const canvas = document.getElementById('bwtest-chart');
  13779. if (!canvas) return;
  13780. const ctx = canvas.getContext('2d');
  13781. const dpr = window.devicePixelRatio || 1;
  13782. const width = canvas.width / dpr;
  13783. const height = canvas.height / dpr;
  13784. ctx.clearRect(0, 0, width, height);
  13785. const points = bwtestState.chartPoints;
  13786. if (!points || points.length === 0) return;
  13787. // Determine scale ceiling
  13788. let maxRate = 10;
  13789. for (const p of points) {
  13790. if (p.tx > maxRate) maxRate = p.tx;
  13791. if (p.rx > maxRate) maxRate = p.rx;
  13792. }
  13793. maxRate = Math.ceil(maxRate * 1.25); // 25% headroom
  13794. const paddingLeft = 55;
  13795. const paddingBottom = 24;
  13796. const paddingTop = 12;
  13797. const paddingRight = 16;
  13798. const chartW = width - paddingLeft - paddingRight;
  13799. const chartH = height - paddingTop - paddingBottom;
  13800. // Grid Lines and Y-Axis labels
  13801. ctx.strokeStyle = 'rgba(51, 65, 85, 0.4)';
  13802. ctx.lineWidth = 1;
  13803. ctx.fillStyle = '#94a3b8';
  13804. ctx.font = '10px monospace';
  13805. ctx.textAlign = 'right';
  13806. const gridSteps = 4;
  13807. for (let i = 0; i <= gridSteps; i++) {
  13808. const val = (maxRate / gridSteps) * i;
  13809. const y = paddingTop + chartH - (i / gridSteps) * chartH;
  13810. ctx.beginPath();
  13811. ctx.moveTo(paddingLeft, y);
  13812. ctx.lineTo(width - paddingRight, y);
  13813. ctx.stroke();
  13814. ctx.fillText(`${Math.round(val)}M`, paddingLeft - 8, y + 3);
  13815. }
  13816. // Draw TX Line (Cyan #22d3ee)
  13817. drawSeries(ctx, points, p => p.tx, maxRate, paddingLeft, paddingTop, chartW, chartH, '#22d3ee', 'rgba(34, 211, 238, 0.15)');
  13818. // Draw RX Line (Purple #a855f7)
  13819. drawSeries(ctx, points, p => p.rx, maxRate, paddingLeft, paddingTop, chartW, chartH, '#a855f7', 'rgba(168, 85, 247, 0.15)');
  13820. }
  13821. function drawSeries(ctx, points, valFn, maxVal, left, top, w, h, strokeColor, fillColor) {
  13822. if (points.length < 2) return;
  13823. const stepX = w / Math.max(points.length - 1, 1);
  13824. // Gradient area fill
  13825. const grad = ctx.createLinearGradient(0, top, 0, top + h);
  13826. grad.addColorStop(0, fillColor);
  13827. grad.addColorStop(1, 'rgba(0, 0, 0, 0)');
  13828. ctx.beginPath();
  13829. points.forEach((p, idx) => {
  13830. const x = left + idx * stepX;
  13831. const val = valFn(p);
  13832. const y = top + h - (val / maxVal) * h;
  13833. if (idx === 0) {
  13834. ctx.moveTo(x, y);
  13835. } else {
  13836. ctx.lineTo(x, y);
  13837. }
  13838. });
  13839. // Complete path for fill
  13840. ctx.lineTo(left + (points.length - 1) * stepX, top + h);
  13841. ctx.lineTo(left, top + h);
  13842. ctx.closePath();
  13843. ctx.fillStyle = grad;
  13844. ctx.fill();
  13845. // Draw line stroke
  13846. ctx.beginPath();
  13847. ctx.lineWidth = 2.5;
  13848. ctx.strokeStyle = strokeColor;
  13849. points.forEach((p, idx) => {
  13850. const x = left + idx * stepX;
  13851. const val = valFn(p);
  13852. const y = top + h - (val / maxVal) * h;
  13853. if (idx === 0) {
  13854. ctx.moveTo(x, y);
  13855. } else {
  13856. ctx.lineTo(x, y);
  13857. }
  13858. });
  13859. ctx.stroke();
  13860. // Draw end point halo
  13861. const lastP = points[points.length - 1];
  13862. const lastX = left + (points.length - 1) * stepX;
  13863. const lastY = top + h - (valFn(lastP) / maxVal) * h;
  13864. ctx.fillStyle = strokeColor;
  13865. ctx.beginPath();
  13866. ctx.arc(lastX, lastY, 4, 0, 2 * Math.PI);
  13867. ctx.fill();
  13868. }
  13869. async function loadBwTestHistory() {
  13870. try {
  13871. const res = await fetch(`${API_BASE}/tools/bwtest/history`);
  13872. if (!res.ok) return;
  13873. const list = await res.json();
  13874. renderBwTestHistory(Array.isArray(list) ? list : []);
  13875. } catch (err) {
  13876. console.error('Failed to load BwTest history:', err);
  13877. }
  13878. }
  13879. function renderBwTestHistory(list) {
  13880. const tbody = document.getElementById('bwtest-history-tbody');
  13881. if (!tbody) return;
  13882. if (list.length === 0) {
  13883. 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>`;
  13884. return;
  13885. }
  13886. tbody.innerHTML = '';
  13887. list.forEach(item => {
  13888. const s = item.summary || {};
  13889. const tr = document.createElement('tr');
  13890. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  13891. const dirBadge = item.direction === 'both'
  13892. ? `<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>`
  13893. : item.direction === 'tx'
  13894. ? `<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>`
  13895. : `<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>`;
  13896. const protoBadge = item.protocol === 'tcp'
  13897. ? `<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>`
  13898. : `<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>`;
  13899. const dateStr = item.timestamp ? new Date(item.timestamp).toLocaleString() : '-';
  13900. tr.innerHTML = `
  13901. <td class="py-2.5 px-4 font-bold text-white font-mono text-[11px]">${escapeHtml(item.id || '-')}</td>
  13902. <td class="py-2.5 px-4 text-emerald-400 font-mono font-medium">${escapeHtml(item.target || '-')}</td>
  13903. <td class="py-2.5 px-4">${protoBadge}</td>
  13904. <td class="py-2.5 px-4">${dirBadge}</td>
  13905. <td class="py-2.5 px-4 text-slate-300">${(s.duration_sec || 0).toFixed(1)}s</td>
  13906. <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>
  13907. <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>
  13908. <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>
  13909. <td class="py-2.5 px-4 text-slate-300 font-mono">${(s.avg_jitter_ms || 0).toFixed(2)} ms</td>
  13910. <td class="py-2.5 px-4 text-slate-400 text-[11px] font-sans">${escapeHtml(dateStr)}</td>
  13911. `;
  13912. tbody.appendChild(tr);
  13913. });
  13914. }
  13915. // ======================== SETTINGS & ROUTER DNS ========================
  13916. state.settingsSubTab = 'dns';
  13917. state.dnsSettings = null;
  13918. state.dnsStaticRecords = [];
  13919. state.dnsStatus = null;
  13920. function switchSettingsSubTab(sub) {
  13921. state.settingsSubTab = sub;
  13922. const btnDns = document.getElementById('btn-settings-subtab-dns');
  13923. const btnSys = document.getElementById('btn-settings-subtab-system');
  13924. const tabDns = document.getElementById('settings-subtab-dns');
  13925. const tabSys = document.getElementById('settings-subtab-system');
  13926. if (sub === 'dns') {
  13927. if (btnDns) {
  13928. 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';
  13929. }
  13930. if (btnSys) {
  13931. 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';
  13932. }
  13933. tabDns?.classList.remove('hidden');
  13934. tabSys?.classList.add('hidden');
  13935. loadDNSSettings();
  13936. } else {
  13937. if (btnSys) {
  13938. 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';
  13939. }
  13940. if (btnDns) {
  13941. 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';
  13942. }
  13943. tabSys?.classList.remove('hidden');
  13944. tabDns?.classList.add('hidden');
  13945. loadSystemSettings();
  13946. }
  13947. }
  13948. async function loadSettingsData(showLoading = false) {
  13949. if (state.settingsSubTab === 'system') {
  13950. await loadSystemSettings();
  13951. } else {
  13952. await loadDNSSettings();
  13953. }
  13954. }
  13955. async function loadDNSSettings() {
  13956. try {
  13957. const [settingsRes, staticRes, statusRes] = await Promise.all([
  13958. fetch(`${API_BASE}/dns/settings`),
  13959. fetch(`${API_BASE}/dns/static`),
  13960. fetch(`${API_BASE}/dns/status`)
  13961. ]);
  13962. if (settingsRes.ok) {
  13963. state.dnsSettings = await settingsRes.json();
  13964. populateDNSSettingsForm(state.dnsSettings);
  13965. }
  13966. if (staticRes.ok) {
  13967. state.dnsStaticRecords = await staticRes.json();
  13968. renderStaticDNSList();
  13969. }
  13970. if (statusRes.ok) {
  13971. state.dnsStatus = await statusRes.json();
  13972. updateDNSStatusView(state.dnsStatus);
  13973. }
  13974. } catch (err) {
  13975. console.error('Failed to load DNS settings:', err);
  13976. }
  13977. }
  13978. function populateDNSSettingsForm(s) {
  13979. if (!s) return;
  13980. const dnsForm = document.getElementById('form-dns-settings');
  13981. const isEditing = dnsForm && (dnsForm.contains(document.activeElement) || dnsForm.dataset.dirty === 'true');
  13982. const dynamicEl = document.getElementById('dns-dynamic-servers-list');
  13983. if (dynamicEl) {
  13984. if (Array.isArray(s.dynamic_servers) && s.dynamic_servers.length > 0) {
  13985. 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(' ');
  13986. } else {
  13987. dynamicEl.innerText = 'None';
  13988. }
  13989. }
  13990. // If user is actively typing or editing in the form, do not overwrite their inputs!
  13991. if (isEditing) return;
  13992. const serversInput = document.getElementById('dns-servers-input');
  13993. if (serversInput) serversInput.value = (s.servers || []).join(', ');
  13994. const cacheSizeInput = document.getElementById('dns-cache-size-input');
  13995. if (cacheSizeInput) cacheSizeInput.value = s.cache_size || 2048;
  13996. const domainInput = document.getElementById('dns-domain-input');
  13997. if (domainInput) domainInput.value = s.domain || '';
  13998. const allowRemoteInput = document.getElementById('dns-allow-remote-input');
  13999. if (allowRemoteInput) allowRemoteInput.checked = s.allow_remote_requests !== false;
  14000. }
  14001. function updateDNSStatusView(st) {
  14002. if (!st) return;
  14003. const preview = document.getElementById('dns-resolv-preview');
  14004. if (preview) preview.innerText = st.resolv_conf_content || '(empty)';
  14005. const pillText = document.getElementById('dns-live-status-text');
  14006. const pill = document.getElementById('dns-live-status-pill');
  14007. if (pill && pillText) {
  14008. if (st.service_running) {
  14009. 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';
  14010. pillText.innerText = 'DNS Service Active';
  14011. } else {
  14012. 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';
  14013. pillText.innerText = 'DNS Service Inactive';
  14014. }
  14015. }
  14016. }
  14017. function appendDNSPreset(preset) {
  14018. const input = document.getElementById('dns-servers-input');
  14019. if (!input) return;
  14020. const dnsForm = document.getElementById('form-dns-settings');
  14021. if (dnsForm) dnsForm.dataset.dirty = 'true';
  14022. const current = input.value.trim();
  14023. if (!current) {
  14024. input.value = preset;
  14025. } else {
  14026. const existing = current.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  14027. const toAdd = preset.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  14028. toAdd.forEach(ip => {
  14029. if (!existing.includes(ip)) existing.push(ip);
  14030. });
  14031. input.value = existing.join(', ');
  14032. }
  14033. }
  14034. async function saveDNSSettings(e) {
  14035. e.preventDefault();
  14036. const rawServers = document.getElementById('dns-servers-input')?.value || '';
  14037. const servers = rawServers.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  14038. if (servers.length === 0) {
  14039. showToast('Validation Error', 'Please enter at least one upstream DNS server IP', 'error');
  14040. return;
  14041. }
  14042. const cacheSize = parseInt(document.getElementById('dns-cache-size-input')?.value || '2048', 10);
  14043. const domain = (document.getElementById('dns-domain-input')?.value || '').trim();
  14044. const allowRemote = document.getElementById('dns-allow-remote-input')?.checked ?? true;
  14045. try {
  14046. const res = await fetch(`${API_BASE}/dns/settings`, {
  14047. method: 'POST',
  14048. headers: { 'Content-Type': 'application/json' },
  14049. body: JSON.stringify({
  14050. servers: servers,
  14051. cache_size: cacheSize,
  14052. domain: domain,
  14053. allow_remote_requests: allowRemote
  14054. })
  14055. });
  14056. const data = await res.json();
  14057. if (res.ok) {
  14058. const dnsForm = document.getElementById('form-dns-settings');
  14059. if (dnsForm) dnsForm.dataset.dirty = 'false';
  14060. showToast('DNS Applied', 'Router DNS forwarders and resolver settings updated successfully', 'success');
  14061. loadDNSSettings();
  14062. } else {
  14063. showToast('Error', data.error || data.message || 'Failed to save DNS settings', 'error');
  14064. }
  14065. } catch (err) {
  14066. showToast('Error', err.message, 'error');
  14067. }
  14068. }
  14069. async function flushDNSCache() {
  14070. try {
  14071. const res = await fetch(`${API_BASE}/dns/flush`, { method: 'POST' });
  14072. if (res.ok) {
  14073. showToast('Cache Flushed', 'Router DNS cache cleared and static hosts reloaded', 'success');
  14074. loadDNSSettings();
  14075. } else {
  14076. const err = await res.json();
  14077. showToast('Error', err.error || 'Failed to flush cache', 'error');
  14078. }
  14079. } catch (err) {
  14080. showToast('Error', err.message, 'error');
  14081. }
  14082. }
  14083. function renderStaticDNSList() {
  14084. const tbody = document.getElementById('dns-static-tbody');
  14085. const empty = document.getElementById('dns-static-empty');
  14086. const badge = document.getElementById('dns-static-count-badge');
  14087. if (!tbody) return;
  14088. tbody.innerHTML = '';
  14089. const records = state.dnsStaticRecords || [];
  14090. if (badge) badge.innerText = `${records.length} Records`;
  14091. if (records.length === 0) {
  14092. empty?.classList.remove('hidden');
  14093. return;
  14094. }
  14095. empty?.classList.add('hidden');
  14096. records.forEach(rec => {
  14097. const tr = document.createElement('tr');
  14098. tr.className = `hover:bg-slate-800/40 transition text-xs ${rec.disabled ? 'opacity-50' : ''}`;
  14099. tr.innerHTML = `
  14100. <td class="py-2.5 px-4 font-bold text-white">${escapeHtml(rec.name)}</td>
  14101. <td class="py-2.5 px-4">
  14102. <span class="px-2 py-0.5 rounded text-[10px] font-bold ${
  14103. rec.type === 'CNAME' ? 'bg-purple-950 text-purple-300 border border-purple-800' :
  14104. (rec.type === 'AAAA' ? 'bg-blue-950 text-blue-300 border border-blue-800' : 'bg-cyan-950 text-cyan-300 border border-cyan-800')
  14105. }">
  14106. ${rec.type || 'A'}
  14107. </span>
  14108. </td>
  14109. <td class="py-2.5 px-4 text-emerald-400 font-mono">${escapeHtml(rec.address)}</td>
  14110. <td class="py-2.5 px-4 text-slate-400 font-mono">${rec.ttl || 3600}s</td>
  14111. <td class="py-2.5 px-4 text-slate-400 italic truncate max-w-[140px]">${escapeHtml(rec.comment || '-')}</td>
  14112. <td class="py-2.5 px-4">
  14113. <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'}">
  14114. ${rec.disabled ? 'Disabled' : 'Active'}
  14115. </span>
  14116. </td>
  14117. <td class="py-2.5 px-4 text-right space-x-2 font-sans whitespace-nowrap">
  14118. <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>
  14119. <button onclick="openStaticDNSModal('${rec.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold">Edit</button>
  14120. <button onclick="deleteStaticDNS('${rec.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  14121. </td>
  14122. `;
  14123. tbody.appendChild(tr);
  14124. });
  14125. }
  14126. function openStaticDNSModal(id = null) {
  14127. const modal = document.getElementById('modal-static-dns');
  14128. const title = document.getElementById('modal-static-dns-title');
  14129. const form = document.getElementById('form-static-dns');
  14130. if (!modal || !form) return;
  14131. form.reset();
  14132. document.getElementById('modal-static-dns-id').value = '';
  14133. if (id) {
  14134. const rec = (state.dnsStaticRecords || []).find(r => r.id === id);
  14135. if (rec) {
  14136. if (title) title.innerText = 'Edit Static DNS Record';
  14137. document.getElementById('modal-static-dns-id').value = rec.id;
  14138. document.getElementById('modal-static-dns-name').value = rec.name;
  14139. document.getElementById('modal-static-dns-type').value = rec.type || 'A';
  14140. document.getElementById('modal-static-dns-addr').value = rec.address;
  14141. document.getElementById('modal-static-dns-ttl').value = rec.ttl || 3600;
  14142. document.getElementById('modal-static-dns-comment').value = rec.comment || '';
  14143. document.getElementById('modal-static-dns-disabled').checked = !!rec.disabled;
  14144. }
  14145. } else {
  14146. if (title) title.innerText = 'Add Static DNS Record';
  14147. }
  14148. modal.classList.remove('hidden');
  14149. }
  14150. function closeStaticDNSModal() {
  14151. document.getElementById('modal-static-dns')?.classList.add('hidden');
  14152. }
  14153. async function submitSaveStaticDNS(e) {
  14154. e.preventDefault();
  14155. const id = document.getElementById('modal-static-dns-id')?.value || '';
  14156. const name = (document.getElementById('modal-static-dns-name')?.value || '').trim();
  14157. const type = document.getElementById('modal-static-dns-type')?.value || 'A';
  14158. const address = (document.getElementById('modal-static-dns-addr')?.value || '').trim();
  14159. const ttl = parseInt(document.getElementById('modal-static-dns-ttl')?.value || '3600', 10);
  14160. const comment = (document.getElementById('modal-static-dns-comment')?.value || '').trim();
  14161. const disabled = document.getElementById('modal-static-dns-disabled')?.checked ?? false;
  14162. if (!name || !address) {
  14163. showToast('Validation Error', 'Name and Target Address are required', 'error');
  14164. return;
  14165. }
  14166. try {
  14167. const res = await fetch(`${API_BASE}/dns/static`, {
  14168. method: 'POST',
  14169. headers: { 'Content-Type': 'application/json' },
  14170. body: JSON.stringify({ id, name, type, address, ttl, comment, disabled })
  14171. });
  14172. const data = await res.json();
  14173. if (res.ok) {
  14174. showToast('Static DNS Saved', `Saved record ${name} -> ${address}`, 'success');
  14175. closeStaticDNSModal();
  14176. loadDNSSettings();
  14177. } else {
  14178. showToast('Error', data.error || data.message || 'Failed to save record', 'error');
  14179. }
  14180. } catch (err) {
  14181. showToast('Error', err.message, 'error');
  14182. }
  14183. }
  14184. async function deleteStaticDNS(id) {
  14185. if (!confirm('Are you sure you want to delete this static DNS entry?')) return;
  14186. try {
  14187. const res = await fetch(`${API_BASE}/dns/static/${encodeURIComponent(id)}`, { method: 'DELETE' });
  14188. if (res.ok) {
  14189. showToast('Deleted', 'Static DNS record deleted', 'success');
  14190. loadDNSSettings();
  14191. }
  14192. } catch (err) {
  14193. showToast('Error', err.message, 'error');
  14194. }
  14195. }
  14196. async function toggleStaticDNS(id, disabled) {
  14197. try {
  14198. const res = await fetch(`${API_BASE}/dns/static/${encodeURIComponent(id)}/state`, {
  14199. method: 'POST',
  14200. headers: { 'Content-Type': 'application/json' },
  14201. body: JSON.stringify({ disabled })
  14202. });
  14203. if (res.ok) {
  14204. showToast('Updated', `Record ${disabled ? 'disabled' : 'enabled'}`, 'success');
  14205. loadDNSSettings();
  14206. }
  14207. } catch (err) {
  14208. showToast('Error', err.message, 'error');
  14209. }
  14210. }
  14211. async function loadSystemSettings() {
  14212. try {
  14213. const sysForm = document.getElementById('form-system-settings');
  14214. const isEditing = sysForm && (sysForm.contains(document.activeElement) || sysForm.dataset.dirty === 'true');
  14215. const res = await fetch(`${API_BASE}/system/settings`);
  14216. if (res.ok) {
  14217. const data = await res.json();
  14218. if (!isEditing) {
  14219. const hostInput = document.getElementById('system-hostname-input');
  14220. if (hostInput) hostInput.value = data.hostname || '';
  14221. const tzInput = document.getElementById('system-timezone-input');
  14222. if (tzInput && data.timezone) tzInput.value = data.timezone;
  14223. }
  14224. }
  14225. } catch (err) {
  14226. console.error('Failed to load system settings:', err);
  14227. }
  14228. }
  14229. async function saveSystemSettings(e) {
  14230. e.preventDefault();
  14231. const hostname = (document.getElementById('system-hostname-input')?.value || '').trim();
  14232. const timezone = document.getElementById('system-timezone-input')?.value || 'UTC';
  14233. try {
  14234. const res = await fetch(`${API_BASE}/system/settings`, {
  14235. method: 'POST',
  14236. headers: { 'Content-Type': 'application/json' },
  14237. body: JSON.stringify({ hostname, timezone })
  14238. });
  14239. const data = await res.json();
  14240. if (res.ok) {
  14241. const sysForm = document.getElementById('form-system-settings');
  14242. if (sysForm) sysForm.dataset.dirty = 'false';
  14243. showToast('System Updated', 'Hostname and timezone saved successfully', 'success');
  14244. const sideH = document.getElementById('side-hostname');
  14245. if (sideH) sideH.innerText = data.hostname;
  14246. } else {
  14247. showToast('Error', data.error || 'Failed to save system settings', 'error');
  14248. }
  14249. } catch (err) {
  14250. showToast('Error', err.message, 'error');
  14251. }
  14252. }
  14253. // =============================================================================
  14254. // AUTHENTICATION & USER MANAGER
  14255. // =============================================================================
  14256. async function checkAuthStatus() {
  14257. try {
  14258. const res = await originalFetch(`${API_BASE}/auth/me`, {
  14259. headers: {
  14260. 'Authorization': `Bearer ${localStorage.getItem('debtik_token') || ''}`
  14261. }
  14262. });
  14263. if (res.ok) {
  14264. const user = await res.json();
  14265. state.currentUser = user;
  14266. updateUserProfileHeader(user);
  14267. hideLoginScreen();
  14268. state.isPolling = true;
  14269. fetchData();
  14270. initLiveTrafficStream();
  14271. return true;
  14272. } else {
  14273. showLoginScreen(false);
  14274. return false;
  14275. }
  14276. } catch (err) {
  14277. showLoginScreen(false);
  14278. return false;
  14279. }
  14280. }
  14281. function showLoginScreen(isExpired = false) {
  14282. const el = document.getElementById('login-screen');
  14283. if (el) el.classList.remove('hidden');
  14284. const errEl = document.getElementById('login-error');
  14285. const errTxt = document.getElementById('login-error-text');
  14286. if (isExpired && errEl && errTxt) {
  14287. errTxt.innerText = 'Session expired. Please sign in again.';
  14288. errEl.classList.remove('hidden');
  14289. } else if (errEl) {
  14290. errEl.classList.add('hidden');
  14291. }
  14292. const pwInput = document.getElementById('login-password');
  14293. if (pwInput) pwInput.value = '';
  14294. const userInput = document.getElementById('login-username');
  14295. if (userInput && !userInput.value) userInput.focus();
  14296. else if (pwInput) pwInput.focus();
  14297. }
  14298. function hideLoginScreen() {
  14299. const el = document.getElementById('login-screen');
  14300. if (el) el.classList.add('hidden');
  14301. const errEl = document.getElementById('login-error');
  14302. if (errEl) errEl.classList.add('hidden');
  14303. }
  14304. async function handleLoginSubmit(event) {
  14305. event.preventDefault();
  14306. const username = (document.getElementById('login-username')?.value || '').trim();
  14307. const password = document.getElementById('login-password')?.value || '';
  14308. const errEl = document.getElementById('login-error');
  14309. const errTxt = document.getElementById('login-error-text');
  14310. const btn = document.getElementById('login-submit-btn');
  14311. const btnText = document.getElementById('login-btn-text');
  14312. const spinner = document.getElementById('login-btn-spinner');
  14313. if (!username || !password) {
  14314. if (errTxt) errTxt.innerText = 'Username and password are required.';
  14315. if (errEl) errEl.classList.remove('hidden');
  14316. return;
  14317. }
  14318. if (errEl) errEl.classList.add('hidden');
  14319. if (btn) btn.disabled = true;
  14320. if (btnText) btnText.innerText = 'Authenticating...';
  14321. if (spinner) spinner.classList.remove('hidden');
  14322. try {
  14323. const res = await originalFetch(`${API_BASE}/auth/login`, {
  14324. method: 'POST',
  14325. headers: { 'Content-Type': 'application/json' },
  14326. body: JSON.stringify({ username, password })
  14327. });
  14328. const data = await res.json();
  14329. if (res.ok && data.success) {
  14330. localStorage.setItem('debtik_token', data.token);
  14331. state.currentUser = data.user;
  14332. updateUserProfileHeader(data.user);
  14333. hideLoginScreen();
  14334. state.isPolling = true;
  14335. showToast('Authenticated', `Signed in as ${data.user.username}`, 'success');
  14336. const hash = window.location.hash.replace('#', '') || 'dashboard';
  14337. navigate(hash);
  14338. fetchData();
  14339. initLiveTrafficStream();
  14340. // Ensure background telemetry polling is active
  14341. if (!window._telemetryInterval) {
  14342. window._telemetryInterval = setInterval(() => {
  14343. if (state.isPolling && state.currentUser) {
  14344. fetchData(false);
  14345. }
  14346. }, 5000);
  14347. }
  14348. } else {
  14349. if (errTxt) errTxt.innerText = data.message || 'Invalid username or password';
  14350. if (errEl) errEl.classList.remove('hidden');
  14351. }
  14352. } catch (err) {
  14353. if (errTxt) errTxt.innerText = err.message || 'Failed to connect to router';
  14354. if (errEl) errEl.classList.remove('hidden');
  14355. } finally {
  14356. if (btn) btn.disabled = false;
  14357. if (btnText) btnText.innerText = 'Sign In to Controller';
  14358. if (spinner) spinner.classList.add('hidden');
  14359. }
  14360. }
  14361. async function handleLogoutClick() {
  14362. try {
  14363. await originalFetch(`${API_BASE}/auth/logout`, {
  14364. method: 'POST',
  14365. headers: {
  14366. 'Authorization': `Bearer ${localStorage.getItem('debtik_token') || ''}`
  14367. }
  14368. });
  14369. } catch (e) {}
  14370. localStorage.removeItem('debtik_token');
  14371. state.currentUser = null;
  14372. state.isPolling = false;
  14373. if (window._telemetryInterval) {
  14374. clearInterval(window._telemetryInterval);
  14375. window._telemetryInterval = null;
  14376. }
  14377. if (trafficEventSource) {
  14378. trafficEventSource.close();
  14379. trafficEventSource = null;
  14380. }
  14381. if (trafficPollFallback) {
  14382. clearInterval(trafficPollFallback);
  14383. trafficPollFallback = null;
  14384. }
  14385. showLoginScreen(false);
  14386. showToast('Signed Out', 'You have been signed out successfully', 'info');
  14387. }
  14388. function togglePasswordVisibility(id) {
  14389. const input = document.getElementById(id);
  14390. if (!input) return;
  14391. input.type = input.type === 'password' ? 'text' : 'password';
  14392. }
  14393. function toggleUserMenu() {
  14394. const menu = document.getElementById('user-menu-dropdown');
  14395. if (menu) menu.classList.toggle('hidden');
  14396. }
  14397. function closeUserMenu() {
  14398. const menu = document.getElementById('user-menu-dropdown');
  14399. if (menu) menu.classList.add('hidden');
  14400. }
  14401. // Close user menu on outside click
  14402. document.addEventListener('click', (e) => {
  14403. const menu = document.getElementById('user-menu-dropdown');
  14404. if (!menu || menu.classList.contains('hidden')) return;
  14405. if (!e.target.closest('#user-menu-dropdown') && !e.target.closest('button[onclick*="toggleUserMenu"]')) {
  14406. menu.classList.add('hidden');
  14407. }
  14408. });
  14409. function updateUserProfileHeader(user) {
  14410. if (!user) return;
  14411. const navName = document.getElementById('nav-user-name');
  14412. if (navName) navName.innerText = user.username;
  14413. const dropName = document.getElementById('dropdown-user-name');
  14414. if (dropName) dropName.innerText = user.username;
  14415. const navRole = document.getElementById('nav-user-role');
  14416. if (navRole) navRole.innerText = (user.role || 'read').toUpperCase();
  14417. const navAvatar = document.getElementById('nav-user-avatar');
  14418. if (navAvatar) {
  14419. const initials = (user.username || 'AD').slice(0, 2).toUpperCase();
  14420. navAvatar.innerText = initials;
  14421. }
  14422. const statCurUser = document.getElementById('stat-current-user');
  14423. if (statCurUser) statCurUser.innerText = user.username;
  14424. const statCurRole = document.getElementById('stat-current-role');
  14425. if (statCurRole) statCurRole.innerText = (user.role || 'read').toUpperCase();
  14426. // Role permissions UI visibility: hide user management for non-admins
  14427. const isFullAdmin = user.role === 'full';
  14428. const navUsers = document.getElementById('nav-users');
  14429. if (navUsers) {
  14430. if (isFullAdmin) navUsers.classList.remove('hidden');
  14431. else navUsers.classList.add('hidden');
  14432. }
  14433. const dropdownUsers = document.getElementById('dropdown-item-users');
  14434. if (dropdownUsers) {
  14435. if (isFullAdmin) dropdownUsers.classList.remove('hidden');
  14436. else dropdownUsers.classList.add('hidden');
  14437. }
  14438. }
  14439. // ================= User Management CRUD =================
  14440. async function loadUsers(isManual = false) {
  14441. try {
  14442. const res = await fetch(`${API_BASE}/users`);
  14443. if (res.status === 403) {
  14444. const tbody = document.getElementById('users-table-tbody');
  14445. if (tbody) {
  14446. tbody.innerHTML = `
  14447. <tr>
  14448. <td colspan="6" class="p-6 text-center text-amber-400 font-sans">
  14449. <div class="inline-flex items-center gap-2">
  14450. <svg class="w-5 h-5 text-amber-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"/></svg>
  14451. <span>Viewing and managing users requires Super Administrator (full) permissions.</span>
  14452. </div>
  14453. </td>
  14454. </tr>
  14455. `;
  14456. }
  14457. return;
  14458. }
  14459. if (res.ok) {
  14460. state.users = await res.json();
  14461. renderUsersTable();
  14462. const totalUsers = document.getElementById('stat-total-users');
  14463. if (totalUsers) totalUsers.innerText = state.users.length;
  14464. const adminCount = state.users.filter(u => u.role === 'full' && !u.disabled).length;
  14465. const adminUsers = document.getElementById('stat-admin-users');
  14466. if (adminUsers) adminUsers.innerText = adminCount;
  14467. const badgeCount = document.getElementById('badge-users-count');
  14468. if (badgeCount) badgeCount.innerText = state.users.length;
  14469. if (isManual) showToast('Refreshed', 'User list updated', 'info');
  14470. }
  14471. } catch (err) {
  14472. console.error('Failed to load users:', err);
  14473. }
  14474. }
  14475. function renderUsersTable() {
  14476. const tbody = document.getElementById('users-table-tbody');
  14477. const emptyState = document.getElementById('users-empty-state');
  14478. if (!tbody) return;
  14479. tbody.innerHTML = '';
  14480. const query = (document.getElementById('users-search-input')?.value || '').trim().toLowerCase();
  14481. const filtered = (state.users || []).filter(u => {
  14482. if (!query) return true;
  14483. return u.username.toLowerCase().includes(query) ||
  14484. (u.role || '').toLowerCase().includes(query) ||
  14485. (u.comment || '').toLowerCase().includes(query);
  14486. });
  14487. if (filtered.length === 0) {
  14488. if (emptyState) emptyState.classList.remove('hidden');
  14489. return;
  14490. }
  14491. if (emptyState) emptyState.classList.add('hidden');
  14492. const currentAuthUser = state.currentUser?.username || '';
  14493. filtered.forEach(u => {
  14494. const isSelf = u.username === currentAuthUser;
  14495. const isFull = u.role === 'full';
  14496. const isWrite = u.role === 'write';
  14497. let roleBadge = `<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-slate-800 text-slate-300 border border-slate-700">READ (OBSERVER)</span>`;
  14498. if (isFull) {
  14499. roleBadge = `<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-purple-500/15 text-purple-300 border border-purple-500/30">FULL (SUPER ADMIN)</span>`;
  14500. } else if (isWrite) {
  14501. roleBadge = `<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-sky-500/15 text-sky-300 border border-sky-500/30">WRITE (OPERATOR)</span>`;
  14502. }
  14503. const statusBadge = u.disabled
  14504. ? `<span class="inline-flex items-center gap-1.5 px-2 py-0.5 rounded-full text-[10px] font-semibold bg-rose-500/15 text-rose-300 border border-rose-500/30"><span class="w-1.5 h-1.5 rounded-full bg-rose-400"></span>Disabled</span>`
  14505. : `<span class="inline-flex items-center gap-1.5 px-2 py-0.5 rounded-full text-[10px] font-semibold bg-emerald-500/15 text-emerald-300 border border-emerald-500/30"><span class="w-1.5 h-1.5 rounded-full bg-emerald-400"></span>Active</span>`;
  14506. let lastLoginText = 'Never';
  14507. if (u.last_login_at && !u.last_login_at.startsWith('0001-01-01')) {
  14508. const dt = new Date(u.last_login_at);
  14509. lastLoginText = dt.toLocaleString();
  14510. }
  14511. const initials = u.username.slice(0, 2).toUpperCase();
  14512. const tr = document.createElement('tr');
  14513. tr.className = 'hover:bg-slate-800/40 transition group';
  14514. tr.innerHTML = `
  14515. <td class="py-3 px-4">
  14516. <div class="flex items-center gap-3">
  14517. <div class="w-8 h-8 rounded-xl bg-slate-800 border border-slate-700/80 flex items-center justify-center font-bold text-xs text-white">
  14518. ${initials}
  14519. </div>
  14520. <div>
  14521. <div class="font-bold text-white text-xs flex items-center gap-2">
  14522. <span>${escapeHtml(u.username)}</span>
  14523. ${isSelf ? '<span class="text-[9px] bg-brand-500/20 text-brand-300 border border-brand-500/30 px-1.5 py-0.2 rounded font-mono">YOU</span>' : ''}
  14524. </div>
  14525. <div class="text-[10px] text-slate-500 font-sans">Created: ${u.created_at ? new Date(u.created_at).toLocaleDateString() : '-'}</div>
  14526. </div>
  14527. </div>
  14528. </td>
  14529. <td class="py-3 px-4 font-sans">
  14530. ${roleBadge}
  14531. </td>
  14532. <td class="py-3 px-4 font-sans">
  14533. ${statusBadge}
  14534. </td>
  14535. <td class="py-3 px-4 text-slate-300 font-sans text-xs">
  14536. ${escapeHtml(u.comment) || '<span class="text-slate-600">-</span>'}
  14537. </td>
  14538. <td class="py-3 px-4 text-slate-400 text-xs">
  14539. ${lastLoginText}
  14540. </td>
  14541. <td class="py-3 px-4 text-right space-x-1.5 font-sans">
  14542. <button onclick="openAdminResetPasswordModal('${escapeHtml(u.username)}')"
  14543. class="p-1.5 rounded-lg text-slate-400 hover:text-amber-400 hover:bg-slate-800 transition" title="Reset User Password">
  14544. <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 7a2 2 0 012 2m4 0a6 6 0 01-7.743 5.743L11 17H9v2H7v2H4a1 1 0 01-1-1v-2.586a1 1 0 01.293-.707l5.964-5.964A6 6 0 1121 9z"/></svg>
  14545. </button>
  14546. <button onclick="openEditUserModal('${escapeHtml(u.username)}')"
  14547. class="p-1.5 rounded-lg text-slate-400 hover:text-cyan-400 hover:bg-slate-800 transition" title="Edit User">
  14548. <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"/></svg>
  14549. </button>
  14550. ${!isSelf ? `
  14551. <button onclick="deleteUser('${escapeHtml(u.username)}')"
  14552. class="p-1.5 rounded-lg text-slate-400 hover:text-rose-400 hover:bg-slate-800 transition" title="Delete User">
  14553. <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/></svg>
  14554. </button>
  14555. ` : ''}
  14556. </td>
  14557. `;
  14558. tbody.appendChild(tr);
  14559. });
  14560. }
  14561. function openAddUserModal() {
  14562. document.getElementById('user-add-username').value = '';
  14563. document.getElementById('user-add-password').value = '';
  14564. document.getElementById('user-add-confirm').value = '';
  14565. document.getElementById('user-add-role').value = 'full';
  14566. document.getElementById('user-add-comment').value = '';
  14567. document.getElementById('modal-add-user')?.classList.remove('hidden');
  14568. document.getElementById('user-add-username')?.focus();
  14569. }
  14570. function closeAddUserModal() {
  14571. document.getElementById('modal-add-user')?.classList.add('hidden');
  14572. }
  14573. async function submitAddUser(event) {
  14574. event.preventDefault();
  14575. const username = (document.getElementById('user-add-username')?.value || '').trim();
  14576. const password = document.getElementById('user-add-password')?.value || '';
  14577. const confirm = document.getElementById('user-add-confirm')?.value || '';
  14578. const role = document.getElementById('user-add-role')?.value || 'full';
  14579. const comment = (document.getElementById('user-add-comment')?.value || '').trim();
  14580. if (password !== confirm) {
  14581. showToast('Validation Error', 'Passwords do not match', 'warning');
  14582. return;
  14583. }
  14584. if (password.length < 4) {
  14585. showToast('Validation Error', 'Password must be at least 4 characters', 'warning');
  14586. return;
  14587. }
  14588. try {
  14589. const res = await fetch(`${API_BASE}/users`, {
  14590. method: 'POST',
  14591. headers: { 'Content-Type': 'application/json' },
  14592. body: JSON.stringify({ username, password, role, comment })
  14593. });
  14594. const data = await res.json();
  14595. if (res.ok) {
  14596. showToast('User Created', `Created user ${username} with ${role.toUpperCase()} permissions`, 'success');
  14597. closeAddUserModal();
  14598. loadUsers(false);
  14599. } else {
  14600. showToast('Error', data.message || 'Failed to create user', 'error');
  14601. }
  14602. } catch (err) {
  14603. showToast('Error', err.message, 'error');
  14604. }
  14605. }
  14606. function openEditUserModal(username) {
  14607. const user = (state.users || []).find(u => u.username === username);
  14608. if (!user) return;
  14609. document.getElementById('user-edit-username').value = user.username;
  14610. document.getElementById('user-edit-username-title').innerText = `@${user.username}`;
  14611. document.getElementById('user-edit-role').value = user.role || 'read';
  14612. document.getElementById('user-edit-comment').value = user.comment || '';
  14613. document.getElementById('user-edit-disabled').checked = !!user.disabled;
  14614. document.getElementById('modal-edit-user')?.classList.remove('hidden');
  14615. }
  14616. function closeEditUserModal() {
  14617. document.getElementById('modal-edit-user')?.classList.add('hidden');
  14618. }
  14619. async function submitEditUser(event) {
  14620. event.preventDefault();
  14621. const username = document.getElementById('user-edit-username')?.value;
  14622. const role = document.getElementById('user-edit-role')?.value || 'read';
  14623. const comment = (document.getElementById('user-edit-comment')?.value || '').trim();
  14624. const disabled = document.getElementById('user-edit-disabled')?.checked || false;
  14625. try {
  14626. const res = await fetch(`${API_BASE}/users/${encodeURIComponent(username)}`, {
  14627. method: 'PUT',
  14628. headers: { 'Content-Type': 'application/json' },
  14629. body: JSON.stringify({ role, comment, disabled })
  14630. });
  14631. const data = await res.json();
  14632. if (res.ok) {
  14633. showToast('User Updated', `Updated settings for ${username}`, 'success');
  14634. closeEditUserModal();
  14635. loadUsers(false);
  14636. // If updated own role/disabled status, refresh self profile
  14637. if (username === state.currentUser?.username) {
  14638. checkAuthStatus();
  14639. }
  14640. } else {
  14641. showToast('Error', data.message || 'Failed to update user', 'error');
  14642. }
  14643. } catch (err) {
  14644. showToast('Error', err.message, 'error');
  14645. }
  14646. }
  14647. function openAdminResetPasswordModal(username) {
  14648. document.getElementById('admin-reset-username').value = username;
  14649. document.getElementById('admin-reset-username-title').innerText = `@${username}`;
  14650. document.getElementById('admin-reset-new-pw').value = '';
  14651. document.getElementById('admin-reset-confirm-pw').value = '';
  14652. document.getElementById('modal-admin-reset-pw')?.classList.remove('hidden');
  14653. document.getElementById('admin-reset-new-pw')?.focus();
  14654. }
  14655. function closeAdminResetPasswordModal() {
  14656. document.getElementById('modal-admin-reset-pw')?.classList.add('hidden');
  14657. }
  14658. async function submitAdminResetPassword(event) {
  14659. event.preventDefault();
  14660. const username = document.getElementById('admin-reset-username')?.value;
  14661. const newPassword = document.getElementById('admin-reset-new-pw')?.value || '';
  14662. const confirm = document.getElementById('admin-reset-confirm-pw')?.value || '';
  14663. if (newPassword !== confirm) {
  14664. showToast('Validation Error', 'Passwords do not match', 'warning');
  14665. return;
  14666. }
  14667. if (newPassword.length < 4) {
  14668. showToast('Validation Error', 'Password must be at least 4 characters', 'warning');
  14669. return;
  14670. }
  14671. try {
  14672. const res = await fetch(`${API_BASE}/users/${encodeURIComponent(username)}/password`, {
  14673. method: 'POST',
  14674. headers: { 'Content-Type': 'application/json' },
  14675. body: JSON.stringify({ new_password: newPassword })
  14676. });
  14677. const data = await res.json();
  14678. if (res.ok) {
  14679. showToast('Password Reset', `Password for user ${username} updated successfully`, 'success');
  14680. closeAdminResetPasswordModal();
  14681. } else {
  14682. showToast('Error', data.message || 'Failed to reset password', 'error');
  14683. }
  14684. } catch (err) {
  14685. showToast('Error', err.message, 'error');
  14686. }
  14687. }
  14688. async function deleteUser(username) {
  14689. if (username === state.currentUser?.username) {
  14690. showToast('Action Forbidden', 'You cannot delete your own account', 'warning');
  14691. return;
  14692. }
  14693. if (!confirm(`Are you sure you want to completely remove user "${username}"?`)) {
  14694. return;
  14695. }
  14696. try {
  14697. const res = await fetch(`${API_BASE}/users/${encodeURIComponent(username)}`, {
  14698. method: 'DELETE'
  14699. });
  14700. const data = await res.json();
  14701. if (res.ok) {
  14702. showToast('User Deleted', `User ${username} has been removed`, 'success');
  14703. loadUsers(false);
  14704. } else {
  14705. showToast('Error', data.message || 'Failed to delete user', 'error');
  14706. }
  14707. } catch (err) {
  14708. showToast('Error', err.message, 'error');
  14709. }
  14710. }
  14711. function openSelfPasswordModal() {
  14712. document.getElementById('self-current-password').value = '';
  14713. document.getElementById('self-new-password').value = '';
  14714. document.getElementById('self-confirm-password').value = '';
  14715. document.getElementById('modal-self-password')?.classList.remove('hidden');
  14716. document.getElementById('self-current-password')?.focus();
  14717. }
  14718. function closeSelfPasswordModal() {
  14719. document.getElementById('modal-self-password')?.classList.add('hidden');
  14720. }
  14721. async function submitSelfPassword(event) {
  14722. event.preventDefault();
  14723. const oldPassword = document.getElementById('self-current-password')?.value || '';
  14724. const newPassword = document.getElementById('self-new-password')?.value || '';
  14725. const confirm = document.getElementById('self-confirm-password')?.value || '';
  14726. if (newPassword !== confirm) {
  14727. showToast('Validation Error', 'New passwords do not match', 'warning');
  14728. return;
  14729. }
  14730. if (newPassword.length < 4) {
  14731. showToast('Validation Error', 'Password must be at least 4 characters', 'warning');
  14732. return;
  14733. }
  14734. try {
  14735. const res = await fetch(`${API_BASE}/auth/change-password`, {
  14736. method: 'POST',
  14737. headers: { 'Content-Type': 'application/json' },
  14738. body: JSON.stringify({ old_password: oldPassword, new_password: newPassword })
  14739. });
  14740. const data = await res.json();
  14741. if (res.ok) {
  14742. showToast('Password Changed', 'Your password has been changed successfully', 'success');
  14743. closeSelfPasswordModal();
  14744. } else {
  14745. showToast('Error', data.message || 'Failed to change password', 'error');
  14746. }
  14747. } catch (err) {
  14748. showToast('Error', err.message, 'error');
  14749. }
  14750. }