app.js 686 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389
  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.isPolling) {
  27. state.isPolling = false;
  28. showLoginScreen(true);
  29. }
  30. }
  31. return response;
  32. };
  33. let state = {
  34. currentUser: null,
  35. users: [],
  36. interfaces: [],
  37. vlans: [],
  38. systemStatus: null,
  39. vpnStatus: null,
  40. routes: [],
  41. activeTab: 'dashboard',
  42. fwSubTab: 'filter',
  43. bridgeSubTab: 'bridges',
  44. bridges: [],
  45. bridgePorts: [],
  46. bridgeVLANs: [],
  47. bridgeHosts: [],
  48. bridgeSummary: null,
  49. routesSubTab: 'routes',
  50. pppSubTab: 'secrets',
  51. eoipTunnels: [],
  52. pppSecrets: [],
  53. pppProfiles: [],
  54. pppActiveSessions: [],
  55. pppoeServer: null,
  56. pptpServer: null,
  57. l2tpServer: null,
  58. ipsecServer: null,
  59. ifaceFilter: 'all',
  60. currentModalIface: null,
  61. isPolling: true,
  62. expandedParents: new Set(['eth0']),
  63. pppoeData: null,
  64. wgData: null,
  65. ipsecData: null,
  66. l2tpData: null,
  67. pptpData: null,
  68. fwSummary: null,
  69. filterRules: [],
  70. natRules: [],
  71. mangleRules: [],
  72. addressLists: [],
  73. connections: [],
  74. policyRules: [],
  75. routingTables: [],
  76. routingFilters: [],
  77. filterChainSelected: 'all',
  78. activeToolsSubTab: 'ping',
  79. dhcpClients: [],
  80. dhcpSummary: null,
  81. dhcpServerTab: 'servers',
  82. dhcpServers: [],
  83. dhcpNetworks: [],
  84. dhcpLeases: [],
  85. dhcpOptions: [],
  86. dhcpServerSummary: null
  87. };
  88. const API_BASE = '/api';
  89. function escapeHtml(str) {
  90. if (str === null || str === undefined) return '';
  91. return String(str)
  92. .replace(/&/g, '&')
  93. .replace(/</g, '&lt;')
  94. .replace(/>/g, '&gt;')
  95. .replace(/"/g, '&quot;')
  96. .replace(/'/g, '&#039;');
  97. }
  98. function formatBytes(bytes) {
  99. if (bytes === undefined || bytes === null || isNaN(bytes) || bytes === 0) return '0 B';
  100. const k = 1024;
  101. const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
  102. const i = Math.floor(Math.log(bytes) / Math.log(k));
  103. if (i < 0 || i >= sizes.length) return `${bytes} B`;
  104. return `${parseFloat((bytes / Math.pow(k, i)).toFixed(2))} ${sizes[i]}`;
  105. }
  106. // Initialize on page load
  107. document.addEventListener('DOMContentLoaded', async () => {
  108. const hash = window.location.hash.replace('#', '') || 'dashboard';
  109. navigate(hash);
  110. initTableSorting();
  111. // Verify authentication before bootstrapping telemetry
  112. await checkAuthStatus();
  113. // Full state telemetry polling every 5 seconds (smooth & flicker-free)
  114. setInterval(() => {
  115. if (state.isPolling && state.currentUser) {
  116. fetchData(false);
  117. }
  118. }, 5000);
  119. });
  120. let trafficEventSource = null;
  121. let trafficPollFallback = null;
  122. function initLiveTrafficStream() {
  123. if (trafficEventSource) {
  124. try { trafficEventSource.close(); } catch(e) {}
  125. trafficEventSource = null;
  126. }
  127. if (trafficPollFallback) {
  128. clearInterval(trafficPollFallback);
  129. trafficPollFallback = null;
  130. }
  131. if (window.EventSource) {
  132. try {
  133. trafficEventSource = new EventSource(`${API_BASE}/interfaces/traffic/stream`);
  134. trafficEventSource.onmessage = (event) => {
  135. try {
  136. const data = JSON.parse(event.data);
  137. updateLiveInterfaceTraffic(data);
  138. } catch (e) {
  139. console.error('Error parsing live traffic event:', e);
  140. }
  141. };
  142. trafficEventSource.onerror = () => {
  143. // Fallback polling if SSE disconnects
  144. if (!trafficPollFallback) {
  145. trafficPollFallback = setInterval(pollLiveTrafficSnapshot, 1000);
  146. }
  147. };
  148. trafficEventSource.onopen = () => {
  149. if (trafficPollFallback) {
  150. clearInterval(trafficPollFallback);
  151. trafficPollFallback = null;
  152. }
  153. };
  154. return;
  155. } catch (e) {
  156. console.warn('EventSource failed, using 1s polling fallback:', e);
  157. }
  158. }
  159. // Fallback if EventSource is unavailable
  160. trafficPollFallback = setInterval(pollLiveTrafficSnapshot, 1000);
  161. }
  162. async function pollLiveTrafficSnapshot() {
  163. try {
  164. const res = await fetch(`${API_BASE}/interfaces/traffic/rates`);
  165. if (res.ok) {
  166. const data = await res.json();
  167. updateLiveInterfaceTraffic(data);
  168. }
  169. } catch (e) {}
  170. }
  171. function updateLiveInterfaceTraffic(data) {
  172. if (!data || !data.interfaces) return;
  173. state.latestTraffic = data;
  174. // 1. Update Top & Dashboard Total Bandwidth Indicators
  175. const rxHuman = data.total_rx_human || '0 B/s';
  176. const txHuman = data.total_tx_human || '0 B/s';
  177. const statRx = document.getElementById('stat-traffic-rx');
  178. if (statRx && statRx.innerText !== rxHuman) statRx.innerText = rxHuman;
  179. const statTx = document.getElementById('stat-traffic-tx');
  180. if (statTx && statTx.innerText !== txHuman) statTx.innerText = txHuman;
  181. // 2. Update state.interfaces rates in-memory
  182. if (Array.isArray(state.interfaces)) {
  183. state.interfaces.forEach(i => {
  184. const live = data.interfaces[i.name];
  185. if (live) {
  186. i.rate = {
  187. rx_bytes_sec: live.rx_bytes_sec,
  188. tx_bytes_sec: live.tx_bytes_sec,
  189. rx_human: live.rx_human,
  190. tx_human: live.tx_human
  191. };
  192. i.stats = {
  193. rx_bytes: live.rx_bytes,
  194. tx_bytes: live.tx_bytes,
  195. rx_packets: live.rx_packets,
  196. tx_packets: live.tx_packets,
  197. rx_errors: live.rx_errors,
  198. tx_errors: live.tx_errors,
  199. rx_dropped: live.rx_dropped,
  200. tx_dropped: live.tx_dropped
  201. };
  202. }
  203. });
  204. }
  205. // 3. Update all live UI rate spans in-place (ZERO flicker)
  206. Object.keys(data.interfaces).forEach(name => {
  207. const live = data.interfaces[name];
  208. // Dashboard Port Matrix Card
  209. const cardRate = document.getElementById(`port-card-rate-${name}`);
  210. if (cardRate && cardRate.innerText !== live.rx_human) {
  211. cardRate.innerText = live.rx_human;
  212. }
  213. // Dashboard Quick Interfaces Table
  214. const quickRx = document.getElementById(`quick-rx-${name}`);
  215. if (quickRx) quickRx.innerText = `↓ ${live.rx_human}`;
  216. const quickTx = document.getElementById(`quick-tx-${name}`);
  217. if (quickTx) quickTx.innerText = `↑ ${live.tx_human}`;
  218. // Main Interfaces Tree Table
  219. const ifaceRx = document.getElementById(`iface-rate-rx-${name}`);
  220. if (ifaceRx) ifaceRx.innerText = `↓ ${live.rx_human}`;
  221. const ifaceTx = document.getElementById(`iface-rate-tx-${name}`);
  222. if (ifaceTx) ifaceTx.innerText = `↑ ${live.tx_human}`;
  223. // VLAN Sub-interfaces Table
  224. const vlanRx = document.getElementById(`vlan-rate-rx-${name}`);
  225. if (vlanRx) vlanRx.innerText = `↓ ${live.rx_human}`;
  226. const vlanTx = document.getElementById(`vlan-rate-tx-${name}`);
  227. if (vlanTx) vlanTx.innerText = `↑ ${live.tx_human}`;
  228. // VLAN Page Table
  229. const vlanPageRx = document.getElementById(`vlan-page-rate-rx-${name}`);
  230. if (vlanPageRx) vlanPageRx.innerText = `↓ ${live.rx_human}`;
  231. const vlanPageTx = document.getElementById(`vlan-page-rate-tx-${name}`);
  232. if (vlanPageTx) vlanPageTx.innerText = `↑ ${live.tx_human}`;
  233. });
  234. }
  235. // Navigation Handler
  236. function navigate(tabName) {
  237. if (tabName === 'dynamic-routing' || tabName === 'routing') {
  238. navigate('bgp');
  239. return;
  240. }
  241. if (tabName === 'vlans') {
  242. navigate('interfaces');
  243. return;
  244. }
  245. state.activeTab = tabName;
  246. window.location.hash = tabName;
  247. // Update nav links styling
  248. document.querySelectorAll('.nav-link').forEach(link => {
  249. 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';
  250. });
  251. const activeNav = document.getElementById(`nav-${tabName}`);
  252. if (activeNav) {
  253. 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';
  254. }
  255. // Update page headers
  256. const titles = {
  257. dashboard: { title: 'Dashboard Overview', sub: 'Live router performance and network telemetry' },
  258. interfaces: { title: 'Network Interfaces', sub: 'Interface Table View' },
  259. 'dhcp-client': { title: 'DHCP Client', sub: 'DHCP Client List' },
  260. 'dhcp-server': { title: 'DHCP Server & Subnets', sub: 'DHCP Server instances, subnet networks (NTP, TFTP, DNS), dynamic leases & static reservations' },
  261. bridge: { title: 'Bridge Interfaces', sub: 'IEEE 802.1D / 802.1Q VLAN-aware Layer 2 switching, RSTP & hardware forwarding (FDB)' },
  262. vlans: { title: 'VLAN Virtual Networks', sub: 'IEEE 802.1Q sub-interface segmentation and routing' },
  263. firewall: { title: 'Network Firewall', sub: 'Stateful packet inspection, NAT, traffic mangle, address lists & connection tracking' },
  264. routes: { title: 'Routing & Policy', sub: 'Routing tables, static routes (DAS/DAC), and policy routing rules' },
  265. bgp: { title: 'BGP Dynamic Routing', sub: 'BGP multi-instance peering sessions, advertised networks, and routing table (RIB)' },
  266. ospf: { title: 'OSPF Dynamic Routing', sub: 'OSPFv2 link-state routing, dynamic neighbor adjacencies, and multi-area topology' },
  267. 'routing-filters': { title: 'Routing Policy Filters', sub: 'Route filter chains, prefix matching, BGP community maps & policy-based path control' },
  268. 'dynamic-routing': { title: 'BGP Dynamic Routing', sub: 'Dynamic routing engine and peering sessions' },
  269. ppp: { title: 'PPP Servers & Secrets', sub: 'Subscriber authentication, dynamic IP pools and VPN access concentrators' },
  270. eoip: { title: 'EoIP Tunnels', sub: 'Ethernet over IP (EoIP / GRETAP) Layer 2 encapsulation & transparent network bridging' },
  271. aerotun: { title: 'AeroTUN High-Speed VPN', sub: 'Ultra-fast Layer 3 encrypted tunnel with ChaCha20-Poly1305 and live Adaptive LZ4 compression' },
  272. pppoe: { title: 'PPPoE Client WAN', sub: 'Point-to-Point Protocol over Ethernet WAN access' },
  273. wireguard: { title: 'WireGuard VPN', sub: 'High-performance cryptographic Layer 3 tunnels with ChaCha20-Poly1305 key exchange' },
  274. ipsec: { title: 'IPSec (IKEv2) strongSwan', sub: 'Enterprise Site-to-Site & Roadwarrior IPSec controller' },
  275. l2tp: { title: 'L2TP VPN Client', sub: 'Layer 2 Tunneling Protocol via xl2tpd' },
  276. pptp: { title: 'PPTP VPN Client', sub: 'Point-to-Point Tunneling Protocol with MPPE-128 encryption' },
  277. vrrp: { title: 'VRRP High Availability', sub: 'Virtual Router Redundancy Protocol, active-backup gateway failover & Virtual IP (VIP) routing' },
  278. bwtest: { title: 'Bandwidth Test Benchmark', sub: 'High-speed line-rate throughput benchmark, token-bucket rate limiting, loss & jitter telemetry' },
  279. tools: { title: 'Diagnostic & Troubleshooting Tools', sub: 'Network latency analysis, ICMP/MTR telemetry, path tracing, DNS resolution and TCP probing' },
  280. persistence: { title: 'Debian Configuration', sub: 'Native /etc/network/interfaces.d/ persistence manager' },
  281. settings: { title: 'Router Settings & DNS', sub: 'System DNS forwarder, upstream resolvers, static host mappings, and appliance identity' },
  282. users: { title: 'Local User Manager', sub: 'Manage local system administrator credentials and access permissions' }
  283. };
  284. const header = titles[tabName] || titles.dashboard;
  285. const pTitle = document.getElementById('page-title');
  286. if (pTitle) pTitle.innerText = header.title;
  287. const pSub = document.getElementById('page-subtitle');
  288. if (pSub) pSub.innerText = header.sub;
  289. // Toggle sections dynamically for all section elements
  290. document.querySelectorAll('main section[id^="section-"]').forEach(el => {
  291. if (el.id === `section-${tabName}`) {
  292. el.classList.remove('hidden');
  293. } else {
  294. el.classList.add('hidden');
  295. }
  296. });
  297. if (tabName === 'interfaces') {
  298. loadRoles();
  299. if (state.activeIfaceSubTab === 'roles') switchIfaceSubTab('roles');
  300. else switchIfaceSubTab('tree');
  301. }
  302. if (tabName === 'bridge') loadBridge();
  303. if (tabName === 'firewall') loadFirewall();
  304. if (tabName === 'routes') loadRoutes();
  305. if (tabName === 'bgp') {
  306. loadDynamicRouting();
  307. switchBgpSubTab(state.activeBgpSubTab || 'bgp-peers');
  308. }
  309. if (tabName === 'ospf') {
  310. loadDynamicRouting();
  311. switchOspfTab(state.activeOspfTab || 'instances');
  312. }
  313. if (tabName === 'routing-filters') loadDynamicRouting();
  314. if (tabName === 'dynamic-routing') loadDynamicRouting();
  315. if (tabName === 'ppp') loadPPP();
  316. if (tabName === 'eoip') loadEoIP();
  317. if (tabName === 'aerotun') loadAeroTUN();
  318. if (tabName === 'persistence') loadDebianConfig();
  319. if (tabName === 'pppoe') loadPPPoE();
  320. if (tabName === 'wireguard') loadWireGuard();
  321. if (tabName === 'ipsec') loadIPSec();
  322. if (tabName === 'l2tp') loadL2TP();
  323. if (tabName === 'pptp') loadPPTP();
  324. if (tabName === 'tools') loadToolsView();
  325. if (tabName === 'dhcp-client') loadDHCPClients();
  326. if (tabName === 'dhcp-server') loadDHCPServer();
  327. if (tabName === 'vrrp') loadVRRP();
  328. if (tabName === 'bwtest') loadBwTestView();
  329. if (tabName === 'settings') loadSettingsData();
  330. if (tabName === 'users') loadUsers();
  331. setTimeout(initTableSorting, 50);
  332. }
  333. // Fetch all core system, network and VPN telemetry
  334. async function fetchData(isManual = false) {
  335. const spinner = document.getElementById('refresh-spinner');
  336. if (isManual && spinner) spinner.classList.add('animate-spin');
  337. try {
  338. const [statusRes, ifacesRes, vlansRes, vpnRes, fwRes, dynRes, brSummaryRes, dhcpSumRes, dhcpClientsRes, vrrpSumRes, rolesRes] = await Promise.all([
  339. fetch(`${API_BASE}/system/status`),
  340. fetch(`${API_BASE}/interfaces`),
  341. fetch(`${API_BASE}/vlans`),
  342. fetch(`${API_BASE}/vpn/status`),
  343. fetch(`${API_BASE}/firewall/summary`),
  344. fetch(`${API_BASE}/routing/dynamic/summary`),
  345. fetch(`${API_BASE}/bridge/summary`),
  346. fetch(`${API_BASE}/dhcp/clients/summary`),
  347. fetch(`${API_BASE}/dhcp/clients`),
  348. fetch(`${API_BASE}/vrrp/summary`).catch(() => null),
  349. fetch(`${API_BASE}/roles`).catch(() => null)
  350. ]);
  351. if (rolesRes && rolesRes.ok) {
  352. state.roles = await rolesRes.json();
  353. const countEl = document.getElementById('badge-roles-count');
  354. if (countEl) countEl.innerText = (state.roles || []).length;
  355. }
  356. if (vrrpSumRes && vrrpSumRes.ok) {
  357. state.vrrpSummary = await vrrpSumRes.json();
  358. renderVRRPSummary();
  359. }
  360. if (dhcpSumRes && dhcpSumRes.ok) {
  361. state.dhcpSummary = await dhcpSumRes.json();
  362. const bDhcp = document.getElementById('badge-dhcp-client-count');
  363. if (bDhcp) bDhcp.innerText = state.dhcpSummary?.total_clients || 0;
  364. }
  365. if (dhcpClientsRes && dhcpClientsRes.ok) {
  366. state.dhcpClients = await dhcpClientsRes.json();
  367. }
  368. if (brSummaryRes.ok) {
  369. state.bridgeSummary = await brSummaryRes.json();
  370. const bBridge = document.getElementById('badge-bridge-count');
  371. if (bBridge) bBridge.innerText = state.bridgeSummary?.bridges_count || 0;
  372. const sBr = document.getElementById('bridge-stat-bridges');
  373. if (sBr) sBr.innerText = state.bridgeSummary?.bridges_count || 0;
  374. const sPorts = document.getElementById('bridge-stat-ports');
  375. if (sPorts) sPorts.innerText = state.bridgeSummary?.ports_count || 0;
  376. const sHosts = document.getElementById('bridge-stat-hosts');
  377. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  378. }
  379. if (statusRes.ok) state.systemStatus = await statusRes.json();
  380. if (ifacesRes.ok) {
  381. const ifacesData = await ifacesRes.json();
  382. const rawIfaces = Array.isArray(ifacesData) ? ifacesData : [];
  383. state.interfaces = rawIfaces.filter(i => {
  384. if (!i.name) return false;
  385. if (i.name.startsWith('ep_')) return false;
  386. return !['gre0', 'gretap0', 'erspan0', 'sit0', 'tunl0', 'ip6tnl0', 'ip6gre0', 'ip6erspan0'].includes(i.name);
  387. });
  388. try { populateToolsInterfaces(); } catch (e) {}
  389. }
  390. if (vlansRes.ok) {
  391. const vlansData = await vlansRes.json();
  392. state.vlans = Array.isArray(vlansData) ? vlansData : [];
  393. }
  394. if (vpnRes.ok) state.vpnStatus = await vpnRes.json();
  395. if (fwRes && fwRes.ok) state.fwSummary = await fwRes.json();
  396. if (dynRes && dynRes.ok) state.dynSummary = await dynRes.json();
  397. updateSystemMetrics();
  398. updateBadges();
  399. if (state.activeTab === 'dashboard') renderDashboard();
  400. if (state.activeTab === 'interfaces') {
  401. if (state.activeIfaceSubTab === 'roles') renderRolesTable();
  402. else renderInterfacesList();
  403. }
  404. if (state.activeTab === 'vlans') renderVlansList();
  405. if (state.activeTab === 'firewall') loadFirewall(false);
  406. if (state.activeTab === 'routes') loadRoutes(false);
  407. if (state.activeTab === 'dynamic-routing' || state.activeTab === 'bgp' || state.activeTab === 'ospf') loadDynamicRouting(false);
  408. if (state.activeTab === 'ppp') loadPPP(false);
  409. if (state.activeTab === 'eoip') loadEoIP(false);
  410. if (state.activeTab === 'aerotun') loadAeroTUN(false);
  411. if (state.activeTab === 'pppoe') loadPPPoE(false);
  412. if (state.activeTab === 'wireguard') loadWireGuard(false);
  413. if (state.activeTab === 'ipsec') loadIPSec(false);
  414. if (state.activeTab === 'l2tp') loadL2TP(false);
  415. if (state.activeTab === 'pptp') loadPPTP(false);
  416. if (state.activeTab === 'dhcp-client') loadDHCPClients(false);
  417. if (state.activeTab === 'dhcp-server') loadDHCPServer(false);
  418. if (state.activeTab === 'vrrp') loadVRRP(false);
  419. if (state.activeTab === 'settings') loadSettingsData(false);
  420. if (state.activeTab === 'users') loadUsers(false);
  421. fetchBwTestServerStatus();
  422. } catch (err) {
  423. console.error('Failed to fetch router state:', err);
  424. } finally {
  425. if (isManual && spinner) {
  426. setTimeout(() => spinner.classList.remove('animate-spin'), 300);
  427. }
  428. }
  429. }
  430. // Update Top KPI and Sidebar Telemetry
  431. function updateSystemMetrics() {
  432. const s = state.systemStatus;
  433. const v = state.vpnStatus;
  434. if (!s) return;
  435. // Sidebar Host & Uptime
  436. const sideHost = document.getElementById('side-hostname');
  437. if (sideHost) sideHost.innerText = s.hostname || 'debian-lxc';
  438. const sideUp = document.getElementById('side-uptime');
  439. if (sideUp) sideUp.innerText = s.uptime_human || '0m';
  440. const sideGw = document.getElementById('side-gateway-ip');
  441. if (sideGw) sideGw.innerText = s.default_gateway ? `GW: ${s.default_gateway}` : 'GW: Isolated';
  442. // Compute CPU Metrics
  443. let cpuPct = 0;
  444. if (s.cpu_pct !== undefined) {
  445. cpuPct = s.cpu_pct;
  446. } else if (s.cpu_load && s.cpu_load.length > 0) {
  447. const cores = s.cpu_cores || 1;
  448. cpuPct = Math.min(100, Math.round((parseFloat(s.cpu_load[0]) / cores) * 100));
  449. }
  450. const cpuPctStr = `${cpuPct.toFixed(1)}%`;
  451. const cpuWidth = `${Math.max(3, Math.min(100, cpuPct))}%`;
  452. const loadStr = s.cpu_load ? s.cpu_load.join(', ') : '-';
  453. // Sidebar CPU
  454. const sideCpuVal = document.getElementById('side-cpu-val');
  455. if (sideCpuVal) sideCpuVal.innerText = cpuPctStr;
  456. const sideCpuBar = document.getElementById('side-cpu-bar');
  457. if (sideCpuBar) {
  458. sideCpuBar.style.width = cpuWidth;
  459. sideCpuBar.title = `Container: ${cpuPctStr} | Host Loadavg: ${loadStr} (${s.cpu_cores || 1} cores)`;
  460. }
  461. // Dashboard CPU Card
  462. const dashCpuVal = document.getElementById('dash-cpu-val');
  463. if (dashCpuVal) dashCpuVal.innerText = cpuPctStr;
  464. const dashCpuBar = document.getElementById('dash-cpu-bar');
  465. if (dashCpuBar) {
  466. dashCpuBar.style.width = cpuWidth;
  467. if (cpuPct > 85) {
  468. dashCpuBar.className = 'h-full rounded-full bg-rose-500 transition-all duration-500';
  469. } else if (cpuPct > 65) {
  470. dashCpuBar.className = 'h-full rounded-full bg-amber-500 transition-all duration-500';
  471. } else {
  472. dashCpuBar.className = 'h-full rounded-full bg-emerald-500 transition-all duration-500';
  473. }
  474. }
  475. const dashCpuCores = document.getElementById('dash-cpu-cores');
  476. if (dashCpuCores) dashCpuCores.innerText = `${s.cpu_cores || 1} Cores`;
  477. const dashCpuLoad = document.getElementById('dash-cpu-load');
  478. if (dashCpuLoad) dashCpuLoad.innerText = loadStr;
  479. const dashCpuStatus = document.getElementById('dash-cpu-status');
  480. if (dashCpuStatus) {
  481. if (cpuPct > 85) {
  482. dashCpuStatus.innerText = 'High';
  483. dashCpuStatus.className = 'text-[11px] font-semibold text-rose-400 uppercase px-2 py-0.5 rounded bg-rose-500/10';
  484. } else if (cpuPct > 65) {
  485. dashCpuStatus.innerText = 'Heavy';
  486. dashCpuStatus.className = 'text-[11px] font-semibold text-amber-400 uppercase px-2 py-0.5 rounded bg-amber-500/10';
  487. } else {
  488. dashCpuStatus.innerText = 'Normal';
  489. dashCpuStatus.className = 'text-[11px] font-semibold text-emerald-400 uppercase px-2 py-0.5 rounded bg-emerald-500/10';
  490. }
  491. }
  492. // Compute RAM Metrics
  493. const memPct = Math.round(s.mem_usage_pct || 0);
  494. const memPctStr = `${memPct}%`;
  495. const memWidth = `${Math.max(3, Math.min(100, memPct))}%`;
  496. const usedMB = s.mem_used_mb || 0;
  497. const totalMB = s.mem_total_mb || 0;
  498. const freeMB = totalMB > usedMB ? totalMB - usedMB : 0;
  499. function fmtMemMB(mb) {
  500. if (mb >= 1024) {
  501. return `${(mb / 1024).toFixed(1)} GB`;
  502. }
  503. return `${mb} MB`;
  504. }
  505. // Sidebar RAM
  506. const sideRamVal = document.getElementById('side-ram-val');
  507. if (sideRamVal) sideRamVal.innerText = memPctStr;
  508. const sideRamBar = document.getElementById('side-ram-bar');
  509. if (sideRamBar) sideRamBar.style.width = memWidth;
  510. // Dashboard RAM Card
  511. const dashRamVal = document.getElementById('dash-ram-val');
  512. if (dashRamVal) dashRamVal.innerText = memPctStr;
  513. const dashRamBar = document.getElementById('dash-ram-bar');
  514. if (dashRamBar) {
  515. dashRamBar.style.width = memWidth;
  516. if (memPct > 85) {
  517. dashRamBar.className = 'h-full rounded-full bg-rose-500 transition-all duration-500';
  518. } else if (memPct > 70) {
  519. dashRamBar.className = 'h-full rounded-full bg-amber-500 transition-all duration-500';
  520. } else {
  521. dashRamBar.className = 'h-full rounded-full bg-indigo-500 transition-all duration-500';
  522. }
  523. }
  524. const dashRamUsedTotal = document.getElementById('dash-ram-used-total');
  525. if (dashRamUsedTotal) {
  526. dashRamUsedTotal.innerText = `${fmtMemMB(usedMB)} / ${fmtMemMB(totalMB)}`;
  527. }
  528. const dashRamFree = document.getElementById('dash-ram-free');
  529. if (dashRamFree) {
  530. dashRamFree.innerText = fmtMemMB(freeMB);
  531. }
  532. const dashRamStatus = document.getElementById('dash-ram-status');
  533. if (dashRamStatus) {
  534. if (memPct > 85) {
  535. dashRamStatus.innerText = 'High';
  536. dashRamStatus.className = 'text-[11px] font-semibold text-rose-400 uppercase px-2 py-0.5 rounded bg-rose-500/10';
  537. } else {
  538. dashRamStatus.innerText = 'Active';
  539. dashRamStatus.className = 'text-[11px] font-semibold text-indigo-400 uppercase px-2 py-0.5 rounded bg-indigo-500/10';
  540. }
  541. }
  542. // Legacy Dashboard Stats (Safe checks)
  543. const elIfacesUp = document.getElementById('stat-ifaces-up');
  544. if (elIfacesUp) elIfacesUp.innerText = s.up_ifaces || 0;
  545. const elIfacesTot = document.getElementById('stat-ifaces-total');
  546. if (elIfacesTot) elIfacesTot.innerText = `${s.total_ifaces || 0} Total`;
  547. const elIfacesDown = document.getElementById('stat-ifaces-down');
  548. if (elIfacesDown) elIfacesDown.innerText = `${s.down_ifaces || 0} DOWN`;
  549. const elVlans = document.getElementById('stat-vlans-count');
  550. if (elVlans) elVlans.innerText = s.vlan_ifaces || 0;
  551. // VPN Status Indicators
  552. if (v) {
  553. const totalActive = v.total_active_tunnels || 0;
  554. const statVpnActive = document.getElementById('stat-vpn-active');
  555. if (statVpnActive) statVpnActive.innerText = totalActive;
  556. const tunnelsDot = document.getElementById('tunnels-dot');
  557. const tunnelsLabel = document.getElementById('tunnels-label');
  558. if (tunnelsDot && tunnelsLabel) {
  559. if (totalActive > 0) {
  560. tunnelsDot.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  561. tunnelsLabel.innerText = `${totalActive} Active VPN Tunnel${totalActive > 1 ? 's' : ''}`;
  562. } else {
  563. tunnelsDot.className = 'w-2 h-2 rounded-full bg-slate-500';
  564. tunnelsLabel.innerText = '0 Active VPN Tunnels';
  565. }
  566. }
  567. setDotBadge('badge-pppoe-status', (v.active_pppoe || 0) > 0 || v.pppoe_connected);
  568. setDotBadge('badge-wg-status', (v.active_wireguard || 0) > 0 || v.wireguard_active);
  569. setDotBadge('badge-ipsec-status', (v.active_ipsec || 0) > 0 || v.ipsec_active);
  570. setDotBadge('badge-l2tp-status', (v.active_l2tp || 0) > 0 || v.l2tp_connected);
  571. setDotBadge('badge-pptp-status', (v.active_pptp || 0) > 0 || v.pptp_connected);
  572. }
  573. // Total Live Bandwidth Rate
  574. let totalRx = 0;
  575. let totalTx = 0;
  576. (state.interfaces || []).forEach(i => {
  577. if (i.rate) {
  578. totalRx += i.rate.rx_bytes_sec || 0;
  579. totalTx += i.rate.tx_bytes_sec || 0;
  580. }
  581. });
  582. document.getElementById('stat-traffic-rx').innerText = formatTraffic(totalRx);
  583. document.getElementById('stat-traffic-tx').innerText = formatTraffic(totalTx);
  584. }
  585. function setDotBadge(id, active) {
  586. const el = document.getElementById(id);
  587. if (!el) return;
  588. if (active) {
  589. el.className = 'w-2 h-2 rounded-full bg-emerald-400 shadow-sm shadow-emerald-400/80';
  590. } else {
  591. el.className = 'w-2 h-2 rounded-full bg-slate-600';
  592. }
  593. }
  594. function updateBadges() {
  595. const bIfaces = document.getElementById('badge-ifaces-count');
  596. if (bIfaces) bIfaces.innerText = (state.interfaces || []).length;
  597. const bVlans = document.getElementById('badge-vlans-count');
  598. if (bVlans) bVlans.innerText = (state.vlans || []).length;
  599. if (state.fwSummary) {
  600. const totalFwRules = (state.fwSummary.filter_rules_count || 0) + (state.fwSummary.nat_rules_count || 0) + (state.fwSummary.mangle_rules_count || 0);
  601. const badgeFw = document.getElementById('badge-firewall-count');
  602. if (badgeFw) badgeFw.innerText = totalFwRules;
  603. }
  604. if (state.vpnStatus) {
  605. const v = state.vpnStatus;
  606. const bEoIP = document.getElementById('badge-eoip-count');
  607. if (bEoIP) bEoIP.innerText = v.total_eoip || 0;
  608. const bAero = document.getElementById('badge-aerotun-count');
  609. if (bAero) bAero.innerText = v.total_aerotun || 0;
  610. const bPPPSess = document.getElementById('badge-ppp-sessions');
  611. if (bPPPSess) bPPPSess.innerText = v.total_ppp_sessions || 0;
  612. setDotBadge('badge-pppoe-status', v.active_pppoe > 0 || v.pppoe_server_running);
  613. setDotBadge('badge-wg-status', v.active_wireguard > 0);
  614. setDotBadge('badge-ipsec-status', v.active_ipsec > 0 || v.ipsec_server_running);
  615. setDotBadge('badge-l2tp-status', v.active_l2tp > 0 || v.l2tp_server_running);
  616. setDotBadge('badge-pptp-status', v.active_pptp > 0 || v.pptp_server_running);
  617. }
  618. if (state.dynSummary) {
  619. const d = state.dynSummary;
  620. setDotBadge('badge-bgp-dot', d.bgp_running);
  621. setDotBadge('badge-ospf-dot', d.ospf_running);
  622. const bBgp = document.getElementById('badge-bgp-count');
  623. if (bBgp) bBgp.innerText = (state.bgpPeers || []).length;
  624. const bOspf = document.getElementById('badge-ospf-count');
  625. if (bOspf) bOspf.innerText = (state.ospfInterfaces || []).length;
  626. const bFilters = document.getElementById('badge-filters-count');
  627. if (bFilters) bFilters.innerText = (state.routingFilters || []).length;
  628. }
  629. const bDhcpServer = document.getElementById('badge-dhcp-server-count');
  630. if (bDhcpServer) {
  631. bDhcpServer.innerText = state.dhcpServerSummary ? (state.dhcpServerSummary.active_leases || state.dhcpServerSummary.total_servers || 0) : (state.dhcpServers || []).length;
  632. }
  633. }
  634. // Render Dashboard View
  635. function renderDashboard() {
  636. const matrix = document.getElementById('port-matrix');
  637. if (!matrix) return;
  638. const ifaces = state.interfaces || [];
  639. const sig = ifaces.map(i => `${i.name}:${i.state}:${(i.ipv4 || []).join(',')}:${i.type}:${i.is_vlan}`).join(';');
  640. if (matrix.dataset.sig === sig) {
  641. return; // Structure & link states haven't changed! Do not rebuild or flicker!
  642. }
  643. matrix.dataset.sig = sig;
  644. matrix.innerHTML = '';
  645. (state.interfaces || []).forEach(iface => {
  646. const isUp = iface.state === 'UP';
  647. const isVlan = iface.is_vlan;
  648. const portCard = document.createElement('div');
  649. portCard.className = `p-3 rounded-xl border transition-all cursor-pointer select-none group ${
  650. isUp
  651. ? (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')
  652. : 'bg-slate-900/40 border-slate-800/60 opacity-60 hover:opacity-100 hover:border-slate-700'
  653. }`;
  654. portCard.onclick = () => openIfaceModal(iface.name);
  655. let statusPillClass = isUp ? 'bg-emerald-500 shadow-sm shadow-emerald-500/50' : 'bg-rose-500';
  656. if (isVlan) statusPillClass = isUp ? 'bg-cyan-400 shadow-sm shadow-cyan-400/50' : 'bg-rose-500';
  657. portCard.innerHTML = `
  658. <div class="flex items-center justify-between mb-2">
  659. <span class="font-bold text-xs font-mono text-white group-hover:text-brand-400 transition truncate">${iface.name}</span>
  660. <span class="w-2 h-2 rounded-full ${statusPillClass}"></span>
  661. </div>
  662. <div class="text-[11px] font-mono text-slate-300 truncate">${iface.ipv4 && iface.ipv4.length > 0 ? iface.ipv4[0] : (iface.mac || 'No IP')}</div>
  663. <div class="mt-2 flex items-center justify-between text-[10px] text-slate-400">
  664. <span class="uppercase tracking-wider font-semibold">${isVlan ? `VLAN ${iface.vlan_id}` : iface.type}</span>
  665. <span id="port-card-rate-${iface.name}">${iface.rate?.rx_human || '0 B/s'}</span>
  666. </div>
  667. `;
  668. matrix.appendChild(portCard);
  669. });
  670. const ifaceTbody = document.getElementById('quick-interfaces-table');
  671. if (ifaceTbody) {
  672. ifaceTbody.innerHTML = '';
  673. (state.interfaces || []).forEach(i => {
  674. const isUp = i.state === 'UP';
  675. const tr = document.createElement('tr');
  676. tr.className = 'hover:bg-slate-800/40 transition cursor-pointer';
  677. tr.onclick = () => openIfaceModal(i.name);
  678. const rxStr = i.rate?.rx_human || '0 B/s';
  679. const txStr = i.rate?.tx_human || '0 B/s';
  680. tr.innerHTML = `
  681. <td class="py-2.5 font-bold text-white flex items-center gap-2">
  682. <span class="w-2 h-2 rounded-full ${isUp ? 'bg-emerald-400 shadow-sm shadow-emerald-400/50' : 'bg-rose-400'}"></span>
  683. <span>${i.name}</span>
  684. </td>
  685. <td class="py-2.5 text-slate-300 font-sans">
  686. ${getRoleBadge(i.role || 'LAN')}
  687. </td>
  688. <td class="py-2.5 text-slate-400 text-[11px] font-mono">${i.mac || '-'}</td>
  689. <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>
  690. <td class="py-2.5 text-slate-300 text-[11px] font-mono">
  691. <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>
  692. </td>
  693. <td class="py-2.5 text-right font-sans font-semibold">
  694. <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>
  695. </td>
  696. `;
  697. ifaceTbody.appendChild(tr);
  698. });
  699. }
  700. const vlanTbody = document.getElementById('quick-vlans-table');
  701. if (vlanTbody) {
  702. vlanTbody.innerHTML = '';
  703. }
  704. }
  705. // Expand / Collapse Handlers
  706. function toggleExpand(parentName) {
  707. if (state.expandedParents.has(parentName)) {
  708. state.expandedParents.delete(parentName);
  709. } else {
  710. state.expandedParents.add(parentName);
  711. }
  712. renderInterfacesList();
  713. }
  714. // VLAN Support Checker: 802.1Q sub-interfaces are only supported on physical ethernet, veth, bridge, bond
  715. function supportsVLAN(iface) {
  716. if (!iface) return false;
  717. if (iface.is_vlan) return false;
  718. const name = (iface.name || '').toLowerCase();
  719. const type = (iface.type || '').toLowerCase();
  720. const role = (iface.role || '').toLowerCase();
  721. // Exclude loopback
  722. if (name === 'lo' || type === 'loopback' || role === 'loopback') return false;
  723. // Exclude WireGuard (Layer 3 tunnel, no 802.1Q support)
  724. if (type === 'wireguard' || name.startsWith('wg')) return false;
  725. // Exclude PPP / PPPoE
  726. if (type === 'ppp' || name.startsWith('ppp')) return false;
  727. // Exclude other Layer 3 tunnels and dummy devices
  728. if (type === 'dummy' || type === 'gre' || type === 'sit' || type === 'tun' || type === 'tap' ||
  729. name.startsWith('gre') || name.startsWith('sit') || name.startsWith('ipsec') || name.startsWith('xfrm') || name.startsWith('dummy')) {
  730. return false;
  731. }
  732. // If name already contains a dot, it's already a sub-interface
  733. if (name.includes('.')) return false;
  734. return true;
  735. }
  736. // DHCP Client Support Checker: Only broadcast-capable layer-2 interfaces (Ethernet, veth, VLAN, bridge, bond)
  737. function supportsDHCPClient(iface) {
  738. if (!iface) return false;
  739. const name = (iface.name || '').toLowerCase();
  740. const type = (iface.type || '').toLowerCase();
  741. const role = (iface.role || '').toLowerCase();
  742. // Exclude loopback
  743. if (name === 'lo' || type === 'loopback' || role === 'loopback') return false;
  744. // Exclude WireGuard (Layer 3 point-to-point tunnel, no broadcast/DHCP)
  745. if (type === 'wireguard' || name.startsWith('wg')) return false;
  746. // Exclude PPP / PPPoE / L2TP / PPTP tunnels
  747. if (type === 'ppp' || name.startsWith('ppp') || name.startsWith('l2tp') || name.startsWith('pptp')) return false;
  748. // Exclude other Layer 3 tunnels and dummy devices
  749. if (type === 'dummy' || type === 'gre' || type === 'sit' || type === 'tun' || type === 'tap' ||
  750. name.startsWith('gre') || name.startsWith('sit') || name.startsWith('ipsec') || name.startsWith('xfrm') || name.startsWith('dummy')) {
  751. return false;
  752. }
  753. // Exclude bridge member/slave ports (bridge itself handles IP / DHCP)
  754. const isBridgePort = (state.bridgePorts || []).some(bp => bp.interface === iface.name);
  755. if (isBridgePort) return false;
  756. return true;
  757. }
  758. // Expand / Collapse Handlers
  759. function toggleExpand(parentName) {
  760. const childVlans = (state.vlans || []).filter(v => v.parent_name === parentName || v.name.startsWith(parentName + '.'));
  761. if (childVlans.length === 0) {
  762. // Cannot expand an interface with no VLANs
  763. state.expandedParents.delete(parentName);
  764. return;
  765. }
  766. if (state.expandedParents.has(parentName)) {
  767. state.expandedParents.delete(parentName);
  768. } else {
  769. state.expandedParents.add(parentName);
  770. }
  771. renderInterfacesList();
  772. }
  773. function expandAllIfaces(expand) {
  774. if (expand) {
  775. (state.interfaces || []).forEach(i => {
  776. const hasVlans = (state.vlans || []).some(v => v.parent_name === i.name || v.name.startsWith(i.name + '.'));
  777. if (!i.is_vlan && hasVlans) state.expandedParents.add(i.name);
  778. });
  779. } else {
  780. state.expandedParents.clear();
  781. }
  782. renderInterfacesList();
  783. }
  784. // =========================================================================
  785. // INTERFACE ROLE TAGS MANAGEMENT
  786. // =========================================================================
  787. const ROLE_COLORS = {
  788. amber: { bg: 'bg-amber-500/20', text: 'text-amber-300', border: 'border-amber-500/30' },
  789. blue: { bg: 'bg-blue-500/20', text: 'text-blue-300', border: 'border-blue-500/30' },
  790. cyan: { bg: 'bg-cyan-500/20', text: 'text-cyan-300', border: 'border-cyan-500/30' },
  791. emerald: { bg: 'bg-emerald-500/20', text: 'text-emerald-300', border: 'border-emerald-500/30' },
  792. purple: { bg: 'bg-purple-500/20', text: 'text-purple-300', border: 'border-purple-500/30' },
  793. rose: { bg: 'bg-rose-500/20', text: 'text-rose-300', border: 'border-rose-500/30' },
  794. indigo: { bg: 'bg-indigo-500/20', text: 'text-indigo-300', border: 'border-indigo-500/30' },
  795. sky: { bg: 'bg-sky-500/20', text: 'text-sky-300', border: 'border-sky-500/30' },
  796. slate: { bg: 'bg-slate-800', text: 'text-slate-300', border: 'border-slate-700' }
  797. };
  798. function getRoleBadge(roleName) {
  799. const name = roleName || 'LAN';
  800. const role = (state.roles || []).find(r => r.name.toLowerCase() === name.toLowerCase() || r.id.toLowerCase() === name.toLowerCase());
  801. const colorKey = (role?.color || 'blue').toLowerCase();
  802. const theme = ROLE_COLORS[colorKey] || ROLE_COLORS.blue;
  803. 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>`;
  804. }
  805. function switchIfaceSubTab(subTab) {
  806. state.activeIfaceSubTab = subTab;
  807. const treeTab = document.getElementById('ifaces-subtab-tree');
  808. const rolesTab = document.getElementById('ifaces-subtab-roles');
  809. const btnTree = document.getElementById('ifaces-subtab-btn-tree');
  810. const btnRoles = document.getElementById('ifaces-subtab-btn-roles');
  811. if (subTab === 'roles') {
  812. treeTab?.classList.add('hidden');
  813. rolesTab?.classList.remove('hidden');
  814. if (btnRoles) {
  815. 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';
  816. }
  817. if (btnTree) {
  818. 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';
  819. }
  820. loadRoles();
  821. } else {
  822. rolesTab?.classList.add('hidden');
  823. treeTab?.classList.remove('hidden');
  824. if (btnTree) {
  825. 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';
  826. }
  827. if (btnRoles) {
  828. 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';
  829. }
  830. renderInterfacesList();
  831. }
  832. }
  833. async function loadRoles() {
  834. try {
  835. const res = await fetch(`${API_BASE}/roles`);
  836. if (res.ok) {
  837. state.roles = await res.json();
  838. const countEl = document.getElementById('badge-roles-count');
  839. if (countEl) countEl.innerText = (state.roles || []).length;
  840. renderRolesTable();
  841. populateRoleSelects();
  842. }
  843. } catch (err) {
  844. console.error('Failed to load role tags:', err);
  845. }
  846. }
  847. function renderRolesTable() {
  848. const tbody = document.getElementById('roles-table-body');
  849. const empty = document.getElementById('roles-empty-state');
  850. if (!tbody) return;
  851. const roles = state.roles || [];
  852. if (roles.length === 0) {
  853. tbody.innerHTML = '';
  854. empty?.classList.remove('hidden');
  855. return;
  856. }
  857. empty?.classList.add('hidden');
  858. const sig = roles.map(r => `${r.id}:${r.name}:${r.color}:${r.description}:${(r.interfaces||[]).join(',')}`).join(';');
  859. if (tbody.dataset.sig === sig) return;
  860. tbody.dataset.sig = sig;
  861. tbody.innerHTML = roles.map(r => {
  862. const colorKey = (r.color || 'blue').toLowerCase();
  863. const theme = ROLE_COLORS[colorKey] || ROLE_COLORS.blue;
  864. const ifaces = Array.isArray(r.interfaces) ? r.interfaces : [];
  865. const ifacesChips = ifaces.length > 0
  866. ? 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('')
  867. : '<span class="text-slate-600 font-sans text-xs italic">Unassigned (0)</span>';
  868. return `
  869. <tr class="hover:bg-slate-800/40 transition">
  870. <td class="py-3 px-4">
  871. <span class="px-2.5 py-1 rounded text-xs font-semibold ${theme.bg} ${theme.text} border ${theme.border}">
  872. ${escapeHtml(r.name)}
  873. </span>
  874. </td>
  875. <td class="py-3 px-4 font-bold text-white font-mono flex items-center gap-2">
  876. <span>${escapeHtml(r.name)}</span>
  877. ${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>' : ''}
  878. </td>
  879. <td class="py-3 px-4 font-sans capitalize text-slate-300">
  880. <span class="inline-flex items-center gap-1.5">
  881. <span class="w-2 h-2 rounded-full ${theme.bg.replace('/20', '')}"></span>
  882. <span>${escapeHtml(r.color || 'blue')}</span>
  883. </span>
  884. </td>
  885. <td class="py-3 px-4 font-sans text-slate-400 text-xs">${escapeHtml(r.description || '-')}</td>
  886. <td class="py-3 px-4 font-sans">
  887. <div class="flex flex-wrap items-center">
  888. ${ifacesChips}
  889. </div>
  890. </td>
  891. <td class="py-3 px-4 text-right space-x-2 font-sans whitespace-nowrap">
  892. <button onclick="openRoleModal('${escapeHtml(r.id)}')"
  893. class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold px-2 py-1 rounded hover:bg-slate-800 transition">
  894. Edit
  895. </button>
  896. <button onclick="deleteRoleTag('${escapeHtml(r.id)}', '${escapeHtml(r.name)}')"
  897. class="text-xs text-rose-400 hover:text-rose-300 font-semibold px-2 py-1 rounded hover:bg-slate-800 transition">
  898. Delete
  899. </button>
  900. </td>
  901. </tr>
  902. `;
  903. }).join('');
  904. }
  905. function openRoleModal(id = null) {
  906. const modal = document.getElementById('role-modal');
  907. if (!modal) return;
  908. const idInput = document.getElementById('role-modal-id');
  909. const nameInput = document.getElementById('role-modal-name');
  910. const colorSelect = document.getElementById('role-modal-color');
  911. const descInput = document.getElementById('role-modal-desc');
  912. const title = document.getElementById('role-modal-title');
  913. if (id) {
  914. const role = (state.roles || []).find(r => r.id === id);
  915. if (role) {
  916. if (title) title.innerText = `Edit Role Tag: ${role.name}`;
  917. if (idInput) idInput.value = role.id;
  918. if (nameInput) nameInput.value = role.name;
  919. if (colorSelect) colorSelect.value = role.color || 'blue';
  920. if (descInput) descInput.value = role.description || '';
  921. }
  922. } else {
  923. if (title) title.innerText = 'Add Role Tag';
  924. if (idInput) idInput.value = '';
  925. if (nameInput) nameInput.value = '';
  926. if (colorSelect) colorSelect.value = 'blue';
  927. if (descInput) descInput.value = '';
  928. }
  929. updateRoleModalPreview();
  930. modal.classList.remove('hidden');
  931. }
  932. function closeRoleModal() {
  933. const modal = document.getElementById('role-modal');
  934. if (modal) modal.classList.add('hidden');
  935. }
  936. function updateRoleModalPreview() {
  937. const name = document.getElementById('role-modal-name')?.value.trim() || 'Preview';
  938. const colorKey = (document.getElementById('role-modal-color')?.value || 'blue').toLowerCase();
  939. const theme = ROLE_COLORS[colorKey] || ROLE_COLORS.blue;
  940. const preview = document.getElementById('role-modal-preview');
  941. if (preview) {
  942. preview.innerText = name;
  943. preview.className = `px-2.5 py-1 rounded text-xs font-semibold ${theme.bg} ${theme.text} border ${theme.border}`;
  944. }
  945. }
  946. async function submitSaveRole(e) {
  947. e.preventDefault();
  948. const id = document.getElementById('role-modal-id')?.value;
  949. const name = document.getElementById('role-modal-name')?.value.trim();
  950. const color = document.getElementById('role-modal-color')?.value;
  951. const desc = document.getElementById('role-modal-desc')?.value.trim();
  952. if (!name) return;
  953. try {
  954. const payload = { id, name, color, description: desc };
  955. const method = id ? 'PUT' : 'POST';
  956. const url = id ? `${API_BASE}/roles/${encodeURIComponent(id)}` : `${API_BASE}/roles`;
  957. const res = await fetch(url, {
  958. method,
  959. headers: { 'Content-Type': 'application/json' },
  960. body: JSON.stringify(payload)
  961. });
  962. if (res.ok) {
  963. showToast('Role Tag Saved', `Role tag "${name}" saved successfully`, 'success');
  964. closeRoleModal();
  965. await loadRoles();
  966. fetchData(false);
  967. } else {
  968. const err = await res.json();
  969. showToast('Error', err.error || err.message || 'Failed to save role tag', 'error');
  970. }
  971. } catch (err) {
  972. showToast('Error', err.message, 'error');
  973. }
  974. }
  975. async function deleteRoleTag(id, name) {
  976. if (!confirm(`Are you sure you want to delete role tag "${name}"?\nInterfaces assigned to this role will default to LAN.`)) return;
  977. try {
  978. const res = await fetch(`${API_BASE}/roles/${encodeURIComponent(id)}`, {
  979. method: 'DELETE'
  980. });
  981. if (res.ok) {
  982. showToast('Role Tag Deleted', `Role tag "${name}" removed`, 'success');
  983. await loadRoles();
  984. fetchData(false);
  985. } else {
  986. const err = await res.json();
  987. showToast('Error', err.error || err.message || 'Failed to delete role tag', 'error');
  988. }
  989. } catch (err) {
  990. showToast('Error', err.message, 'error');
  991. }
  992. }
  993. function populateRoleSelects(selectedRole = '') {
  994. const ifaceSelect = document.getElementById('modal-iface-role');
  995. const vlanSelect = document.getElementById('vlan-role');
  996. const roles = state.roles || [];
  997. const optionsHtml = roles.map(r => `<option value="${escapeHtml(r.name)}">${escapeHtml(r.name)}${r.description ? ` (${escapeHtml(r.description)})` : ''}</option>`).join('');
  998. if (ifaceSelect) {
  999. const currentVal = selectedRole || ifaceSelect.value || 'LAN';
  1000. if (ifaceSelect.dataset.optionsSig !== optionsHtml) {
  1001. ifaceSelect.innerHTML = optionsHtml;
  1002. ifaceSelect.dataset.optionsSig = optionsHtml;
  1003. }
  1004. if (currentVal) ifaceSelect.value = currentVal;
  1005. }
  1006. if (vlanSelect) {
  1007. const currentVal = selectedRole || vlanSelect.value || 'LAN';
  1008. if (vlanSelect.dataset.optionsSig !== optionsHtml) {
  1009. vlanSelect.innerHTML = optionsHtml;
  1010. vlanSelect.dataset.optionsSig = optionsHtml;
  1011. }
  1012. if (currentVal) vlanSelect.value = currentVal;
  1013. }
  1014. }
  1015. // Filter and Render Hierarchical Interfaces List
  1016. function filterIfaces(filter) {
  1017. state.ifaceFilter = filter || 'all';
  1018. renderInterfacesList();
  1019. }
  1020. function renderInterfacesList() {
  1021. const tbody = document.getElementById('interfaces-tree-tbody');
  1022. const emptyState = document.getElementById('interfaces-empty-state');
  1023. const summary = document.getElementById('ifaces-list-summary');
  1024. const query = (document.getElementById('iface-search')?.value || '').trim().toLowerCase();
  1025. const allIfaces = state.interfaces || [];
  1026. const allVlans = state.vlans || [];
  1027. const parentIfaces = allIfaces.filter(i => !i.is_vlan);
  1028. const filteredParents = parentIfaces.filter(parent => {
  1029. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  1030. if (query) {
  1031. const matchName = parent.name.toLowerCase().includes(query);
  1032. const matchIp = (parent.ipv4 || []).some(ip => ip.toLowerCase().includes(query));
  1033. const matchRole = (parent.role || '').toLowerCase().includes(query);
  1034. const matchType = (parent.type || '').toLowerCase().includes(query);
  1035. const matchVlan = childVlans.some(v =>
  1036. v.name.toLowerCase().includes(query) ||
  1037. String(v.vlan_id).includes(query) ||
  1038. (v.ipv4 || []).some(ip => ip.toLowerCase().includes(query)) ||
  1039. (v.description || '').toLowerCase().includes(query)
  1040. );
  1041. if (!matchName && !matchIp && !matchRole && !matchType && !matchVlan) return false;
  1042. }
  1043. if (state.ifaceFilter === 'has_vlans') return childVlans.length > 0;
  1044. if (state.ifaceFilter === 'physical') return parent.type !== 'loopback';
  1045. if (state.ifaceFilter === 'up') return parent.state === 'UP';
  1046. return true;
  1047. });
  1048. if (summary) {
  1049. summary.innerText = `${parentIfaces.length} Interfaces • ${allVlans.length} Active VLANs`;
  1050. }
  1051. if (filteredParents.length === 0) {
  1052. emptyState?.classList.remove('hidden');
  1053. tbody.innerHTML = '';
  1054. return;
  1055. }
  1056. emptyState?.classList.add('hidden');
  1057. const sig = `${state.ifaceFilter}|${query}|` + filteredParents.map(p => {
  1058. const cVlans = allVlans.filter(v => v.parent_name === p.name || v.name.startsWith(p.name + '.'));
  1059. const dhcp = (state.dhcpClients || []).find(dc => dc.interface === p.name);
  1060. return `${p.name}:${p.state}:${p.role||'LAN'}:${(p.ipv4||[]).join(',')}:${p.mtu}:${cVlans.length}:${state.expandedParents.has(p.name)}:${dhcp?.status || ''}`;
  1061. }).join(';');
  1062. if (tbody.dataset.sig === sig) {
  1063. return; // ZERO changes to structure, links, IPs or VLANs! Do not rebuild DOM!
  1064. }
  1065. tbody.dataset.sig = sig;
  1066. tbody.innerHTML = '';
  1067. filteredParents.forEach(parent => {
  1068. const isUp = parent.state === 'UP';
  1069. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  1070. const hasVlans = childVlans.length > 0;
  1071. const isExpanded = hasVlans && state.expandedParents.has(parent.name);
  1072. const canHaveVlan = supportsVLAN(parent);
  1073. const parentRow = document.createElement('tr');
  1074. parentRow.className = `hover:bg-slate-800/50 transition border-b border-slate-800/80 ${isExpanded ? 'bg-slate-900/80' : ''}`;
  1075. parentRow.innerHTML = `
  1076. <td class="py-3 px-3 text-center">
  1077. ${hasVlans ? `
  1078. <button onclick="toggleExpand('${parent.name}')" title="${isExpanded ? 'Collapse VLANs' : 'Expand VLANs'}"
  1079. class="w-6 h-6 rounded flex items-center justify-center hover:bg-slate-800 text-slate-400 hover:text-white transition">
  1080. <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">
  1081. <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M9 5l7 7-7 7" />
  1082. </svg>
  1083. </button>
  1084. ` : `
  1085. <div class="w-6 h-6 flex items-center justify-center text-slate-700 select-none">
  1086. <span class="w-1.5 h-1.5 rounded-full bg-slate-800"></span>
  1087. </div>
  1088. `}
  1089. </td>
  1090. <td class="py-3 px-4">
  1091. <div class="flex items-center space-x-2.5">
  1092. <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">
  1093. ${parent.type === 'loopback' ? 'LO' : (parent.type === 'wireguard' ? 'WG' : (parent.type === 'bridge' ? 'BR' : 'NIC'))}
  1094. </div>
  1095. <div>
  1096. <div class="flex items-center gap-2">
  1097. <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'}">
  1098. <span>${parent.name}</span>
  1099. <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>
  1100. </span>
  1101. ${hasVlans ? `
  1102. <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>
  1103. ` : `
  1104. <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>
  1105. `}
  1106. </div>
  1107. <div class="text-[10px] text-slate-500 font-sans mt-0.5">${parent.type}</div>
  1108. </div>
  1109. </div>
  1110. </td>
  1111. <td class="py-3 px-4 font-sans">
  1112. <div class="flex items-center gap-1.5">
  1113. ${getRoleBadge(parent.role || 'LAN')}
  1114. <span class="text-xs text-slate-400 truncate max-w-[120px]">${parent.description || '-'}</span>
  1115. </div>
  1116. </td>
  1117. <td class="py-3 px-4">
  1118. ${parent.ipv4 && parent.ipv4.length > 0
  1119. ? `<div class="text-white font-medium">${parent.ipv4[0]}</div>`
  1120. : '<span class="text-slate-600 font-sans">Unassigned</span>'
  1121. }
  1122. ${(() => {
  1123. const c = (state.dhcpClients || []).find(dc => dc.interface === parent.name);
  1124. if (!c) return '';
  1125. 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');
  1126. 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>`;
  1127. })()}
  1128. </td>
  1129. <td class="py-3 px-4 text-slate-400 text-[11px]">
  1130. <div>${parent.mac || 'N/A'}</div>
  1131. <div class="text-[10px] text-slate-500">MTU ${parent.mtu}</div>
  1132. </td>
  1133. <td class="py-3 px-4 text-[11px]">
  1134. <div class="flex items-center space-x-2">
  1135. <span id="iface-rate-rx-${parent.name}" class="text-emerald-400">↓ ${parent.rate?.rx_human || '0 B/s'}</span>
  1136. <span id="iface-rate-tx-${parent.name}" class="text-cyan-400">↑ ${parent.rate?.tx_human || '0 B/s'}</span>
  1137. </div>
  1138. </td>
  1139. <td class="py-3 px-4 font-sans">
  1140. <button onclick="toggleInterfaceState('${parent.name}', '${isUp ? 'down' : 'up'}')"
  1141. class="flex items-center gap-1.5 text-xs font-semibold px-2.5 py-1 rounded-full transition ${
  1142. 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'
  1143. }" title="Click to toggle link status">
  1144. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  1145. <span>${parent.state}</span>
  1146. </button>
  1147. </td>
  1148. <td class="py-3 px-4 text-right space-x-2 font-sans">
  1149. ${(() => {
  1150. const c = (state.dhcpClients || []).find(dc => dc.interface === parent.name);
  1151. if (c) {
  1152. 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>`;
  1153. }
  1154. if (!supportsDHCPClient(parent)) {
  1155. return '';
  1156. }
  1157. 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>`;
  1158. })()}
  1159. ${canHaveVlan ? `
  1160. <button onclick="openVlanModal('${parent.name}')"
  1161. 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">
  1162. + Add VLAN
  1163. </button>
  1164. ` : ''}
  1165. <button onclick="openIfaceModal('${parent.name}')"
  1166. 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">
  1167. Edit
  1168. </button>
  1169. </td>
  1170. `;
  1171. tbody.appendChild(parentRow);
  1172. if (isExpanded) {
  1173. const drawerRow = document.createElement('tr');
  1174. drawerRow.className = 'bg-slate-950/80 border-b border-slate-800/90';
  1175. const drawerCell = document.createElement('td');
  1176. drawerCell.colSpan = 8;
  1177. drawerCell.className = 'p-0';
  1178. drawerCell.innerHTML = `
  1179. <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">
  1180. <div class="flex items-center justify-between mb-3">
  1181. <div class="flex items-center space-x-3">
  1182. <span class="font-bold text-xs text-white uppercase tracking-wider flex items-center gap-1.5 font-sans">
  1183. <span>VLAN Sub-interfaces on <code class="text-cyan-300 lowercase">${parent.name}</code></span>
  1184. </span>
  1185. <span class="text-[11px] bg-cyan-950 text-cyan-400 px-2 py-0.5 rounded-full border border-cyan-800/60 font-mono">
  1186. ${childVlans.length} Attached
  1187. </span>
  1188. </div>
  1189. <button onclick="openVlanModal('${parent.name}')"
  1190. 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">
  1191. <span>+ Create VLAN on ${parent.name}</span>
  1192. </button>
  1193. </div>
  1194. ${childVlans.length === 0 ? `
  1195. <div class="p-6 text-center border border-dashed border-slate-800 rounded-xl bg-slate-900/40 font-sans">
  1196. <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>
  1197. <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">
  1198. <span>+ Create Your First VLAN on ${parent.name}</span>
  1199. </button>
  1200. </div>
  1201. ` : `
  1202. <div class="overflow-x-auto rounded-lg border border-slate-800 bg-slate-900/90 shadow-inner">
  1203. <table class="w-full text-left text-xs font-mono">
  1204. <thead class="text-slate-400 bg-slate-950/70 border-b border-slate-800 uppercase tracking-wider text-[10px] font-sans">
  1205. <tr>
  1206. <th class="py-2.5 px-4">VLAN ID</th>
  1207. <th class="py-2.5 px-4">Interface Device</th>
  1208. <th class="py-2.5 px-4">Subnet Gateway</th>
  1209. <th class="py-2.5 px-4">Role / Alias</th>
  1210. <th class="py-2.5 px-4">MTU</th>
  1211. <th class="py-2.5 px-4">Throughput</th>
  1212. <th class="py-2.5 px-4">Status</th>
  1213. <th class="py-2.5 px-4 text-right">Actions</th>
  1214. </tr>
  1215. </thead>
  1216. <tbody class="divide-y divide-slate-800/70">
  1217. ${childVlans.map(v => {
  1218. const isVlanUp = v.state === 'UP';
  1219. return `
  1220. <tr class="hover:bg-slate-800/40 transition">
  1221. <td class="py-2.5 px-4">
  1222. <span class="px-2 py-0.5 rounded text-xs font-bold bg-cyan-950 text-cyan-300 border border-cyan-800 shadow-sm">
  1223. VLAN ${v.vlan_id}
  1224. </span>
  1225. </td>
  1226. <td class="py-2.5 px-4 font-bold text-white flex items-center gap-1.5">
  1227. <span class="text-cyan-500">└─</span>
  1228. <span class="cursor-pointer hover:text-cyan-400 flex items-center gap-1" onclick="openIfaceModal('${v.name}')" title="Configure / Rename ${v.name}">
  1229. <span>${v.name}</span>
  1230. <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>
  1231. </span>
  1232. </td>
  1233. <td class="py-2.5 px-4 text-emerald-400 font-medium">
  1234. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  1235. ${(() => {
  1236. const c = (state.dhcpClients || []).find(dc => dc.interface === v.name);
  1237. if (!c) return '';
  1238. 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';
  1239. 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>`;
  1240. })()}
  1241. </td>
  1242. <td class="py-2.5 px-4 font-sans text-slate-300">
  1243. <div class="flex items-center gap-1.5">
  1244. ${getRoleBadge(v.role || 'LAN')}
  1245. <span class="text-slate-400 text-xs">${v.description || '-'}</span>
  1246. </div>
  1247. </td>
  1248. <td class="py-2.5 px-4 text-slate-400">${v.mtu}</td>
  1249. <td class="py-2.5 px-4 text-[11px]">
  1250. <span id="vlan-rate-rx-${v.name}" class="text-emerald-400">↓ ${v.rate?.rx_human || '0 B/s'}</span>
  1251. <span id="vlan-rate-tx-${v.name}" class="text-cyan-400 ml-1.5">↑ ${v.rate?.tx_human || '0 B/s'}</span>
  1252. </td>
  1253. <td class="py-2.5 px-4 font-sans">
  1254. <button onclick="toggleInterfaceState('${v.name}', '${isVlanUp ? 'down' : 'up'}')"
  1255. class="flex items-center gap-1 text-[11px] font-semibold px-2 py-0.5 rounded-full ${
  1256. 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'
  1257. }">
  1258. <span class="w-1.5 h-1.5 rounded-full ${isVlanUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  1259. <span>${v.state}</span>
  1260. </button>
  1261. </td>
  1262. <td class="py-2.5 px-4 text-right space-x-1.5 font-sans">
  1263. ${(() => {
  1264. const c = (state.dhcpClients || []).find(dc => dc.interface === v.name);
  1265. if (c) {
  1266. 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>`;
  1267. }
  1268. if (!supportsDHCPClient(v)) {
  1269. return '';
  1270. }
  1271. 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>`;
  1272. })()}
  1273. <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>
  1274. <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>
  1275. </td>
  1276. </tr>
  1277. `;
  1278. }).join('')}
  1279. </tbody>
  1280. </table>
  1281. </div>
  1282. `}
  1283. </div>
  1284. `;
  1285. drawerRow.appendChild(drawerCell);
  1286. tbody.appendChild(drawerRow);
  1287. }
  1288. });
  1289. }
  1290. // Render VLANs Dedicated View
  1291. function renderVlansList() {
  1292. const tbody = document.getElementById('vlans-table-body');
  1293. if (!tbody) return;
  1294. const emptyState = document.getElementById('vlans-empty-state');
  1295. const countBadge = document.getElementById('vlans-table-count');
  1296. const query = (document.getElementById('vlan-search')?.value || '').toLowerCase();
  1297. const allVlans = state.vlans || [];
  1298. if (countBadge) countBadge.innerText = allVlans.length;
  1299. const filtered = allVlans.filter(v => {
  1300. if (!query) return true;
  1301. return v.name.toLowerCase().includes(query) ||
  1302. String(v.vlan_id).includes(query) ||
  1303. (v.description || '').toLowerCase().includes(query) ||
  1304. (v.ipv4 && v.ipv4.some(ip => ip.includes(query)));
  1305. });
  1306. if (allVlans.length === 0) {
  1307. emptyState.classList.remove('hidden');
  1308. tbody.innerHTML = '';
  1309. return;
  1310. }
  1311. emptyState.classList.add('hidden');
  1312. const sig = `${query}|` + filtered.map(v => `${v.name}:${v.state}:${(v.ipv4||[]).join(',')}:${v.vlan_id}:${v.mtu}`).join(';');
  1313. if (tbody.dataset.sig === sig) return;
  1314. tbody.dataset.sig = sig;
  1315. tbody.innerHTML = '';
  1316. filtered.forEach(v => {
  1317. const isUp = v.state === 'UP';
  1318. const tr = document.createElement('tr');
  1319. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  1320. tr.innerHTML = `
  1321. <td class="py-3 px-4">
  1322. <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">
  1323. VLAN ${v.vlan_id}
  1324. </span>
  1325. </td>
  1326. <td class="py-3 px-4 font-bold text-white">
  1327. <span class="cursor-pointer hover:text-cyan-400 flex items-center gap-1.5" onclick="openIfaceModal('${v.name}')" title="Configure / Rename ${v.name}">
  1328. <span>${v.name}</span>
  1329. <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>
  1330. </span>
  1331. </td>
  1332. <td class="py-3 px-4 text-slate-300">
  1333. <span class="bg-slate-800 text-slate-200 px-2 py-0.5 rounded text-[11px]">${v.parent_name || 'eth0'}</span>
  1334. </td>
  1335. <td class="py-3 px-4 text-emerald-400 font-medium">
  1336. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  1337. </td>
  1338. <td class="py-3 px-4 text-slate-300 font-sans">
  1339. <span class="text-slate-400 text-xs">${v.description || v.role || '-'}</span>
  1340. </td>
  1341. <td class="py-3 px-4 text-slate-400">${v.mtu}</td>
  1342. <td class="py-3 px-4 font-sans">
  1343. <button onclick="toggleInterfaceState('${v.name}', '${isUp ? 'down' : 'up'}')"
  1344. class="flex items-center gap-1.5 text-xs font-semibold px-2 py-0.5 rounded-full ${
  1345. 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'
  1346. }">
  1347. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  1348. <span>${v.state}</span>
  1349. </button>
  1350. </td>
  1351. <td class="py-3 px-4 text-right space-x-2 font-sans">
  1352. <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>
  1353. <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>
  1354. </td>
  1355. `;
  1356. tbody.appendChild(tr);
  1357. });
  1358. }
  1359. // Toggle interface UP / DOWN
  1360. async function toggleInterfaceState(name, newState) {
  1361. try {
  1362. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(name)}/state`, {
  1363. method: 'POST',
  1364. headers: { 'Content-Type': 'application/json' },
  1365. body: JSON.stringify({ state: newState })
  1366. });
  1367. const data = await res.json();
  1368. if (res.ok) {
  1369. showToast('Interface Updated', `Interface ${name} is now ${newState.toUpperCase()}`, 'success');
  1370. fetchData(false);
  1371. } else {
  1372. showToast('Error', data.message || 'Failed to toggle interface state', 'error');
  1373. }
  1374. } catch (err) {
  1375. showToast('Error', err.message, 'error');
  1376. }
  1377. }
  1378. // ---------------- MikroTik Flag & Utilities ----------------
  1379. function renderMikroTikFlag(running, disabled) {
  1380. if (running) {
  1381. 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>`;
  1382. }
  1383. if (disabled) {
  1384. 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>`;
  1385. }
  1386. 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>`;
  1387. }
  1388. function copyToClipboard(text, label = 'Text') {
  1389. navigator.clipboard.writeText(text).then(() => {
  1390. showToast('Copied', `${label} copied to clipboard`, 'success');
  1391. }).catch(() => {
  1392. prompt('Copy value:', text);
  1393. });
  1394. }
  1395. // ======================== PPP Profiles Shared Helper ========================
  1396. async function fetchPPPProfilesList() {
  1397. try {
  1398. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`);
  1399. if (res.ok) {
  1400. state.pppProfiles = await res.json();
  1401. }
  1402. } catch (err) {
  1403. console.error('Failed to load PPP profiles:', err);
  1404. }
  1405. }
  1406. function populateProfileSelect(selectId, selectedVal, defaultVal = 'default') {
  1407. const sel = document.getElementById(selectId);
  1408. if (!sel) return;
  1409. const profiles = (state.pppProfiles && state.pppProfiles.length > 0) ? state.pppProfiles : [
  1410. { name: 'default', use_encryption: 'no' },
  1411. { name: 'default-encryption', use_encryption: 'required' }
  1412. ];
  1413. sel.innerHTML = '';
  1414. profiles.forEach(p => {
  1415. const opt = document.createElement('option');
  1416. opt.value = p.name;
  1417. const encBadge = p.use_encryption === 'required' ? ' (MPPE-128)' : (p.use_encryption === 'yes' ? ' (MPPE)' : '');
  1418. opt.innerText = `${p.name}${encBadge}`;
  1419. sel.appendChild(opt);
  1420. });
  1421. if (selectedVal) {
  1422. sel.value = selectedVal;
  1423. } else {
  1424. sel.value = defaultVal;
  1425. }
  1426. if (!sel.value && sel.options.length > 0) {
  1427. sel.selectedIndex = 0;
  1428. }
  1429. }
  1430. // ======================== PPPoE Multi-Instance ========================
  1431. async function loadPPPoE(populateInputs = true) {
  1432. try {
  1433. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  1434. await fetchPPPProfilesList();
  1435. }
  1436. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`);
  1437. const list = await res.json();
  1438. state.pppoeList = Array.isArray(list) ? list : [];
  1439. const badge = document.getElementById('pppoe-count-badge');
  1440. if (badge) badge.innerText = `${state.pppoeList.length} Interface${state.pppoeList.length !== 1 ? 's' : ''}`;
  1441. const tbody = document.getElementById('pppoe-table-body');
  1442. const empty = document.getElementById('pppoe-empty');
  1443. if (!tbody) return;
  1444. tbody.innerHTML = '';
  1445. if (state.pppoeList.length === 0) {
  1446. if (empty) empty.classList.remove('hidden');
  1447. } else {
  1448. if (empty) empty.classList.add('hidden');
  1449. state.pppoeList.forEach(inst => {
  1450. const tr = document.createElement('tr');
  1451. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1452. tr.innerHTML = `
  1453. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  1454. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  1455. <td class="py-2.5 px-3 text-cyan-400 font-mono">${escapeHtml(inst.interface)}</td>
  1456. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  1457. <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>
  1458. <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>
  1459. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  1460. <td class="py-2.5 px-3 text-center">
  1461. <span class="px-2 py-0.5 rounded text-[10px] font-sans ${inst.default_route ? 'bg-blue-500/20 text-blue-300 border border-blue-500/30' : 'bg-slate-800 text-slate-500'}">
  1462. ${inst.default_route ? 'Yes' : 'No'}
  1463. </span>
  1464. </td>
  1465. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  1466. ${inst.running ? `
  1467. <button onclick="disconnectPPPoEInstance('${inst.name}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  1468. ` : `
  1469. <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>
  1470. `}
  1471. <button onclick="togglePPPoEState('${inst.name}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  1472. ${inst.disabled ? 'Enable' : 'Disable'}
  1473. </button>
  1474. <button onclick="openEditPPPoEModal('${inst.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  1475. <button onclick="deletePPPoEInstance('${inst.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  1476. </td>
  1477. `;
  1478. tbody.appendChild(tr);
  1479. });
  1480. }
  1481. } catch (err) {
  1482. console.error('Failed to load PPPoE:', err);
  1483. }
  1484. }
  1485. function openAddPPPoEModal() {
  1486. document.getElementById('pppoe-modal-title').innerText = 'Add PPPoE Client Interface';
  1487. document.getElementById('pppoe-modal-edit-orig').value = '';
  1488. document.getElementById('pppoe-modal-name').value = `pppoe-out${(state.pppoeList || []).length + 1}`;
  1489. document.getElementById('pppoe-modal-name').readOnly = false;
  1490. document.getElementById('pppoe-modal-user').value = '';
  1491. document.getElementById('pppoe-modal-pass').value = '';
  1492. document.getElementById('pppoe-modal-service').value = '';
  1493. document.getElementById('pppoe-modal-mtu').value = '1492';
  1494. document.getElementById('pppoe-modal-defroute').checked = true;
  1495. document.getElementById('pppoe-modal-reconnect').checked = true;
  1496. document.getElementById('pppoe-modal-disabled').checked = false;
  1497. // Populate profiles
  1498. populateProfileSelect('pppoe-modal-profile', 'default', 'default');
  1499. // Populate interfaces
  1500. const sel = document.getElementById('pppoe-modal-iface');
  1501. sel.innerHTML = '';
  1502. (state.interfaces || []).forEach(i => {
  1503. if (i.name === 'lo') return;
  1504. const opt = document.createElement('option');
  1505. opt.value = i.name;
  1506. opt.innerText = `${i.name} (${i.role || i.type})`;
  1507. sel.appendChild(opt);
  1508. });
  1509. document.getElementById('pppoe-modal').classList.remove('hidden');
  1510. }
  1511. function openEditPPPoEModal(name) {
  1512. const inst = (state.pppoeList || []).find(i => i.name === name);
  1513. if (!inst) return;
  1514. document.getElementById('pppoe-modal-title').innerText = `Edit PPPoE Client: ${name}`;
  1515. document.getElementById('pppoe-modal-edit-orig').value = name;
  1516. document.getElementById('pppoe-modal-name').value = inst.name;
  1517. document.getElementById('pppoe-modal-name').readOnly = true;
  1518. document.getElementById('pppoe-modal-user').value = inst.username || '';
  1519. document.getElementById('pppoe-modal-pass').value = inst.password || '';
  1520. document.getElementById('pppoe-modal-service').value = inst.service_name || '';
  1521. document.getElementById('pppoe-modal-mtu').value = inst.mtu || 1492;
  1522. document.getElementById('pppoe-modal-defroute').checked = inst.default_route ?? true;
  1523. document.getElementById('pppoe-modal-reconnect').checked = inst.auto_reconnect ?? true;
  1524. document.getElementById('pppoe-modal-disabled').checked = !!inst.disabled;
  1525. // Populate profiles
  1526. populateProfileSelect('pppoe-modal-profile', inst.profile || 'default', 'default');
  1527. const sel = document.getElementById('pppoe-modal-iface');
  1528. sel.innerHTML = '';
  1529. (state.interfaces || []).forEach(i => {
  1530. if (i.name === 'lo') return;
  1531. const opt = document.createElement('option');
  1532. opt.value = i.name;
  1533. opt.innerText = `${i.name} (${i.role || i.type})`;
  1534. if (i.name === inst.interface) opt.selected = true;
  1535. sel.appendChild(opt);
  1536. });
  1537. document.getElementById('pppoe-modal').classList.remove('hidden');
  1538. }
  1539. function closePPPoEModal() {
  1540. document.getElementById('pppoe-modal').classList.add('hidden');
  1541. }
  1542. async function submitSavePPPoE(e) {
  1543. e.preventDefault();
  1544. const name = document.getElementById('pppoe-modal-name').value.trim();
  1545. const iface = document.getElementById('pppoe-modal-iface').value;
  1546. const user = document.getElementById('pppoe-modal-user').value.trim();
  1547. const pass = document.getElementById('pppoe-modal-pass').value;
  1548. const profile = document.getElementById('pppoe-modal-profile')?.value || 'default';
  1549. const service = document.getElementById('pppoe-modal-service').value.trim();
  1550. const mtu = parseInt(document.getElementById('pppoe-modal-mtu').value, 10) || 1492;
  1551. const defRoute = document.getElementById('pppoe-modal-defroute').checked;
  1552. const reconnect = document.getElementById('pppoe-modal-reconnect').checked;
  1553. const disabled = document.getElementById('pppoe-modal-disabled').checked;
  1554. try {
  1555. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`, {
  1556. method: 'POST',
  1557. headers: { 'Content-Type': 'application/json' },
  1558. body: JSON.stringify({
  1559. name,
  1560. interface: iface,
  1561. username: user,
  1562. password: pass,
  1563. profile: profile,
  1564. service_name: service,
  1565. mtu,
  1566. default_route: defRoute,
  1567. auto_reconnect: reconnect,
  1568. disabled
  1569. })
  1570. });
  1571. if (res.ok) {
  1572. showToast('PPPoE Saved', `Configuration for ${name} saved`, 'success');
  1573. closePPPoEModal();
  1574. loadPPPoE(false);
  1575. fetchData(false);
  1576. } else {
  1577. const err = await res.json();
  1578. showToast('Error', err.message || 'Failed to save PPPoE', 'error');
  1579. }
  1580. } catch (err) {
  1581. showToast('Error', err.message, 'error');
  1582. }
  1583. }
  1584. async function connectPPPoEInstance(name) {
  1585. try {
  1586. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  1587. if (res.ok) {
  1588. showToast('Connecting', `Dialing ${name}...`, 'info');
  1589. setTimeout(() => loadPPPoE(false), 2000);
  1590. }
  1591. } catch (err) {
  1592. showToast('Error', err.message, 'error');
  1593. }
  1594. }
  1595. async function disconnectPPPoEInstance(name) {
  1596. try {
  1597. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  1598. if (res.ok) {
  1599. showToast('Disconnected', `${name} session terminated`, 'info');
  1600. setTimeout(() => loadPPPoE(false), 1000);
  1601. }
  1602. } catch (err) {
  1603. showToast('Error', err.message, 'error');
  1604. }
  1605. }
  1606. async function togglePPPoEState(name, enable) {
  1607. try {
  1608. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/state`, {
  1609. method: 'POST',
  1610. headers: { 'Content-Type': 'application/json' },
  1611. body: JSON.stringify({ enabled: enable })
  1612. });
  1613. if (res.ok) {
  1614. showToast(enable ? 'Enabled' : 'Disabled', `${name} is now ${enable ? 'enabled' : 'disabled'}`, 'info');
  1615. loadPPPoE(false);
  1616. }
  1617. } catch (err) {
  1618. showToast('Error', err.message, 'error');
  1619. }
  1620. }
  1621. async function deletePPPoEInstance(name) {
  1622. if (!confirm(`Are you sure you want to delete PPPoE client ${name}?`)) return;
  1623. try {
  1624. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1625. if (res.ok) {
  1626. showToast('Deleted', `PPPoE client ${name} removed`, 'success');
  1627. loadPPPoE(false);
  1628. fetchData(false);
  1629. }
  1630. } catch (err) {
  1631. showToast('Error', err.message, 'error');
  1632. }
  1633. }
  1634. // ======================== WireGuard Multi-Interface & Multi-Peer ========================
  1635. state.wgSubTab = 'ifaces';
  1636. function switchWGSubTab(tab) {
  1637. state.wgSubTab = tab;
  1638. const ifacesPanel = document.getElementById('wg-subtab-ifaces');
  1639. const peersPanel = document.getElementById('wg-subtab-peers');
  1640. const ifacesBtn = document.getElementById('wg-subtab-btn-ifaces');
  1641. const peersBtn = document.getElementById('wg-subtab-btn-peers');
  1642. if (tab === 'ifaces') {
  1643. ifacesPanel?.classList.remove('hidden');
  1644. peersPanel?.classList.add('hidden');
  1645. 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';
  1646. 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';
  1647. } else {
  1648. ifacesPanel?.classList.add('hidden');
  1649. peersPanel?.classList.remove('hidden');
  1650. 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';
  1651. 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';
  1652. renderWGPeers();
  1653. }
  1654. }
  1655. async function loadWireGuard(populateInputs = true) {
  1656. try {
  1657. const [ifacesRes, peersRes] = await Promise.all([
  1658. fetch(`${API_BASE}/vpn/wireguard/interfaces`),
  1659. fetch(`${API_BASE}/vpn/wireguard/peers`)
  1660. ]);
  1661. const ifaces = ifacesRes.ok ? await ifacesRes.json() : [];
  1662. const peers = peersRes.ok ? await peersRes.json() : [];
  1663. state.wgInterfaces = Array.isArray(ifaces) ? ifaces : [];
  1664. state.wgPeers = Array.isArray(peers) ? peers : [];
  1665. // Badges
  1666. const ifacesCountBadge = document.getElementById('wg-ifaces-count');
  1667. if (ifacesCountBadge) ifacesCountBadge.innerText = `${state.wgInterfaces.length} Interfaces`;
  1668. const peersCountBadge = document.getElementById('wg-peers-count');
  1669. if (peersCountBadge) peersCountBadge.innerText = `${state.wgPeers.length} Peers`;
  1670. const subTabIfaces = document.getElementById('wg-subtab-badge-ifaces');
  1671. if (subTabIfaces) subTabIfaces.innerText = state.wgInterfaces.length;
  1672. const subTabPeers = document.getElementById('wg-subtab-badge-peers');
  1673. if (subTabPeers) subTabPeers.innerText = state.wgPeers.length;
  1674. // Render Interfaces
  1675. const ifacesTbody = document.getElementById('wg-ifaces-table-body');
  1676. const ifacesEmpty = document.getElementById('wg-ifaces-empty');
  1677. if (ifacesTbody) {
  1678. ifacesTbody.innerHTML = '';
  1679. if (state.wgInterfaces.length === 0) {
  1680. if (ifacesEmpty) ifacesEmpty.classList.remove('hidden');
  1681. } else {
  1682. if (ifacesEmpty) ifacesEmpty.classList.add('hidden');
  1683. state.wgInterfaces.forEach(iface => {
  1684. const peersOnIface = state.wgPeers.filter(p => p.interface === iface.name).length;
  1685. const tr = document.createElement('tr');
  1686. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1687. tr.innerHTML = `
  1688. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(iface.running, iface.disabled)}</td>
  1689. <td class="py-2.5 px-3">
  1690. <div class="flex items-center gap-1.5">
  1691. <span class="font-bold text-white">${escapeHtml(iface.name)}</span>
  1692. ${iface.comment ? `<span class="text-[10px] text-slate-400 font-sans italic">(${escapeHtml(iface.comment)})</span>` : ''}
  1693. </div>
  1694. </td>
  1695. <td class="py-2.5 px-3 text-amber-400 font-mono">${iface.listen_port}</td>
  1696. <td class="py-2.5 px-3 text-emerald-400 font-mono">${iface.address || '<span class="text-slate-600 font-sans">--</span>'}</td>
  1697. <td class="py-2.5 px-3 text-slate-300 font-mono">
  1698. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${iface.public_key}', 'Public Key')" title="Click to copy: ${iface.public_key}">
  1699. ${(iface.public_key || '').substring(0, 10)}... 📋
  1700. </span>
  1701. </td>
  1702. <td class="py-2.5 px-3 text-slate-400 font-mono">${iface.mtu || 1420}</td>
  1703. <td class="py-2.5 px-3 text-center">
  1704. <span class="px-2 py-0.5 rounded text-[10px] font-sans bg-slate-800 text-slate-300">${peersOnIface} peer${peersOnIface !== 1 ? 's' : ''}</span>
  1705. </td>
  1706. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  1707. ${iface.running ? `
  1708. <button onclick="stopWGInterface('${iface.name}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Stop</button>
  1709. ` : `
  1710. <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>
  1711. `}
  1712. <button onclick="toggleWGInterfaceState('${iface.name}', ${iface.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white font-medium">
  1713. ${iface.disabled ? 'Enable' : 'Disable'}
  1714. </button>
  1715. <button onclick="openEditWGInterfaceModal('${iface.name}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Edit</button>
  1716. <button onclick="deleteWGInterface('${iface.name}')" class="text-xs text-slate-500 hover:text-rose-400 font-medium">Delete</button>
  1717. </td>
  1718. `;
  1719. ifacesTbody.appendChild(tr);
  1720. });
  1721. }
  1722. }
  1723. // Populate filter dropdown in peers tab
  1724. const filterSel = document.getElementById('wg-peers-filter-iface');
  1725. if (filterSel) {
  1726. const currentVal = filterSel.value;
  1727. filterSel.innerHTML = '<option value="">All Interfaces</option>';
  1728. state.wgInterfaces.forEach(i => {
  1729. const opt = document.createElement('option');
  1730. opt.value = i.name;
  1731. opt.innerText = i.name;
  1732. if (i.name === currentVal) opt.selected = true;
  1733. filterSel.appendChild(opt);
  1734. });
  1735. }
  1736. renderWGPeers();
  1737. } catch (err) {
  1738. console.error('Failed to load WireGuard:', err);
  1739. }
  1740. }
  1741. function formatWGPeerEndpoint(address, port) {
  1742. if (!address || address === '(none)') return '--';
  1743. let addr = address.trim();
  1744. let p = port || 0;
  1745. while (addr.includes(':') && !addr.startsWith('[')) {
  1746. const lastColon = addr.lastIndexOf(':');
  1747. const maybePort = addr.substring(lastColon + 1);
  1748. if (!isNaN(parseInt(maybePort, 10)) && parseInt(maybePort, 10) > 0) {
  1749. if (!p) p = parseInt(maybePort, 10);
  1750. addr = addr.substring(0, lastColon);
  1751. } else {
  1752. break;
  1753. }
  1754. }
  1755. return p ? `${addr}:${p}` : addr;
  1756. }
  1757. function renderWGPeers() {
  1758. const filterSel = document.getElementById('wg-peers-filter-iface');
  1759. const selectedIface = filterSel ? filterSel.value : '';
  1760. const tbody = document.getElementById('wg-peers-table-body');
  1761. const empty = document.getElementById('wg-peers-empty');
  1762. if (!tbody) return;
  1763. tbody.innerHTML = '';
  1764. const filtered = selectedIface ? state.wgPeers.filter(p => p.interface === selectedIface) : state.wgPeers;
  1765. if (filtered.length === 0) {
  1766. if (empty) empty.classList.remove('hidden');
  1767. } else {
  1768. if (empty) empty.classList.add('hidden');
  1769. filtered.forEach(p => {
  1770. const isOnline = p.latest_handshake && !p.latest_handshake.includes('Never');
  1771. const tr = document.createElement('tr');
  1772. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1773. tr.innerHTML = `
  1774. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(isOnline, p.disabled)}</td>
  1775. <td class="py-2.5 px-3 font-mono font-bold text-rose-400">${escapeHtml(p.interface)}</td>
  1776. <td class="py-2.5 px-3 font-bold text-white font-sans">${escapeHtml(p.name || 'Unnamed')}</td>
  1777. <td class="py-2.5 px-3 text-slate-300 font-mono">
  1778. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${p.public_key}', 'Peer Public Key')" title="${p.public_key}">
  1779. ${(p.public_key || '').substring(0, 10)}... 📋
  1780. </span>
  1781. </td>
  1782. <td class="py-2.5 px-3 text-emerald-400 font-mono font-semibold">${(p.allowed_ips || []).join(', ')}</td>
  1783. <td class="py-2.5 px-3 text-slate-400 font-mono">${formatWGPeerEndpoint(p.endpoint_address, p.endpoint_port)}</td>
  1784. <td class="py-2.5 px-3 text-slate-300 font-sans">${p.latest_handshake || 'Never'}</td>
  1785. <td class="py-2.5 px-3 font-mono text-[11px]">
  1786. <span class="text-emerald-400">↓ ${p.transfer_rx_human || '0 B'}</span>
  1787. <span class="text-cyan-400 ml-1">↑ ${p.transfer_tx_human || '0 B'}</span>
  1788. </td>
  1789. <td class="py-2.5 px-3 text-right font-sans space-x-2 whitespace-nowrap">
  1790. <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">
  1791. ${p.disabled ? 'Enable' : 'Disable'}
  1792. </button>
  1793. <button onclick="openEditWGPeerModal('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Edit</button>
  1794. <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>
  1795. <button onclick="deleteWGPeer('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Delete</button>
  1796. </td>
  1797. `;
  1798. tbody.appendChild(tr);
  1799. });
  1800. }
  1801. }
  1802. function openAddWGInterfaceModal() {
  1803. document.getElementById('wg-iface-modal-title').innerText = 'Add WireGuard Interface';
  1804. document.getElementById('wg-iface-modal-edit-orig').value = '';
  1805. const nameEl = document.getElementById('wg-iface-modal-name');
  1806. nameEl.value = `wg${(state.wgInterfaces || []).length}`;
  1807. nameEl.readOnly = false;
  1808. document.getElementById('wg-iface-modal-port').value = 51820 + (state.wgInterfaces || []).length;
  1809. document.getElementById('wg-iface-modal-addr').value = `10.${10 + (state.wgInterfaces || []).length}.0.1/24`;
  1810. document.getElementById('wg-iface-modal-mtu').value = '1420';
  1811. document.getElementById('wg-iface-modal-comment').value = '';
  1812. document.getElementById('wg-iface-modal-pubkey').value = '';
  1813. document.getElementById('wg-iface-modal-privkey').value = '';
  1814. document.getElementById('wg-iface-modal-disabled').checked = false;
  1815. generateWGInterfaceKeys();
  1816. document.getElementById('wg-iface-modal').classList.remove('hidden');
  1817. }
  1818. function openEditWGInterfaceModal(name) {
  1819. const iface = (state.wgInterfaces || []).find(i => i.name === name);
  1820. if (!iface) return;
  1821. document.getElementById('wg-iface-modal-title').innerText = `Edit WireGuard Interface: ${name}`;
  1822. document.getElementById('wg-iface-modal-edit-orig').value = name;
  1823. const nameEl = document.getElementById('wg-iface-modal-name');
  1824. nameEl.value = iface.name;
  1825. nameEl.readOnly = false; // ALLOW RENAMING
  1826. document.getElementById('wg-iface-modal-port').value = iface.listen_port || 51820;
  1827. document.getElementById('wg-iface-modal-addr').value = iface.address || '';
  1828. document.getElementById('wg-iface-modal-mtu').value = iface.mtu || 1420;
  1829. document.getElementById('wg-iface-modal-comment').value = iface.comment || '';
  1830. document.getElementById('wg-iface-modal-pubkey').value = iface.public_key || '';
  1831. document.getElementById('wg-iface-modal-privkey').value = iface.private_key || '';
  1832. document.getElementById('wg-iface-modal-disabled').checked = !!iface.disabled;
  1833. document.getElementById('wg-iface-modal').classList.remove('hidden');
  1834. }
  1835. function closeAddWGInterfaceModal() {
  1836. document.getElementById('wg-iface-modal').classList.add('hidden');
  1837. }
  1838. async function generateWGInterfaceKeys() {
  1839. try {
  1840. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  1841. const keys = await res.json();
  1842. if (res.ok) {
  1843. document.getElementById('wg-iface-modal-privkey').value = keys.private_key;
  1844. document.getElementById('wg-iface-modal-pubkey').value = keys.public_key;
  1845. }
  1846. } catch (err) {
  1847. showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
  1848. }
  1849. }
  1850. async function onWGInterfacePrivKeyInput() {
  1851. const privKey = document.getElementById('wg-iface-modal-privkey').value.trim();
  1852. if (!privKey) return;
  1853. try {
  1854. const res = await fetch(`${API_BASE}/vpn/wireguard/calc-pubkey`, {
  1855. method: 'POST',
  1856. headers: { 'Content-Type': 'application/json' },
  1857. body: JSON.stringify({ private_key: privKey })
  1858. });
  1859. if (res.ok) {
  1860. const data = await res.json();
  1861. if (data.public_key) {
  1862. document.getElementById('wg-iface-modal-pubkey').value = data.public_key;
  1863. }
  1864. }
  1865. } catch (err) {
  1866. // Ignore while typing
  1867. }
  1868. }
  1869. function toggleWGPrivKeyVisibility() {
  1870. const el = document.getElementById('wg-iface-modal-privkey');
  1871. const btn = document.getElementById('btn-toggle-wg-privkey');
  1872. if (el.type === 'password') {
  1873. el.type = 'text';
  1874. btn.innerText = '🙈 Hide';
  1875. } else {
  1876. el.type = 'password';
  1877. btn.innerText = '👁️ Show';
  1878. }
  1879. }
  1880. function copyWGInterfacePubKey() {
  1881. const pub = document.getElementById('wg-iface-modal-pubkey').value;
  1882. if (pub) copyToClipboard(pub, 'Interface Public Key');
  1883. }
  1884. async function submitSaveWGInterface(e) {
  1885. e.preventDefault();
  1886. const origName = document.getElementById('wg-iface-modal-edit-orig').value.trim();
  1887. const name = document.getElementById('wg-iface-modal-name').value.trim();
  1888. const port = parseInt(document.getElementById('wg-iface-modal-port').value, 10) || 51820;
  1889. const addr = document.getElementById('wg-iface-modal-addr').value.trim();
  1890. const mtu = parseInt(document.getElementById('wg-iface-modal-mtu').value, 10) || 1420;
  1891. const comment = document.getElementById('wg-iface-modal-comment').value.trim();
  1892. const pub = document.getElementById('wg-iface-modal-pubkey').value.trim();
  1893. const priv = document.getElementById('wg-iface-modal-privkey').value.trim();
  1894. const disabled = document.getElementById('wg-iface-modal-disabled').checked;
  1895. try {
  1896. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces`, {
  1897. method: 'POST',
  1898. headers: { 'Content-Type': 'application/json' },
  1899. body: JSON.stringify({
  1900. orig_name: origName,
  1901. name,
  1902. listen_port: port,
  1903. address: addr,
  1904. mtu,
  1905. comment,
  1906. public_key: pub,
  1907. private_key: priv,
  1908. disabled
  1909. })
  1910. });
  1911. const data = await res.json();
  1912. if (res.ok) {
  1913. showToast('WireGuard Saved', `Interface ${name} configured successfully`, 'success');
  1914. closeAddWGInterfaceModal();
  1915. loadWireGuard(false);
  1916. fetchData(false);
  1917. } else {
  1918. showToast('Error', data.error || 'Failed to save interface', 'error');
  1919. }
  1920. } catch (err) {
  1921. showToast('Error', err.message, 'error');
  1922. }
  1923. }
  1924. async function startWGInterface(name) {
  1925. try {
  1926. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/start`, { method: 'POST' });
  1927. if (res.ok) {
  1928. showToast('Interface UP', `Started WireGuard interface ${name}`, 'success');
  1929. loadWireGuard(false);
  1930. fetchData(false);
  1931. }
  1932. } catch (err) {
  1933. showToast('Error', err.message, 'error');
  1934. }
  1935. }
  1936. async function stopWGInterface(name) {
  1937. try {
  1938. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  1939. if (res.ok) {
  1940. showToast('Interface DOWN', `Stopped WireGuard interface ${name}`, 'info');
  1941. loadWireGuard(false);
  1942. fetchData(false);
  1943. }
  1944. } catch (err) {
  1945. showToast('Error', err.message, 'error');
  1946. }
  1947. }
  1948. async function toggleWGInterfaceState(name, enable) {
  1949. try {
  1950. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/state`, {
  1951. method: 'POST',
  1952. headers: { 'Content-Type': 'application/json' },
  1953. body: JSON.stringify({ enabled: enable })
  1954. });
  1955. if (res.ok) {
  1956. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  1957. loadWireGuard(false);
  1958. fetchData(false);
  1959. }
  1960. } catch (err) {
  1961. showToast('Error', err.message, 'error');
  1962. }
  1963. }
  1964. async function deleteWGInterface(name) {
  1965. if (!confirm(`Are you sure you want to delete WireGuard interface ${name}? All associated peers will also be removed.`)) return;
  1966. try {
  1967. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1968. if (res.ok) {
  1969. showToast('Deleted', `Interface ${name} removed`, 'success');
  1970. loadWireGuard(false);
  1971. fetchData(false);
  1972. }
  1973. } catch (err) {
  1974. showToast('Error', err.message, 'error');
  1975. }
  1976. }
  1977. function populateWGPeerIfaceSelect(selectedIface = '') {
  1978. const sel = document.getElementById('wg-peer-modal-iface');
  1979. if (!sel) return;
  1980. sel.innerHTML = '';
  1981. (state.wgInterfaces || []).forEach(i => {
  1982. const opt = document.createElement('option');
  1983. opt.value = i.name;
  1984. opt.innerText = `${i.name} (${i.address || 'No IP'})`;
  1985. if (i.name === selectedIface) opt.selected = true;
  1986. sel.appendChild(opt);
  1987. });
  1988. }
  1989. function openAddWGPeerModal() {
  1990. if ((state.wgInterfaces || []).length === 0) {
  1991. showToast('No Interfaces', 'Please add a WireGuard interface first before adding peers', 'warning');
  1992. openAddWGInterfaceModal();
  1993. return;
  1994. }
  1995. document.getElementById('wg-peer-modal-title').innerText = 'Add WireGuard Peer';
  1996. document.getElementById('wg-peer-modal-edit-orig-iface').value = '';
  1997. document.getElementById('wg-peer-modal-edit-orig-pubkey').value = '';
  1998. populateWGPeerIfaceSelect();
  1999. document.getElementById('wg-peer-modal-name').value = '';
  2000. document.getElementById('wg-peer-modal-pubkey').value = '';
  2001. document.getElementById('wg-peer-modal-allowedips').value = '10.10.0.2/32';
  2002. document.getElementById('wg-peer-modal-endpoint').value = '';
  2003. document.getElementById('wg-peer-modal-port').value = '';
  2004. document.getElementById('wg-peer-modal-keepalive').value = '25';
  2005. document.getElementById('wg-peer-modal-preshared').value = '';
  2006. document.getElementById('wg-peer-modal-disabled').checked = false;
  2007. document.getElementById('wg-peer-key-warning').classList.add('hidden');
  2008. document.getElementById('wg-peer-gen-key-box').classList.add('hidden');
  2009. document.getElementById('wg-peer-modal').classList.remove('hidden');
  2010. }
  2011. function openEditWGPeerModal(ifaceName, pubKey) {
  2012. const peer = (state.wgPeers || []).find(p => p.interface === ifaceName && p.public_key === pubKey);
  2013. if (!peer) {
  2014. showToast('Not Found', 'Peer not found', 'warning');
  2015. return;
  2016. }
  2017. document.getElementById('wg-peer-modal-title').innerText = `Edit WireGuard Peer (${peer.name || ifaceName})`;
  2018. document.getElementById('wg-peer-modal-edit-orig-iface').value = peer.interface;
  2019. document.getElementById('wg-peer-modal-edit-orig-pubkey').value = peer.public_key;
  2020. populateWGPeerIfaceSelect(peer.interface);
  2021. document.getElementById('wg-peer-modal-name').value = peer.name || '';
  2022. document.getElementById('wg-peer-modal-pubkey').value = peer.public_key || '';
  2023. document.getElementById('wg-peer-modal-allowedips').value = (peer.allowed_ips || []).join(', ');
  2024. let epHost = (peer.endpoint_address || '').trim();
  2025. let epPort = peer.endpoint_port || '';
  2026. while (epHost.includes(':') && !epHost.startsWith('[')) {
  2027. const lastColon = epHost.lastIndexOf(':');
  2028. const maybePort = epHost.substring(lastColon + 1);
  2029. if (!isNaN(parseInt(maybePort, 10)) && parseInt(maybePort, 10) > 0) {
  2030. if (!epPort) epPort = parseInt(maybePort, 10);
  2031. epHost = epHost.substring(0, lastColon);
  2032. } else {
  2033. break;
  2034. }
  2035. }
  2036. document.getElementById('wg-peer-modal-endpoint').value = epHost;
  2037. document.getElementById('wg-peer-modal-port').value = epPort;
  2038. document.getElementById('wg-peer-modal-keepalive').value = peer.persistent_keepalive ?? 25;
  2039. document.getElementById('wg-peer-modal-preshared').value = peer.preshared_key || '';
  2040. document.getElementById('wg-peer-modal-disabled').checked = !!peer.disabled;
  2041. document.getElementById('wg-peer-key-warning').classList.add('hidden');
  2042. document.getElementById('wg-peer-gen-key-box').classList.add('hidden');
  2043. document.getElementById('wg-peer-modal').classList.remove('hidden');
  2044. }
  2045. function closeAddWGPeerModal() {
  2046. document.getElementById('wg-peer-modal').classList.add('hidden');
  2047. }
  2048. async function generatePeerKeypairHelper() {
  2049. try {
  2050. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  2051. const keys = await res.json();
  2052. if (res.ok) {
  2053. document.getElementById('wg-peer-modal-pubkey').value = keys.public_key;
  2054. document.getElementById('wg-peer-gen-privkey').value = keys.private_key;
  2055. document.getElementById('wg-peer-gen-key-box').classList.remove('hidden');
  2056. checkWGPeerKeyValidity();
  2057. showToast('Keypair Generated', 'Public key inserted and client private key ready to copy', 'info');
  2058. }
  2059. } catch (err) {
  2060. showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
  2061. }
  2062. }
  2063. function copyGeneratedPeerPrivKey() {
  2064. const priv = document.getElementById('wg-peer-gen-privkey').value;
  2065. if (priv) copyToClipboard(priv, 'Client Private Key');
  2066. }
  2067. async function generatePeerPSK() {
  2068. try {
  2069. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  2070. const keys = await res.json();
  2071. if (res.ok && keys.private_key) {
  2072. document.getElementById('wg-peer-modal-preshared').value = keys.private_key;
  2073. showToast('PSK Generated', 'Generated 256-bit preshared key', 'info');
  2074. }
  2075. } catch (err) {
  2076. showToast('Error', err.message, 'error');
  2077. }
  2078. }
  2079. function checkWGPeerKeyValidity() {
  2080. const ifaceName = document.getElementById('wg-peer-modal-iface').value;
  2081. const peerPubKey = document.getElementById('wg-peer-modal-pubkey').value.trim();
  2082. const warningEl = document.getElementById('wg-peer-key-warning');
  2083. if (!warningEl) return;
  2084. const targetIface = (state.wgInterfaces || []).find(i => i.name === ifaceName);
  2085. if (targetIface && targetIface.public_key && peerPubKey && targetIface.public_key === peerPubKey) {
  2086. warningEl.classList.remove('hidden');
  2087. } else {
  2088. warningEl.classList.add('hidden');
  2089. }
  2090. }
  2091. async function submitSaveWGPeer(e) {
  2092. e.preventDefault();
  2093. const origIface = document.getElementById('wg-peer-modal-edit-orig-iface').value.trim();
  2094. const origPubKey = document.getElementById('wg-peer-modal-edit-orig-pubkey').value.trim();
  2095. const iface = document.getElementById('wg-peer-modal-iface').value;
  2096. const name = document.getElementById('wg-peer-modal-name').value.trim();
  2097. const pub = document.getElementById('wg-peer-modal-pubkey').value.trim();
  2098. const allowed = document.getElementById('wg-peer-modal-allowedips').value
  2099. .split(',')
  2100. .map(s => s.trim())
  2101. .filter(s => s.length > 0);
  2102. let epHost = document.getElementById('wg-peer-modal-endpoint').value.trim();
  2103. let epPort = parseInt(document.getElementById('wg-peer-modal-port').value, 10) || 0;
  2104. while (epHost.includes(':') && !epHost.startsWith('[')) {
  2105. const lastColon = epHost.lastIndexOf(':');
  2106. const maybePort = epHost.substring(lastColon + 1);
  2107. if (!isNaN(parseInt(maybePort, 10)) && parseInt(maybePort, 10) > 0) {
  2108. if (!epPort) epPort = parseInt(maybePort, 10);
  2109. epHost = epHost.substring(0, lastColon);
  2110. } else {
  2111. break;
  2112. }
  2113. }
  2114. const keepalive = parseInt(document.getElementById('wg-peer-modal-keepalive').value, 10) || 0;
  2115. const psk = document.getElementById('wg-peer-modal-preshared').value.trim();
  2116. const disabled = document.getElementById('wg-peer-modal-disabled').checked;
  2117. // Validation
  2118. const targetIface = (state.wgInterfaces || []).find(i => i.name === iface);
  2119. if (targetIface && targetIface.public_key === pub) {
  2120. showToast('Invalid Peer Key', 'Peer public key cannot be the same as the interface public key!', 'error');
  2121. return;
  2122. }
  2123. try {
  2124. const res = await fetch(`${API_BASE}/vpn/wireguard/peers`, {
  2125. method: 'POST',
  2126. headers: { 'Content-Type': 'application/json' },
  2127. body: JSON.stringify({
  2128. orig_interface: origIface,
  2129. orig_public_key: origPubKey,
  2130. interface: iface,
  2131. name,
  2132. public_key: pub,
  2133. allowed_ips: allowed,
  2134. endpoint_address: epHost,
  2135. endpoint_port: epPort,
  2136. persistent_keepalive: keepalive,
  2137. preshared_key: psk,
  2138. disabled
  2139. })
  2140. });
  2141. const data = await res.json();
  2142. if (res.ok) {
  2143. showToast('Peer Saved', `Peer ${name} saved on ${iface}`, 'success');
  2144. closeAddWGPeerModal();
  2145. loadWireGuard(false);
  2146. } else {
  2147. showToast('Error', data.error || 'Failed to save peer', 'error');
  2148. }
  2149. } catch (err) {
  2150. showToast('Error', err.message, 'error');
  2151. }
  2152. }
  2153. async function toggleWGPeerState(iface, pubkey, enable) {
  2154. try {
  2155. const res = await fetch(`${API_BASE}/vpn/wireguard/peers/state`, {
  2156. method: 'POST',
  2157. headers: { 'Content-Type': 'application/json' },
  2158. body: JSON.stringify({ interface: iface, public_key: pubkey, enabled: enable })
  2159. });
  2160. const data = await res.json();
  2161. if (res.ok) {
  2162. showToast(enable ? 'Peer Enabled' : 'Peer Disabled', `Peer state updated on ${iface}`, 'info');
  2163. loadWireGuard(false);
  2164. } else {
  2165. showToast('Error', data.error || 'Failed to update peer state', 'error');
  2166. }
  2167. } catch (err) {
  2168. showToast('Error', err.message, 'error');
  2169. }
  2170. }
  2171. async function deleteWGPeer(iface, pubkey) {
  2172. if (!confirm(`Are you sure you want to remove peer from ${iface}?`)) return;
  2173. try {
  2174. const res = await fetch(`${API_BASE}/vpn/wireguard/peers/delete`, {
  2175. method: 'POST',
  2176. headers: { 'Content-Type': 'application/json' },
  2177. body: JSON.stringify({ interface: iface, public_key: pubkey })
  2178. });
  2179. const data = await res.json();
  2180. if (res.ok) {
  2181. showToast('Peer Deleted', 'WireGuard peer removed', 'success');
  2182. loadWireGuard(false);
  2183. } else {
  2184. showToast('Error', data.error || 'Failed to remove peer', 'error');
  2185. }
  2186. } catch (err) {
  2187. showToast('Error', err.message, 'error');
  2188. }
  2189. }
  2190. // ======================== IPSec FortiGate Phase 1 & 2 Multi-Tunnel Engine ========================
  2191. function switchIpsecModalTab(tab) {
  2192. const p1Tab = document.getElementById('tab-btn-ipsec-p1');
  2193. const p2Tab = document.getElementById('tab-btn-ipsec-p2');
  2194. const p1Content = document.getElementById('ipsec-tab-content-p1');
  2195. const p2Content = document.getElementById('ipsec-tab-content-p2');
  2196. const stepBtn = document.getElementById('btn-ipsec-switch-step');
  2197. if (tab === 'p1') {
  2198. if (p1Tab) {
  2199. 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';
  2200. }
  2201. if (p2Tab) {
  2202. 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';
  2203. }
  2204. if (p1Content) p1Content.classList.remove('hidden');
  2205. if (p2Content) p2Content.classList.add('hidden');
  2206. if (stepBtn) stepBtn.innerHTML = 'Next: Phase 2 Selectors &rarr;';
  2207. } else {
  2208. if (p1Tab) {
  2209. 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';
  2210. }
  2211. if (p2Tab) {
  2212. 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';
  2213. }
  2214. if (p1Content) p1Content.classList.add('hidden');
  2215. if (p2Content) p2Content.classList.remove('hidden');
  2216. if (stepBtn) stepBtn.innerHTML = '&larr; Back: Phase 1 (IKE)';
  2217. }
  2218. }
  2219. function toggleIpsecPhaseStep() {
  2220. const p1Content = document.getElementById('ipsec-tab-content-p1');
  2221. if (p1Content && !p1Content.classList.contains('hidden')) {
  2222. switchIpsecModalTab('p2');
  2223. } else {
  2224. switchIpsecModalTab('p1');
  2225. }
  2226. }
  2227. function toggleIpsecPskVisibility() {
  2228. const pskInput = document.getElementById('ipsec-modal-psk');
  2229. if (!pskInput) return;
  2230. pskInput.type = pskInput.type === 'password' ? 'text' : 'password';
  2231. }
  2232. function addIpsecLocalSubnet(val = '') {
  2233. const container = document.getElementById('ipsec-modal-local-subnets-container');
  2234. if (!container) return;
  2235. const row = document.createElement('div');
  2236. row.className = 'flex items-center gap-2 ipsec-subnet-row';
  2237. row.innerHTML = `
  2238. <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">
  2239. <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>
  2240. `;
  2241. container.appendChild(row);
  2242. }
  2243. function addIpsecRemoteSubnet(val = '') {
  2244. const container = document.getElementById('ipsec-modal-remote-subnets-container');
  2245. if (!container) return;
  2246. const row = document.createElement('div');
  2247. row.className = 'flex items-center gap-2 ipsec-subnet-row';
  2248. row.innerHTML = `
  2249. <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">
  2250. <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>
  2251. `;
  2252. container.appendChild(row);
  2253. }
  2254. function updateIpsecEspProposalFromPFS(val) {
  2255. const prop = document.getElementById('ipsec-modal-espprop');
  2256. if (!prop) return;
  2257. if (val === 'none') {
  2258. prop.value = 'aes256-sha256,aes128-sha256,default';
  2259. } else {
  2260. prop.value = `aes256-sha256-${val},aes128-sha256-${val},default`;
  2261. }
  2262. }
  2263. function updateIpsecIkeProposalFromDH(dh) {
  2264. const el = document.getElementById('ipsec-modal-ikeprop');
  2265. if (el) {
  2266. el.value = `aes256-sha256-${dh},aes128-sha256-${dh},default`;
  2267. }
  2268. }
  2269. function safeSetVal(id, val) {
  2270. const el = document.getElementById(id);
  2271. if (el) el.value = val;
  2272. }
  2273. function safeSetChecked(id, val) {
  2274. const el = document.getElementById(id);
  2275. if (el) el.checked = !!val;
  2276. }
  2277. function safeGetVal(id, def = '') {
  2278. const el = document.getElementById(id);
  2279. return el ? el.value : def;
  2280. }
  2281. async function loadIPSec(populateInputs = true) {
  2282. try {
  2283. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`);
  2284. const list = await res.json();
  2285. state.ipsecTunnels = Array.isArray(list) ? list : [];
  2286. const activeCount = state.ipsecTunnels.filter(t => t.running || t.status === 'ESTABLISHED').length;
  2287. const badge = document.getElementById('ipsec-sas-badge');
  2288. if (badge) badge.innerText = `${activeCount} Active SAs`;
  2289. const tbody = document.getElementById('ipsec-table-body');
  2290. const empty = document.getElementById('ipsec-empty');
  2291. if (!tbody) return;
  2292. tbody.innerHTML = '';
  2293. if (state.ipsecTunnels.length === 0) {
  2294. if (empty) empty.classList.remove('hidden');
  2295. } else {
  2296. if (empty) empty.classList.add('hidden');
  2297. state.ipsecTunnels.forEach(c => {
  2298. const isEstablished = c.running || c.status === 'ESTABLISHED';
  2299. const tr = document.createElement('tr');
  2300. tr.className = 'hover:bg-slate-800/40 transition text-xs select-none';
  2301. // Local subnets tags
  2302. const localList = (c.local_subnets && c.local_subnets.length > 0) ? c.local_subnets : (c.local_subnet ? [c.local_subnet] : ['0.0.0.0/0']);
  2303. 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('');
  2304. // Remote subnets tags
  2305. const remoteList = (c.remote_subnets && c.remote_subnets.length > 0) ? c.remote_subnets : (c.remote_subnet ? [c.remote_subnet] : ['0.0.0.0/0']);
  2306. 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('');
  2307. const ikeVersionBadge = (c.ike_version || 'ikev2').toUpperCase();
  2308. const p2Name = c.phase2_name || `${c.name}_p2`;
  2309. tr.innerHTML = `
  2310. <td class="py-2.5 px-3 text-center">
  2311. ${isEstablished ? `
  2312. <span class="inline-flex items-center gap-1.5 text-emerald-400 font-mono font-bold text-[11px]" title="Active SA Established">
  2313. <span class="w-2.5 h-2.5 rounded-full bg-emerald-400 animate-pulse"></span>
  2314. <span>UP</span>
  2315. </span>
  2316. ` : (c.disabled ? `
  2317. <span class="inline-flex items-center gap-1.5 text-slate-500 font-mono text-[11px]" title="Tunnel Disabled">
  2318. <span class="w-2 h-2 rounded-full bg-rose-500"></span>
  2319. <span>DOWN</span>
  2320. </span>
  2321. ` : `
  2322. <span class="inline-flex items-center gap-1.5 text-amber-400 font-mono text-[11px]" title="Disconnected / Idle">
  2323. <span class="w-2 h-2 rounded-full bg-amber-400"></span>
  2324. <span>IDLE</span>
  2325. </span>
  2326. `)}
  2327. </td>
  2328. <td class="py-2.5 px-4 font-bold text-white">
  2329. <div class="flex items-center gap-2">
  2330. <span class="text-amber-400">🛡</span>
  2331. <div>
  2332. <div>${escapeHtml(c.name)}</div>
  2333. <div class="text-[10px] text-slate-500 font-normal">P2: ${escapeHtml(p2Name)}</div>
  2334. </div>
  2335. </div>
  2336. </td>
  2337. <td class="py-2.5 px-4 text-slate-300 font-mono font-medium">${escapeHtml(c.remote_addrs || '%any')}</td>
  2338. <td class="py-2.5 px-4 font-sans">
  2339. <div class="flex items-center gap-1.5">
  2340. <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>
  2341. <span class="text-[10px] text-slate-400">${c.auth_method || 'PSK'}</span>
  2342. </div>
  2343. </td>
  2344. <td class="py-2.5 px-4">
  2345. <div class="space-y-1">
  2346. <div class="flex items-center flex-wrap gap-1">
  2347. <span class="text-[9px] text-cyan-400 uppercase font-bold mr-1">Local:</span>
  2348. ${localBadges}
  2349. </div>
  2350. <div class="flex items-center flex-wrap gap-1">
  2351. <span class="text-[9px] text-purple-400 uppercase font-bold mr-1">Remote:</span>
  2352. ${remoteBadges}
  2353. </div>
  2354. </div>
  2355. </td>
  2356. <td class="py-2.5 px-4 font-mono text-[11px] text-slate-400">
  2357. <div class="truncate max-w-[140px]" title="${escapeHtml(c.esp_proposals || '')}">
  2358. ${escapeHtml(c.esp_proposals || 'aes256-sha256')}
  2359. </div>
  2360. <div class="text-[10px] text-slate-500">PFS: ${escapeHtml(c.pfs_group || 'modp2048')}</div>
  2361. </td>
  2362. <td class="py-2.5 px-4 text-right space-x-2 font-sans">
  2363. ${isEstablished ? `
  2364. <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>
  2365. ` : `
  2366. <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>
  2367. `}
  2368. <button onclick="toggleIPSecState('${c.name}', ${c.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  2369. ${c.disabled ? 'Enable' : 'Disable'}
  2370. </button>
  2371. <button onclick="openEditIPSecModal('${c.name}')" class="text-xs text-amber-400 hover:text-amber-300">Edit</button>
  2372. <button onclick="deleteIPSecConn('${c.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2373. </td>
  2374. `;
  2375. tbody.appendChild(tr);
  2376. });
  2377. }
  2378. } catch (err) {
  2379. console.error('Failed to load IPSec:', err);
  2380. }
  2381. }
  2382. function openAddIPSecModal() {
  2383. const modal = document.getElementById('ipsec-modal');
  2384. if (!modal) return;
  2385. const title = document.getElementById('ipsec-modal-title');
  2386. if (title) title.innerText = 'Configure IPSec Site-to-Site Tunnel';
  2387. // Phase 1 Fields
  2388. safeSetVal('ipsec-modal-name', `tunnel-${(state.ipsecTunnels || []).length + 1}`);
  2389. const nameEl = document.getElementById('ipsec-modal-name');
  2390. if (nameEl) nameEl.readOnly = false;
  2391. safeSetVal('ipsec-modal-ikeversion', 'ikev2');
  2392. safeSetVal('ipsec-modal-ikever', 'ikev2');
  2393. safeSetVal('ipsec-modal-remotegw', '');
  2394. safeSetVal('ipsec-modal-localaddrs', '');
  2395. safeSetVal('ipsec-modal-comments', '');
  2396. safeSetVal('ipsec-modal-psk', '');
  2397. safeSetVal('ipsec-modal-ikeprop', 'aes256-sha256-modp2048,aes128-sha256-modp2048,default');
  2398. safeSetVal('ipsec-modal-dhgroup', 'modp2048');
  2399. safeSetVal('ipsec-modal-ikekeylife', '86400');
  2400. safeSetVal('ipsec-modal-localid', '');
  2401. safeSetVal('ipsec-modal-remoteid', '');
  2402. safeSetVal('ipsec-modal-dpd', 'on-demand');
  2403. // Phase 2 Fields
  2404. safeSetVal('ipsec-modal-p2name', `tunnel-${(state.ipsecTunnels || []).length + 1}_p2`);
  2405. safeSetVal('ipsec-modal-espkeylife', '28800');
  2406. safeSetVal('ipsec-modal-espprop', 'aes256-sha256-modp2048,aes128-sha256-modp2048,default');
  2407. safeSetVal('ipsec-modal-pfsgroup', 'modp2048');
  2408. safeSetChecked('ipsec-modal-autostart', true);
  2409. safeSetChecked('ipsec-modal-disabled', false);
  2410. // Clear & Populate default dynamic subnets
  2411. const localContainer = document.getElementById('ipsec-modal-local-subnets-container');
  2412. const remoteContainer = document.getElementById('ipsec-modal-remote-subnets-container');
  2413. if (localContainer) {
  2414. localContainer.innerHTML = '';
  2415. addIpsecLocalSubnet('192.168.10.0/24');
  2416. }
  2417. if (remoteContainer) {
  2418. remoteContainer.innerHTML = '';
  2419. addIpsecRemoteSubnet('192.168.20.0/24');
  2420. }
  2421. switchIpsecModalTab('p1');
  2422. modal.classList.remove('hidden');
  2423. }
  2424. function openEditIPSecModal(name) {
  2425. const modal = document.getElementById('ipsec-modal');
  2426. if (!modal) return;
  2427. const conn = (state.ipsecTunnels || []).find(c => c.name === name);
  2428. if (!conn) return;
  2429. const title = document.getElementById('ipsec-modal-title');
  2430. if (title) title.innerText = `Edit IPSec Tunnel: ${name}`;
  2431. // Phase 1 Fields
  2432. safeSetVal('ipsec-modal-name', conn.name);
  2433. const nameEl = document.getElementById('ipsec-modal-name');
  2434. if (nameEl) nameEl.readOnly = true;
  2435. safeSetVal('ipsec-modal-ikeversion', conn.ike_version || 'ikev2');
  2436. safeSetVal('ipsec-modal-ikever', conn.ike_version || 'ikev2');
  2437. safeSetVal('ipsec-modal-remotegw', conn.remote_addrs || '');
  2438. safeSetVal('ipsec-modal-localaddrs', conn.local_addrs || '');
  2439. safeSetVal('ipsec-modal-comments', conn.comment || '');
  2440. safeSetVal('ipsec-modal-psk', conn.preshared_key || '');
  2441. safeSetVal('ipsec-modal-ikeprop', conn.ike_proposals || 'aes256-sha256-modp2048,default');
  2442. safeSetVal('ipsec-modal-ikekeylife', conn.ike_keylife || 86400);
  2443. safeSetVal('ipsec-modal-localid', conn.local_id || '');
  2444. safeSetVal('ipsec-modal-remoteid', conn.remote_id || '');
  2445. safeSetVal('ipsec-modal-dpd', conn.dpd || 'on-demand');
  2446. // Phase 2 Fields
  2447. safeSetVal('ipsec-modal-p2name', conn.phase2_name || `${conn.name}_p2`);
  2448. safeSetVal('ipsec-modal-espkeylife', conn.esp_keylife || 28800);
  2449. safeSetVal('ipsec-modal-espprop', conn.esp_proposals || 'aes256-sha256-modp2048,default');
  2450. safeSetVal('ipsec-modal-pfsgroup', conn.pfs_group || 'modp2048');
  2451. safeSetChecked('ipsec-modal-autostart', conn.auto_start ?? true);
  2452. safeSetChecked('ipsec-modal-disabled', !!conn.disabled);
  2453. // Populate dynamic subnets
  2454. const localContainer = document.getElementById('ipsec-modal-local-subnets-container');
  2455. const remoteContainer = document.getElementById('ipsec-modal-remote-subnets-container');
  2456. if (localContainer) {
  2457. localContainer.innerHTML = '';
  2458. const locals = (conn.local_subnets && conn.local_subnets.length > 0) ? conn.local_subnets : (conn.local_subnet ? [conn.local_subnet] : ['192.168.10.0/24']);
  2459. locals.forEach(s => addIpsecLocalSubnet(s));
  2460. }
  2461. if (remoteContainer) {
  2462. remoteContainer.innerHTML = '';
  2463. const remotes = (conn.remote_subnets && conn.remote_subnets.length > 0) ? conn.remote_subnets : (conn.remote_subnet ? [conn.remote_subnet] : ['192.168.20.0/24']);
  2464. remotes.forEach(s => addIpsecRemoteSubnet(s));
  2465. }
  2466. switchIpsecModalTab('p1');
  2467. modal.classList.remove('hidden');
  2468. }
  2469. function closeAddIPSecModal() {
  2470. const modal = document.getElementById('ipsec-modal');
  2471. if (modal) modal.classList.add('hidden');
  2472. }
  2473. async function submitSaveIPSec(e) {
  2474. if (e) e.preventDefault();
  2475. const name = safeGetVal('ipsec-modal-name').trim();
  2476. if (!name) {
  2477. showToast('Error', 'Tunnel name is required', 'error');
  2478. return;
  2479. }
  2480. const ikeVersion = safeGetVal('ipsec-modal-ikeversion') || safeGetVal('ipsec-modal-ikever', 'ikev2');
  2481. const remotegw = safeGetVal('ipsec-modal-remotegw').trim();
  2482. const localAddrs = safeGetVal('ipsec-modal-localaddrs').trim() || '%any';
  2483. const comments = safeGetVal('ipsec-modal-comments').trim();
  2484. const psk = safeGetVal('ipsec-modal-psk');
  2485. const ikeProposals = safeGetVal('ipsec-modal-ikeprop', 'aes256-sha256-modp2048,default').trim();
  2486. const ikeKeylife = parseInt(safeGetVal('ipsec-modal-ikekeylife', '86400'), 10) || 86400;
  2487. const localId = safeGetVal('ipsec-modal-localid').trim();
  2488. const remoteId = safeGetVal('ipsec-modal-remoteid').trim();
  2489. const dpd = safeGetVal('ipsec-modal-dpd', 'on-demand');
  2490. const phase2Name = safeGetVal('ipsec-modal-p2name').trim() || `${name}_p2`;
  2491. const espProposals = safeGetVal('ipsec-modal-espprop', 'aes256-sha256-modp2048,default').trim();
  2492. const espKeylife = parseInt(safeGetVal('ipsec-modal-espkeylife', '28800'), 10) || 28800;
  2493. const pfsGroup = safeGetVal('ipsec-modal-pfsgroup', 'modp2048');
  2494. const autostart = document.getElementById('ipsec-modal-autostart')?.checked ?? true;
  2495. const disabled = document.getElementById('ipsec-modal-disabled')?.checked ?? false;
  2496. // Scrape dynamic local and remote subnets
  2497. const localInputs = document.querySelectorAll('#ipsec-modal-local-subnets-container input');
  2498. const localSubnets = [];
  2499. localInputs.forEach(inp => {
  2500. const v = inp.value.trim();
  2501. if (v) localSubnets.push(v);
  2502. });
  2503. const remoteInputs = document.querySelectorAll('#ipsec-modal-remote-subnets-container input');
  2504. const remoteSubnets = [];
  2505. remoteInputs.forEach(inp => {
  2506. const v = inp.value.trim();
  2507. if (v) remoteSubnets.push(v);
  2508. });
  2509. try {
  2510. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`, {
  2511. method: 'POST',
  2512. headers: { 'Content-Type': 'application/json' },
  2513. body: JSON.stringify({
  2514. name,
  2515. comment: comments,
  2516. ike_version: ikeVersion,
  2517. local_addrs: localAddrs,
  2518. remote_addrs: remotegw,
  2519. preshared_key: psk,
  2520. ike_proposals: ikeProposals,
  2521. ike_keylife: ikeKeylife,
  2522. local_id: localId,
  2523. remote_id: remoteId,
  2524. dpd: dpd,
  2525. phase2_name: phase2Name,
  2526. esp_proposals: espProposals,
  2527. esp_keylife: espKeylife,
  2528. pfs_group: pfsGroup,
  2529. pfs: pfsGroup !== 'none',
  2530. local_subnets: localSubnets,
  2531. remote_subnets: remoteSubnets,
  2532. local_subnet: localSubnets[0] || '0.0.0.0/0',
  2533. remote_subnet: remoteSubnets[0] || '0.0.0.0/0',
  2534. auto_start: autostart,
  2535. disabled
  2536. })
  2537. });
  2538. if (res.ok) {
  2539. showToast('IPSec Saved', `FortiGate Tunnel ${name} configured`, 'success');
  2540. closeAddIPSecModal();
  2541. loadIPSec(false);
  2542. } else {
  2543. const err = await res.json();
  2544. showToast('Error', err.error || 'Failed to save IPSec tunnel', 'error');
  2545. }
  2546. } catch (err) {
  2547. showToast('Error', err.message, 'error');
  2548. }
  2549. }
  2550. async function startIPSecTunnel(name) {
  2551. try {
  2552. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/start`, { method: 'POST' });
  2553. if (res.ok) {
  2554. showToast('Initiating Tunnel', `Attempting SA handshake for ${name}...`, 'info');
  2555. setTimeout(() => loadIPSec(false), 2000);
  2556. }
  2557. } catch (err) {
  2558. showToast('Error', err.message, 'error');
  2559. }
  2560. }
  2561. async function stopIPSecTunnel(name) {
  2562. try {
  2563. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  2564. if (res.ok) {
  2565. showToast('Terminated', `IPSec SA for ${name} closed`, 'info');
  2566. loadIPSec(false);
  2567. }
  2568. } catch (err) {
  2569. showToast('Error', err.message, 'error');
  2570. }
  2571. }
  2572. async function toggleIPSecState(name, enable) {
  2573. try {
  2574. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/state`, {
  2575. method: 'POST',
  2576. headers: { 'Content-Type': 'application/json' },
  2577. body: JSON.stringify({ enabled: enable })
  2578. });
  2579. if (res.ok) {
  2580. showToast(enable ? 'Enabled' : 'Disabled', `IPSec tunnel ${name} updated`, 'info');
  2581. loadIPSec(false);
  2582. }
  2583. } catch (err) {
  2584. showToast('Error', err.message, 'error');
  2585. }
  2586. }
  2587. async function deleteIPSecConn(name) {
  2588. if (!confirm(`Are you sure you want to delete IPSec tunnel ${name}?`)) return;
  2589. try {
  2590. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2591. if (res.ok) {
  2592. showToast('Deleted', `IPSec connection ${name} removed`, 'success');
  2593. loadIPSec(false);
  2594. fetchData(false);
  2595. }
  2596. } catch (err) {
  2597. showToast('Error', err.message, 'error');
  2598. }
  2599. }
  2600. // ======================== L2TP Multi-Instance ========================
  2601. async function loadL2TP(populateInputs = true) {
  2602. try {
  2603. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2604. await fetchPPPProfilesList();
  2605. }
  2606. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`);
  2607. const list = await res.json();
  2608. state.l2tpList = Array.isArray(list) ? list : [];
  2609. const badge = document.getElementById('l2tp-count-badge');
  2610. if (badge) badge.innerText = `${state.l2tpList.length} Client${state.l2tpList.length !== 1 ? 's' : ''}`;
  2611. const tbody = document.getElementById('l2tp-table-body');
  2612. const empty = document.getElementById('l2tp-empty');
  2613. if (!tbody) return;
  2614. tbody.innerHTML = '';
  2615. if (state.l2tpList.length === 0) {
  2616. if (empty) empty.classList.remove('hidden');
  2617. } else {
  2618. if (empty) empty.classList.add('hidden');
  2619. state.l2tpList.forEach(inst => {
  2620. const tr = document.createElement('tr');
  2621. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  2622. tr.innerHTML = `
  2623. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  2624. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  2625. <td class="py-2.5 px-3 text-cyan-400 font-mono">${escapeHtml(inst.connect_to)}</td>
  2626. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  2627. <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>
  2628. <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>
  2629. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  2630. <td class="py-2.5 px-3 text-center">
  2631. <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'}">
  2632. ${inst.default_route ? 'Yes' : 'No'}
  2633. </span>
  2634. </td>
  2635. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  2636. ${inst.running ? `
  2637. <button onclick="disconnectL2TPInstance('${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  2638. ` : `
  2639. <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>
  2640. `}
  2641. <button onclick="toggleL2TPState('${escapeHtml(inst.name)}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  2642. ${inst.disabled ? 'Enable' : 'Disable'}
  2643. </button>
  2644. <button onclick="openEditL2TPModal('${escapeHtml(inst.name)}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2645. <button onclick="deleteL2TPInstance('${escapeHtml(inst.name)}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2646. </td>
  2647. `;
  2648. tbody.appendChild(tr);
  2649. });
  2650. }
  2651. } catch (err) {
  2652. console.error('Failed to load L2TP:', err);
  2653. }
  2654. }
  2655. async function openAddL2TPModal() {
  2656. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2657. await fetchPPPProfilesList();
  2658. }
  2659. document.getElementById('l2tp-modal-title').innerText = 'Add L2TP Client Interface';
  2660. document.getElementById('l2tp-modal-name').value = `l2tp-out${(state.l2tpList || []).length + 1}`;
  2661. document.getElementById('l2tp-modal-name').readOnly = false;
  2662. document.getElementById('l2tp-modal-server').value = '';
  2663. document.getElementById('l2tp-modal-user').value = '';
  2664. document.getElementById('l2tp-modal-pass').value = '';
  2665. document.getElementById('l2tp-modal-ipsec').value = '';
  2666. document.getElementById('l2tp-modal-defroute').checked = true;
  2667. document.getElementById('l2tp-modal-disabled').checked = false;
  2668. populateProfileSelect('l2tp-modal-profile', 'default-encryption', 'default-encryption');
  2669. document.getElementById('l2tp-modal').classList.remove('hidden');
  2670. }
  2671. async function openEditL2TPModal(name) {
  2672. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2673. await fetchPPPProfilesList();
  2674. }
  2675. const inst = (state.l2tpList || []).find(i => i.name === name);
  2676. if (!inst) return;
  2677. document.getElementById('l2tp-modal-title').innerText = `Edit L2TP Client: ${name}`;
  2678. document.getElementById('l2tp-modal-name').value = inst.name;
  2679. document.getElementById('l2tp-modal-name').readOnly = true;
  2680. document.getElementById('l2tp-modal-server').value = inst.connect_to || '';
  2681. document.getElementById('l2tp-modal-user').value = inst.username || '';
  2682. document.getElementById('l2tp-modal-pass').value = inst.password || '';
  2683. document.getElementById('l2tp-modal-ipsec').value = inst.ipsec_secret || '';
  2684. document.getElementById('l2tp-modal-defroute').checked = inst.default_route ?? true;
  2685. document.getElementById('l2tp-modal-disabled').checked = !!inst.disabled;
  2686. populateProfileSelect('l2tp-modal-profile', inst.profile || 'default-encryption', 'default-encryption');
  2687. document.getElementById('l2tp-modal').classList.remove('hidden');
  2688. }
  2689. function closeL2TPModal() {
  2690. document.getElementById('l2tp-modal').classList.add('hidden');
  2691. }
  2692. async function submitSaveL2TP(e) {
  2693. e.preventDefault();
  2694. const name = document.getElementById('l2tp-modal-name').value.trim();
  2695. const server = document.getElementById('l2tp-modal-server').value.trim();
  2696. const user = document.getElementById('l2tp-modal-user').value.trim();
  2697. const pass = document.getElementById('l2tp-modal-pass').value;
  2698. const profile = document.getElementById('l2tp-modal-profile')?.value || 'default-encryption';
  2699. const ipsec = document.getElementById('l2tp-modal-ipsec').value;
  2700. const defRoute = document.getElementById('l2tp-modal-defroute').checked;
  2701. const disabled = document.getElementById('l2tp-modal-disabled').checked;
  2702. try {
  2703. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`, {
  2704. method: 'POST',
  2705. headers: { 'Content-Type': 'application/json' },
  2706. body: JSON.stringify({
  2707. name,
  2708. connect_to: server,
  2709. username: user,
  2710. password: pass,
  2711. profile: profile,
  2712. ipsec_secret: ipsec,
  2713. default_route: defRoute,
  2714. disabled
  2715. })
  2716. });
  2717. if (res.ok) {
  2718. showToast('L2TP Saved', `Client ${name} configuration saved`, 'success');
  2719. closeL2TPModal();
  2720. loadL2TP(false);
  2721. fetchData(false);
  2722. }
  2723. } catch (err) {
  2724. showToast('Error', err.message, 'error');
  2725. }
  2726. }
  2727. async function connectL2TPInstance(name) {
  2728. try {
  2729. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  2730. if (res.ok) {
  2731. showToast('Connecting', `Dialing L2TP ${name}...`, 'info');
  2732. setTimeout(() => loadL2TP(false), 2000);
  2733. }
  2734. } catch (err) {
  2735. showToast('Error', err.message, 'error');
  2736. }
  2737. }
  2738. async function disconnectL2TPInstance(name) {
  2739. try {
  2740. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  2741. if (res.ok) {
  2742. showToast('Disconnected', `L2TP tunnel ${name} terminated`, 'info');
  2743. loadL2TP(false);
  2744. }
  2745. } catch (err) {
  2746. showToast('Error', err.message, 'error');
  2747. }
  2748. }
  2749. async function toggleL2TPState(name, enable) {
  2750. try {
  2751. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/state`, {
  2752. method: 'POST',
  2753. headers: { 'Content-Type': 'application/json' },
  2754. body: JSON.stringify({ enabled: enable })
  2755. });
  2756. if (res.ok) {
  2757. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  2758. loadL2TP(false);
  2759. }
  2760. } catch (err) {
  2761. showToast('Error', err.message, 'error');
  2762. }
  2763. }
  2764. async function deleteL2TPInstance(name) {
  2765. if (!confirm(`Are you sure you want to delete L2TP client ${name}?`)) return;
  2766. try {
  2767. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2768. if (res.ok) {
  2769. showToast('Deleted', `L2TP client ${name} removed`, 'success');
  2770. loadL2TP(false);
  2771. fetchData(false);
  2772. }
  2773. } catch (err) {
  2774. showToast('Error', err.message, 'error');
  2775. }
  2776. }
  2777. // ======================== PPTP Multi-Instance ========================
  2778. async function loadPPTP(populateInputs = true) {
  2779. try {
  2780. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2781. await fetchPPPProfilesList();
  2782. }
  2783. const res = await fetch(`${API_BASE}/vpn/pptp/clients`);
  2784. const list = await res.json();
  2785. state.pptpList = Array.isArray(list) ? list : [];
  2786. const badge = document.getElementById('pptp-count-badge');
  2787. if (badge) badge.innerText = `${state.pptpList.length} Client${state.pptpList.length !== 1 ? 's' : ''}`;
  2788. const tbody = document.getElementById('pptp-table-body');
  2789. const empty = document.getElementById('pptp-empty');
  2790. if (!tbody) return;
  2791. tbody.innerHTML = '';
  2792. if (state.pptpList.length === 0) {
  2793. if (empty) empty.classList.remove('hidden');
  2794. } else {
  2795. if (empty) empty.classList.add('hidden');
  2796. state.pptpList.forEach(inst => {
  2797. const tr = document.createElement('tr');
  2798. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  2799. tr.innerHTML = `
  2800. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  2801. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  2802. <td class="py-2.5 px-3 text-purple-400 font-mono">${escapeHtml(inst.connect_to)}</td>
  2803. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  2804. <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>
  2805. <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>
  2806. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  2807. <td class="py-2.5 px-3 text-center">
  2808. <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'}">
  2809. ${inst.require_mppe ? 'MPPE-128' : 'None'}
  2810. </span>
  2811. </td>
  2812. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  2813. ${inst.running ? `
  2814. <button onclick="disconnectPPTPInstance('${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  2815. ` : `
  2816. <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>
  2817. `}
  2818. <button onclick="togglePPTPState('${escapeHtml(inst.name)}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  2819. ${inst.disabled ? 'Enable' : 'Disable'}
  2820. </button>
  2821. <button onclick="openEditPPTPModal('${escapeHtml(inst.name)}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2822. <button onclick="deletePPTPInstance('${escapeHtml(inst.name)}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2823. </td>
  2824. `;
  2825. tbody.appendChild(tr);
  2826. });
  2827. }
  2828. } catch (err) {
  2829. console.error('Failed to load PPTP:', err);
  2830. }
  2831. }
  2832. async function openAddPPTPModal() {
  2833. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2834. await fetchPPPProfilesList();
  2835. }
  2836. document.getElementById('pptp-modal-title').innerText = 'Add PPTP Client Interface';
  2837. document.getElementById('pptp-modal-name').value = `pptp-out${(state.pptpList || []).length + 1}`;
  2838. document.getElementById('pptp-modal-name').readOnly = false;
  2839. document.getElementById('pptp-modal-server').value = '';
  2840. document.getElementById('pptp-modal-user').value = '';
  2841. document.getElementById('pptp-modal-pass').value = '';
  2842. document.getElementById('pptp-modal-mppe').checked = true;
  2843. document.getElementById('pptp-modal-defroute').checked = true;
  2844. document.getElementById('pptp-modal-disabled').checked = false;
  2845. populateProfileSelect('pptp-modal-profile', 'default-encryption', 'default-encryption');
  2846. document.getElementById('pptp-modal').classList.remove('hidden');
  2847. }
  2848. async function openEditPPTPModal(name) {
  2849. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2850. await fetchPPPProfilesList();
  2851. }
  2852. const inst = (state.pptpList || []).find(i => i.name === name);
  2853. if (!inst) return;
  2854. document.getElementById('pptp-modal-title').innerText = `Edit PPTP Client: ${name}`;
  2855. document.getElementById('pptp-modal-name').value = inst.name;
  2856. document.getElementById('pptp-modal-name').readOnly = true;
  2857. document.getElementById('pptp-modal-server').value = inst.connect_to || '';
  2858. document.getElementById('pptp-modal-user').value = inst.username || '';
  2859. document.getElementById('pptp-modal-pass').value = inst.password || '';
  2860. document.getElementById('pptp-modal-mppe').checked = inst.require_mppe ?? true;
  2861. document.getElementById('pptp-modal-defroute').checked = inst.default_route ?? true;
  2862. document.getElementById('pptp-modal-disabled').checked = !!inst.disabled;
  2863. populateProfileSelect('pptp-modal-profile', inst.profile || 'default-encryption', 'default-encryption');
  2864. document.getElementById('pptp-modal').classList.remove('hidden');
  2865. }
  2866. function closePPTPModal() {
  2867. document.getElementById('pptp-modal').classList.add('hidden');
  2868. }
  2869. async function submitSavePPTP(e) {
  2870. e.preventDefault();
  2871. const name = document.getElementById('pptp-modal-name').value.trim();
  2872. const server = document.getElementById('pptp-modal-server').value.trim();
  2873. const user = document.getElementById('pptp-modal-user').value.trim();
  2874. const pass = document.getElementById('pptp-modal-pass').value;
  2875. const profile = document.getElementById('pptp-modal-profile')?.value || 'default-encryption';
  2876. const mppe = document.getElementById('pptp-modal-mppe').checked;
  2877. const defRoute = document.getElementById('pptp-modal-defroute').checked;
  2878. const disabled = document.getElementById('pptp-modal-disabled').checked;
  2879. try {
  2880. const res = await fetch(`${API_BASE}/vpn/pptp/clients`, {
  2881. method: 'POST',
  2882. headers: { 'Content-Type': 'application/json' },
  2883. body: JSON.stringify({
  2884. name,
  2885. connect_to: server,
  2886. username: user,
  2887. password: pass,
  2888. profile: profile,
  2889. require_mppe: mppe,
  2890. default_route: defRoute,
  2891. auto_reconnect: true,
  2892. disabled
  2893. })
  2894. });
  2895. if (res.ok) {
  2896. showToast('PPTP Saved', `Client ${name} configuration saved`, 'success');
  2897. closePPTPModal();
  2898. loadPPTP(false);
  2899. fetchData(false);
  2900. }
  2901. } catch (err) {
  2902. showToast('Error', err.message, 'error');
  2903. }
  2904. }
  2905. async function connectPPTPInstance(name) {
  2906. try {
  2907. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  2908. if (res.ok) {
  2909. showToast('Connecting', `Dialing PPTP ${name}...`, 'info');
  2910. setTimeout(() => loadPPTP(false), 2000);
  2911. }
  2912. } catch (err) {
  2913. showToast('Error', err.message, 'error');
  2914. }
  2915. }
  2916. async function disconnectPPTPInstance(name) {
  2917. try {
  2918. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  2919. if (res.ok) {
  2920. showToast('Disconnected', `PPTP tunnel ${name} terminated`, 'info');
  2921. loadPPTP(false);
  2922. }
  2923. } catch (err) {
  2924. showToast('Error', err.message, 'error');
  2925. }
  2926. }
  2927. async function togglePPTPState(name, enable) {
  2928. try {
  2929. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/state`, {
  2930. method: 'POST',
  2931. headers: { 'Content-Type': 'application/json' },
  2932. body: JSON.stringify({ enabled: enable })
  2933. });
  2934. if (res.ok) {
  2935. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  2936. loadPPTP(false);
  2937. }
  2938. } catch (err) {
  2939. showToast('Error', err.message, 'error');
  2940. }
  2941. }
  2942. async function deletePPTPInstance(name) {
  2943. if (!confirm(`Are you sure you want to delete PPTP client ${name}?`)) return;
  2944. try {
  2945. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2946. if (res.ok) {
  2947. showToast('Deleted', `PPTP client ${name} removed`, 'success');
  2948. loadPPTP(false);
  2949. fetchData(false);
  2950. }
  2951. } catch (err) {
  2952. showToast('Error', err.message, 'error');
  2953. }
  2954. }
  2955. // ---------------- Modal & Helper Functions ----------------
  2956. function openVlanModal(defaultParent = '') {
  2957. const select = document.getElementById('vlan-parent');
  2958. select.innerHTML = '';
  2959. const allIfaces = state.interfaces || [];
  2960. const eligible = allIfaces.filter(i => supportsVLAN(i));
  2961. if (eligible.length === 0) {
  2962. const opt = document.createElement('option');
  2963. opt.value = '';
  2964. opt.innerText = 'No VLAN-capable interfaces available';
  2965. select.appendChild(opt);
  2966. } else {
  2967. eligible.forEach(i => {
  2968. const opt = document.createElement('option');
  2969. opt.value = i.name;
  2970. opt.innerText = `${i.name} (${i.role || i.type || 'Ethernet'} - ${i.state})`;
  2971. if (i.name === defaultParent) opt.selected = true;
  2972. select.appendChild(opt);
  2973. });
  2974. }
  2975. document.getElementById('vlan-id').value = '';
  2976. document.getElementById('vlan-name').value = '';
  2977. document.getElementById('vlan-ip').value = '';
  2978. document.getElementById('vlan-desc').value = '';
  2979. populateRoleSelects('LAN');
  2980. autoSuggestVlanName();
  2981. document.getElementById('vlan-modal').classList.remove('hidden');
  2982. }
  2983. function closeVlanModal() {
  2984. document.getElementById('vlan-modal').classList.add('hidden');
  2985. }
  2986. function autoSuggestVlanName() {
  2987. const parent = document.getElementById('vlan-parent').value;
  2988. if (!parent) return;
  2989. const id = document.getElementById('vlan-id').value;
  2990. const nameInput = document.getElementById('vlan-name');
  2991. if (parent && id) nameInput.placeholder = `${parent}.${id}`;
  2992. }
  2993. function setSubnetPreset(cidr) {
  2994. const ipInput = document.getElementById('vlan-ip');
  2995. const id = document.getElementById('vlan-id').value || '10';
  2996. ipInput.value = `192.168.${id}.1${cidr}`;
  2997. }
  2998. async function submitCreateVlan(e) {
  2999. e.preventDefault();
  3000. const btn = document.getElementById('vlan-submit-btn');
  3001. btn.disabled = true;
  3002. btn.innerText = 'Creating...';
  3003. const parent = document.getElementById('vlan-parent').value;
  3004. if (!parent) {
  3005. showToast('Error', 'Please select a valid VLAN-capable parent interface', 'error');
  3006. btn.disabled = false;
  3007. btn.innerText = 'Create VLAN';
  3008. return;
  3009. }
  3010. const id = parseInt(document.getElementById('vlan-id').value, 10);
  3011. const name = document.getElementById('vlan-name').value.trim();
  3012. const ip = document.getElementById('vlan-ip').value.trim();
  3013. const role = document.getElementById('vlan-role').value;
  3014. const desc = document.getElementById('vlan-desc').value.trim();
  3015. try {
  3016. const res = await fetch(`${API_BASE}/vlans`, {
  3017. method: 'POST',
  3018. headers: { 'Content-Type': 'application/json' },
  3019. body: JSON.stringify({
  3020. parent_name: parent,
  3021. vlan_id: id,
  3022. name: name,
  3023. ip_address: ip,
  3024. role: role,
  3025. description: desc,
  3026. mtu: 1500,
  3027. auto_up: true
  3028. })
  3029. });
  3030. const data = await res.json();
  3031. if (res.ok) {
  3032. showToast('VLAN Created', `Created ${data.name} (VLAN ${data.vlan_id})`, 'success');
  3033. state.expandedParents.add(parent);
  3034. closeVlanModal();
  3035. await fetchData(true);
  3036. if (state.activeTab !== 'interfaces') navigate('interfaces');
  3037. } else {
  3038. showToast('Creation Failed', data.message || 'Failed to create VLAN', 'error');
  3039. }
  3040. } catch (err) {
  3041. showToast('Error', err.message, 'error');
  3042. } finally {
  3043. btn.disabled = false;
  3044. btn.innerText = 'Create VLAN';
  3045. }
  3046. }
  3047. async function confirmDeleteVlan(name) {
  3048. if (!confirm(`Delete VLAN interface ${name}?`)) return;
  3049. try {
  3050. const res = await fetch(`${API_BASE}/vlans/${encodeURIComponent(name)}`, { method: 'DELETE' });
  3051. if (res.ok) {
  3052. showToast('VLAN Deleted', `Interface ${name} removed`, 'success');
  3053. closeIfaceModal();
  3054. fetchData(true);
  3055. }
  3056. } catch (err) {
  3057. showToast('Error', err.message, 'error');
  3058. }
  3059. }
  3060. function openIfaceModal(name) {
  3061. const iface = (state.interfaces || []).find(i => i.name === name);
  3062. if (!iface) return;
  3063. state.currentModalIface = iface.name;
  3064. document.getElementById('modal-iface-name').innerText = iface.name;
  3065. document.getElementById('modal-iface-badge').innerText = iface.is_vlan ? `VLAN ${iface.vlan_id}` : iface.type;
  3066. document.getElementById('modal-iface-mtu').value = iface.mtu;
  3067. populateRoleSelects(iface.role || 'LAN');
  3068. document.getElementById('modal-iface-desc').value = iface.description || '';
  3069. const nameInput = document.getElementById('modal-iface-new-name');
  3070. const renameBtn = document.getElementById('modal-btn-rename');
  3071. const renameHelp = document.getElementById('modal-iface-rename-help');
  3072. if (nameInput) {
  3073. nameInput.value = iface.name;
  3074. if (iface.name === 'lo' || iface.type === 'loopback') {
  3075. nameInput.disabled = true;
  3076. if (renameBtn) renameBtn.disabled = true;
  3077. if (renameHelp) renameHelp.innerText = 'Loopback interface cannot be renamed.';
  3078. } else {
  3079. nameInput.disabled = false;
  3080. if (renameBtn) renameBtn.disabled = false;
  3081. if (renameHelp) renameHelp.innerText = 'Device name in Linux (max 15 characters). Automatically preserves operational link state and metadata.';
  3082. }
  3083. }
  3084. const delBtn = document.getElementById('modal-delete-vlan-btn');
  3085. if (iface.is_vlan) {
  3086. delBtn.classList.remove('hidden');
  3087. } else {
  3088. delBtn.classList.add('hidden');
  3089. }
  3090. renderModalIPs(iface);
  3091. document.getElementById('iface-modal').classList.remove('hidden');
  3092. }
  3093. function renderModalIPs(iface) {
  3094. const container = document.getElementById('modal-ip-list');
  3095. container.innerHTML = '';
  3096. const addrs = [...(iface.ipv4 || []), ...(iface.ipv6 || [])];
  3097. if (addrs.length === 0) {
  3098. container.innerHTML = `<span class="text-slate-500 text-xs font-sans">No IP addresses currently bound</span>`;
  3099. return;
  3100. }
  3101. addrs.forEach(addr => {
  3102. const row = document.createElement('div');
  3103. row.className = 'flex items-center justify-between p-2 rounded bg-slate-900 border border-slate-800';
  3104. row.innerHTML = `
  3105. <span class="text-white">${addr}</span>
  3106. <button onclick="removeInterfaceIP('${addr}')" class="text-[11px] text-rose-400 hover:text-rose-300 font-sans">Remove</button>
  3107. `;
  3108. container.appendChild(row);
  3109. });
  3110. }
  3111. function closeIfaceModal() {
  3112. document.getElementById('iface-modal').classList.add('hidden');
  3113. state.currentModalIface = null;
  3114. }
  3115. async function setIfaceState(name, newState) {
  3116. const target = name || state.currentModalIface;
  3117. if (!target) return;
  3118. await toggleInterfaceState(target, newState);
  3119. const updated = (state.interfaces || []).find(i => i.name === target);
  3120. if (updated) openIfaceModal(target);
  3121. }
  3122. async function applyMTU() {
  3123. const mtu = parseInt(document.getElementById('modal-iface-mtu').value, 10);
  3124. try {
  3125. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/mtu`, {
  3126. method: 'POST',
  3127. headers: { 'Content-Type': 'application/json' },
  3128. body: JSON.stringify({ mtu })
  3129. });
  3130. if (res.ok) {
  3131. showToast('MTU Applied', `Set MTU to ${mtu} on ${state.currentModalIface}`, 'success');
  3132. fetchData(false);
  3133. }
  3134. } catch (err) {
  3135. showToast('Error', err.message, 'error');
  3136. }
  3137. }
  3138. async function addInterfaceIP() {
  3139. const ip = document.getElementById('modal-new-ip').value.trim();
  3140. if (!ip) return;
  3141. try {
  3142. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  3143. method: 'POST',
  3144. headers: { 'Content-Type': 'application/json' },
  3145. body: JSON.stringify({ ip })
  3146. });
  3147. if (res.ok) {
  3148. showToast('IP Added', `Bound ${ip} to ${state.currentModalIface}`, 'success');
  3149. document.getElementById('modal-new-ip').value = '';
  3150. await fetchData(false);
  3151. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  3152. if (iface) renderModalIPs(iface);
  3153. } else {
  3154. const err = await res.json();
  3155. showToast('Error', err.error || err.message || 'Failed to add IP address', 'error');
  3156. }
  3157. } catch (err) {
  3158. showToast('Error', err.message, 'error');
  3159. }
  3160. }
  3161. async function removeInterfaceIP(ip) {
  3162. if (!confirm(`Remove IP ${ip}?`)) return;
  3163. try {
  3164. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  3165. method: 'DELETE',
  3166. headers: { 'Content-Type': 'application/json' },
  3167. body: JSON.stringify({ ip })
  3168. });
  3169. if (res.ok) {
  3170. showToast('IP Removed', `Removed ${ip}`, 'success');
  3171. await fetchData(false);
  3172. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  3173. if (iface) renderModalIPs(iface);
  3174. }
  3175. } catch (err) {
  3176. showToast('Error', err.message, 'error');
  3177. }
  3178. }
  3179. async function renameInterface() {
  3180. const oldName = state.currentModalIface;
  3181. const newNameInput = document.getElementById('modal-iface-new-name');
  3182. const newName = (newNameInput?.value || '').trim();
  3183. if (!oldName) return;
  3184. if (!newName) {
  3185. showToast('Warning', 'Interface name cannot be empty', 'warning');
  3186. return;
  3187. }
  3188. if (newName === oldName) {
  3189. showToast('Info', `Interface name is already "${oldName}"`, 'info');
  3190. return;
  3191. }
  3192. if (newName.length > 15) {
  3193. showToast('Validation Error', 'Interface name cannot exceed 15 characters (Linux IFNAMSIZ)', 'error');
  3194. return;
  3195. }
  3196. if (!/^[a-zA-Z0-9_][a-zA-Z0-9_.-]*$/.test(newName)) {
  3197. showToast('Validation Error', 'Name must contain only alphanumeric characters, underscores, hyphens or dots', 'error');
  3198. return;
  3199. }
  3200. const renameBtn = document.getElementById('modal-btn-rename');
  3201. if (renameBtn) {
  3202. renameBtn.disabled = true;
  3203. renameBtn.innerHTML = `<span class="animate-spin inline-block mr-1">⟳</span> Renaming...`;
  3204. }
  3205. try {
  3206. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(oldName)}/rename`, {
  3207. method: 'POST',
  3208. headers: { 'Content-Type': 'application/json' },
  3209. body: JSON.stringify({ new_name: newName })
  3210. });
  3211. const data = await res.json();
  3212. if (!res.ok) {
  3213. showToast('Rename Failed', data.error || data.message || 'Failed to rename interface', 'error');
  3214. return;
  3215. }
  3216. showToast('Interface Renamed', `Successfully renamed ${oldName} → ${newName}`, 'success');
  3217. state.currentModalIface = newName;
  3218. document.getElementById('modal-iface-name').innerText = newName;
  3219. // Refresh application state
  3220. await fetchData(false);
  3221. const updated = (state.interfaces || []).find(i => i.name === newName);
  3222. if (updated) {
  3223. openIfaceModal(newName);
  3224. } else {
  3225. closeIfaceModal();
  3226. }
  3227. } catch (err) {
  3228. showToast('Error', err.message, 'error');
  3229. } finally {
  3230. if (renameBtn) {
  3231. renameBtn.disabled = false;
  3232. renameBtn.innerHTML = `
  3233. <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>
  3234. <span>Rename</span>
  3235. `;
  3236. }
  3237. }
  3238. }
  3239. async function saveInterfaceMetadata() {
  3240. const oldName = state.currentModalIface;
  3241. const newName = (document.getElementById('modal-iface-new-name')?.value || '').trim();
  3242. const role = document.getElementById('modal-iface-role').value;
  3243. const desc = document.getElementById('modal-iface-desc').value.trim();
  3244. let targetName = oldName;
  3245. // If user changed the name before clicking Save Changes, execute rename first
  3246. if (newName && newName !== oldName && oldName !== 'lo') {
  3247. try {
  3248. const renameRes = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(oldName)}/rename`, {
  3249. method: 'POST',
  3250. headers: { 'Content-Type': 'application/json' },
  3251. body: JSON.stringify({ new_name: newName })
  3252. });
  3253. const data = await renameRes.json();
  3254. if (!renameRes.ok) {
  3255. showToast('Rename Failed', data.error || data.message || 'Could not rename interface', 'error');
  3256. return;
  3257. }
  3258. targetName = newName;
  3259. state.currentModalIface = newName;
  3260. showToast('Renamed', `Interface renamed from ${oldName} to ${newName}`, 'success');
  3261. } catch (err) {
  3262. showToast('Error', err.message, 'error');
  3263. return;
  3264. }
  3265. }
  3266. try {
  3267. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(targetName)}/metadata`, {
  3268. method: 'POST',
  3269. headers: { 'Content-Type': 'application/json' },
  3270. body: JSON.stringify({ role, description: desc })
  3271. });
  3272. if (res.ok) {
  3273. showToast('Saved', 'Interface configuration updated', 'success');
  3274. closeIfaceModal();
  3275. fetchData(false);
  3276. } else {
  3277. const err = await res.json();
  3278. showToast('Error', err.error || err.message || 'Failed to save metadata', 'error');
  3279. }
  3280. } catch (err) {
  3281. showToast('Error', err.message, 'error');
  3282. }
  3283. }
  3284. // ======================== MIKROTIK FIREWALL (/ip firewall) ========================
  3285. state.fwSubTab = 'filter';
  3286. state.routesSubTab = 'routes';
  3287. function renderRuleFlag(disabled, hasComment) {
  3288. let flags = '';
  3289. if (disabled) flags += '<span class="text-rose-400 font-bold" title="Disabled">X</span>';
  3290. if (hasComment) flags += '<span class="text-amber-400 font-bold ml-1" title="Has Comment">C</span>';
  3291. return flags || '<span class="text-slate-600">-</span>';
  3292. }
  3293. function renderActionBadge(action) {
  3294. const act = (action || '').toLowerCase();
  3295. let color = 'bg-slate-800 text-slate-300';
  3296. if (act === 'accept') color = 'bg-emerald-500/20 text-emerald-300 border border-emerald-500/30';
  3297. else if (act === 'drop' || act === 'reject') color = 'bg-rose-500/20 text-rose-300 border border-rose-500/30';
  3298. else if (act === 'masquerade' || act === 'src-nat' || act === 'dst-nat') color = 'bg-amber-500/20 text-amber-300 border border-amber-500/30';
  3299. else if (act.startsWith('mark-')) color = 'bg-purple-500/20 text-purple-300 border border-purple-500/30';
  3300. else if (act === 'log') color = 'bg-cyan-500/20 text-cyan-300 border border-cyan-500/30';
  3301. return `<span class="px-2 py-0.5 rounded text-[10px] font-mono font-semibold ${color}">${action}</span>`;
  3302. }
  3303. function switchFWSubTab(tab) {
  3304. state.fwSubTab = tab;
  3305. const tabs = ['filter', 'nat', 'mangle', 'addrlist', 'geo', 'connections'];
  3306. tabs.forEach(t => {
  3307. const panel = document.getElementById(`fw-subtab-${t}`);
  3308. const btn = document.getElementById(`fw-subtab-btn-${t}`);
  3309. if (panel) {
  3310. if (t === tab) panel.classList.remove('hidden');
  3311. else panel.classList.add('hidden');
  3312. }
  3313. if (btn) {
  3314. if (t === tab) {
  3315. 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';
  3316. } else {
  3317. 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';
  3318. }
  3319. }
  3320. });
  3321. const addBtn = document.getElementById('fw-primary-add-btn');
  3322. if (addBtn) {
  3323. if (tab === 'filter') addBtn.innerHTML = '<span>+ Add Filter Rule</span>';
  3324. else if (tab === 'nat') addBtn.innerHTML = '<span>+ Add NAT Rule</span>';
  3325. else if (tab === 'mangle') addBtn.innerHTML = '<span>+ Add Mangle Rule</span>';
  3326. else if (tab === 'addrlist') addBtn.innerHTML = '<span>+ Add Address List</span>';
  3327. else if (tab === 'geo') addBtn.innerHTML = '<span>⚙️ Schedule Settings</span>';
  3328. else if (tab === 'connections') addBtn.innerHTML = '<span>Refresh Flows</span>';
  3329. }
  3330. if (tab === 'filter') renderFilterRules();
  3331. else if (tab === 'nat') renderNATRules();
  3332. else if (tab === 'mangle') renderMangleRules();
  3333. else if (tab === 'addrlist') renderAddressLists();
  3334. else if (tab === 'geo') loadGeoIP();
  3335. else if (tab === 'connections') loadConnections();
  3336. setTimeout(initTableSorting, 50);
  3337. }
  3338. function openCurrentFWModal() {
  3339. if (state.fwSubTab === 'filter') openAddFilterModal();
  3340. else if (state.fwSubTab === 'nat') openAddNATModal();
  3341. else if (state.fwSubTab === 'mangle') openAddMangleModal();
  3342. else if (state.fwSubTab === 'addrlist') openAddAddrListModal();
  3343. else if (state.fwSubTab === 'geo') openGeoIntervalModal();
  3344. else if (state.fwSubTab === 'connections') loadConnections();
  3345. }
  3346. async function loadFirewall(populateDropdowns = true) {
  3347. try {
  3348. const [summaryRes, filterRes, natRes, mangleRes, addrlistRes, geoStatusRes, geoCountriesRes] = await Promise.all([
  3349. fetch(`${API_BASE}/firewall/summary`),
  3350. fetch(`${API_BASE}/firewall/filter`),
  3351. fetch(`${API_BASE}/firewall/nat`),
  3352. fetch(`${API_BASE}/firewall/mangle`),
  3353. fetch(`${API_BASE}/firewall/address-lists`),
  3354. fetch(`${API_BASE}/firewall/geoip/status`),
  3355. fetch(`${API_BASE}/firewall/geoip/countries`)
  3356. ]);
  3357. if (summaryRes.ok) state.fwSummary = await summaryRes.json();
  3358. if (filterRes.ok) state.filterRules = await filterRes.json();
  3359. if (natRes.ok) state.natRules = await natRes.json();
  3360. if (mangleRes.ok) state.mangleRules = await mangleRes.json();
  3361. if (addrlistRes.ok) state.addressLists = await addrlistRes.json();
  3362. if (geoStatusRes.ok) state.geoStatus = await geoStatusRes.json();
  3363. if (geoCountriesRes.ok) state.geoCountries = await geoCountriesRes.json();
  3364. // Badges
  3365. const bFilter = document.getElementById('fw-badge-filter');
  3366. if (bFilter) bFilter.innerText = (state.filterRules || []).length;
  3367. const bNat = document.getElementById('fw-badge-nat');
  3368. if (bNat) bNat.innerText = (state.natRules || []).length;
  3369. const bMangle = document.getElementById('fw-badge-mangle');
  3370. if (bMangle) bMangle.innerText = (state.mangleRules || []).length;
  3371. const bAddr = document.getElementById('fw-badge-addrlist');
  3372. if (bAddr) bAddr.innerText = (state.addressLists || []).length;
  3373. const bGeo = document.getElementById('fw-badge-geo');
  3374. if (bGeo) bGeo.innerText = state.geoStatus?.enabled_count || 0;
  3375. const sigFilter = (state.filterRules || []).map(r => `${r.id}:${r.chain}:${r.action}:${r.disabled}`).join(';');
  3376. const sigNat = (state.natRules || []).map(r => `${r.id}:${r.chain}:${r.action}:${r.disabled}`).join(';');
  3377. const sigMangle = (state.mangleRules || []).map(r => `${r.id}:${r.chain}:${r.action}:${r.disabled}`).join(';');
  3378. const sigAddr = (state.addressLists || []).map(a => `${a.id}:${a.name}:${a.address}:${a.disabled}`).join(';');
  3379. const tbodyFilter = document.getElementById('filter-table-body');
  3380. if (tbodyFilter) {
  3381. if (populateDropdowns || tbodyFilter.dataset.sig !== sigFilter) {
  3382. tbodyFilter.dataset.sig = sigFilter;
  3383. renderFilterRules();
  3384. } else {
  3385. // In-place live stats update (ZERO flicker)
  3386. (state.filterRules || []).forEach(r => {
  3387. const p = document.getElementById(`filter-pkts-${r.id}`);
  3388. if (p) p.innerText = `${(r.packets || 0).toLocaleString()}p`;
  3389. const b = document.getElementById(`filter-bytes-${r.id}`);
  3390. if (b) b.innerText = formatTraffic(r.bytes || 0).replace('/s', '');
  3391. });
  3392. }
  3393. }
  3394. const tbodyNat = document.getElementById('nat-table-body');
  3395. if (tbodyNat) {
  3396. if (populateDropdowns || tbodyNat.dataset.sig !== sigNat) {
  3397. tbodyNat.dataset.sig = sigNat;
  3398. renderNATRules();
  3399. } else {
  3400. (state.natRules || []).forEach(r => {
  3401. const p = document.getElementById(`nat-pkts-${r.id}`);
  3402. if (p) p.innerText = `${(r.packets || 0).toLocaleString()}p`;
  3403. const b = document.getElementById(`nat-bytes-${r.id}`);
  3404. if (b) b.innerText = formatTraffic(r.bytes || 0).replace('/s', '');
  3405. });
  3406. }
  3407. }
  3408. const tbodyMangle = document.getElementById('mangle-table-body');
  3409. if (tbodyMangle) {
  3410. if (populateDropdowns || tbodyMangle.dataset.sig !== sigMangle) {
  3411. tbodyMangle.dataset.sig = sigMangle;
  3412. renderMangleRules();
  3413. } else {
  3414. (state.mangleRules || []).forEach(r => {
  3415. const p = document.getElementById(`mangle-pkts-${r.id}`);
  3416. if (p) p.innerText = `${(r.packets || 0).toLocaleString()}p`;
  3417. const b = document.getElementById(`mangle-bytes-${r.id}`);
  3418. if (b) b.innerText = formatTraffic(r.bytes || 0).replace('/s', '');
  3419. });
  3420. }
  3421. }
  3422. const tbodyAddr = document.getElementById('addrlist-table-body');
  3423. if (tbodyAddr && (populateDropdowns || tbodyAddr.dataset.sig !== sigAddr)) {
  3424. tbodyAddr.dataset.sig = sigAddr;
  3425. renderAddressLists();
  3426. }
  3427. renderGeoCountries();
  3428. if (state.fwSubTab === 'connections') {
  3429. loadConnections();
  3430. }
  3431. } catch (err) {
  3432. console.error('Failed to load firewall:', err);
  3433. }
  3434. }
  3435. // ----------------- Filter Rules -----------------
  3436. function renderFilterRules() {
  3437. const chainFilter = document.getElementById('filter-filter-chain')?.value || '';
  3438. const tbody = document.getElementById('filter-table-body');
  3439. const empty = document.getElementById('filter-empty');
  3440. if (!tbody) return;
  3441. tbody.innerHTML = '';
  3442. const rules = (state.filterRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  3443. document.getElementById('filter-count-badge').innerText = `${rules.length} Rules`;
  3444. if (rules.length === 0) {
  3445. empty?.classList.remove('hidden');
  3446. return;
  3447. }
  3448. empty?.classList.add('hidden');
  3449. rules.forEach((r, idx) => {
  3450. const tr = document.createElement('tr');
  3451. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  3452. const ports = [r.src_port ? 's:' + r.src_port : '', r.dst_port ? 'd:' + r.dst_port : ''].filter(Boolean).join(' ');
  3453. const ifaces = [r.in_interface ? 'in:' + r.in_interface : '', r.out_interface ? 'out:' + r.out_interface : ''].filter(Boolean).join(' ');
  3454. let actionExtra = '';
  3455. if (r.action === 'reject') {
  3456. actionExtra = `<span class="block text-[10px] text-rose-300 font-mono mt-0.5">(${r.reject_with || 'icmp-net-unreach'})</span>`;
  3457. } else if (r.action === 'jump') {
  3458. actionExtra = `<span class="block text-[10px] text-yellow-300 font-mono mt-0.5">&rarr; ${r.jump_target || '-'}</span>`;
  3459. } else if (r.action.includes('address-list') || r.action.includes('address list')) {
  3460. actionExtra = `<span class="block text-[10px] text-emerald-300 font-mono mt-0.5">&rarr; ${r.address_list || '-'}</span>`;
  3461. } else if (r.action === 'log' && r.log_prefix) {
  3462. actionExtra = `<span class="block text-[10px] text-slate-400 font-mono mt-0.5">${r.log_prefix}</span>`;
  3463. }
  3464. tr.innerHTML = `
  3465. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  3466. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  3467. <td class="py-2.5 px-3 font-bold text-white">${r.chain}</td>
  3468. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  3469. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  3470. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}</td>
  3471. <td class="py-2.5 px-3 text-amber-400">${ports || '-'}</td>
  3472. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  3473. <td class="py-2.5 px-3">${renderActionBadge(r.action)}${actionExtra}</td>
  3474. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  3475. <span class="text-slate-300" id="filter-pkts-${r.id}">${(r.packets || 0).toLocaleString()}p</span> /
  3476. <span class="text-slate-500" id="filter-bytes-${r.id}">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  3477. </td>
  3478. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  3479. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  3480. <button onclick="moveFilterRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  3481. <button onclick="moveFilterRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  3482. <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>
  3483. <button onclick="openEditFilterModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  3484. <button onclick="deleteFilterRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  3485. </td>
  3486. `;
  3487. tbody.appendChild(tr);
  3488. });
  3489. }
  3490. function formatTarget(addr, list, geo) {
  3491. const parts = [];
  3492. if (addr) parts.push(`<span>${addr}</span>`);
  3493. if (list) {
  3494. const inv = list.startsWith('!') ? '!' : '';
  3495. const clean = list.replace(/^!/, '');
  3496. 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>`);
  3497. }
  3498. if (geo) {
  3499. const inv = geo.startsWith('!') ? '!' : '';
  3500. const clean = geo.replace(/^!/, '').replace(/^geo:/, '');
  3501. 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>`);
  3502. }
  3503. if (parts.length === 0) return '<span class="text-slate-600">0.0.0.0/0</span>';
  3504. return parts.join(' ');
  3505. }
  3506. function populateInterfaceSelect(selectId, currentVal = '') {
  3507. const sel = document.getElementById(selectId);
  3508. if (!sel) return;
  3509. sel.innerHTML = '<option value="">(Any Interface)</option>';
  3510. (state.interfaces || []).forEach(i => {
  3511. const opt = document.createElement('option');
  3512. opt.value = i.name;
  3513. opt.innerText = `${i.name} (${i.role || i.type})`;
  3514. if (i.name === currentVal) opt.selected = true;
  3515. sel.appendChild(opt);
  3516. });
  3517. }
  3518. function populateAddressListSelect(selectId, currentVal = '') {
  3519. const sel = document.getElementById(selectId);
  3520. if (!sel) return;
  3521. sel.innerHTML = '<option value="">(None)</option>';
  3522. const cleanVal = (currentVal || '').replace(/^!/, '');
  3523. const customNames = Array.from(new Set((state.addressLists || []).map(a => a.name))).sort();
  3524. customNames.forEach(name => {
  3525. const count = (state.addressLists || []).filter(a => a.name === name).length;
  3526. const opt = document.createElement('option');
  3527. opt.value = name;
  3528. opt.innerText = `${name} (${count} entries)`;
  3529. if (name === cleanVal) opt.selected = true;
  3530. sel.appendChild(opt);
  3531. });
  3532. if (cleanVal && !sel.querySelector(`option[value="${cleanVal}"]`)) {
  3533. const opt = document.createElement('option');
  3534. opt.value = cleanVal;
  3535. opt.innerText = cleanVal;
  3536. opt.selected = true;
  3537. sel.appendChild(opt);
  3538. }
  3539. populateCommonAddrListDatalist();
  3540. }
  3541. function populateCommonAddrListDatalist() {
  3542. const dl = document.getElementById('fw-addrlist-datalist');
  3543. if (!dl) return;
  3544. dl.innerHTML = '';
  3545. const names = Array.from(new Set((state.addressLists || []).map(a => a.name).filter(Boolean))).sort();
  3546. names.forEach(name => {
  3547. const opt = document.createElement('option');
  3548. opt.value = name;
  3549. dl.appendChild(opt);
  3550. });
  3551. }
  3552. function populateGeoIPSelect(selectId, currentVal = '') {
  3553. const sel = document.getElementById(selectId);
  3554. if (!sel) return;
  3555. sel.innerHTML = '<option value="">(None)</option>';
  3556. const cleanVal = (currentVal || '').replace(/^!/, '').replace(/^geo:/, '').toUpperCase();
  3557. // Presets optgroup
  3558. const grpPresets = document.createElement('optgroup');
  3559. grpPresets.label = '⚡ Regional Presets';
  3560. const presets = [
  3561. { code: 'EU', label: '🇪🇺 European Union (EU - 27 countries)' },
  3562. { code: 'BALKANS', label: '🏛️ Balkans (GR, CY, BG, RO, AL, etc.)' },
  3563. { code: 'BLOCKLIST', label: '🛡️ High-Risk Blocklist (CN, RU, IR, KP, BY)' }
  3564. ];
  3565. presets.forEach(p => {
  3566. const opt = document.createElement('option');
  3567. opt.value = p.code;
  3568. opt.innerText = p.label;
  3569. if (p.code === cleanVal) opt.selected = true;
  3570. grpPresets.appendChild(opt);
  3571. });
  3572. sel.appendChild(grpPresets);
  3573. // All Countries optgroup
  3574. const grpCountries = document.createElement('optgroup');
  3575. grpCountries.label = '🌍 All Countries';
  3576. const countries = (state.geoCountries || []).slice().sort((a, b) => a.name.localeCompare(b.name));
  3577. countries.forEach(c => {
  3578. const opt = document.createElement('option');
  3579. opt.value = c.code;
  3580. const subnetsInfo = c.subnet_count ? ` [${c.subnet_count.toLocaleString()} subnets]` : '';
  3581. opt.innerText = `${c.name} (${c.code})${subnetsInfo}`;
  3582. if (c.code === cleanVal) opt.selected = true;
  3583. grpCountries.appendChild(opt);
  3584. });
  3585. sel.appendChild(grpCountries);
  3586. }
  3587. // ==================== FIREWALL FILTER MODAL (ROUTEROS WEBFIG / WINBOX V4) ====================
  3588. function switchFwRuleTab(tab) {
  3589. state.activeFwRuleTab = tab;
  3590. document.querySelectorAll('.fw-rule-tab-btn').forEach(btn => {
  3591. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  3592. btn.classList.add('text-slate-400', 'border-transparent');
  3593. });
  3594. const activeBtn = document.getElementById(`fw-tab-btn-${tab}`);
  3595. if (activeBtn) {
  3596. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  3597. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  3598. }
  3599. document.querySelectorAll('.fw-rule-pane').forEach(p => p.classList.add('hidden'));
  3600. const activePane = document.getElementById(`fw-pane-${tab}`);
  3601. if (activePane) activePane.classList.remove('hidden');
  3602. if (tab === 'statistics') {
  3603. startFwStatPolling();
  3604. } else {
  3605. stopFwStatPolling();
  3606. }
  3607. }
  3608. function toggleFwField(fieldKey, expand) {
  3609. const plusBtn = document.getElementById(`fw-plus-${fieldKey}`);
  3610. const fieldBox = document.getElementById(`fw-field-${fieldKey}`);
  3611. if (!plusBtn || !fieldBox) return;
  3612. if (expand) {
  3613. plusBtn.classList.add('hidden');
  3614. fieldBox.classList.remove('hidden');
  3615. const valInput = document.getElementById(`fw-val-${fieldKey}`);
  3616. if (valInput) valInput.focus();
  3617. } else {
  3618. fieldBox.classList.add('hidden');
  3619. plusBtn.classList.remove('hidden');
  3620. const valInput = document.getElementById(`fw-val-${fieldKey}`);
  3621. if (valInput) {
  3622. if (valInput.tagName === 'SELECT') {
  3623. valInput.selectedIndex = 0;
  3624. } else {
  3625. valInput.value = '';
  3626. }
  3627. }
  3628. const invInput = document.getElementById(`fw-inv-${fieldKey}`);
  3629. if (invInput) invInput.checked = false;
  3630. if (fieldKey === 'cs') {
  3631. ['filter-modal-cs-established', 'filter-modal-cs-related', 'filter-modal-cs-new', 'filter-modal-cs-invalid', 'filter-modal-cs-untracked'].forEach(id => {
  3632. const el = document.getElementById(id);
  3633. if (el) el.checked = false;
  3634. });
  3635. }
  3636. if (fieldKey === 'natstate') {
  3637. ['filter-modal-nat-srcnat', 'filter-modal-nat-dstnat'].forEach(id => {
  3638. const el = document.getElementById(id);
  3639. if (el) el.checked = false;
  3640. });
  3641. }
  3642. if (fieldKey === 'days') {
  3643. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3644. const el = document.getElementById(`fw-day-${d}`);
  3645. if (el) el.checked = true;
  3646. });
  3647. }
  3648. }
  3649. }
  3650. function setFwFieldVal(fieldKey, value, hasInvert = false) {
  3651. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  3652. toggleFwField(fieldKey, true);
  3653. let strVal = String(value);
  3654. if (hasInvert) {
  3655. const inv = strVal.startsWith('!');
  3656. if (inv) strVal = strVal.slice(1);
  3657. const invEl = document.getElementById(`fw-inv-${fieldKey}`);
  3658. if (invEl) invEl.checked = inv;
  3659. }
  3660. const valEl = document.getElementById(`fw-val-${fieldKey}`);
  3661. if (valEl) valEl.value = strVal;
  3662. } else {
  3663. toggleFwField(fieldKey, false);
  3664. }
  3665. }
  3666. function getFwFieldVal(fieldKey, hasInvert = false) {
  3667. const fieldBox = document.getElementById(`fw-field-${fieldKey}`);
  3668. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  3669. const valEl = document.getElementById(`fw-val-${fieldKey}`);
  3670. let v = valEl ? valEl.value.trim() : '';
  3671. if (!v) return '';
  3672. if (hasInvert) {
  3673. const invEl = document.getElementById(`fw-inv-${fieldKey}`);
  3674. if (invEl && invEl.checked) {
  3675. v = '!' + v.replace(/^!/, '');
  3676. }
  3677. }
  3678. return v;
  3679. }
  3680. function toggleMaximizeFilterModal() {
  3681. const win = document.getElementById('filter-modal-window');
  3682. if (!win) return;
  3683. if (win.classList.contains('max-w-[720px]')) {
  3684. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  3685. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  3686. } else {
  3687. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  3688. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  3689. }
  3690. }
  3691. function openAddFilterModal() {
  3692. switchFwRuleTab('general');
  3693. const badge = document.getElementById('fw-modal-badge');
  3694. if (badge) badge.innerText = 'New...';
  3695. document.getElementById('filter-modal-id').value = '';
  3696. document.getElementById('filter-modal-enabled').checked = true;
  3697. document.getElementById('filter-modal-comment').value = '';
  3698. document.getElementById('filter-modal-chain').value = 'forward';
  3699. document.getElementById('filter-modal-action').value = 'accept';
  3700. document.getElementById('filter-modal-log').checked = false;
  3701. populateInterfaceSelect('fw-val-iniface');
  3702. populateInterfaceSelect('fw-val-outiface');
  3703. populateAddressListSelect('fw-val-srclist');
  3704. populateAddressListSelect('fw-val-dstlist');
  3705. populateGeoIPSelect('fw-val-srcgeo');
  3706. populateGeoIPSelect('fw-val-dstgeo');
  3707. const allFieldKeys = [
  3708. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  3709. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  3710. 'routingmark', 'conntype', 'cs', 'natstate',
  3711. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  3712. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  3713. 'ipsec', 'tlshost', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  3714. 'pktsize', 'random', 'tcpflags', 'icmpoptions', 'ipv4options', 'ttl',
  3715. 'time', 'days', 'limit', 'dstlimit', 'psd', 'logprefix'
  3716. ];
  3717. allFieldKeys.forEach(k => toggleFwField(k, false));
  3718. resetCurrentRuleCounters();
  3719. toggleFilterActionFields();
  3720. document.getElementById('filter-modal').classList.remove('hidden');
  3721. }
  3722. function openEditFilterModal(id) {
  3723. const r = (state.filterRules || []).find(rule => rule.id === id);
  3724. if (!r) return;
  3725. switchFwRuleTab('general');
  3726. const badge = document.getElementById('fw-modal-badge');
  3727. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  3728. document.getElementById('filter-modal-id').value = r.id;
  3729. document.getElementById('filter-modal-enabled').checked = !r.disabled;
  3730. document.getElementById('filter-modal-comment').value = r.comment || '';
  3731. document.getElementById('filter-modal-chain').value = r.chain || 'forward';
  3732. document.getElementById('filter-modal-action').value = r.action || 'accept';
  3733. document.getElementById('filter-modal-log').checked = !!r.log;
  3734. populateInterfaceSelect('fw-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  3735. populateInterfaceSelect('fw-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  3736. populateAddressListSelect('fw-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  3737. populateAddressListSelect('fw-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  3738. populateGeoIPSelect('fw-val-srcgeo', r.src_geoip || '');
  3739. populateGeoIPSelect('fw-val-dstgeo', r.dst_geoip || '');
  3740. setFwFieldVal('src', r.src_address, true);
  3741. setFwFieldVal('dst', r.dst_address, true);
  3742. setFwFieldVal('srclist', r.src_address_list, true);
  3743. setFwFieldVal('dstlist', r.dst_address_list, true);
  3744. setFwFieldVal('srcgeo', r.src_geoip, true);
  3745. setFwFieldVal('dstgeo', r.dst_geoip, true);
  3746. if (r.protocol && r.protocol !== 'all') {
  3747. setFwFieldVal('proto', r.protocol, true);
  3748. } else {
  3749. toggleFwField('proto', false);
  3750. }
  3751. setFwFieldVal('sport', r.src_port, true);
  3752. setFwFieldVal('dport', r.dst_port, true);
  3753. setFwFieldVal('anyport', r.any_port, true);
  3754. setFwFieldVal('iniface', r.in_interface, true);
  3755. setFwFieldVal('outiface', r.out_interface, true);
  3756. setFwFieldVal('inifacelist', r.in_interface_list, true);
  3757. setFwFieldVal('outifacelist', r.out_interface_list, true);
  3758. setFwFieldVal('pktmark', r.packet_mark, true);
  3759. setFwFieldVal('connmark', r.connection_mark, true);
  3760. setFwFieldVal('routingmark', r.routing_mark, true);
  3761. setFwFieldVal('conntype', r.connection_type, false);
  3762. const states = r.connection_state || [];
  3763. if (states.length > 0) {
  3764. toggleFwField('cs', true);
  3765. document.getElementById('filter-modal-cs-established').checked = states.includes('established');
  3766. document.getElementById('filter-modal-cs-related').checked = states.includes('related');
  3767. document.getElementById('filter-modal-cs-new').checked = states.includes('new');
  3768. document.getElementById('filter-modal-cs-invalid').checked = states.includes('invalid');
  3769. document.getElementById('filter-modal-cs-untracked').checked = states.includes('untracked');
  3770. } else {
  3771. toggleFwField('cs', false);
  3772. }
  3773. const natStates = r.connection_nat_state || [];
  3774. if (natStates.length > 0) {
  3775. toggleFwField('natstate', true);
  3776. document.getElementById('filter-modal-nat-srcnat').checked = natStates.includes('srcnat');
  3777. document.getElementById('filter-modal-nat-dstnat').checked = natStates.includes('dstnat');
  3778. } else {
  3779. toggleFwField('natstate', false);
  3780. }
  3781. // Advanced tab fields
  3782. setFwFieldVal('layer7', r.layer7_protocol, false);
  3783. setFwFieldVal('content', r.content, false);
  3784. setFwFieldVal('connbytes', r.connection_bytes, false);
  3785. setFwFieldVal('connrate', r.connection_rate, false);
  3786. setFwFieldVal('pcc', r.pcc, false);
  3787. setFwFieldVal('srcmac', r.src_mac_address, true);
  3788. setFwFieldVal('outbridgeport', r.out_bridge_port, false);
  3789. setFwFieldVal('inbridgeport', r.in_bridge_port, false);
  3790. setFwFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  3791. setFwFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  3792. setFwFieldVal('ipsec', r.ipsec_policy, false);
  3793. setFwFieldVal('tlshost', r.tls_host, false);
  3794. setFwFieldVal('ingresspriority', r.ingress_priority, false);
  3795. setFwFieldVal('priority', r.priority, false);
  3796. setFwFieldVal('dscp', r.dscp, false);
  3797. setFwFieldVal('tcpmss', r.tcp_mss, false);
  3798. if (r.tos) {
  3799. const tosEl = document.getElementById('fw-val-tos');
  3800. if (tosEl) tosEl.value = r.tos;
  3801. }
  3802. setFwFieldVal('pktsize', r.packet_size, false);
  3803. setFwFieldVal('random', r.random, false);
  3804. setFwFieldVal('tcpflags', r.tcp_flags, false);
  3805. setFwFieldVal('icmpoptions', r.icmp_options, false);
  3806. setFwFieldVal('ipv4options', r.ipv4_options, false);
  3807. setFwFieldVal('ttl', r.ttl, false);
  3808. // Extra tab fields
  3809. setFwFieldVal('time', r.time, false);
  3810. if (r.days) {
  3811. toggleFwField('days', true);
  3812. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3813. const chk = document.getElementById(`fw-day-${d}`);
  3814. if (chk) chk.checked = r.days.includes(d);
  3815. });
  3816. } else {
  3817. toggleFwField('days', false);
  3818. }
  3819. setFwFieldVal('limit', r.limit, false);
  3820. setFwFieldVal('dstlimit', r.dst_limit, false);
  3821. setFwFieldVal('psd', r.psd, false);
  3822. // Action fields
  3823. if (r.reject_with) {
  3824. const rwEl = document.getElementById('filter-modal-rejectwith');
  3825. if (rwEl) rwEl.value = r.reject_with;
  3826. }
  3827. if (r.jump_target) {
  3828. const jtEl = document.getElementById('filter-modal-jumptarget');
  3829. if (jtEl) jtEl.value = r.jump_target;
  3830. }
  3831. if (r.address_list) {
  3832. const alEl = document.getElementById('filter-modal-action-addrlist');
  3833. if (alEl) alEl.value = r.address_list;
  3834. }
  3835. if (r.address_list_timeout) {
  3836. const toEl = document.getElementById('filter-modal-action-timeout');
  3837. if (toEl) toEl.value = r.address_list_timeout;
  3838. }
  3839. setFwFieldVal('logprefix', r.log_prefix, false);
  3840. // Statistics
  3841. const bEl = document.getElementById('fw-stat-bytes');
  3842. const pEl = document.getElementById('fw-stat-packets');
  3843. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  3844. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  3845. state.fwLastBytes = r.bytes || 0;
  3846. state.fwLastPackets = r.packets || 0;
  3847. state.fwLastTimestamp = Date.now();
  3848. state.fwStatRateHistory = new Array(30).fill(0);
  3849. state.fwStatPktHistory = new Array(30).fill(0);
  3850. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  3851. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  3852. toggleFilterActionFields();
  3853. document.getElementById('filter-modal').classList.remove('hidden');
  3854. }
  3855. function closeFilterModal() {
  3856. stopFwStatPolling();
  3857. document.getElementById('filter-modal').classList.add('hidden');
  3858. }
  3859. function toggleFilterActionFields() {
  3860. const act = document.getElementById('filter-modal-action')?.value || 'accept';
  3861. const rejectBox = document.getElementById('filter-action-reject-box');
  3862. const jumpBox = document.getElementById('filter-action-jump-box');
  3863. const addrBox = document.getElementById('filter-action-addrlist-box');
  3864. if (rejectBox) {
  3865. if (act === 'reject') rejectBox.classList.remove('hidden');
  3866. else rejectBox.classList.add('hidden');
  3867. }
  3868. if (jumpBox) {
  3869. if (act === 'jump') jumpBox.classList.remove('hidden');
  3870. else jumpBox.classList.add('hidden');
  3871. }
  3872. if (addrBox) {
  3873. if (act === 'add-dst-to-address-list' || act === 'add-src-to-address-list' || act.includes('address-list') || act.includes('address list')) {
  3874. addrBox.classList.remove('hidden');
  3875. } else {
  3876. addrBox.classList.add('hidden');
  3877. }
  3878. }
  3879. if (act === 'log') {
  3880. const logEl = document.getElementById('filter-modal-log');
  3881. if (logEl) logEl.checked = true;
  3882. toggleFwField('logprefix', true);
  3883. }
  3884. }
  3885. function toggleFwLogPrefix() {
  3886. const isLog = document.getElementById('filter-modal-log')?.checked;
  3887. toggleFwField('logprefix', !!isLog);
  3888. }
  3889. function copyFilterRule() {
  3890. document.getElementById('filter-modal-id').value = '';
  3891. const badge = document.getElementById('fw-modal-badge');
  3892. if (badge) badge.innerText = 'New...';
  3893. showToast('Rule Cloned', 'Ready to save as a new rule copy', 'info');
  3894. }
  3895. function resetCurrentRuleCounters() {
  3896. state.fwStatRateHistory = new Array(30).fill(0);
  3897. state.fwStatPktHistory = new Array(30).fill(0);
  3898. state.fwLastBytes = 0;
  3899. state.fwLastPackets = 0;
  3900. state.fwLastTimestamp = Date.now();
  3901. const bEl = document.getElementById('fw-stat-bytes');
  3902. const pEl = document.getElementById('fw-stat-packets');
  3903. const rEl = document.getElementById('fw-stat-rate');
  3904. const prEl = document.getElementById('fw-stat-pktrate');
  3905. if (bEl) bEl.value = '0 B';
  3906. if (pEl) pEl.value = '0';
  3907. if (rEl) rEl.value = '0 bps';
  3908. if (prEl) prEl.value = '0 p/s';
  3909. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  3910. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  3911. showToast('Counters Reset', 'Rule counter display reset to 0', 'info');
  3912. }
  3913. async function resetAllFwCounters() {
  3914. try {
  3915. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  3916. if (res.ok) {
  3917. resetCurrentRuleCounters();
  3918. showToast('All Counters Reset', 'All firewall counters zeroed', 'success');
  3919. loadFirewall(false);
  3920. }
  3921. } catch (err) {
  3922. showToast('Error', err.message, 'error');
  3923. }
  3924. }
  3925. async function applyFilterRule(closeAfter = false) {
  3926. const id = document.getElementById('filter-modal-id').value;
  3927. const chain = document.getElementById('filter-modal-chain').value;
  3928. const action = document.getElementById('filter-modal-action').value;
  3929. const comment = document.getElementById('filter-modal-comment').value.trim();
  3930. const enabled = document.getElementById('filter-modal-enabled').checked;
  3931. const src = getFwFieldVal('src', true);
  3932. const dst = getFwFieldVal('dst', true);
  3933. const srclist = getFwFieldVal('srclist', true);
  3934. const dstlist = getFwFieldVal('dstlist', true);
  3935. const srcgeo = getFwFieldVal('srcgeo', true);
  3936. const dstgeo = getFwFieldVal('dstgeo', true);
  3937. const proto = getFwFieldVal('proto', true);
  3938. const sport = getFwFieldVal('sport', true);
  3939. const dport = getFwFieldVal('dport', true);
  3940. const anyport = getFwFieldVal('anyport', true);
  3941. const iniface = getFwFieldVal('iniface', true);
  3942. const outiface = getFwFieldVal('outiface', true);
  3943. const inifacelist = getFwFieldVal('inifacelist', true);
  3944. const outifacelist = getFwFieldVal('outifacelist', true);
  3945. const pktmark = getFwFieldVal('pktmark', true);
  3946. const connmark = getFwFieldVal('connmark', true);
  3947. const routingmark = getFwFieldVal('routingmark', true);
  3948. const conntype = getFwFieldVal('conntype', false);
  3949. const states = [];
  3950. const csBox = document.getElementById('fw-field-cs');
  3951. if (csBox && !csBox.classList.contains('hidden')) {
  3952. if (document.getElementById('filter-modal-cs-established')?.checked) states.push('established');
  3953. if (document.getElementById('filter-modal-cs-related')?.checked) states.push('related');
  3954. if (document.getElementById('filter-modal-cs-new')?.checked) states.push('new');
  3955. if (document.getElementById('filter-modal-cs-invalid')?.checked) states.push('invalid');
  3956. if (document.getElementById('filter-modal-cs-untracked')?.checked) states.push('untracked');
  3957. }
  3958. const natStates = [];
  3959. const natBox = document.getElementById('fw-field-natstate');
  3960. if (natBox && !natBox.classList.contains('hidden')) {
  3961. if (document.getElementById('filter-modal-nat-srcnat')?.checked) natStates.push('srcnat');
  3962. if (document.getElementById('filter-modal-nat-dstnat')?.checked) natStates.push('dstnat');
  3963. }
  3964. const payload = {
  3965. id,
  3966. chain,
  3967. action,
  3968. protocol: proto || 'all',
  3969. src_address: src,
  3970. dst_address: dst,
  3971. src_port: sport,
  3972. dst_port: dport,
  3973. any_port: anyport,
  3974. in_interface: iniface,
  3975. out_interface: outiface,
  3976. in_interface_list: inifacelist,
  3977. out_interface_list: outifacelist,
  3978. packet_mark: pktmark,
  3979. connection_mark: connmark,
  3980. routing_mark: routingmark,
  3981. connection_type: conntype,
  3982. connection_state: states,
  3983. connection_nat_state: natStates,
  3984. src_address_list: srclist,
  3985. dst_address_list: dstlist,
  3986. src_geoip: srcgeo,
  3987. dst_geoip: dstgeo,
  3988. comment,
  3989. disabled: !enabled,
  3990. // Advanced tab
  3991. layer7_protocol: getFwFieldVal('layer7', false),
  3992. content: getFwFieldVal('content', false),
  3993. connection_bytes: getFwFieldVal('connbytes', false),
  3994. connection_rate: getFwFieldVal('connrate', false),
  3995. pcc: getFwFieldVal('pcc', false),
  3996. src_mac_address: getFwFieldVal('srcmac', true),
  3997. out_bridge_port: getFwFieldVal('outbridgeport', false),
  3998. in_bridge_port: getFwFieldVal('inbridgeport', false),
  3999. in_bridge_port_list: getFwFieldVal('inbridgeportlist', false),
  4000. out_bridge_port_list: getFwFieldVal('outbridgeportlist', false),
  4001. ipsec_policy: getFwFieldVal('ipsec', false),
  4002. tls_host: getFwFieldVal('tlshost', false),
  4003. ingress_priority: getFwFieldVal('ingresspriority', false),
  4004. priority: getFwFieldVal('priority', false),
  4005. dscp: getFwFieldVal('dscp', false),
  4006. tcp_mss: getFwFieldVal('tcpmss', false),
  4007. tos: document.getElementById('fw-val-tos')?.value || '',
  4008. packet_size: getFwFieldVal('pktsize', false),
  4009. random: getFwFieldVal('random', false),
  4010. tcp_flags: getFwFieldVal('tcpflags', false),
  4011. icmp_options: getFwFieldVal('icmpoptions', false),
  4012. ipv4_options: getFwFieldVal('ipv4options', false),
  4013. ttl: getFwFieldVal('ttl', false),
  4014. // Extra tab
  4015. time: getFwFieldVal('time', false),
  4016. limit: getFwFieldVal('limit', false),
  4017. dst_limit: getFwFieldVal('dstlimit', false),
  4018. psd: getFwFieldVal('psd', false),
  4019. // Action tab
  4020. reject_with: action === 'reject' ? (document.getElementById('filter-modal-rejectwith')?.value || '') : '',
  4021. jump_target: action === 'jump' ? (document.getElementById('filter-modal-jumptarget')?.value || '') : '',
  4022. address_list: action.startsWith('add-') ? (document.getElementById('filter-modal-action-addrlist')?.value || '') : '',
  4023. address_list_timeout: action.startsWith('add-') ? (document.getElementById('filter-modal-action-timeout')?.value || '') : '',
  4024. log: document.getElementById('filter-modal-log')?.checked || false,
  4025. log_prefix: getFwFieldVal('logprefix', false)
  4026. };
  4027. try {
  4028. const res = await fetch(`${API_BASE}/firewall/filter`, {
  4029. method: 'POST',
  4030. headers: { 'Content-Type': 'application/json' },
  4031. body: JSON.stringify(payload)
  4032. });
  4033. if (res.ok) {
  4034. const data = await res.json();
  4035. showToast('Filter Rule Saved', 'Rule applied successfully to firewall', 'success');
  4036. loadFirewall(false);
  4037. if (closeAfter) {
  4038. closeFilterModal();
  4039. } else {
  4040. if (data.id) {
  4041. document.getElementById('filter-modal-id').value = data.id;
  4042. const badge = document.getElementById('fw-modal-badge');
  4043. if (badge) badge.innerText = `#${data.id}`;
  4044. }
  4045. }
  4046. } else {
  4047. const err = await res.json();
  4048. showToast('Error', err.message || 'Failed to save rule', 'error');
  4049. }
  4050. } catch (err) {
  4051. showToast('Error', err.message, 'error');
  4052. }
  4053. }
  4054. function submitSaveFilterRule(e) {
  4055. if (e && e.preventDefault) e.preventDefault();
  4056. return applyFilterRule(true);
  4057. }
  4058. function startFwStatPolling() {
  4059. stopFwStatPolling();
  4060. pollRuleStats();
  4061. state.fwStatInterval = setInterval(pollRuleStats, 1000);
  4062. }
  4063. function stopFwStatPolling() {
  4064. if (state.fwStatInterval) {
  4065. clearInterval(state.fwStatInterval);
  4066. state.fwStatInterval = null;
  4067. }
  4068. }
  4069. async function pollRuleStats() {
  4070. const id = document.getElementById('filter-modal-id')?.value;
  4071. if (!id) {
  4072. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory || new Array(30).fill(0), 'bps', 'fw-stat-legend-rate');
  4073. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory || new Array(30).fill(0), 'p/s', 'fw-stat-legend-pktrate');
  4074. return;
  4075. }
  4076. try {
  4077. const res = await fetch(`${API_BASE}/firewall/filter`);
  4078. if (!res.ok) return;
  4079. const rules = await res.json();
  4080. const r = rules.find(x => x.id === id);
  4081. if (!r) return;
  4082. const now = Date.now();
  4083. const dt = Math.max(0.2, (now - (state.fwLastTimestamp || now)) / 1000);
  4084. state.fwLastTimestamp = now;
  4085. const curBytes = r.bytes || 0;
  4086. const curPackets = r.packets || 0;
  4087. const deltaBytes = Math.max(0, curBytes - (state.fwLastBytes || curBytes));
  4088. const deltaPkts = Math.max(0, curPackets - (state.fwLastPackets || curPackets));
  4089. state.fwLastBytes = curBytes;
  4090. state.fwLastPackets = curPackets;
  4091. const rateBps = Math.round((deltaBytes * 8) / dt);
  4092. const ratePkt = Math.round(deltaPkts / dt);
  4093. if (!state.fwStatRateHistory) state.fwStatRateHistory = new Array(30).fill(0);
  4094. if (!state.fwStatPktHistory) state.fwStatPktHistory = new Array(30).fill(0);
  4095. state.fwStatRateHistory.push(rateBps);
  4096. if (state.fwStatRateHistory.length > 30) state.fwStatRateHistory.shift();
  4097. state.fwStatPktHistory.push(ratePkt);
  4098. if (state.fwStatPktHistory.length > 30) state.fwStatPktHistory.shift();
  4099. const bEl = document.getElementById('fw-stat-bytes');
  4100. const pEl = document.getElementById('fw-stat-packets');
  4101. const rEl = document.getElementById('fw-stat-rate');
  4102. const prEl = document.getElementById('fw-stat-pktrate');
  4103. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  4104. if (pEl) pEl.value = curPackets.toLocaleString();
  4105. if (rEl) rEl.value = formatBps(rateBps);
  4106. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  4107. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  4108. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  4109. } catch (e) {
  4110. console.error('Error polling rule stats', e);
  4111. }
  4112. }
  4113. function formatBps(bps) {
  4114. if (bps >= 1000000000) return (bps / 1000000000).toFixed(1) + ' Gbps';
  4115. if (bps >= 1000000) return (bps / 1000000).toFixed(1) + ' Mbps';
  4116. if (bps >= 1000) return (bps / 1000).toFixed(1) + ' kbps';
  4117. return bps + ' bps';
  4118. }
  4119. function renderFwSparkline(svgId, dataArray, unit, legendId) {
  4120. const svg = document.getElementById(svgId);
  4121. if (!svg) return;
  4122. const w = 500;
  4123. const h = 100;
  4124. const paddingRight = 45;
  4125. const graphWidth = w - paddingRight;
  4126. const maxVal = Math.max(5, ...dataArray);
  4127. const currentVal = dataArray[dataArray.length - 1] || 0;
  4128. const leg = document.getElementById(legendId);
  4129. if (leg) {
  4130. leg.innerText = unit === 'bps' ? formatBps(currentVal) : `${currentVal.toLocaleString()} p/s`;
  4131. }
  4132. let gridLines = '';
  4133. for (let i = 0; i <= 5; i++) {
  4134. const y = 8 + (i * (h - 18) / 5);
  4135. const valAtLevel = Math.round(maxVal * (5 - i) / 5);
  4136. const label = unit === 'bps' ? formatBps(valAtLevel) : `${valAtLevel} p/s`;
  4137. gridLines += `
  4138. <line x1="0" y1="${y.toFixed(1)}" x2="${graphWidth}" y2="${y.toFixed(1)}" stroke="#1e2c3e" stroke-width="1" />
  4139. <text x="${w - 2}" y="${(y + 3).toFixed(1)}" fill="#64748b" font-size="9" font-family="monospace" text-anchor="end">${label}</text>
  4140. `;
  4141. }
  4142. const step = graphWidth / (dataArray.length - 1);
  4143. const points = dataArray.map((val, idx) => {
  4144. const x = idx * step;
  4145. const y = (h - 10) - (val / maxVal) * (h - 20);
  4146. return `${x.toFixed(1)},${y.toFixed(1)}`;
  4147. });
  4148. const polylineStr = points.join(' ');
  4149. const areaPath = `M 0,${h - 10} L ${polylineStr} L ${graphWidth},${h - 10} Z`;
  4150. svg.innerHTML = `
  4151. ${gridLines}
  4152. <path d="${areaPath}" fill="rgba(14, 165, 233, 0.12)" />
  4153. <polyline fill="none" stroke="#38bdf8" stroke-width="1.8" stroke-linejoin="round" points="${polylineStr}" />
  4154. <circle cx="${graphWidth}" cy="${points[points.length - 1].split(',')[1]}" r="3" fill="#38bdf8" />
  4155. `;
  4156. }
  4157. async function moveFilterRule(id, dir) {
  4158. try {
  4159. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/move`, {
  4160. method: 'POST',
  4161. headers: { 'Content-Type': 'application/json' },
  4162. body: JSON.stringify({ direction: dir })
  4163. });
  4164. if (res.ok) loadFirewall(false);
  4165. } catch (err) {
  4166. showToast('Error', err.message, 'error');
  4167. }
  4168. }
  4169. async function toggleFilterRuleState(id, disabled) {
  4170. try {
  4171. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/state`, {
  4172. method: 'POST',
  4173. headers: { 'Content-Type': 'application/json' },
  4174. body: JSON.stringify({ disabled })
  4175. });
  4176. if (res.ok) loadFirewall(false);
  4177. } catch (err) {
  4178. showToast('Error', err.message, 'error');
  4179. }
  4180. }
  4181. async function deleteFilterRule(id) {
  4182. if (!confirm('Are you sure you want to delete this filter rule?')) return;
  4183. try {
  4184. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4185. if (res.ok) {
  4186. showToast('Deleted', 'Filter rule removed', 'success');
  4187. loadFirewall(false);
  4188. }
  4189. } catch (err) {
  4190. showToast('Error', err.message, 'error');
  4191. }
  4192. }
  4193. // ----------------- NAT Rules -----------------
  4194. function renderNATRules() {
  4195. const chainFilter = document.getElementById('nat-filter-chain')?.value || '';
  4196. const tbody = document.getElementById('nat-table-body');
  4197. const empty = document.getElementById('nat-empty');
  4198. if (!tbody) return;
  4199. tbody.innerHTML = '';
  4200. const rules = (state.natRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  4201. document.getElementById('nat-count-badge').innerText = `${rules.length} Rules`;
  4202. if (rules.length === 0) {
  4203. empty?.classList.remove('hidden');
  4204. return;
  4205. }
  4206. empty?.classList.add('hidden');
  4207. rules.forEach((r, idx) => {
  4208. const tr = document.createElement('tr');
  4209. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  4210. let toTarget = '-';
  4211. if (r.action === 'jump') {
  4212. toTarget = `<span class="text-yellow-300 font-mono font-bold">&rarr; ${r.jump_target || '-'}</span>`;
  4213. } else if (r.action.includes('address-list') || r.action.includes('address list')) {
  4214. toTarget = `<span class="text-emerald-300 font-mono font-bold">&rarr; ${r.address_list || '-'}</span>`;
  4215. } else if (r.action === 'redirect') {
  4216. toTarget = `<span class="text-amber-300 font-mono font-bold">ports:${r.to_ports || 'all'}</span>`;
  4217. } else if (r.action === 'masquerade') {
  4218. 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>`;
  4219. } else if (r.action === 'log') {
  4220. toTarget = `<span class="text-slate-400 font-mono font-bold">${r.log_prefix || 'log'}</span>`;
  4221. } else {
  4222. const parts = [r.to_addresses, r.to_ports].filter(Boolean);
  4223. toTarget = parts.length ? `<span class="text-amber-300 font-mono font-bold">${parts.join(':')}</span>` : '-';
  4224. }
  4225. const ifaces = [r.out_interface ? 'out:' + r.out_interface : '', r.in_interface ? 'in:' + r.in_interface : ''].filter(Boolean).join(' ');
  4226. tr.innerHTML = `
  4227. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  4228. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  4229. <td class="py-2.5 px-3 font-bold text-amber-400">${r.chain}</td>
  4230. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  4231. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  4232. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}${r.dst_port ? ':' + r.dst_port : ''}</td>
  4233. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  4234. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  4235. <td class="py-2.5 px-3 font-mono text-xs">${toTarget}</td>
  4236. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  4237. <span class="text-slate-300" id="nat-pkts-${r.id}">${(r.packets || 0).toLocaleString()}p</span> /
  4238. <span class="text-slate-500" id="nat-bytes-${r.id}">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  4239. </td>
  4240. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  4241. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  4242. <button onclick="moveNATRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  4243. <button onclick="moveNATRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  4244. <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>
  4245. <button onclick="openEditNATModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  4246. <button onclick="deleteNATRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  4247. </td>
  4248. `;
  4249. tbody.appendChild(tr);
  4250. });
  4251. }
  4252. // ==================== FIREWALL NAT MODAL (ROUTEROS WEBFIG / WINBOX V4) ====================
  4253. function switchNATRuleTab(tab) {
  4254. state.activeNATRuleTab = tab;
  4255. document.querySelectorAll('.nat-rule-tab-btn').forEach(btn => {
  4256. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  4257. btn.classList.add('text-slate-400', 'border-transparent');
  4258. });
  4259. const activeBtn = document.getElementById(`nat-tab-btn-${tab}`);
  4260. if (activeBtn) {
  4261. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  4262. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  4263. }
  4264. document.querySelectorAll('.nat-rule-pane').forEach(p => p.classList.add('hidden'));
  4265. const activePane = document.getElementById(`nat-pane-${tab}`);
  4266. if (activePane) activePane.classList.remove('hidden');
  4267. if (tab === 'statistics') {
  4268. startNATStatPolling();
  4269. } else {
  4270. stopNATStatPolling();
  4271. }
  4272. }
  4273. function toggleNATField(fieldKey, expand) {
  4274. const plusBtn = document.getElementById(`nat-plus-${fieldKey}`);
  4275. const fieldBox = document.getElementById(`nat-field-${fieldKey}`);
  4276. if (!plusBtn || !fieldBox) return;
  4277. if (expand) {
  4278. plusBtn.classList.add('hidden');
  4279. fieldBox.classList.remove('hidden');
  4280. const valInput = document.getElementById(`nat-val-${fieldKey}`);
  4281. if (valInput) valInput.focus();
  4282. } else {
  4283. fieldBox.classList.add('hidden');
  4284. plusBtn.classList.remove('hidden');
  4285. const valInput = document.getElementById(`nat-val-${fieldKey}`);
  4286. if (valInput) {
  4287. if (valInput.tagName === 'SELECT') {
  4288. valInput.selectedIndex = 0;
  4289. } else {
  4290. valInput.value = '';
  4291. }
  4292. }
  4293. const invInput = document.getElementById(`nat-inv-${fieldKey}`);
  4294. if (invInput) invInput.checked = false;
  4295. if (fieldKey === 'days') {
  4296. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  4297. const el = document.getElementById(`nat-day-${d}`);
  4298. if (el) el.checked = true;
  4299. });
  4300. }
  4301. }
  4302. }
  4303. function setNATFieldVal(fieldKey, value, hasInvert = false) {
  4304. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  4305. toggleNATField(fieldKey, true);
  4306. let strVal = String(value);
  4307. if (hasInvert) {
  4308. const inv = strVal.startsWith('!');
  4309. if (inv) strVal = strVal.slice(1);
  4310. const invEl = document.getElementById(`nat-inv-${fieldKey}`);
  4311. if (invEl) invEl.checked = inv;
  4312. }
  4313. const valEl = document.getElementById(`nat-val-${fieldKey}`);
  4314. if (valEl) valEl.value = strVal;
  4315. } else {
  4316. toggleNATField(fieldKey, false);
  4317. }
  4318. }
  4319. function getNATFieldVal(fieldKey, hasInvert = false) {
  4320. const fieldBox = document.getElementById(`nat-field-${fieldKey}`);
  4321. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  4322. const valEl = document.getElementById(`nat-val-${fieldKey}`);
  4323. let v = valEl ? valEl.value.trim() : '';
  4324. if (!v) return '';
  4325. if (hasInvert) {
  4326. const invEl = document.getElementById(`nat-inv-${fieldKey}`);
  4327. if (invEl && invEl.checked) {
  4328. v = '!' + v.replace(/^!/, '');
  4329. }
  4330. }
  4331. return v;
  4332. }
  4333. function toggleMaximizeNATModal() {
  4334. const win = document.getElementById('nat-modal-window');
  4335. if (!win) return;
  4336. if (win.classList.contains('max-w-[720px]')) {
  4337. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  4338. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  4339. } else {
  4340. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  4341. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  4342. }
  4343. }
  4344. function handleNATChainChange() {
  4345. const ch = document.getElementById('nat-modal-chain')?.value || 'srcnat';
  4346. const actSel = document.getElementById('nat-modal-action');
  4347. if (actSel) {
  4348. if (ch === 'srcnat' && (actSel.value === 'dst-nat' || actSel.value === 'redirect')) {
  4349. actSel.value = 'masquerade';
  4350. } else if (ch === 'dstnat' && (actSel.value === 'masquerade' || actSel.value === 'src-nat')) {
  4351. actSel.value = 'dst-nat';
  4352. }
  4353. }
  4354. toggleNATActionFields();
  4355. }
  4356. function toggleNATActionFields() {
  4357. const act = document.getElementById('nat-modal-action')?.value || 'masquerade';
  4358. const rowAddr = document.getElementById('nat-row-toaddr');
  4359. const rowPort = document.getElementById('nat-row-toport');
  4360. const jumpBox = document.getElementById('nat-action-jump-box');
  4361. const addrBox = document.getElementById('nat-action-addrlist-box');
  4362. // Hide all dynamic rows first
  4363. if (rowAddr) rowAddr.classList.add('hidden');
  4364. if (rowPort) rowPort.classList.add('hidden');
  4365. if (jumpBox) jumpBox.classList.add('hidden');
  4366. if (addrBox) addrBox.classList.add('hidden');
  4367. if (['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat'].includes(act)) {
  4368. if (rowAddr) rowAddr.classList.remove('hidden');
  4369. if (rowPort) rowPort.classList.remove('hidden');
  4370. } else if (act === 'redirect' || act === 'masquerade') {
  4371. if (rowPort) rowPort.classList.remove('hidden');
  4372. } else if (act === 'jump') {
  4373. if (jumpBox) jumpBox.classList.remove('hidden');
  4374. } else if (act.includes('address-list') || act.includes('address list')) {
  4375. if (addrBox) addrBox.classList.remove('hidden');
  4376. }
  4377. if (act === 'log') {
  4378. const logEl = document.getElementById('nat-modal-log');
  4379. if (logEl) logEl.checked = true;
  4380. toggleNATField('logprefix', true);
  4381. }
  4382. }
  4383. function toggleNATLogPrefix() {
  4384. const isLog = document.getElementById('nat-modal-log')?.checked;
  4385. toggleNATField('logprefix', !!isLog);
  4386. }
  4387. function openAddNATModal() {
  4388. switchNATRuleTab('general');
  4389. const badge = document.getElementById('nat-modal-badge');
  4390. if (badge) badge.innerText = 'New...';
  4391. document.getElementById('nat-modal-id').value = '';
  4392. document.getElementById('nat-modal-enabled').checked = true;
  4393. document.getElementById('nat-modal-comment').value = '';
  4394. document.getElementById('nat-modal-chain').value = 'srcnat';
  4395. document.getElementById('nat-modal-action').value = 'masquerade';
  4396. document.getElementById('nat-modal-toaddr').value = '';
  4397. document.getElementById('nat-modal-toport').value = '';
  4398. document.getElementById('nat-modal-log').checked = false;
  4399. populateInterfaceSelect('nat-val-iniface');
  4400. populateInterfaceSelect('nat-val-outiface');
  4401. populateAddressListSelect('nat-val-srclist');
  4402. populateAddressListSelect('nat-val-dstlist');
  4403. populateGeoIPSelect('nat-val-srcgeo');
  4404. populateGeoIPSelect('nat-val-dstgeo');
  4405. const allFieldKeys = [
  4406. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  4407. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  4408. 'routingmark', 'conntype',
  4409. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  4410. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  4411. 'ipsec', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  4412. 'pktsize', 'random', 'icmpoptions', 'ipv4options', 'ttl',
  4413. 'time', 'days', 'limit', 'dstlimit', 'psd', 'logprefix'
  4414. ];
  4415. allFieldKeys.forEach(k => toggleNATField(k, false));
  4416. resetCurrentNATRuleCounters();
  4417. toggleNATActionFields();
  4418. document.getElementById('nat-modal').classList.remove('hidden');
  4419. }
  4420. function openEditNATModal(id) {
  4421. const r = (state.natRules || []).find(rule => rule.id === id);
  4422. if (!r) return;
  4423. switchNATRuleTab('general');
  4424. const badge = document.getElementById('nat-modal-badge');
  4425. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  4426. document.getElementById('nat-modal-id').value = r.id;
  4427. document.getElementById('nat-modal-enabled').checked = !r.disabled;
  4428. document.getElementById('nat-modal-comment').value = r.comment || '';
  4429. document.getElementById('nat-modal-chain').value = r.chain || 'srcnat';
  4430. document.getElementById('nat-modal-action').value = r.action || 'masquerade';
  4431. document.getElementById('nat-modal-toaddr').value = r.to_addresses || '';
  4432. document.getElementById('nat-modal-toport').value = r.to_ports || '';
  4433. document.getElementById('nat-modal-log').checked = !!r.log;
  4434. populateInterfaceSelect('nat-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  4435. populateInterfaceSelect('nat-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  4436. populateAddressListSelect('nat-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  4437. populateAddressListSelect('nat-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  4438. populateGeoIPSelect('nat-val-srcgeo', r.src_geoip || '');
  4439. populateGeoIPSelect('nat-val-dstgeo', r.dst_geoip || '');
  4440. setNATFieldVal('src', r.src_address, true);
  4441. setNATFieldVal('dst', r.dst_address, true);
  4442. setNATFieldVal('srclist', r.src_address_list, true);
  4443. setNATFieldVal('dstlist', r.dst_address_list, true);
  4444. setNATFieldVal('srcgeo', r.src_geoip, true);
  4445. setNATFieldVal('dstgeo', r.dst_geoip, true);
  4446. if (r.protocol && r.protocol !== 'all') {
  4447. setNATFieldVal('proto', r.protocol, true);
  4448. } else {
  4449. toggleNATField('proto', false);
  4450. }
  4451. setNATFieldVal('sport', r.src_port, true);
  4452. setNATFieldVal('dport', r.dst_port, true);
  4453. setNATFieldVal('anyport', r.any_port, true);
  4454. setNATFieldVal('iniface', r.in_interface, true);
  4455. setNATFieldVal('outiface', r.out_interface, true);
  4456. setNATFieldVal('inifacelist', r.in_interface_list, true);
  4457. setNATFieldVal('outifacelist', r.out_interface_list, true);
  4458. setNATFieldVal('pktmark', r.packet_mark, true);
  4459. setNATFieldVal('connmark', r.connection_mark, true);
  4460. setNATFieldVal('routingmark', r.routing_mark, true);
  4461. setNATFieldVal('conntype', r.connection_type, false);
  4462. // Advanced tab fields
  4463. setNATFieldVal('layer7', r.layer7_protocol, false);
  4464. setNATFieldVal('content', r.content, false);
  4465. setNATFieldVal('connbytes', r.connection_bytes, false);
  4466. setNATFieldVal('connrate', r.connection_rate, false);
  4467. setNATFieldVal('pcc', r.pcc, false);
  4468. setNATFieldVal('srcmac', r.src_mac_address, true);
  4469. setNATFieldVal('outbridgeport', r.out_bridge_port, false);
  4470. setNATFieldVal('inbridgeport', r.in_bridge_port, false);
  4471. setNATFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  4472. setNATFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  4473. setNATFieldVal('ipsec', r.ipsec_policy, false);
  4474. setNATFieldVal('ingresspriority', r.ingress_priority, false);
  4475. setNATFieldVal('priority', r.priority, false);
  4476. setNATFieldVal('dscp', r.dscp, false);
  4477. setNATFieldVal('tcpmss', r.tcp_mss, false);
  4478. if (r.tos) {
  4479. const tosEl = document.getElementById('nat-val-tos');
  4480. if (tosEl) tosEl.value = r.tos;
  4481. }
  4482. setNATFieldVal('pktsize', r.packet_size, false);
  4483. setNATFieldVal('random', r.random, false);
  4484. setNATFieldVal('icmpoptions', r.icmp_options, false);
  4485. setNATFieldVal('ipv4options', r.ipv4_options, false);
  4486. setNATFieldVal('ttl', r.ttl, false);
  4487. // Extra tab fields
  4488. setNATFieldVal('time', r.time, false);
  4489. if (r.days) {
  4490. toggleNATField('days', true);
  4491. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  4492. const chk = document.getElementById(`nat-day-${d}`);
  4493. if (chk) chk.checked = r.days.includes(d);
  4494. });
  4495. } else {
  4496. toggleNATField('days', false);
  4497. }
  4498. setNATFieldVal('limit', r.limit, false);
  4499. setNATFieldVal('dstlimit', r.dst_limit, false);
  4500. setNATFieldVal('psd', r.psd, false);
  4501. // Action fields
  4502. if (r.jump_target) {
  4503. const jtEl = document.getElementById('nat-modal-jumptarget');
  4504. if (jtEl) jtEl.value = r.jump_target;
  4505. }
  4506. if (r.address_list) {
  4507. const alEl = document.getElementById('nat-modal-action-addrlist');
  4508. if (alEl) alEl.value = r.address_list;
  4509. }
  4510. if (r.address_list_timeout) {
  4511. const toEl = document.getElementById('nat-modal-action-timeout');
  4512. if (toEl) toEl.value = r.address_list_timeout;
  4513. }
  4514. setNATFieldVal('logprefix', r.log_prefix, false);
  4515. // Statistics
  4516. const bEl = document.getElementById('nat-stat-bytes');
  4517. const pEl = document.getElementById('nat-stat-packets');
  4518. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  4519. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  4520. state.natLastBytes = r.bytes || 0;
  4521. state.natLastPackets = r.packets || 0;
  4522. state.natLastTimestamp = Date.now();
  4523. state.natStatRateHistory = new Array(30).fill(0);
  4524. state.natStatPktHistory = new Array(30).fill(0);
  4525. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  4526. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  4527. toggleNATActionFields();
  4528. document.getElementById('nat-modal').classList.remove('hidden');
  4529. }
  4530. function closeNATModal() {
  4531. stopNATStatPolling();
  4532. document.getElementById('nat-modal').classList.add('hidden');
  4533. }
  4534. function copyNATRule() {
  4535. document.getElementById('nat-modal-id').value = '';
  4536. const badge = document.getElementById('nat-modal-badge');
  4537. if (badge) badge.innerText = 'New...';
  4538. showToast('Rule Cloned', 'Ready to save as a new NAT rule copy', 'info');
  4539. }
  4540. function resetCurrentNATRuleCounters() {
  4541. state.natStatRateHistory = new Array(30).fill(0);
  4542. state.natStatPktHistory = new Array(30).fill(0);
  4543. state.natLastBytes = 0;
  4544. state.natLastPackets = 0;
  4545. state.natLastTimestamp = Date.now();
  4546. const bEl = document.getElementById('nat-stat-bytes');
  4547. const pEl = document.getElementById('nat-stat-packets');
  4548. const rEl = document.getElementById('nat-stat-rate');
  4549. const prEl = document.getElementById('nat-stat-pktrate');
  4550. if (bEl) bEl.value = '0 B';
  4551. if (pEl) pEl.value = '0';
  4552. if (rEl) rEl.value = '0 bps';
  4553. if (prEl) prEl.value = '0 p/s';
  4554. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  4555. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  4556. showToast('Counters Reset', 'NAT rule counter display reset to 0', 'info');
  4557. }
  4558. async function applyNATRule(closeAfter = false) {
  4559. const id = document.getElementById('nat-modal-id').value;
  4560. const chain = document.getElementById('nat-modal-chain').value;
  4561. const action = document.getElementById('nat-modal-action').value;
  4562. const comment = document.getElementById('nat-modal-comment').value.trim();
  4563. const enabled = document.getElementById('nat-modal-enabled').checked;
  4564. const src = getNATFieldVal('src', true);
  4565. const dst = getNATFieldVal('dst', true);
  4566. const srclist = getNATFieldVal('srclist', true);
  4567. const dstlist = getNATFieldVal('dstlist', true);
  4568. const srcgeo = getNATFieldVal('srcgeo', true);
  4569. const dstgeo = getNATFieldVal('dstgeo', true);
  4570. const proto = getNATFieldVal('proto', true);
  4571. const sport = getNATFieldVal('sport', true);
  4572. const dport = getNATFieldVal('dport', true);
  4573. const anyport = getNATFieldVal('anyport', true);
  4574. const iniface = getNATFieldVal('iniface', true);
  4575. const outiface = getNATFieldVal('outiface', true);
  4576. const inifacelist = getNATFieldVal('inifacelist', true);
  4577. const outifacelist = getNATFieldVal('outifacelist', true);
  4578. const pktmark = getNATFieldVal('pktmark', true);
  4579. const connmark = getNATFieldVal('connmark', true);
  4580. const routingmark = getNATFieldVal('routingmark', true);
  4581. const conntype = getNATFieldVal('conntype', false);
  4582. const usesAddr = ['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat'].includes(action);
  4583. const usesPort = ['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat', 'redirect', 'masquerade'].includes(action);
  4584. const payload = {
  4585. id,
  4586. chain,
  4587. action,
  4588. to_addresses: usesAddr ? (document.getElementById('nat-modal-toaddr')?.value.trim() || '') : '',
  4589. to_ports: usesPort ? (document.getElementById('nat-modal-toport')?.value.trim() || '') : '',
  4590. protocol: proto || 'all',
  4591. src_address: src,
  4592. dst_address: dst,
  4593. src_port: sport,
  4594. dst_port: dport,
  4595. any_port: anyport,
  4596. in_interface: iniface,
  4597. out_interface: outiface,
  4598. in_interface_list: inifacelist,
  4599. out_interface_list: outifacelist,
  4600. packet_mark: pktmark,
  4601. connection_mark: connmark,
  4602. routing_mark: routingmark,
  4603. connection_type: conntype,
  4604. src_address_list: srclist,
  4605. dst_address_list: dstlist,
  4606. src_geoip: srcgeo,
  4607. dst_geoip: dstgeo,
  4608. comment,
  4609. disabled: !enabled,
  4610. // Advanced tab
  4611. layer7_protocol: getNATFieldVal('layer7', false),
  4612. content: getNATFieldVal('content', false),
  4613. connection_bytes: getNATFieldVal('connbytes', false),
  4614. connection_rate: getNATFieldVal('connrate', false),
  4615. pcc: getNATFieldVal('pcc', false),
  4616. src_mac_address: getNATFieldVal('srcmac', true),
  4617. out_bridge_port: getNATFieldVal('outbridgeport', false),
  4618. in_bridge_port: getNATFieldVal('inbridgeport', false),
  4619. in_bridge_port_list: getNATFieldVal('inbridgeportlist', false),
  4620. out_bridge_port_list: getNATFieldVal('outbridgeportlist', false),
  4621. ipsec_policy: getNATFieldVal('ipsec', false),
  4622. ingress_priority: getNATFieldVal('ingresspriority', false),
  4623. priority: getNATFieldVal('priority', false),
  4624. dscp: getNATFieldVal('dscp', false),
  4625. tcp_mss: getNATFieldVal('tcpmss', false),
  4626. tos: document.getElementById('nat-val-tos')?.value || '',
  4627. packet_size: getNATFieldVal('pktsize', false),
  4628. random: getNATFieldVal('random', false),
  4629. icmp_options: getNATFieldVal('icmpoptions', false),
  4630. ipv4_options: getNATFieldVal('ipv4options', false),
  4631. ttl: getNATFieldVal('ttl', false),
  4632. // Extra tab
  4633. time: getNATFieldVal('time', false),
  4634. limit: getNATFieldVal('limit', false),
  4635. dst_limit: getNATFieldVal('dstlimit', false),
  4636. psd: getNATFieldVal('psd', false),
  4637. // Action tab
  4638. jump_target: action === 'jump' ? (document.getElementById('nat-modal-jumptarget')?.value || '') : '',
  4639. address_list: action.includes('address') ? (document.getElementById('nat-modal-action-addrlist')?.value || '') : '',
  4640. address_list_timeout: action.includes('address') ? (document.getElementById('nat-modal-action-timeout')?.value || '') : '',
  4641. log: document.getElementById('nat-modal-log')?.checked || false,
  4642. log_prefix: getNATFieldVal('logprefix', false)
  4643. };
  4644. try {
  4645. const res = await fetch(`${API_BASE}/firewall/nat`, {
  4646. method: 'POST',
  4647. headers: { 'Content-Type': 'application/json' },
  4648. body: JSON.stringify(payload)
  4649. });
  4650. if (res.ok) {
  4651. const data = await res.json();
  4652. showToast('NAT Rule Saved', 'NAT mapping updated', 'success');
  4653. loadFirewall(false);
  4654. if (closeAfter) {
  4655. closeNATModal();
  4656. } else {
  4657. if (data.id) {
  4658. document.getElementById('nat-modal-id').value = data.id;
  4659. const badge = document.getElementById('nat-modal-badge');
  4660. if (badge) badge.innerText = `#${data.id}`;
  4661. }
  4662. }
  4663. } else {
  4664. const err = await res.json();
  4665. showToast('Error', err.message || 'Failed to save rule', 'error');
  4666. }
  4667. } catch (err) {
  4668. showToast('Error', err.message, 'error');
  4669. }
  4670. }
  4671. function submitSaveNATRule(e) {
  4672. if (e && e.preventDefault) e.preventDefault();
  4673. return applyNATRule(true);
  4674. }
  4675. function startNATStatPolling() {
  4676. stopNATStatPolling();
  4677. pollNATRuleStats();
  4678. state.natStatInterval = setInterval(pollNATRuleStats, 1000);
  4679. }
  4680. function stopNATStatPolling() {
  4681. if (state.natStatInterval) {
  4682. clearInterval(state.natStatInterval);
  4683. state.natStatInterval = null;
  4684. }
  4685. }
  4686. async function pollNATRuleStats() {
  4687. const id = document.getElementById('nat-modal-id')?.value;
  4688. if (!id) {
  4689. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory || new Array(30).fill(0), 'bps', 'nat-stat-legend-rate');
  4690. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory || new Array(30).fill(0), 'p/s', 'nat-stat-legend-pktrate');
  4691. return;
  4692. }
  4693. try {
  4694. const res = await fetch(`${API_BASE}/firewall/nat`);
  4695. if (!res.ok) return;
  4696. const rules = await res.json();
  4697. const r = rules.find(x => x.id === id);
  4698. if (!r) return;
  4699. const now = Date.now();
  4700. const dt = Math.max(0.2, (now - (state.natLastTimestamp || now)) / 1000);
  4701. state.natLastTimestamp = now;
  4702. const curBytes = r.bytes || 0;
  4703. const curPackets = r.packets || 0;
  4704. const deltaBytes = Math.max(0, curBytes - (state.natLastBytes || curBytes));
  4705. const deltaPkts = Math.max(0, curPackets - (state.natLastPackets || curPackets));
  4706. state.natLastBytes = curBytes;
  4707. state.natLastPackets = curPackets;
  4708. const rateBps = Math.round((deltaBytes * 8) / dt);
  4709. const ratePkt = Math.round(deltaPkts / dt);
  4710. if (!state.natStatRateHistory) state.natStatRateHistory = new Array(30).fill(0);
  4711. if (!state.natStatPktHistory) state.natStatPktHistory = new Array(30).fill(0);
  4712. state.natStatRateHistory.push(rateBps);
  4713. if (state.natStatRateHistory.length > 30) state.natStatRateHistory.shift();
  4714. state.natStatPktHistory.push(ratePkt);
  4715. if (state.natStatPktHistory.length > 30) state.natStatPktHistory.shift();
  4716. const bEl = document.getElementById('nat-stat-bytes');
  4717. const pEl = document.getElementById('nat-stat-packets');
  4718. const rEl = document.getElementById('nat-stat-rate');
  4719. const prEl = document.getElementById('nat-stat-pktrate');
  4720. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  4721. if (pEl) pEl.value = curPackets.toLocaleString();
  4722. if (rEl) rEl.value = formatBps(rateBps);
  4723. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  4724. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  4725. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  4726. } catch (e) {
  4727. console.error('Error polling NAT rule stats', e);
  4728. }
  4729. }
  4730. async function moveNATRule(id, dir) {
  4731. try {
  4732. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/move`, {
  4733. method: 'POST',
  4734. headers: { 'Content-Type': 'application/json' },
  4735. body: JSON.stringify({ direction: dir })
  4736. });
  4737. if (res.ok) loadFirewall(false);
  4738. } catch (err) {
  4739. showToast('Error', err.message, 'error');
  4740. }
  4741. }
  4742. async function toggleNATRuleState(id, disabled) {
  4743. try {
  4744. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/state`, {
  4745. method: 'POST',
  4746. headers: { 'Content-Type': 'application/json' },
  4747. body: JSON.stringify({ disabled })
  4748. });
  4749. if (res.ok) loadFirewall(false);
  4750. } catch (err) {
  4751. showToast('Error', err.message, 'error');
  4752. }
  4753. }
  4754. async function deleteNATRule(id) {
  4755. if (!confirm('Are you sure you want to delete this NAT rule?')) return;
  4756. try {
  4757. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4758. if (res.ok) {
  4759. showToast('Deleted', 'NAT rule removed', 'success');
  4760. loadFirewall(false);
  4761. }
  4762. } catch (err) {
  4763. showToast('Error', err.message, 'error');
  4764. }
  4765. }
  4766. // ----------------- Mangle Rules -----------------
  4767. function renderMangleRules() {
  4768. const chainFilter = document.getElementById('mangle-filter-chain')?.value || '';
  4769. const tbody = document.getElementById('mangle-table-body');
  4770. const empty = document.getElementById('mangle-empty');
  4771. if (!tbody) return;
  4772. tbody.innerHTML = '';
  4773. const rules = (state.mangleRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  4774. document.getElementById('mangle-count-badge').innerText = `${rules.length} Rules`;
  4775. if (rules.length === 0) {
  4776. empty?.classList.remove('hidden');
  4777. return;
  4778. }
  4779. empty?.classList.add('hidden');
  4780. rules.forEach((r, idx) => {
  4781. const tr = document.createElement('tr');
  4782. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  4783. let markVal = '<span class="text-slate-500">-</span>';
  4784. if (r.new_connection_mark) markVal = `<span class="text-cyan-300 font-mono font-bold">${r.new_connection_mark}</span>`;
  4785. else if (r.new_routing_mark) markVal = `<span class="text-amber-300 font-mono font-bold">${r.new_routing_mark}</span>`;
  4786. else if (r.new_packet_mark) markVal = `<span class="text-emerald-300 font-mono font-bold">${r.new_packet_mark}</span>`;
  4787. else if (r.new_mss) markVal = `<span class="text-sky-300 font-mono font-bold">mss:${r.new_mss}</span>`;
  4788. else if (r.new_dscp) markVal = `<span class="text-purple-300 font-mono font-bold">dscp:${r.new_dscp}</span>`;
  4789. else if (r.new_ttl) markVal = `<span class="text-blue-300 font-mono font-bold">ttl:${r.new_ttl}</span>`;
  4790. else if (r.new_priority) markVal = `<span class="text-indigo-300 font-mono font-bold">prio:${r.new_priority}</span>`;
  4791. else if (r.route) markVal = `<span class="text-orange-300 font-mono font-bold">route:${r.route}</span>`;
  4792. else if (r.sniff_target) markVal = `<span class="text-pink-300 font-mono font-bold">sniff:${r.sniff_target}</span>`;
  4793. else if (r.action === 'jump') markVal = `<span class="text-yellow-300 font-mono font-bold">&rarr; ${r.jump_target || '-'}</span>`;
  4794. 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>`;
  4795. else if (r.action === 'log') markVal = `<span class="text-slate-400 font-mono font-bold">${r.log_prefix || 'log'}</span>`;
  4796. tr.innerHTML = `
  4797. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  4798. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  4799. <td class="py-2.5 px-3 font-bold text-purple-400">${r.chain}</td>
  4800. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  4801. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  4802. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  4803. <td class="py-2.5 px-3 font-mono text-xs">${markVal}</td>
  4804. <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>
  4805. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  4806. <span class="text-slate-300" id="mangle-pkts-${r.id}">${(r.packets || 0).toLocaleString()}p</span> /
  4807. <span class="text-slate-500" id="mangle-bytes-${r.id}">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  4808. </td>
  4809. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  4810. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  4811. <button onclick="moveMangleRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  4812. <button onclick="moveMangleRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  4813. <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>
  4814. <button onclick="openEditMangleModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  4815. <button onclick="deleteMangleRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  4816. </td>
  4817. `;
  4818. tbody.appendChild(tr);
  4819. });
  4820. }
  4821. // ==================== FIREWALL MANGLE MODAL (ROUTEROS WEBFIG / WINBOX V4) ====================
  4822. function switchMangleRuleTab(tab) {
  4823. state.activeMangleRuleTab = tab;
  4824. document.querySelectorAll('.mangle-rule-tab-btn').forEach(btn => {
  4825. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  4826. btn.classList.add('text-slate-400', 'border-transparent');
  4827. });
  4828. const activeBtn = document.getElementById(`mangle-tab-btn-${tab}`);
  4829. if (activeBtn) {
  4830. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  4831. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  4832. }
  4833. document.querySelectorAll('.mangle-rule-pane').forEach(p => p.classList.add('hidden'));
  4834. const activePane = document.getElementById(`mangle-pane-${tab}`);
  4835. if (activePane) activePane.classList.remove('hidden');
  4836. if (tab === 'statistics') {
  4837. startMangleStatPolling();
  4838. } else {
  4839. stopMangleStatPolling();
  4840. }
  4841. }
  4842. function toggleMangleField(fieldKey, expand) {
  4843. const plusBtn = document.getElementById(`mangle-plus-${fieldKey}`);
  4844. const fieldBox = document.getElementById(`mangle-field-${fieldKey}`);
  4845. if (!plusBtn || !fieldBox) return;
  4846. if (expand) {
  4847. plusBtn.classList.add('hidden');
  4848. fieldBox.classList.remove('hidden');
  4849. const valInput = document.getElementById(`mangle-val-${fieldKey}`);
  4850. if (valInput) valInput.focus();
  4851. } else {
  4852. fieldBox.classList.add('hidden');
  4853. plusBtn.classList.remove('hidden');
  4854. const valInput = document.getElementById(`mangle-val-${fieldKey}`);
  4855. if (valInput) {
  4856. if (valInput.tagName === 'SELECT') {
  4857. valInput.selectedIndex = 0;
  4858. } else {
  4859. valInput.value = '';
  4860. }
  4861. }
  4862. const invInput = document.getElementById(`mangle-inv-${fieldKey}`);
  4863. if (invInput) invInput.checked = false;
  4864. if (fieldKey === 'cs') {
  4865. ['mangle-modal-cs-established', 'mangle-modal-cs-related', 'mangle-modal-cs-new', 'mangle-modal-cs-invalid', 'mangle-modal-cs-untracked'].forEach(id => {
  4866. const el = document.getElementById(id);
  4867. if (el) el.checked = false;
  4868. });
  4869. }
  4870. if (fieldKey === 'natstate') {
  4871. ['mangle-modal-nat-srcnat', 'mangle-modal-nat-dstnat'].forEach(id => {
  4872. const el = document.getElementById(id);
  4873. if (el) el.checked = false;
  4874. });
  4875. }
  4876. }
  4877. }
  4878. function setMangleFieldVal(fieldKey, value, hasInvert = false) {
  4879. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  4880. toggleMangleField(fieldKey, true);
  4881. let strVal = String(value);
  4882. if (hasInvert) {
  4883. const inv = strVal.startsWith('!');
  4884. if (inv) strVal = strVal.slice(1);
  4885. const invEl = document.getElementById(`mangle-inv-${fieldKey}`);
  4886. if (invEl) invEl.checked = inv;
  4887. }
  4888. const valEl = document.getElementById(`mangle-val-${fieldKey}`);
  4889. if (valEl) valEl.value = strVal;
  4890. } else {
  4891. toggleMangleField(fieldKey, false);
  4892. }
  4893. }
  4894. function getMangleFieldVal(fieldKey, hasInvert = false) {
  4895. const fieldBox = document.getElementById(`mangle-field-${fieldKey}`);
  4896. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  4897. const valEl = document.getElementById(`mangle-val-${fieldKey}`);
  4898. let v = valEl ? valEl.value.trim() : '';
  4899. if (!v) return '';
  4900. if (hasInvert) {
  4901. const invEl = document.getElementById(`mangle-inv-${fieldKey}`);
  4902. if (invEl && invEl.checked) {
  4903. v = '!' + v.replace(/^!/, '');
  4904. }
  4905. }
  4906. return v;
  4907. }
  4908. function toggleMaximizeMangleModal() {
  4909. const win = document.getElementById('mangle-modal-window');
  4910. if (!win) return;
  4911. if (win.classList.contains('max-w-[720px]')) {
  4912. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  4913. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  4914. } else {
  4915. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  4916. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  4917. }
  4918. }
  4919. function toggleMangleActionFields() {
  4920. const act = document.getElementById('mangle-modal-action')?.value || 'mark-connection';
  4921. // Hide all dynamic rows first
  4922. ['newconnmark', 'newroutingmark', 'newpktmark', 'newmss', 'newdscp', 'newttl', 'newpriority', 'route', 'sniff', 'passthrough'].forEach(id => {
  4923. const el = document.getElementById(`mangle-row-${id}`);
  4924. if (el) el.classList.add('hidden');
  4925. });
  4926. const jumpBox = document.getElementById('mangle-action-jump-box');
  4927. const addrBox = document.getElementById('mangle-action-addrlist-box');
  4928. if (jumpBox) jumpBox.classList.add('hidden');
  4929. if (addrBox) addrBox.classList.add('hidden');
  4930. // Activate matching rows
  4931. if (act === 'mark-connection') {
  4932. document.getElementById('mangle-row-newconnmark')?.classList.remove('hidden');
  4933. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4934. } else if (act === 'mark-routing') {
  4935. document.getElementById('mangle-row-newroutingmark')?.classList.remove('hidden');
  4936. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4937. } else if (act === 'mark-packet') {
  4938. document.getElementById('mangle-row-newpktmark')?.classList.remove('hidden');
  4939. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4940. } else if (act === 'change-mss') {
  4941. document.getElementById('mangle-row-newmss')?.classList.remove('hidden');
  4942. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4943. } else if (act === 'change-dscp') {
  4944. document.getElementById('mangle-row-newdscp')?.classList.remove('hidden');
  4945. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4946. } else if (act === 'change-ttl') {
  4947. document.getElementById('mangle-row-newttl')?.classList.remove('hidden');
  4948. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4949. } else if (act === 'set-priority') {
  4950. document.getElementById('mangle-row-newpriority')?.classList.remove('hidden');
  4951. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4952. } else if (act === 'route') {
  4953. document.getElementById('mangle-row-route')?.classList.remove('hidden');
  4954. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4955. } else if (act === 'sniff-pc' || act === 'sniff-tzsp') {
  4956. document.getElementById('mangle-row-sniff')?.classList.remove('hidden');
  4957. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4958. } else if (act === 'clear-df' || act === 'strip-ipv4-options') {
  4959. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4960. } else if (act === 'jump') {
  4961. if (jumpBox) jumpBox.classList.remove('hidden');
  4962. } else if (act.includes('address-list') || act.includes('address list')) {
  4963. if (addrBox) addrBox.classList.remove('hidden');
  4964. }
  4965. if (act === 'log') {
  4966. const logEl = document.getElementById('mangle-modal-log');
  4967. if (logEl) logEl.checked = true;
  4968. toggleMangleField('logprefix', true);
  4969. }
  4970. }
  4971. function toggleMangleLogPrefix() {
  4972. const isLog = document.getElementById('mangle-modal-log')?.checked;
  4973. toggleMangleField('logprefix', !!isLog);
  4974. }
  4975. const allMangleFieldKeys = [
  4976. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  4977. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  4978. 'routingmark', 'conntype', 'cs', 'natstate',
  4979. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  4980. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  4981. 'ipsec', 'tlshost', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  4982. 'pktsize', 'random', 'tcpflags', 'icmpoptions', 'ipv4options', 'ttl',
  4983. 'nth', 'connlimit', 'srcaddrtype', 'dstaddrtype', 'hotspot', 'ipfragment',
  4984. 'limit', 'dstlimit', 'time', 'psd', 'logprefix'
  4985. ];
  4986. function openAddMangleModal() {
  4987. switchMangleRuleTab('general');
  4988. const badge = document.getElementById('mangle-modal-badge');
  4989. if (badge) badge.innerText = 'New...';
  4990. document.getElementById('mangle-modal-id').value = '';
  4991. document.getElementById('mangle-modal-enabled').checked = true;
  4992. document.getElementById('mangle-modal-comment').value = '';
  4993. document.getElementById('mangle-modal-chain').value = 'prerouting';
  4994. document.getElementById('mangle-modal-action').value = 'mark-connection';
  4995. if (document.getElementById('mangle-modal-newconnmark')) document.getElementById('mangle-modal-newconnmark').value = '';
  4996. if (document.getElementById('mangle-modal-newroutingmark')) document.getElementById('mangle-modal-newroutingmark').value = '';
  4997. if (document.getElementById('mangle-modal-newpktmark')) document.getElementById('mangle-modal-newpktmark').value = '';
  4998. if (document.getElementById('mangle-modal-newmss')) document.getElementById('mangle-modal-newmss').value = '';
  4999. if (document.getElementById('mangle-modal-newdscp')) document.getElementById('mangle-modal-newdscp').value = '';
  5000. if (document.getElementById('mangle-modal-newttl')) document.getElementById('mangle-modal-newttl').value = '';
  5001. if (document.getElementById('mangle-modal-newpriority')) document.getElementById('mangle-modal-newpriority').value = '';
  5002. if (document.getElementById('mangle-modal-route')) document.getElementById('mangle-modal-route').value = '';
  5003. if (document.getElementById('mangle-modal-sniff')) document.getElementById('mangle-modal-sniff').value = '';
  5004. if (document.getElementById('mangle-modal-jumptarget')) document.getElementById('mangle-modal-jumptarget').value = '';
  5005. if (document.getElementById('mangle-modal-action-addrlist')) document.getElementById('mangle-modal-action-addrlist').value = '';
  5006. if (document.getElementById('mangle-modal-action-timeout')) document.getElementById('mangle-modal-action-timeout').value = '';
  5007. if (document.getElementById('mangle-modal-passthrough')) document.getElementById('mangle-modal-passthrough').checked = true;
  5008. if (document.getElementById('mangle-modal-log')) document.getElementById('mangle-modal-log').checked = false;
  5009. populateInterfaceSelect('mangle-val-iniface');
  5010. populateInterfaceSelect('mangle-val-outiface');
  5011. populateAddressListSelect('mangle-val-srclist');
  5012. populateAddressListSelect('mangle-val-dstlist');
  5013. populateGeoIPSelect('mangle-val-srcgeo');
  5014. populateGeoIPSelect('mangle-val-dstgeo');
  5015. allMangleFieldKeys.forEach(k => toggleMangleField(k, false));
  5016. resetCurrentMangleRuleCounters();
  5017. toggleMangleActionFields();
  5018. document.getElementById('mangle-modal').classList.remove('hidden');
  5019. }
  5020. function openEditMangleModal(id) {
  5021. const r = (state.mangleRules || []).find(rule => rule.id === id);
  5022. if (!r) return;
  5023. switchMangleRuleTab('general');
  5024. const badge = document.getElementById('mangle-modal-badge');
  5025. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  5026. document.getElementById('mangle-modal-id').value = r.id;
  5027. document.getElementById('mangle-modal-enabled').checked = !r.disabled;
  5028. document.getElementById('mangle-modal-comment').value = r.comment || '';
  5029. document.getElementById('mangle-modal-chain').value = r.chain || 'prerouting';
  5030. document.getElementById('mangle-modal-action').value = r.action || 'mark-connection';
  5031. if (document.getElementById('mangle-modal-newconnmark')) document.getElementById('mangle-modal-newconnmark').value = r.new_connection_mark || '';
  5032. if (document.getElementById('mangle-modal-newroutingmark')) document.getElementById('mangle-modal-newroutingmark').value = r.new_routing_mark || '';
  5033. if (document.getElementById('mangle-modal-newpktmark')) document.getElementById('mangle-modal-newpktmark').value = r.new_packet_mark || '';
  5034. if (document.getElementById('mangle-modal-newmss')) document.getElementById('mangle-modal-newmss').value = r.new_mss || '';
  5035. if (document.getElementById('mangle-modal-newdscp')) document.getElementById('mangle-modal-newdscp').value = r.new_dscp != null ? r.new_dscp : '';
  5036. if (document.getElementById('mangle-modal-newttl')) document.getElementById('mangle-modal-newttl').value = r.new_ttl || '';
  5037. if (document.getElementById('mangle-modal-newpriority')) document.getElementById('mangle-modal-newpriority').value = r.new_priority || '';
  5038. if (document.getElementById('mangle-modal-route')) document.getElementById('mangle-modal-route').value = r.route || '';
  5039. if (document.getElementById('mangle-modal-sniff')) document.getElementById('mangle-modal-sniff').value = r.sniff_target || '';
  5040. if (document.getElementById('mangle-modal-jumptarget')) document.getElementById('mangle-modal-jumptarget').value = r.jump_target || '';
  5041. if (document.getElementById('mangle-modal-action-addrlist')) document.getElementById('mangle-modal-action-addrlist').value = r.address_list || '';
  5042. if (document.getElementById('mangle-modal-action-timeout')) document.getElementById('mangle-modal-action-timeout').value = r.address_list_timeout || '';
  5043. if (document.getElementById('mangle-modal-passthrough')) document.getElementById('mangle-modal-passthrough').checked = r.passthrough ?? true;
  5044. if (document.getElementById('mangle-modal-log')) document.getElementById('mangle-modal-log').checked = !!r.log;
  5045. populateInterfaceSelect('mangle-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  5046. populateInterfaceSelect('mangle-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  5047. populateAddressListSelect('mangle-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  5048. populateAddressListSelect('mangle-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  5049. populateGeoIPSelect('mangle-val-srcgeo', r.src_geoip || '');
  5050. populateGeoIPSelect('mangle-val-dstgeo', r.dst_geoip || '');
  5051. setMangleFieldVal('src', r.src_address, true);
  5052. setMangleFieldVal('dst', r.dst_address, true);
  5053. setMangleFieldVal('srclist', r.src_address_list, true);
  5054. setMangleFieldVal('dstlist', r.dst_address_list, true);
  5055. setMangleFieldVal('srcgeo', r.src_geoip, true);
  5056. setMangleFieldVal('dstgeo', r.dst_geoip, true);
  5057. if (r.protocol && r.protocol !== 'all') {
  5058. setMangleFieldVal('proto', r.protocol, true);
  5059. } else {
  5060. toggleMangleField('proto', false);
  5061. }
  5062. setMangleFieldVal('sport', r.src_port, true);
  5063. setMangleFieldVal('dport', r.dst_port, true);
  5064. setMangleFieldVal('anyport', r.any_port, true);
  5065. setMangleFieldVal('iniface', r.in_interface, true);
  5066. setMangleFieldVal('outiface', r.out_interface, true);
  5067. setMangleFieldVal('inifacelist', r.in_interface_list, true);
  5068. setMangleFieldVal('outifacelist', r.out_interface_list, true);
  5069. setMangleFieldVal('pktmark', r.packet_mark, true);
  5070. setMangleFieldVal('connmark', r.connection_mark, true);
  5071. setMangleFieldVal('routingmark', r.routing_mark, true);
  5072. setMangleFieldVal('conntype', r.connection_type, false);
  5073. // Connection State
  5074. const states = r.connection_state || [];
  5075. if (states.length > 0) {
  5076. toggleMangleField('cs', true);
  5077. ['established', 'related', 'new', 'invalid', 'untracked'].forEach(s => {
  5078. const el = document.getElementById(`mangle-modal-cs-${s}`);
  5079. if (el) el.checked = states.includes(s);
  5080. });
  5081. } else {
  5082. toggleMangleField('cs', false);
  5083. }
  5084. // Connection NAT State
  5085. const natStates = r.connection_nat_state || [];
  5086. if (natStates.length > 0) {
  5087. toggleMangleField('natstate', true);
  5088. ['srcnat', 'dstnat'].forEach(s => {
  5089. const el = document.getElementById(`mangle-modal-nat-${s}`);
  5090. if (el) el.checked = natStates.includes(s);
  5091. });
  5092. } else {
  5093. toggleMangleField('natstate', false);
  5094. }
  5095. // Advanced tab fields
  5096. setMangleFieldVal('layer7', r.layer7_protocol, false);
  5097. setMangleFieldVal('content', r.content, false);
  5098. setMangleFieldVal('connbytes', r.connection_bytes, false);
  5099. setMangleFieldVal('connrate', r.connection_rate, false);
  5100. setMangleFieldVal('pcc', r.pcc, false);
  5101. setMangleFieldVal('srcmac', r.src_mac_address, true);
  5102. setMangleFieldVal('outbridgeport', r.out_bridge_port, false);
  5103. setMangleFieldVal('inbridgeport', r.in_bridge_port, false);
  5104. setMangleFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  5105. setMangleFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  5106. setMangleFieldVal('ipsec', r.ipsec_policy, false);
  5107. setMangleFieldVal('tlshost', r.tls_host, false);
  5108. setMangleFieldVal('ingresspriority', r.ingress_priority, false);
  5109. setMangleFieldVal('priority', r.priority, false);
  5110. setMangleFieldVal('dscp', r.dscp, false);
  5111. setMangleFieldVal('tcpmss', r.tcp_mss, false);
  5112. if (r.tos) {
  5113. const tosEl = document.getElementById('mangle-val-tos');
  5114. if (tosEl) tosEl.value = r.tos;
  5115. }
  5116. setMangleFieldVal('pktsize', r.packet_size, false);
  5117. setMangleFieldVal('random', r.random, false);
  5118. setMangleFieldVal('tcpflags', r.tcp_flags, false);
  5119. setMangleFieldVal('icmpoptions', r.icmp_options, false);
  5120. setMangleFieldVal('ipv4options', r.ipv4_options, false);
  5121. setMangleFieldVal('ttl', r.ttl, false);
  5122. // Extra tab fields
  5123. setMangleFieldVal('nth', r.nth, false);
  5124. setMangleFieldVal('connlimit', r.connection_limit, false);
  5125. setMangleFieldVal('srcaddrtype', r.src_address_type, false);
  5126. setMangleFieldVal('dstaddrtype', r.dst_address_type, false);
  5127. setMangleFieldVal('hotspot', r.hotspot, false);
  5128. setMangleFieldVal('ipfragment', r.ip_fragment, false);
  5129. setMangleFieldVal('limit', r.limit, false);
  5130. setMangleFieldVal('dstlimit', r.dst_limit, false);
  5131. setMangleFieldVal('time', r.time, false);
  5132. setMangleFieldVal('psd', r.psd, false);
  5133. // Action fields
  5134. if (r.jump_target) {
  5135. const jtEl = document.getElementById('mangle-modal-jumptarget');
  5136. if (jtEl) jtEl.value = r.jump_target;
  5137. }
  5138. if (r.address_list) {
  5139. const alEl = document.getElementById('mangle-modal-action-addrlist');
  5140. if (alEl) alEl.value = r.address_list;
  5141. }
  5142. if (r.address_list_timeout) {
  5143. const toEl = document.getElementById('mangle-modal-action-timeout');
  5144. if (toEl) toEl.value = r.address_list_timeout;
  5145. }
  5146. setMangleFieldVal('logprefix', r.log_prefix, false);
  5147. // Statistics
  5148. const bEl = document.getElementById('mangle-stat-bytes');
  5149. const pEl = document.getElementById('mangle-stat-packets');
  5150. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  5151. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  5152. state.mangleLastBytes = r.bytes || 0;
  5153. state.mangleLastPackets = r.packets || 0;
  5154. state.mangleLastTimestamp = Date.now();
  5155. state.mangleStatRateHistory = new Array(30).fill(0);
  5156. state.mangleStatPktHistory = new Array(30).fill(0);
  5157. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  5158. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  5159. toggleMangleActionFields();
  5160. document.getElementById('mangle-modal').classList.remove('hidden');
  5161. }
  5162. function closeMangleModal() {
  5163. stopMangleStatPolling();
  5164. document.getElementById('mangle-modal').classList.add('hidden');
  5165. }
  5166. function copyMangleRule() {
  5167. document.getElementById('mangle-modal-id').value = '';
  5168. const badge = document.getElementById('mangle-modal-badge');
  5169. if (badge) badge.innerText = 'New...';
  5170. showToast('Rule Cloned', 'Ready to save as a new Mangle rule copy', 'info');
  5171. }
  5172. function resetCurrentMangleRuleCounters() {
  5173. state.mangleStatRateHistory = new Array(30).fill(0);
  5174. state.mangleStatPktHistory = new Array(30).fill(0);
  5175. state.mangleLastBytes = 0;
  5176. state.mangleLastPackets = 0;
  5177. state.mangleLastTimestamp = Date.now();
  5178. const bEl = document.getElementById('mangle-stat-bytes');
  5179. const pEl = document.getElementById('mangle-stat-packets');
  5180. const rEl = document.getElementById('mangle-stat-rate');
  5181. const prEl = document.getElementById('mangle-stat-pktrate');
  5182. if (bEl) bEl.value = '0 B';
  5183. if (pEl) pEl.value = '0';
  5184. if (rEl) rEl.value = '0 bps';
  5185. if (prEl) prEl.value = '0 p/s';
  5186. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  5187. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  5188. showToast('Counters Reset', 'Mangle rule counter display reset to 0', 'info');
  5189. }
  5190. async function applyMangleRule(closeAfter = false) {
  5191. const id = document.getElementById('mangle-modal-id').value;
  5192. const chain = document.getElementById('mangle-modal-chain').value;
  5193. const action = document.getElementById('mangle-modal-action').value;
  5194. const comment = document.getElementById('mangle-modal-comment').value.trim();
  5195. const enabled = document.getElementById('mangle-modal-enabled').checked;
  5196. const src = getMangleFieldVal('src', true);
  5197. const dst = getMangleFieldVal('dst', true);
  5198. const srclist = getMangleFieldVal('srclist', true);
  5199. const dstlist = getMangleFieldVal('dstlist', true);
  5200. const srcgeo = getMangleFieldVal('srcgeo', true);
  5201. const dstgeo = getMangleFieldVal('dstgeo', true);
  5202. const proto = getMangleFieldVal('proto', true);
  5203. const sport = getMangleFieldVal('sport', true);
  5204. const dport = getMangleFieldVal('dport', true);
  5205. const anyport = getMangleFieldVal('anyport', true);
  5206. const iniface = getMangleFieldVal('iniface', true);
  5207. const outiface = getMangleFieldVal('outiface', true);
  5208. const inifacelist = getMangleFieldVal('inifacelist', true);
  5209. const outifacelist = getMangleFieldVal('outifacelist', true);
  5210. const pktmark = getMangleFieldVal('pktmark', true);
  5211. const connmark = getMangleFieldVal('connmark', true);
  5212. const routingmark = getMangleFieldVal('routingmark', true);
  5213. const conntype = getMangleFieldVal('conntype', false);
  5214. const states = [];
  5215. const csBox = document.getElementById('mangle-field-cs');
  5216. if (csBox && !csBox.classList.contains('hidden')) {
  5217. ['established', 'related', 'new', 'invalid', 'untracked'].forEach(s => {
  5218. if (document.getElementById(`mangle-modal-cs-${s}`)?.checked) states.push(s);
  5219. });
  5220. }
  5221. const natStates = [];
  5222. const natBox = document.getElementById('mangle-field-natstate');
  5223. if (natBox && !natBox.classList.contains('hidden')) {
  5224. ['srcnat', 'dstnat'].forEach(s => {
  5225. if (document.getElementById(`mangle-modal-nat-${s}`)?.checked) natStates.push(s);
  5226. });
  5227. }
  5228. const payload = {
  5229. id,
  5230. chain,
  5231. action,
  5232. protocol: proto || 'all',
  5233. src_address: src,
  5234. dst_address: dst,
  5235. src_port: sport,
  5236. dst_port: dport,
  5237. any_port: anyport,
  5238. in_interface: iniface,
  5239. out_interface: outiface,
  5240. in_interface_list: inifacelist,
  5241. out_interface_list: outifacelist,
  5242. packet_mark: pktmark,
  5243. connection_mark: connmark,
  5244. routing_mark: routingmark,
  5245. connection_type: conntype,
  5246. connection_state: states,
  5247. connection_nat_state: natStates,
  5248. src_address_list: srclist,
  5249. dst_address_list: dstlist,
  5250. src_geoip: srcgeo,
  5251. dst_geoip: dstgeo,
  5252. comment,
  5253. disabled: !enabled,
  5254. // Advanced tab
  5255. layer7_protocol: getMangleFieldVal('layer7', false),
  5256. content: getMangleFieldVal('content', false),
  5257. connection_bytes: getMangleFieldVal('connbytes', false),
  5258. connection_rate: getMangleFieldVal('connrate', false),
  5259. pcc: getMangleFieldVal('pcc', false),
  5260. src_mac_address: getMangleFieldVal('srcmac', true),
  5261. out_bridge_port: getMangleFieldVal('outbridgeport', false),
  5262. in_bridge_port: getMangleFieldVal('inbridgeport', false),
  5263. in_bridge_port_list: getMangleFieldVal('inbridgeportlist', false),
  5264. out_bridge_port_list: getMangleFieldVal('outbridgeportlist', false),
  5265. ipsec_policy: getMangleFieldVal('ipsec', false),
  5266. tls_host: getMangleFieldVal('tlshost', false),
  5267. ingress_priority: getMangleFieldVal('ingresspriority', false),
  5268. priority: getMangleFieldVal('priority', false),
  5269. dscp: getMangleFieldVal('dscp', false),
  5270. tcp_mss: getMangleFieldVal('tcpmss', false),
  5271. tos: document.getElementById('mangle-val-tos')?.value || '',
  5272. packet_size: getMangleFieldVal('pktsize', false),
  5273. random: getMangleFieldVal('random', false),
  5274. tcp_flags: getMangleFieldVal('tcpflags', false),
  5275. icmp_options: getMangleFieldVal('icmpoptions', false),
  5276. ipv4_options: getMangleFieldVal('ipv4options', false),
  5277. ttl: getMangleFieldVal('ttl', false),
  5278. // Extra tab
  5279. nth: getMangleFieldVal('nth', false),
  5280. connection_limit: getMangleFieldVal('connlimit', false),
  5281. src_address_type: getMangleFieldVal('srcaddrtype', false),
  5282. dst_address_type: getMangleFieldVal('dstaddrtype', false),
  5283. hotspot: getMangleFieldVal('hotspot', false),
  5284. ip_fragment: getMangleFieldVal('ipfragment', false),
  5285. limit: getMangleFieldVal('limit', false),
  5286. dst_limit: getMangleFieldVal('dstlimit', false),
  5287. time: getMangleFieldVal('time', false),
  5288. psd: getMangleFieldVal('psd', false),
  5289. // Action tab
  5290. new_connection_mark: action === 'mark-connection' ? (document.getElementById('mangle-modal-newconnmark')?.value.trim() || '') : '',
  5291. new_routing_mark: action === 'mark-routing' ? (document.getElementById('mangle-modal-newroutingmark')?.value.trim() || '') : '',
  5292. new_packet_mark: action === 'mark-packet' ? (document.getElementById('mangle-modal-newpktmark')?.value.trim() || '') : '',
  5293. new_mss: action === 'change-mss' ? (document.getElementById('mangle-modal-newmss')?.value.trim() || '') : '',
  5294. new_dscp: action === 'change-dscp' ? parseInt(document.getElementById('mangle-modal-newdscp')?.value || '0', 10) : 0,
  5295. new_ttl: action === 'change-ttl' ? (document.getElementById('mangle-modal-newttl')?.value.trim() || '') : '',
  5296. new_priority: action === 'set-priority' ? (document.getElementById('mangle-modal-newpriority')?.value.trim() || '') : '',
  5297. route: action === 'route' ? (document.getElementById('mangle-modal-route')?.value.trim() || '') : '',
  5298. sniff_target: (action === 'sniff-pc' || action === 'sniff-tzsp') ? (document.getElementById('mangle-modal-sniff')?.value.trim() || '') : '',
  5299. passthrough: document.getElementById('mangle-modal-passthrough')?.checked ?? true,
  5300. jump_target: action === 'jump' ? (document.getElementById('mangle-modal-jumptarget')?.value || '') : '',
  5301. address_list: action.includes('address') ? (document.getElementById('mangle-modal-action-addrlist')?.value || '') : '',
  5302. address_list_timeout: action.includes('address') ? (document.getElementById('mangle-modal-action-timeout')?.value || '') : '',
  5303. log: document.getElementById('mangle-modal-log')?.checked || false,
  5304. log_prefix: getMangleFieldVal('logprefix', false)
  5305. };
  5306. try {
  5307. const res = await fetch(`${API_BASE}/firewall/mangle`, {
  5308. method: 'POST',
  5309. headers: { 'Content-Type': 'application/json' },
  5310. body: JSON.stringify(payload)
  5311. });
  5312. if (res.ok) {
  5313. const data = await res.json();
  5314. showToast('Mangle Rule Saved', 'Marking rule updated', 'success');
  5315. loadFirewall(false);
  5316. if (closeAfter) {
  5317. closeMangleModal();
  5318. } else {
  5319. if (data.id) {
  5320. document.getElementById('mangle-modal-id').value = data.id;
  5321. const badge = document.getElementById('mangle-modal-badge');
  5322. if (badge) badge.innerText = `#${data.id}`;
  5323. }
  5324. }
  5325. } else {
  5326. const err = await res.json();
  5327. showToast('Error', err.message || 'Failed to save mangle rule', 'error');
  5328. }
  5329. } catch (err) {
  5330. showToast('Error', err.message, 'error');
  5331. }
  5332. }
  5333. function submitSaveMangleRule(e) {
  5334. if (e && e.preventDefault) e.preventDefault();
  5335. return applyMangleRule(true);
  5336. }
  5337. function startMangleStatPolling() {
  5338. stopMangleStatPolling();
  5339. pollMangleRuleStats();
  5340. state.mangleStatInterval = setInterval(pollMangleRuleStats, 1000);
  5341. }
  5342. function stopMangleStatPolling() {
  5343. if (state.mangleStatInterval) {
  5344. clearInterval(state.mangleStatInterval);
  5345. state.mangleStatInterval = null;
  5346. }
  5347. }
  5348. async function pollMangleRuleStats() {
  5349. const id = document.getElementById('mangle-modal-id')?.value;
  5350. if (!id) {
  5351. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory || new Array(30).fill(0), 'bps', 'mangle-stat-legend-rate');
  5352. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory || new Array(30).fill(0), 'p/s', 'mangle-stat-legend-pktrate');
  5353. return;
  5354. }
  5355. try {
  5356. const res = await fetch(`${API_BASE}/firewall/mangle`);
  5357. if (!res.ok) return;
  5358. const rules = await res.json();
  5359. const r = rules.find(x => x.id === id);
  5360. if (!r) return;
  5361. const now = Date.now();
  5362. const dt = Math.max(0.2, (now - (state.mangleLastTimestamp || now)) / 1000);
  5363. state.mangleLastTimestamp = now;
  5364. const curBytes = r.bytes || 0;
  5365. const curPackets = r.packets || 0;
  5366. const deltaBytes = Math.max(0, curBytes - (state.mangleLastBytes || curBytes));
  5367. const deltaPkts = Math.max(0, curPackets - (state.mangleLastPackets || curPackets));
  5368. state.mangleLastBytes = curBytes;
  5369. state.mangleLastPackets = curPackets;
  5370. const rateBps = Math.round((deltaBytes * 8) / dt);
  5371. const ratePkt = Math.round(deltaPkts / dt);
  5372. if (!state.mangleStatRateHistory) state.mangleStatRateHistory = new Array(30).fill(0);
  5373. if (!state.mangleStatPktHistory) state.mangleStatPktHistory = new Array(30).fill(0);
  5374. state.mangleStatRateHistory.push(rateBps);
  5375. if (state.mangleStatRateHistory.length > 30) state.mangleStatRateHistory.shift();
  5376. state.mangleStatPktHistory.push(ratePkt);
  5377. if (state.mangleStatPktHistory.length > 30) state.mangleStatPktHistory.shift();
  5378. const bEl = document.getElementById('mangle-stat-bytes');
  5379. const pEl = document.getElementById('mangle-stat-packets');
  5380. const rEl = document.getElementById('mangle-stat-rate');
  5381. const prEl = document.getElementById('mangle-stat-pktrate');
  5382. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  5383. if (pEl) pEl.value = curPackets.toLocaleString();
  5384. if (rEl) rEl.value = formatBps(rateBps);
  5385. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  5386. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  5387. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  5388. } catch (e) {
  5389. console.error('Error polling Mangle rule stats', e);
  5390. }
  5391. }
  5392. async function moveMangleRule(id, dir) {
  5393. try {
  5394. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/move`, {
  5395. method: 'POST',
  5396. headers: { 'Content-Type': 'application/json' },
  5397. body: JSON.stringify({ direction: dir })
  5398. });
  5399. if (res.ok) loadFirewall(false);
  5400. } catch (err) {
  5401. showToast('Error', err.message, 'error');
  5402. }
  5403. }
  5404. async function toggleMangleRuleState(id, disabled) {
  5405. try {
  5406. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/state`, {
  5407. method: 'POST',
  5408. headers: { 'Content-Type': 'application/json' },
  5409. body: JSON.stringify({ disabled })
  5410. });
  5411. if (res.ok) loadFirewall(false);
  5412. } catch (err) {
  5413. showToast('Error', err.message, 'error');
  5414. }
  5415. }
  5416. async function deleteMangleRule(id) {
  5417. if (!confirm('Are you sure you want to delete this mangle rule?')) return;
  5418. try {
  5419. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5420. if (res.ok) {
  5421. showToast('Deleted', 'Mangle rule removed', 'success');
  5422. loadFirewall(false);
  5423. }
  5424. } catch (err) {
  5425. showToast('Error', err.message, 'error');
  5426. }
  5427. }
  5428. // ----------------- Address Lists -----------------
  5429. function renderAddressLists() {
  5430. const filterList = document.getElementById('addrlist-filter-name')?.value || '';
  5431. const tbody = document.getElementById('addrlist-table-body');
  5432. const empty = document.getElementById('addrlist-empty');
  5433. if (!tbody) return;
  5434. tbody.innerHTML = '';
  5435. const entries = (state.addressLists || []).filter(e => !filterList || e.name === filterList);
  5436. document.getElementById('addrlist-count-badge').innerText = `${entries.length} Entries`;
  5437. // Update filter select
  5438. const sel = document.getElementById('addrlist-filter-name');
  5439. if (sel) {
  5440. const cur = sel.value;
  5441. sel.innerHTML = '<option value="">All Lists</option>';
  5442. const set = new Set((state.addressLists || []).map(a => a.name));
  5443. set.forEach(n => {
  5444. const opt = document.createElement('option');
  5445. opt.value = n;
  5446. opt.innerText = n;
  5447. if (n === cur) opt.selected = true;
  5448. sel.appendChild(opt);
  5449. });
  5450. }
  5451. if (entries.length === 0) {
  5452. empty?.classList.remove('hidden');
  5453. return;
  5454. }
  5455. empty?.classList.add('hidden');
  5456. entries.forEach((e, idx) => {
  5457. const tr = document.createElement('tr');
  5458. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${e.disabled ? 'opacity-50' : ''}`;
  5459. tr.setAttribute('ondblclick', `openEditAddrListModal('${e.id}')`);
  5460. tr.innerHTML = `
  5461. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  5462. <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>
  5463. <td class="py-2.5 px-3 font-bold text-white font-mono">${e.name}</td>
  5464. <td class="py-2.5 px-3 font-mono font-bold text-emerald-400">${e.address}</td>
  5465. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[150px]">${e.comment || '-'}</td>
  5466. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  5467. <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>
  5468. <button onclick="openEditAddrListModal('${e.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-medium">Edit</button>
  5469. <button onclick="deleteAddrList('${e.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  5470. </td>
  5471. `;
  5472. tbody.appendChild(tr);
  5473. });
  5474. populateCommonAddrListDatalist();
  5475. }
  5476. function openAddAddrListModal() {
  5477. document.getElementById('addrlist-modal-title').innerText = 'Add Address List Entry';
  5478. document.getElementById('addrlist-modal-id').value = '';
  5479. document.getElementById('addrlist-modal-name').value = '';
  5480. document.getElementById('addrlist-modal-addr').value = '';
  5481. document.getElementById('addrlist-modal-comment').value = '';
  5482. document.getElementById('addrlist-modal-disabled').checked = false;
  5483. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  5484. if (submitBtn) submitBtn.innerText = 'Add to List';
  5485. document.getElementById('addrlist-modal').classList.remove('hidden');
  5486. }
  5487. function openEditAddrListModal(id) {
  5488. const e = (state.addressLists || []).find(item => item.id === id);
  5489. if (!e) return;
  5490. document.getElementById('addrlist-modal-title').innerText = `Edit Address List Entry: ${e.name}`;
  5491. document.getElementById('addrlist-modal-id').value = e.id;
  5492. document.getElementById('addrlist-modal-name').value = e.name;
  5493. document.getElementById('addrlist-modal-addr').value = e.address;
  5494. document.getElementById('addrlist-modal-comment').value = e.comment || '';
  5495. document.getElementById('addrlist-modal-disabled').checked = !!e.disabled;
  5496. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  5497. if (submitBtn) submitBtn.innerText = 'Save Changes';
  5498. document.getElementById('addrlist-modal').classList.remove('hidden');
  5499. }
  5500. function closeAddrListModal() {
  5501. document.getElementById('addrlist-modal').classList.add('hidden');
  5502. }
  5503. async function submitSaveAddrList(e) {
  5504. e.preventDefault();
  5505. const id = document.getElementById('addrlist-modal-id').value;
  5506. const name = document.getElementById('addrlist-modal-name').value.trim();
  5507. const addr = document.getElementById('addrlist-modal-addr').value.trim();
  5508. const comment = document.getElementById('addrlist-modal-comment').value.trim();
  5509. const disabled = document.getElementById('addrlist-modal-disabled').checked;
  5510. try {
  5511. const res = await fetch(`${API_BASE}/firewall/address-lists`, {
  5512. method: 'POST',
  5513. headers: { 'Content-Type': 'application/json' },
  5514. body: JSON.stringify({ id, name, address: addr, comment, disabled })
  5515. });
  5516. if (res.ok) {
  5517. showToast('Address List Item Saved', `Saved ${addr} in ${name}`, 'success');
  5518. closeAddrListModal();
  5519. loadFirewall(false);
  5520. } else {
  5521. const err = await res.json();
  5522. showToast('Error', err.message || 'Failed to save address list', 'error');
  5523. }
  5524. } catch (err) {
  5525. showToast('Error', err.message, 'error');
  5526. }
  5527. }
  5528. async function toggleAddrListState(id, disabled) {
  5529. try {
  5530. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}/state`, {
  5531. method: 'POST',
  5532. headers: { 'Content-Type': 'application/json' },
  5533. body: JSON.stringify({ disabled })
  5534. });
  5535. if (res.ok) {
  5536. loadFirewall(false);
  5537. }
  5538. } catch (err) {
  5539. showToast('Error', err.message, 'error');
  5540. }
  5541. }
  5542. async function deleteAddrList(id) {
  5543. if (!confirm('Are you sure you want to delete this address list item?')) return;
  5544. try {
  5545. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5546. if (res.ok) {
  5547. showToast('Deleted', 'Address list item removed', 'info');
  5548. loadFirewall(false);
  5549. }
  5550. } catch (err) {
  5551. showToast('Error', err.message, 'error');
  5552. }
  5553. }
  5554. // ----------------- Geo-Location IP Management -----------------
  5555. async function loadGeoIP() {
  5556. try {
  5557. const [statusRes, countriesRes] = await Promise.all([
  5558. fetch(`${API_BASE}/firewall/geoip/status`),
  5559. fetch(`${API_BASE}/firewall/geoip/countries`)
  5560. ]);
  5561. if (statusRes.ok) state.geoStatus = await statusRes.json();
  5562. if (countriesRes.ok) state.geoCountries = await countriesRes.json();
  5563. updateGeoHeader();
  5564. renderGeoCountries();
  5565. } catch (err) {
  5566. console.error('Failed to load GeoIP:', err);
  5567. }
  5568. }
  5569. function getGeoUsageMap() {
  5570. const usage = {};
  5571. const checkRule = (r, type) => {
  5572. ['src_geoip', 'dst_geoip'].forEach(field => {
  5573. let val = (r && r[field]) || '';
  5574. let code = val.replace(/^!/, '').replace(/^geo:/, '').replace(/^geo_/, '').toUpperCase().trim();
  5575. if (code) {
  5576. if (!usage[code]) usage[code] = [];
  5577. const label = `${type} #${r.priority !== undefined ? r.priority : (r.id || '')}`;
  5578. if (!usage[code].includes(label)) usage[code].push(label);
  5579. }
  5580. });
  5581. };
  5582. (state.filterRules || []).forEach(r => checkRule(r, 'Filter'));
  5583. (state.natRules || []).forEach(r => checkRule(r, 'NAT'));
  5584. (state.mangleRules || []).forEach(r => checkRule(r, 'Mangle'));
  5585. return usage;
  5586. }
  5587. function updateGeoHeader() {
  5588. const s = state.geoStatus || {};
  5589. const statusBadge = document.getElementById('geo-status-badge');
  5590. if (statusBadge) {
  5591. statusBadge.innerText = s.auto_update ? 'Auto-Update ON' : 'Auto-Update OFF';
  5592. statusBadge.className = s.auto_update
  5593. ? 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-emerald-500/20 text-emerald-300 border border-emerald-500/30'
  5594. : 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 text-slate-400';
  5595. }
  5596. const intervalLabel = document.getElementById('geo-interval-label');
  5597. if (intervalLabel) {
  5598. intervalLabel.innerText = `Every ${s.interval_hours || 24}h`;
  5599. }
  5600. const usageMap = getGeoUsageMap();
  5601. const inUseCount = Object.keys(usageMap).length;
  5602. const activeCountEl = document.getElementById('geo-stat-active-countries');
  5603. if (activeCountEl) activeCountEl.innerText = inUseCount.toLocaleString();
  5604. const totalSubnetsEl = document.getElementById('geo-stat-total-subnets');
  5605. if (totalSubnetsEl) totalSubnetsEl.innerText = (s.total_subnets || 0).toLocaleString();
  5606. const lastSyncEl = document.getElementById('geo-stat-last-sync');
  5607. if (lastSyncEl) {
  5608. if (s.last_updated && !s.last_updated.startsWith('0001')) {
  5609. const d = new Date(s.last_updated);
  5610. lastSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  5611. } else {
  5612. lastSyncEl.innerText = 'Never (Sync Pending)';
  5613. }
  5614. }
  5615. const nextSyncEl = document.getElementById('geo-stat-next-sync');
  5616. if (nextSyncEl) {
  5617. if (s.next_update && !s.next_update.startsWith('0001')) {
  5618. const d = new Date(s.next_update);
  5619. nextSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  5620. } else {
  5621. nextSyncEl.innerText = '-';
  5622. }
  5623. }
  5624. const badge = document.getElementById('fw-badge-geo');
  5625. if (badge) badge.innerText = inUseCount || (state.geoCountries || []).filter(c => c.subnet_count > 0).length || 0;
  5626. }
  5627. function renderGeoCountries() {
  5628. const tbody = document.getElementById('geo-table-body');
  5629. const empty = document.getElementById('geo-empty');
  5630. if (!tbody) return;
  5631. tbody.innerHTML = '';
  5632. const q = (document.getElementById('geo-search-input')?.value || '').trim().toLowerCase();
  5633. const continent = document.getElementById('geo-continent-filter')?.value || '';
  5634. const inUseOnly = document.getElementById('geo-filter-inuse-only')?.checked;
  5635. const cachedOnly = document.getElementById('geo-filter-cached-only')?.checked;
  5636. const usageMap = getGeoUsageMap();
  5637. const countries = (state.geoCountries || []).filter(c => {
  5638. const isUsed = !!usageMap[c.code];
  5639. if (inUseOnly && !isUsed) return false;
  5640. if (cachedOnly && (!c.subnet_count || c.subnet_count === 0)) return false;
  5641. if (continent && c.continent !== continent) return false;
  5642. if (q) {
  5643. const matchCode = c.code.toLowerCase().includes(q);
  5644. const matchName = c.name.toLowerCase().includes(q);
  5645. if (!matchCode && !matchName) return false;
  5646. }
  5647. return true;
  5648. });
  5649. if (countries.length === 0) {
  5650. empty?.classList.remove('hidden');
  5651. return;
  5652. }
  5653. empty?.classList.add('hidden');
  5654. countries.forEach(c => {
  5655. const tr = document.createElement('tr');
  5656. const isUsed = !!usageMap[c.code];
  5657. const rulesUsing = usageMap[c.code] || [];
  5658. tr.className = `hover:bg-slate-800/40 transition text-xs ${isUsed ? 'bg-emerald-950/20' : ''}`;
  5659. let statusHtml = '';
  5660. if (isUsed) {
  5661. 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>`;
  5662. } else if (c.subnet_count > 0) {
  5663. 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>';
  5664. } else {
  5665. statusHtml = '<span class="px-2 py-0.5 rounded text-[10px] font-mono text-slate-500 bg-slate-800/60">READY</span>';
  5666. }
  5667. tr.innerHTML = `
  5668. <td class="py-2.5 px-3 text-center">
  5669. <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'}">
  5670. ${c.code}
  5671. </span>
  5672. </td>
  5673. <td class="py-2.5 px-3 font-bold text-white">${c.name}</td>
  5674. <td class="py-2.5 px-3 text-slate-400">${c.continent}</td>
  5675. <td class="py-2.5 px-3 font-mono ${c.subnet_count > 0 ? 'text-emerald-400 font-bold' : 'text-slate-500'}">
  5676. ${c.subnet_count > 0 ? c.subnet_count.toLocaleString() + ' CIDRs' : 'Not Cached'}
  5677. </td>
  5678. <td class="py-2.5 px-3 font-mono text-purple-300">${c.ipset_name}</td>
  5679. <td class="py-2.5 px-3">
  5680. ${statusHtml}
  5681. </td>
  5682. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  5683. <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>
  5684. <button onclick="viewGeoSubnets('${c.code}')" class="text-xs text-slate-400 hover:text-white" title="Preview Subnet Ranges">View</button>
  5685. </td>
  5686. `;
  5687. tbody.appendChild(tr);
  5688. });
  5689. }
  5690. function quickFilterGeo(preset) {
  5691. const searchInput = document.getElementById('geo-search-input');
  5692. const continentSel = document.getElementById('geo-continent-filter');
  5693. const inUseCheck = document.getElementById('geo-filter-inuse-only');
  5694. const cachedCheck = document.getElementById('geo-filter-cached-only');
  5695. if (searchInput) searchInput.value = '';
  5696. if (continentSel) continentSel.value = '';
  5697. if (inUseCheck) inUseCheck.checked = false;
  5698. if (cachedCheck) cachedCheck.checked = false;
  5699. if (preset === 'GR') {
  5700. if (searchInput) searchInput.value = 'Greece';
  5701. } else if (preset === 'Europe') {
  5702. if (continentSel) continentSel.value = 'Europe';
  5703. } else if (preset === 'HIGHRISK') {
  5704. if (searchInput) searchInput.value = 'China';
  5705. }
  5706. renderGeoCountries();
  5707. }
  5708. async function toggleGeoCountry(code, enabled) {
  5709. try {
  5710. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/toggle`, {
  5711. method: 'POST',
  5712. headers: { 'Content-Type': 'application/json' },
  5713. body: JSON.stringify({ enabled })
  5714. });
  5715. if (res.ok) {
  5716. showToast(enabled ? 'Country Enabled' : 'Country Disabled', `${code} ${enabled ? 'active in firewall' : 'removed from firewall'}`, 'success');
  5717. loadGeoIP();
  5718. } else {
  5719. const err = await res.json();
  5720. showToast('Error', err.message || 'Failed to toggle country', 'error');
  5721. }
  5722. } catch (err) {
  5723. showToast('Error', err.message, 'error');
  5724. }
  5725. }
  5726. async function updateGeoCountry(code) {
  5727. try {
  5728. showToast('Syncing Country', `Downloading latest IP blocks for ${code}...`, 'info');
  5729. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/update`, { method: 'POST' });
  5730. if (res.ok) {
  5731. const data = await res.json();
  5732. showToast('Synced', `Loaded ${data.subnets} CIDR blocks for ${code}`, 'success');
  5733. loadGeoIP();
  5734. } else {
  5735. const err = await res.json();
  5736. showToast('Sync Error', err.message || 'Failed to sync country', 'error');
  5737. }
  5738. } catch (err) {
  5739. showToast('Error', err.message, 'error');
  5740. }
  5741. }
  5742. async function triggerGeoUpdateNow() {
  5743. const spinner = document.getElementById('geo-update-spinner');
  5744. if (spinner) spinner.classList.remove('hidden');
  5745. try {
  5746. const res = await fetch(`${API_BASE}/firewall/geoip/update-now`, { method: 'POST' });
  5747. if (res.ok) {
  5748. showToast('Update Started', 'Updating all active GeoIP country zones in background...', 'info');
  5749. setTimeout(() => {
  5750. loadGeoIP();
  5751. if (spinner) spinner.classList.add('hidden');
  5752. }, 2500);
  5753. } else {
  5754. const err = await res.json();
  5755. showToast('Notice', err.message || 'Update in progress', 'info');
  5756. if (spinner) spinner.classList.add('hidden');
  5757. }
  5758. } catch (err) {
  5759. showToast('Error', err.message, 'error');
  5760. if (spinner) spinner.classList.add('hidden');
  5761. }
  5762. }
  5763. async function applyGeoPreset(preset) {
  5764. try {
  5765. const res = await fetch(`${API_BASE}/firewall/geoip/batch-toggle`, {
  5766. method: 'POST',
  5767. headers: { 'Content-Type': 'application/json' },
  5768. body: JSON.stringify({ preset, enabled: preset !== 'NONE' })
  5769. });
  5770. if (res.ok) {
  5771. showToast('Preset Applied', `Preset ${preset} updated in firewall`, 'success');
  5772. loadGeoIP();
  5773. }
  5774. } catch (err) {
  5775. showToast('Error', err.message, 'error');
  5776. }
  5777. }
  5778. function openGeoIntervalModal() {
  5779. const s = state.geoStatus || {};
  5780. document.getElementById('geo-cfg-autoupdate').checked = s.auto_update !== false;
  5781. const sel = document.getElementById('geo-cfg-interval');
  5782. const customBox = document.getElementById('geo-cfg-custom-box');
  5783. const customHoursInput = document.getElementById('geo-cfg-custom-hours');
  5784. const curHours = s.interval_hours || 24;
  5785. const matchOption = Array.from(sel.options).find(o => parseInt(o.value, 10) === curHours);
  5786. if (matchOption) {
  5787. sel.value = String(curHours);
  5788. customBox.classList.add('hidden');
  5789. } else {
  5790. sel.value = 'custom';
  5791. customHoursInput.value = curHours;
  5792. customBox.classList.remove('hidden');
  5793. }
  5794. document.getElementById('geo-interval-modal').classList.remove('hidden');
  5795. }
  5796. function closeGeoIntervalModal() {
  5797. document.getElementById('geo-interval-modal').classList.add('hidden');
  5798. }
  5799. function toggleCustomGeoInterval() {
  5800. const val = document.getElementById('geo-cfg-interval').value;
  5801. const customBox = document.getElementById('geo-cfg-custom-box');
  5802. if (val === 'custom') {
  5803. customBox.classList.remove('hidden');
  5804. } else {
  5805. customBox.classList.add('hidden');
  5806. }
  5807. }
  5808. async function submitGeoIntervalSettings(e) {
  5809. e.preventDefault();
  5810. const autoUpdate = document.getElementById('geo-cfg-autoupdate').checked;
  5811. const intervalVal = document.getElementById('geo-cfg-interval').value;
  5812. let hours = 24;
  5813. if (intervalVal === 'custom') {
  5814. hours = parseInt(document.getElementById('geo-cfg-custom-hours').value, 10) || 24;
  5815. } else {
  5816. hours = parseInt(intervalVal, 10) || 24;
  5817. }
  5818. try {
  5819. const res = await fetch(`${API_BASE}/firewall/geoip/config`, {
  5820. method: 'POST',
  5821. headers: { 'Content-Type': 'application/json' },
  5822. body: JSON.stringify({ auto_update: autoUpdate, interval_hours: hours })
  5823. });
  5824. if (res.ok) {
  5825. showToast('Schedule Saved', `Auto-update set to every ${hours} hours`, 'success');
  5826. closeGeoIntervalModal();
  5827. loadGeoIP();
  5828. } else {
  5829. const err = await res.json();
  5830. showToast('Error', err.message || 'Failed to save schedule', 'error');
  5831. }
  5832. } catch (err) {
  5833. showToast('Error', err.message, 'error');
  5834. }
  5835. }
  5836. async function viewGeoSubnets(code, name) {
  5837. if (!name) {
  5838. const found = (state.geoCountries || []).find(x => x.code === code);
  5839. name = found ? found.name : code;
  5840. }
  5841. document.getElementById('geo-subnets-title').innerText = `${name} (${code}) Subnets`;
  5842. document.getElementById('geo-subnets-subtitle').innerText = `Kernel IPSet: mk_geo_${code}`;
  5843. const listEl = document.getElementById('geo-subnets-list');
  5844. listEl.innerHTML = '<span class="text-slate-500">Loading subnets...</span>';
  5845. document.getElementById('geo-subnets-modal').classList.remove('hidden');
  5846. try {
  5847. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/subnets`);
  5848. if (res.ok) {
  5849. const data = await res.json();
  5850. const subnets = data.subnets || [];
  5851. if (subnets.length === 0) {
  5852. listEl.innerHTML = '<span class="text-slate-500">No cached subnets found. Click Sync to download this zone.</span>';
  5853. } else {
  5854. listEl.innerHTML = subnets.map(s => `<div>${s}</div>`).join('');
  5855. }
  5856. } else {
  5857. listEl.innerHTML = '<span class="text-rose-400">Failed to load subnets.</span>';
  5858. }
  5859. } catch (err) {
  5860. listEl.innerHTML = `<span class="text-rose-400">Error: ${err.message}</span>`;
  5861. }
  5862. }
  5863. function closeGeoSubnetsModal() {
  5864. document.getElementById('geo-subnets-modal').classList.add('hidden');
  5865. }
  5866. // ----------------- Active Connections Tracking -----------------
  5867. async function loadConnections() {
  5868. try {
  5869. const res = await fetch(`${API_BASE}/firewall/connections`);
  5870. const data = await res.json();
  5871. state.connections = Array.isArray(data) ? data : [];
  5872. document.getElementById('fw-badge-connections').innerText = state.connections.length;
  5873. document.getElementById('conns-count-badge').innerText = `${state.connections.length} Flows`;
  5874. renderConnections();
  5875. } catch (err) {
  5876. console.error('Failed to load connections:', err);
  5877. }
  5878. }
  5879. function renderConnections() {
  5880. const search = (document.getElementById('conns-search-input')?.value || '').toLowerCase();
  5881. const protoFilter = document.getElementById('conns-filter-proto')?.value || '';
  5882. const tbody = document.getElementById('conns-table-body');
  5883. const empty = document.getElementById('conns-empty');
  5884. if (!tbody) return;
  5885. tbody.innerHTML = '';
  5886. const conns = (state.connections || []).filter(c => {
  5887. if (protoFilter && c.protocol !== protoFilter) return false;
  5888. if (search) {
  5889. const line = `${c.protocol} ${c.src_address} ${c.dst_address} ${c.src_port} ${c.dst_port} ${c.tcp_state} ${c.connection_mark}`.toLowerCase();
  5890. if (!line.includes(search)) return false;
  5891. }
  5892. return true;
  5893. });
  5894. if (conns.length === 0) {
  5895. empty?.classList.remove('hidden');
  5896. return;
  5897. }
  5898. empty?.classList.add('hidden');
  5899. conns.slice(0, 150).forEach(c => {
  5900. const tr = document.createElement('tr');
  5901. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  5902. let stateColor = 'text-slate-400';
  5903. if (c.tcp_state === 'ESTABLISHED') stateColor = 'text-emerald-400 font-bold';
  5904. else if (c.tcp_state === 'TIME_WAIT' || c.tcp_state === 'SYN_SENT') stateColor = 'text-amber-400';
  5905. tr.innerHTML = `
  5906. <td class="py-2.5 px-3 font-bold text-cyan-400">${c.protocol}</td>
  5907. <td class="py-2.5 px-3 font-mono text-white">${c.src_address}:${c.src_port}</td>
  5908. <td class="py-2.5 px-3 font-mono text-white">${c.dst_address}:${c.dst_port}</td>
  5909. <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>
  5910. <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>
  5911. <td class="py-2.5 px-3 font-mono ${stateColor}">${c.tcp_state}</td>
  5912. <td class="py-2.5 px-3 font-mono text-purple-300">${c.connection_mark || '-'}</td>
  5913. <td class="py-2.5 px-3 text-slate-500">${c.timeout ? c.timeout + 's' : '-'}</td>
  5914. <td class="py-2.5 px-3 text-right font-sans">
  5915. <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>
  5916. </td>
  5917. `;
  5918. tbody.appendChild(tr);
  5919. });
  5920. }
  5921. async function killConnection(protocol, src, sport, dst, dport) {
  5922. try {
  5923. const res = await fetch(`${API_BASE}/firewall/connections/kill`, {
  5924. method: 'POST',
  5925. headers: { 'Content-Type': 'application/json' },
  5926. body: JSON.stringify({ protocol, src, sport, dst, dport })
  5927. });
  5928. if (res.ok) {
  5929. showToast('Terminated', `Killed flow ${src}:${sport} -> ${dst}:${dport}`, 'info');
  5930. loadConnections();
  5931. }
  5932. } catch (err) {
  5933. showToast('Error', err.message, 'error');
  5934. }
  5935. }
  5936. async function resetFirewallCounters() {
  5937. if (!confirm('Reset all firewall packet and byte counters to zero?')) return;
  5938. try {
  5939. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  5940. if (res.ok) {
  5941. showToast('Counters Reset', 'All rules counters reset to 0', 'success');
  5942. loadFirewall(false);
  5943. }
  5944. } catch (err) {
  5945. showToast('Error', err.message, 'error');
  5946. }
  5947. }
  5948. // ======================== MIKROTIK ROUTING & POLICY (/ip route) ========================
  5949. function switchRoutesSubTab(tab) {
  5950. state.routesSubTab = tab;
  5951. const tabs = ['routes', 'rules', 'tables'];
  5952. tabs.forEach(t => {
  5953. const panel = document.getElementById(`routes-subtab-${t}`);
  5954. const btn = document.getElementById(`routes-subtab-btn-${t}`);
  5955. if (panel) {
  5956. if (t === tab) panel.classList.remove('hidden');
  5957. else panel.classList.add('hidden');
  5958. }
  5959. if (btn) {
  5960. if (t === tab) {
  5961. 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';
  5962. } else {
  5963. 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';
  5964. }
  5965. }
  5966. });
  5967. setTimeout(initTableSorting, 50);
  5968. }
  5969. async function loadRoutes() {
  5970. try {
  5971. const [routesRes, rulesRes, tablesRes] = await Promise.all([
  5972. fetch(`${API_BASE}/routes`),
  5973. fetch(`${API_BASE}/routing/rules`),
  5974. fetch(`${API_BASE}/routing/tables`)
  5975. ]);
  5976. if (routesRes.ok) state.routes = await routesRes.json();
  5977. if (rulesRes.ok) state.policyRules = await rulesRes.json();
  5978. if (tablesRes.ok) state.routingTables = await tablesRes.json();
  5979. const bRoutes = document.getElementById('routes-badge-routes');
  5980. if (bRoutes) bRoutes.innerText = (state.routes || []).length;
  5981. const showSystem = document.getElementById('prule-show-system')?.checked;
  5982. const userRules = (state.policyRules || []).filter(pr => showSystem || (!pr.is_default && !pr.is_system));
  5983. const bRules = document.getElementById('routes-badge-rules');
  5984. if (bRules) bRules.innerText = userRules.length;
  5985. const bTables = document.getElementById('routes-badge-tables');
  5986. if (bTables) bTables.innerText = (state.routingTables || []).length;
  5987. const bRoutesCount = document.getElementById('badge-routes-count');
  5988. if (bRoutesCount) bRoutesCount.innerText = (state.routes || []).length;
  5989. renderRoutesList();
  5990. renderPolicyRules();
  5991. renderRoutingTables();
  5992. } catch (err) {
  5993. console.error('Failed to load routing:', err);
  5994. }
  5995. }
  5996. function getRouteProtocolBadge(proto) {
  5997. const p = (proto || 'static').toLowerCase();
  5998. switch (p) {
  5999. case 'bgp':
  6000. 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>`;
  6001. case 'ibgp':
  6002. 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>`;
  6003. case 'ospf':
  6004. 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>`;
  6005. case 'rip':
  6006. 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>`;
  6007. case 'static':
  6008. 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>`;
  6009. case 'connected':
  6010. 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>`;
  6011. case 'dhcp':
  6012. 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>`;
  6013. case 'multicast':
  6014. 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>`;
  6015. default:
  6016. 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>`;
  6017. }
  6018. }
  6019. function renderRoutesList() {
  6020. const tableFilter = document.getElementById('routes-filter-table')?.value || '';
  6021. const typeFilter = document.getElementById('routes-filter-type')?.value || '';
  6022. const tbody = document.getElementById('routes-table-body');
  6023. const empty = document.getElementById('routes-empty');
  6024. if (!tbody) return;
  6025. // Update table filter select
  6026. const sel = document.getElementById('routes-filter-table');
  6027. if (sel) {
  6028. const cur = sel.value;
  6029. sel.innerHTML = '<option value="">All Tables</option>';
  6030. (state.routingTables || []).forEach(t => {
  6031. const opt = document.createElement('option');
  6032. opt.value = t.name;
  6033. opt.innerText = t.name;
  6034. if (t.name === cur) opt.selected = true;
  6035. sel.appendChild(opt);
  6036. });
  6037. }
  6038. const routes = (state.routes || []).filter(r => {
  6039. if (tableFilter && r.routing_table !== tableFilter) return false;
  6040. if (typeFilter === 'ecmp' && !r.ecmp) return false;
  6041. if (typeFilter === 'multicast' && !r.multicast) return false;
  6042. if (typeFilter === 'static' && !r.static) return false;
  6043. if (typeFilter === 'dynamic' && !r.dynamic) return false;
  6044. if (typeFilter === 'connected' && !r.connect) return false;
  6045. if (typeFilter === 'bgp' && (r.protocol || '').toLowerCase() !== 'bgp' && (r.protocol || '').toLowerCase() !== 'ibgp') return false;
  6046. if (typeFilter === 'ospf' && (r.protocol || '').toLowerCase() !== 'ospf') return false;
  6047. if (typeFilter === 'dhcp' && (r.protocol || '').toLowerCase() !== 'dhcp') return false;
  6048. return true;
  6049. });
  6050. const ecmpCount = (state.routes || []).filter(r => r.ecmp).length;
  6051. const mcCount = (state.routes || []).filter(r => r.multicast).length;
  6052. let summaryText = `${routes.length} Routes`;
  6053. if (ecmpCount > 0) summaryText += ` • ${ecmpCount} ECMP`;
  6054. if (mcCount > 0) summaryText += ` • ${mcCount} Multicast/IGMP`;
  6055. const badgeEl = document.getElementById('routes-count-badge');
  6056. if (badgeEl) badgeEl.innerText = summaryText;
  6057. if (routes.length === 0) {
  6058. empty?.classList.remove('hidden');
  6059. tbody.innerHTML = '';
  6060. return;
  6061. }
  6062. empty?.classList.add('hidden');
  6063. 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(';');
  6064. if (tbody.dataset.sig === sig) {
  6065. return; // Routes table unchanged! Do not wipe DOM or flicker!
  6066. }
  6067. tbody.dataset.sig = sig;
  6068. tbody.innerHTML = '';
  6069. routes.forEach(r => {
  6070. const tr = document.createElement('tr');
  6071. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${r.disabled ? 'opacity-50' : ''}`;
  6072. tr.setAttribute('ondblclick', `openEditRouteModal('${r.id}')`);
  6073. // Routing Flags string: D=Dynamic, A=Active, C=Connect, S=Static, E=ECMP, M=Multicast, X=Disabled
  6074. let flags = '';
  6075. if (r.dynamic) flags += 'D';
  6076. if (r.active) flags += 'A';
  6077. if (r.connect) flags += 'C';
  6078. if (r.static) flags += 'S';
  6079. if (r.ecmp) flags += 'E';
  6080. if (r.multicast) flags += 'M';
  6081. if (r.disabled) flags += 'X';
  6082. const isDefault = r.dst_address === 'default' || r.dst_address === '0.0.0.0/0';
  6083. let healthCell = `<span class="text-slate-600 font-mono text-[11px]">-</span>`;
  6084. if (r.check_gateway === 'internet') {
  6085. if (r.health_status === 'online') {
  6086. const ms = (r.health_rtt_ms || 0).toFixed(0);
  6087. healthCell = `
  6088. <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)">
  6089. <span class="w-1.5 h-1.5 rounded-full bg-emerald-400 animate-pulse"></span>
  6090. <span>Internet OK (${ms}ms)</span>
  6091. </span>
  6092. `;
  6093. } else if (r.health_status === 'offline') {
  6094. healthCell = `
  6095. <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.">
  6096. <span class="w-1.5 h-1.5 rounded-full bg-rose-400"></span>
  6097. <span>Internet Down</span>
  6098. </span>
  6099. `;
  6100. } else {
  6101. healthCell = `
  6102. <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">
  6103. <span class="w-1.5 h-1.5 rounded-full bg-amber-400 animate-ping"></span>
  6104. <span>Checking...</span>
  6105. </span>
  6106. `;
  6107. }
  6108. } else if (r.check_gateway === 'ping') {
  6109. if (r.health_status === 'online') {
  6110. healthCell = `
  6111. <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">
  6112. <span class="w-1.5 h-1.5 rounded-full bg-cyan-400"></span>
  6113. <span>Gateway OK (${(r.health_rtt_ms || 0).toFixed(0)}ms)</span>
  6114. </span>
  6115. `;
  6116. } else if (r.health_status === 'offline') {
  6117. healthCell = `
  6118. <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">
  6119. <span class="w-1.5 h-1.5 rounded-full bg-rose-400"></span>
  6120. <span>Gateway Dead</span>
  6121. </span>
  6122. `;
  6123. }
  6124. }
  6125. const flagDescriptions = [];
  6126. if (r.dynamic) flagDescriptions.push('Dynamic (D)');
  6127. if (r.active) flagDescriptions.push('Active (A)');
  6128. if (r.connect) flagDescriptions.push('Connected (C)');
  6129. if (r.static) flagDescriptions.push('Static (S)');
  6130. if (r.ecmp) flagDescriptions.push('ECMP - Equal-Cost Multi-Path (E)');
  6131. if (r.multicast) flagDescriptions.push('Multicast / IGMP Group (M)');
  6132. if (r.disabled) flagDescriptions.push('Disabled (X)');
  6133. tr.innerHTML = `
  6134. <td class="py-2.5 px-3 text-center">
  6135. <span class="px-1.5 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 ${
  6136. 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')
  6137. }" title="Flags: ${flagDescriptions.join(', ')}">
  6138. ${flags || '-'}
  6139. </span>
  6140. </td>
  6141. <td class="py-2.5 px-3">
  6142. <div class="flex items-center gap-1.5 flex-wrap">
  6143. <span class="font-bold ${isDefault ? 'text-cyan-300' : 'text-white'}">${escapeHtml(r.dst_address)}</span>
  6144. ${r.ecmp ? `
  6145. <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)">
  6146. <span>⚡ ECMP</span>
  6147. </span>
  6148. ` : ''}
  6149. ${r.multicast ? `
  6150. <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">
  6151. <span>IGMP</span>
  6152. </span>
  6153. ` : ''}
  6154. </div>
  6155. </td>
  6156. <td class="py-2.5 px-3">${getRouteProtocolBadge(r.protocol)}</td>
  6157. <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>
  6158. <td class="py-2.5 px-3 text-slate-400 font-mono">${(r.distance !== undefined && r.distance !== null) ? r.distance : 0}</td>
  6159. <td class="py-2.5 px-3 font-mono font-semibold text-purple-300">${r.routing_table || 'main'}</td>
  6160. <td class="py-2.5 px-3 text-emerald-400 font-mono">${r.interface || '-'}</td>
  6161. <td class="py-2.5 px-3">${healthCell}</td>
  6162. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]">${r.comment || '-'}</td>
  6163. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  6164. ${r.static ? `
  6165. <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>
  6166. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold">Edit</button>
  6167. <button onclick="deleteRoute('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  6168. ` : `
  6169. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">View</button>
  6170. `}
  6171. </td>
  6172. `;
  6173. tbody.appendChild(tr);
  6174. });
  6175. }
  6176. function openAddRouteModal() {
  6177. document.getElementById('route-modal-title').innerText = 'Add Static Route';
  6178. document.getElementById('route-modal-id').value = '';
  6179. document.getElementById('route-modal-old-dst').value = '';
  6180. document.getElementById('route-modal-old-gw').value = '';
  6181. document.getElementById('route-modal-old-distance').value = '';
  6182. document.getElementById('route-modal-old-table').value = '';
  6183. document.getElementById('route-modal-old-iface').value = '';
  6184. const dstInput = document.getElementById('route-modal-dst');
  6185. const gwInput = document.getElementById('route-modal-gw');
  6186. const distInput = document.getElementById('route-modal-distance');
  6187. const ifaceSelect = document.getElementById('route-modal-iface');
  6188. const tableSelect = document.getElementById('route-modal-table');
  6189. const commentInput = document.getElementById('route-modal-comment');
  6190. const disCheck = document.getElementById('route-modal-disabled');
  6191. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  6192. dstInput.disabled = false;
  6193. dstInput.value = '0.0.0.0/0';
  6194. gwInput.disabled = false;
  6195. gwInput.value = '';
  6196. distInput.disabled = false;
  6197. distInput.value = '1';
  6198. ifaceSelect.disabled = false;
  6199. tableSelect.disabled = false;
  6200. commentInput.disabled = false;
  6201. commentInput.value = '';
  6202. disCheck.disabled = false;
  6203. disCheck.checked = false;
  6204. if (saveBtn) saveBtn.classList.remove('hidden');
  6205. const checkGw = document.getElementById('route-modal-check-gw');
  6206. if (checkGw) checkGw.value = 'internet';
  6207. const checkTarget = document.getElementById('route-modal-check-target');
  6208. if (checkTarget) checkTarget.value = '1.1.1.1';
  6209. const checkInterval = document.getElementById('route-modal-check-interval');
  6210. if (checkInterval) checkInterval.value = '5';
  6211. const checkThresh = document.getElementById('route-modal-check-threshold');
  6212. if (checkThresh) checkThresh.value = '3';
  6213. toggleRouteCheckModeUI();
  6214. populateInterfaceSelect('route-modal-iface');
  6215. // Populate tables
  6216. tableSelect.innerHTML = '';
  6217. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  6218. const opt = document.createElement('option');
  6219. opt.value = t.name;
  6220. opt.innerText = t.name;
  6221. if (t.name === 'main') opt.selected = true;
  6222. tableSelect.appendChild(opt);
  6223. });
  6224. document.getElementById('route-modal').classList.remove('hidden');
  6225. }
  6226. function openEditRouteModal(id) {
  6227. const r = (state.routes || []).find(route => route.id === id);
  6228. if (!r) return;
  6229. const isStatic = !!r.static;
  6230. document.getElementById('route-modal-title').innerText = isStatic
  6231. ? `Edit Route: ${r.dst_address}`
  6232. : `Route Properties (Read Only): ${r.dst_address}`;
  6233. document.getElementById('route-modal-id').value = r.id;
  6234. document.getElementById('route-modal-old-dst').value = r.dst_address || '';
  6235. document.getElementById('route-modal-old-gw').value = r.gateway || '';
  6236. document.getElementById('route-modal-old-distance').value = (r.distance !== undefined && r.distance !== null) ? r.distance : '';
  6237. document.getElementById('route-modal-old-table').value = r.routing_table || 'main';
  6238. document.getElementById('route-modal-old-iface').value = r.interface || '';
  6239. const dstInput = document.getElementById('route-modal-dst');
  6240. const gwInput = document.getElementById('route-modal-gw');
  6241. const distInput = document.getElementById('route-modal-distance');
  6242. const ifaceSelect = document.getElementById('route-modal-iface');
  6243. const tableSelect = document.getElementById('route-modal-table');
  6244. const commentInput = document.getElementById('route-modal-comment');
  6245. const disCheck = document.getElementById('route-modal-disabled');
  6246. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  6247. dstInput.value = r.dst_address;
  6248. gwInput.value = r.gateway || '';
  6249. distInput.value = (r.distance !== undefined && r.distance !== null) ? r.distance : 1;
  6250. commentInput.value = r.comment || '';
  6251. disCheck.checked = !!r.disabled;
  6252. const checkGw = document.getElementById('route-modal-check-gw');
  6253. if (checkGw) checkGw.value = r.check_gateway || 'none';
  6254. const checkTarget = document.getElementById('route-modal-check-target');
  6255. if (checkTarget) checkTarget.value = r.check_target || '1.1.1.1';
  6256. const checkInterval = document.getElementById('route-modal-check-interval');
  6257. if (checkInterval) checkInterval.value = r.check_interval || 5;
  6258. const checkThresh = document.getElementById('route-modal-check-threshold');
  6259. if (checkThresh) checkThresh.value = r.check_threshold || 3;
  6260. toggleRouteCheckModeUI();
  6261. dstInput.disabled = !isStatic;
  6262. gwInput.disabled = !isStatic;
  6263. distInput.disabled = !isStatic;
  6264. ifaceSelect.disabled = !isStatic;
  6265. tableSelect.disabled = !isStatic;
  6266. commentInput.disabled = !isStatic;
  6267. disCheck.disabled = !isStatic;
  6268. if (checkGw) checkGw.disabled = !isStatic;
  6269. if (checkTarget) checkTarget.disabled = !isStatic;
  6270. if (checkInterval) checkInterval.disabled = !isStatic;
  6271. if (checkThresh) checkThresh.disabled = !isStatic;
  6272. if (saveBtn) {
  6273. if (isStatic) {
  6274. saveBtn.classList.remove('hidden');
  6275. } else {
  6276. saveBtn.classList.add('hidden');
  6277. }
  6278. }
  6279. populateInterfaceSelect('route-modal-iface', r.interface);
  6280. tableSelect.innerHTML = '';
  6281. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  6282. const opt = document.createElement('option');
  6283. opt.value = t.name;
  6284. opt.innerText = t.name;
  6285. if (t.name === (r.routing_table || 'main')) opt.selected = true;
  6286. tableSelect.appendChild(opt);
  6287. });
  6288. document.getElementById('route-modal').classList.remove('hidden');
  6289. }
  6290. function closeRouteModal() {
  6291. document.getElementById('route-modal').classList.add('hidden');
  6292. }
  6293. function setRouteCheckTarget(ip) {
  6294. const inp = document.getElementById('route-modal-check-target');
  6295. if (inp) inp.value = ip;
  6296. }
  6297. function toggleRouteCheckModeUI() {
  6298. const mode = document.getElementById('route-modal-check-gw')?.value || 'none';
  6299. const targetRow = document.getElementById('route-row-check-target');
  6300. const paramsRow = document.getElementById('route-row-check-params');
  6301. if (mode === 'none') {
  6302. if (targetRow) targetRow.classList.add('opacity-40', 'pointer-events-none');
  6303. if (paramsRow) paramsRow.classList.add('opacity-40', 'pointer-events-none');
  6304. } else if (mode === 'ping') {
  6305. if (targetRow) targetRow.classList.add('opacity-40', 'pointer-events-none');
  6306. if (paramsRow) paramsRow.classList.remove('opacity-40', 'pointer-events-none');
  6307. } else { // internet
  6308. if (targetRow) targetRow.classList.remove('opacity-40', 'pointer-events-none');
  6309. if (paramsRow) paramsRow.classList.remove('opacity-40', 'pointer-events-none');
  6310. }
  6311. }
  6312. async function submitSaveRoute(e) {
  6313. e.preventDefault();
  6314. const id = document.getElementById('route-modal-id').value;
  6315. const oldDst = document.getElementById('route-modal-old-dst')?.value || '';
  6316. const oldGw = document.getElementById('route-modal-old-gw')?.value || '';
  6317. const oldDistStr = document.getElementById('route-modal-old-distance')?.value;
  6318. const oldTable = document.getElementById('route-modal-old-table')?.value || '';
  6319. const oldIface = document.getElementById('route-modal-old-iface')?.value || '';
  6320. const dst = document.getElementById('route-modal-dst').value.trim();
  6321. const gw = document.getElementById('route-modal-gw').value.trim();
  6322. const table = document.getElementById('route-modal-table').value;
  6323. const distance = parseInt(document.getElementById('route-modal-distance').value, 10) || 0;
  6324. const iface = document.getElementById('route-modal-iface').value;
  6325. const comment = document.getElementById('route-modal-comment').value.trim();
  6326. const disabled = document.getElementById('route-modal-disabled').checked;
  6327. const check_gateway = document.getElementById('route-modal-check-gw')?.value || 'none';
  6328. const check_target = document.getElementById('route-modal-check-target')?.value.trim() || '1.1.1.1';
  6329. const check_interval = parseInt(document.getElementById('route-modal-check-interval')?.value, 10) || 5;
  6330. const check_threshold = parseInt(document.getElementById('route-modal-check-threshold')?.value, 10) || 3;
  6331. if (!dst) {
  6332. showToast('Error', 'Destination address is required', 'error');
  6333. return;
  6334. }
  6335. if (!gw && !iface) {
  6336. showToast('Error', 'Either Gateway IP or Interface must be specified', 'error');
  6337. return;
  6338. }
  6339. const payload = {
  6340. id,
  6341. old_dst_address: oldDst,
  6342. old_gateway: oldGw,
  6343. old_routing_table: oldTable,
  6344. old_interface: oldIface,
  6345. dst_address: dst,
  6346. gateway: gw || iface,
  6347. routing_table: table,
  6348. distance,
  6349. interface: iface,
  6350. comment,
  6351. disabled,
  6352. check_gateway,
  6353. check_target,
  6354. check_interval,
  6355. check_threshold
  6356. };
  6357. if (oldDistStr !== undefined && oldDistStr !== '') {
  6358. payload.old_distance = parseInt(oldDistStr, 10);
  6359. }
  6360. try {
  6361. const res = await fetch(`${API_BASE}/routes`, {
  6362. method: 'POST',
  6363. headers: { 'Content-Type': 'application/json' },
  6364. body: JSON.stringify(payload)
  6365. });
  6366. if (res.ok) {
  6367. showToast('Route Saved', `Route to ${dst} installed`, 'success');
  6368. closeRouteModal();
  6369. loadRoutes();
  6370. } else {
  6371. const err = await res.json();
  6372. showToast('Error', err.message || 'Failed to save route', 'error');
  6373. }
  6374. } catch (err) {
  6375. showToast('Error', err.message, 'error');
  6376. }
  6377. }
  6378. async function toggleRouteState(id, disabled) {
  6379. try {
  6380. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}/state`, {
  6381. method: 'POST',
  6382. headers: { 'Content-Type': 'application/json' },
  6383. body: JSON.stringify({ disabled })
  6384. });
  6385. if (res.ok) loadRoutes();
  6386. } catch (err) {
  6387. showToast('Error', err.message, 'error');
  6388. }
  6389. }
  6390. async function deleteRoute(id) {
  6391. if (!confirm('Are you sure you want to delete this route?')) return;
  6392. try {
  6393. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6394. if (res.ok) {
  6395. showToast('Deleted', 'Route removed', 'success');
  6396. loadRoutes();
  6397. }
  6398. } catch (err) {
  6399. showToast('Error', err.message, 'error');
  6400. }
  6401. }
  6402. // ----------------- Policy Rules (/ip route rule) -----------------
  6403. function renderPolicyRules() {
  6404. const tbody = document.getElementById('rules-table-body');
  6405. const empty = document.getElementById('rules-empty');
  6406. if (!tbody) return;
  6407. const showSystem = document.getElementById('prule-show-system')?.checked;
  6408. const filtered = (state.policyRules || []).filter(pr => showSystem || (!pr.is_default && !pr.is_system));
  6409. const countBadge = document.getElementById('rules-count-badge');
  6410. if (countBadge) countBadge.innerText = `${filtered.length} Rules`;
  6411. const bRules = document.getElementById('routes-badge-rules');
  6412. if (bRules) bRules.innerText = filtered.length;
  6413. if (filtered.length === 0) {
  6414. empty?.classList.remove('hidden');
  6415. tbody.innerHTML = '';
  6416. return;
  6417. }
  6418. empty?.classList.add('hidden');
  6419. const sig = `${showSystem}|` + filtered.map(pr => `${pr.id}:${pr.priority}:${pr.src_address}:${pr.dst_address}:${pr.table}:${pr.routing_mark}`).join(';');
  6420. if (tbody.dataset.sig === sig) return;
  6421. tbody.dataset.sig = sig;
  6422. tbody.innerHTML = '';
  6423. filtered.forEach(pr => {
  6424. const isSys = pr.is_default || pr.is_system;
  6425. const tr = document.createElement('tr');
  6426. tr.className = `hover:bg-slate-800/40 transition text-xs ${isSys ? 'opacity-70 bg-slate-950/20' : ''}`;
  6427. tr.innerHTML = `
  6428. <td class="py-2.5 px-3 font-mono text-cyan-400 font-bold">${pr.priority}</td>
  6429. <td class="py-2.5 px-3 font-mono text-white">${pr.src_address || '<span class="text-slate-600">all</span>'}</td>
  6430. <td class="py-2.5 px-3 font-mono text-white">${pr.dst_address || '<span class="text-slate-600">all</span>'}</td>
  6431. <td class="py-2.5 px-3 font-mono font-bold text-purple-300">${pr.routing_mark || '<span class="text-slate-600">-</span>'}</td>
  6432. <td class="py-2.5 px-3 font-mono font-bold text-amber-300">${pr.table}</td>
  6433. <td class="py-2.5 px-3 font-mono text-slate-300">${pr.action}</td>
  6434. <td class="py-2.5 px-3 text-right font-sans">
  6435. ${!pr.is_default ? `
  6436. <button onclick="deletePolicyRule('${pr.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  6437. ` : `<span class="text-slate-600 text-[10px]">Default</span>`}
  6438. </td>
  6439. `;
  6440. tbody.appendChild(tr);
  6441. });
  6442. }
  6443. function openAddPolicyRuleModal() {
  6444. const userRules = (state.policyRules || []).filter(pr => !pr.is_default && !pr.is_system);
  6445. document.getElementById('prule-modal-pref').value = userRules.length * 10 + 1000;
  6446. document.getElementById('prule-modal-mark').value = '';
  6447. document.getElementById('prule-modal-src').value = '';
  6448. document.getElementById('prule-modal-dst').value = '';
  6449. const sel = document.getElementById('prule-modal-table');
  6450. sel.innerHTML = '';
  6451. (state.routingTables || []).forEach(t => {
  6452. const opt = document.createElement('option');
  6453. opt.value = t.name;
  6454. opt.innerText = t.name;
  6455. sel.appendChild(opt);
  6456. });
  6457. document.getElementById('prule-modal').classList.remove('hidden');
  6458. }
  6459. function closePolicyRuleModal() {
  6460. document.getElementById('prule-modal').classList.add('hidden');
  6461. }
  6462. async function submitSavePolicyRule(e) {
  6463. e.preventDefault();
  6464. const pref = parseInt(document.getElementById('prule-modal-pref').value, 10) || 1000;
  6465. const mark = document.getElementById('prule-modal-mark').value.trim();
  6466. const src = document.getElementById('prule-modal-src').value.trim();
  6467. const dst = document.getElementById('prule-modal-dst').value.trim();
  6468. const table = document.getElementById('prule-modal-table').value;
  6469. const action = document.getElementById('prule-modal-action').value;
  6470. try {
  6471. const res = await fetch(`${API_BASE}/routing/rules`, {
  6472. method: 'POST',
  6473. headers: { 'Content-Type': 'application/json' },
  6474. body: JSON.stringify({ priority: pref, routing_mark: mark, src_address: src, dst_address: dst, table, action })
  6475. });
  6476. if (res.ok) {
  6477. showToast('Rule Added', `Policy rule installed for table ${table}`, 'success');
  6478. closePolicyRuleModal();
  6479. loadRoutes();
  6480. } else {
  6481. const err = await res.json();
  6482. showToast('Error', err.message, 'error');
  6483. }
  6484. } catch (err) {
  6485. showToast('Error', err.message, 'error');
  6486. }
  6487. }
  6488. async function deletePolicyRule(id) {
  6489. if (!confirm('Are you sure you want to remove this policy rule?')) return;
  6490. try {
  6491. const res = await fetch(`${API_BASE}/routing/rules/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6492. if (res.ok) {
  6493. showToast('Rule Removed', 'Policy rule deleted', 'success');
  6494. loadRoutes();
  6495. }
  6496. } catch (err) {
  6497. showToast('Error', err.message, 'error');
  6498. }
  6499. }
  6500. // ----------------- Routing Tables -----------------
  6501. function renderRoutingTables() {
  6502. const tbody = document.getElementById('tables-table-body');
  6503. if (!tbody) return;
  6504. const tables = state.routingTables || [];
  6505. const sig = tables.map(t => `${t.table_id}:${t.name}:${t.comment}`).join(';');
  6506. if (tbody.dataset.sig === sig) return;
  6507. tbody.dataset.sig = sig;
  6508. tbody.innerHTML = '';
  6509. (state.routingTables || []).forEach(t => {
  6510. const tr = document.createElement('tr');
  6511. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  6512. tr.innerHTML = `
  6513. <td class="py-2.5 px-3 text-cyan-400 font-bold">${t.table_id}</td>
  6514. <td class="py-2.5 px-3 font-bold text-white">${t.name}</td>
  6515. <td class="py-2.5 px-3 text-slate-400 italic">${t.comment || '-'}</td>
  6516. `;
  6517. tbody.appendChild(tr);
  6518. });
  6519. }
  6520. function openAddTableModal() {
  6521. document.getElementById('table-modal-name').value = '';
  6522. document.getElementById('table-modal-id').value = '';
  6523. document.getElementById('table-modal-comment').value = '';
  6524. document.getElementById('table-modal').classList.remove('hidden');
  6525. }
  6526. function closeTableModal() {
  6527. document.getElementById('table-modal').classList.add('hidden');
  6528. }
  6529. async function submitSaveTable(e) {
  6530. e.preventDefault();
  6531. const name = document.getElementById('table-modal-name').value.trim();
  6532. const id = parseInt(document.getElementById('table-modal-id').value, 10) || 0;
  6533. const comment = document.getElementById('table-modal-comment').value.trim();
  6534. try {
  6535. const res = await fetch(`${API_BASE}/routing/tables`, {
  6536. method: 'POST',
  6537. headers: { 'Content-Type': 'application/json' },
  6538. body: JSON.stringify({ name, table_id: id, comment })
  6539. });
  6540. if (res.ok) {
  6541. showToast('Table Created', `Routing table ${name} registered`, 'success');
  6542. closeTableModal();
  6543. loadRoutes();
  6544. } else {
  6545. const err = await res.json();
  6546. showToast('Error', err.message, 'error');
  6547. }
  6548. } catch (err) {
  6549. showToast('Error', err.message, 'error');
  6550. }
  6551. }
  6552. async function loadDebianConfig() {
  6553. const view = document.getElementById('debian-config-view');
  6554. view.innerText = 'Generating live configuration...';
  6555. try {
  6556. const res = await fetch(`${API_BASE}/debian/config`);
  6557. const data = await res.json();
  6558. view.innerText = data.content || '# Empty config';
  6559. } catch (err) {
  6560. view.innerText = 'Failed to generate Debian network config.';
  6561. }
  6562. }
  6563. async function saveDebianConfig() {
  6564. try {
  6565. const res = await fetch(`${API_BASE}/debian/apply`, { method: 'POST' });
  6566. const data = await res.json();
  6567. if (res.ok) {
  6568. showToast('Configuration Saved', data.message || 'Saved to /etc/network/interfaces.d/vlans.cfg', 'success');
  6569. loadDebianConfig();
  6570. }
  6571. } catch (err) {
  6572. showToast('Error', err.message, 'error');
  6573. }
  6574. }
  6575. function showToast(title, message, type = 'info') {
  6576. const container = document.getElementById('toast-container');
  6577. const toast = document.createElement('div');
  6578. const borderColors = {
  6579. success: 'border-emerald-500/40 bg-slate-900/95 text-emerald-400',
  6580. error: 'border-rose-500/40 bg-slate-900/95 text-rose-400',
  6581. info: 'border-cyan-500/40 bg-slate-900/95 text-cyan-400'
  6582. };
  6583. 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}`;
  6584. toast.innerHTML = `
  6585. <div class="flex-1">
  6586. <div class="font-bold text-xs text-white">${title}</div>
  6587. <div class="text-[11px] text-slate-300 mt-0.5 leading-relaxed font-sans">${message}</div>
  6588. </div>
  6589. `;
  6590. container.appendChild(toast);
  6591. requestAnimationFrame(() => toast.classList.remove('translate-y-2', 'opacity-0'));
  6592. setTimeout(() => {
  6593. toast.classList.add('opacity-0', 'translate-y-2');
  6594. setTimeout(() => toast.remove(), 300);
  6595. }, 4000);
  6596. }
  6597. function formatTraffic(bytesPerSec) {
  6598. if (bytesPerSec < 1024) return `${Math.round(bytesPerSec)} B/s`;
  6599. const kb = bytesPerSec / 1024;
  6600. if (kb < 1024) return `${kb.toFixed(1)} KB/s`;
  6601. const mb = kb / 1024;
  6602. return `${mb.toFixed(2)} MB/s`;
  6603. }
  6604. function toggleSidebar() {
  6605. const sb = document.getElementById('sidebar');
  6606. sb.classList.toggle('-translate-x-full');
  6607. }
  6608. // ======================== EoIP (Ethernet over IP) ========================
  6609. async function loadEoIP(populate = true) {
  6610. try {
  6611. const res = await fetch(`${API_BASE}/vpn/eoip`);
  6612. const data = await res.json();
  6613. state.eoipTunnels = Array.isArray(data) ? data : [];
  6614. const badge = document.getElementById('eoip-count-badge');
  6615. if (badge) badge.innerText = `${state.eoipTunnels.length} Tunnels`;
  6616. const sideBadge = document.getElementById('badge-eoip-count');
  6617. if (sideBadge) sideBadge.innerText = state.eoipTunnels.length;
  6618. renderEoIPTunnels();
  6619. } catch (err) {
  6620. console.error('Failed to load EoIP:', err);
  6621. }
  6622. }
  6623. function renderEoIPTunnels() {
  6624. const tbody = document.getElementById('eoip-table-body');
  6625. const empty = document.getElementById('eoip-empty');
  6626. if (!tbody) return;
  6627. tbody.innerHTML = '';
  6628. const tunnels = state.eoipTunnels || [];
  6629. if (tunnels.length === 0) {
  6630. empty?.classList.remove('hidden');
  6631. return;
  6632. }
  6633. empty?.classList.add('hidden');
  6634. tunnels.forEach(t => {
  6635. const tr = document.createElement('tr');
  6636. tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
  6637. tr.innerHTML = `
  6638. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.running, t.disabled)}</td>
  6639. <td class="py-2.5 px-3 font-bold text-white font-mono">${t.name}</td>
  6640. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${t.tunnel_id}</td>
  6641. <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>
  6642. <td class="py-2.5 px-3 text-cyan-300 font-mono">${t.remote_address}</td>
  6643. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.local_address || '(any)'}</td>
  6644. <td class="py-2.5 px-3 text-slate-300 font-mono text-[11px]">${t.mac_address || '-'}</td>
  6645. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.mtu || 1500}</td>
  6646. <td class="py-2.5 px-3 font-mono text-[11px]">
  6647. <span class="text-emerald-400">↓ ${t.rx_human || '0 B'}</span>
  6648. <span class="text-cyan-400 ml-1">↑ ${t.tx_human || '0 B'}</span>
  6649. </td>
  6650. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${t.comment || ''}">${t.comment || '-'}</td>
  6651. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  6652. <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>
  6653. <button onclick="openEditEoIPModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  6654. <button onclick="deleteEoIP('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  6655. </td>
  6656. `;
  6657. tbody.appendChild(tr);
  6658. });
  6659. }
  6660. function openAddEoIPModal() {
  6661. document.getElementById('eoip-modal-title').innerText = 'Add EoIP Tunnel';
  6662. document.getElementById('eoip-modal-id').value = '';
  6663. document.getElementById('eoip-modal-name').value = `eoip-tunnel${(state.eoipTunnels || []).length + 1}`;
  6664. document.getElementById('eoip-modal-tunnelid').value = (state.eoipTunnels || []).length + 10;
  6665. document.getElementById('eoip-modal-remote').value = '';
  6666. document.getElementById('eoip-modal-ip').value = '';
  6667. document.getElementById('eoip-modal-local').value = '';
  6668. document.getElementById('eoip-modal-mac').value = '';
  6669. document.getElementById('eoip-modal-mtu').value = '1500';
  6670. document.getElementById('eoip-modal-comment').value = '';
  6671. document.getElementById('eoip-modal-clampmss').checked = true;
  6672. document.getElementById('eoip-modal-disabled').checked = false;
  6673. document.getElementById('eoip-modal').classList.remove('hidden');
  6674. }
  6675. function openEditEoIPModal(id) {
  6676. const t = (state.eoipTunnels || []).find(tun => tun.id === id);
  6677. if (!t) return;
  6678. document.getElementById('eoip-modal-title').innerText = `Edit EoIP Tunnel (${t.name})`;
  6679. document.getElementById('eoip-modal-id').value = t.id;
  6680. document.getElementById('eoip-modal-name').value = t.name;
  6681. document.getElementById('eoip-modal-tunnelid').value = t.tunnel_id;
  6682. document.getElementById('eoip-modal-remote').value = t.remote_address;
  6683. document.getElementById('eoip-modal-ip').value = t.ip_address || '';
  6684. document.getElementById('eoip-modal-local').value = t.local_address || '';
  6685. document.getElementById('eoip-modal-mac').value = t.mac_address || '';
  6686. document.getElementById('eoip-modal-mtu').value = t.mtu || 1500;
  6687. document.getElementById('eoip-modal-comment').value = t.comment || '';
  6688. document.getElementById('eoip-modal-clampmss').checked = !!t.clamp_mss;
  6689. document.getElementById('eoip-modal-disabled').checked = !!t.disabled;
  6690. document.getElementById('eoip-modal').classList.remove('hidden');
  6691. }
  6692. function closeEoIPModal() {
  6693. document.getElementById('eoip-modal').classList.add('hidden');
  6694. }
  6695. async function submitSaveEoIP(e) {
  6696. e.preventDefault();
  6697. const id = document.getElementById('eoip-modal-id').value;
  6698. const name = document.getElementById('eoip-modal-name').value.trim();
  6699. const tunnelId = parseInt(document.getElementById('eoip-modal-tunnelid').value);
  6700. const remote = document.getElementById('eoip-modal-remote').value.trim();
  6701. const ipAddress = document.getElementById('eoip-modal-ip').value.trim();
  6702. const local = document.getElementById('eoip-modal-local').value.trim();
  6703. const mac = document.getElementById('eoip-modal-mac').value.trim();
  6704. const mtu = parseInt(document.getElementById('eoip-modal-mtu').value) || 1500;
  6705. const comment = document.getElementById('eoip-modal-comment').value.trim();
  6706. const clampMss = document.getElementById('eoip-modal-clampmss').checked;
  6707. const disabled = document.getElementById('eoip-modal-disabled').checked;
  6708. try {
  6709. const res = await fetch(`${API_BASE}/vpn/eoip`, {
  6710. method: 'POST',
  6711. headers: { 'Content-Type': 'application/json' },
  6712. body: JSON.stringify({
  6713. id,
  6714. name,
  6715. tunnel_id: tunnelId,
  6716. remote_address: remote,
  6717. ip_address: ipAddress,
  6718. local_address: local,
  6719. mac_address: mac,
  6720. mtu,
  6721. clamp_mss: clampMss,
  6722. comment,
  6723. disabled
  6724. })
  6725. });
  6726. if (res.ok) {
  6727. showToast('EoIP Saved', `Tunnel ${name} configured successfully`, 'success');
  6728. closeEoIPModal();
  6729. loadEoIP(false);
  6730. fetchData(false);
  6731. } else {
  6732. const err = await res.json();
  6733. showToast('Error', err.message, 'error');
  6734. }
  6735. } catch (err) {
  6736. showToast('Error', err.message, 'error');
  6737. }
  6738. }
  6739. async function toggleEoIPState(id, disabled) {
  6740. try {
  6741. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}/state`, {
  6742. method: 'POST',
  6743. headers: { 'Content-Type': 'application/json' },
  6744. body: JSON.stringify({ disabled })
  6745. });
  6746. if (res.ok) {
  6747. showToast(disabled ? 'Disabled' : 'Enabled', 'EoIP tunnel state updated', 'info');
  6748. loadEoIP(false);
  6749. fetchData(false);
  6750. }
  6751. } catch (err) {
  6752. showToast('Error', err.message, 'error');
  6753. }
  6754. }
  6755. async function deleteEoIP(id) {
  6756. if (!confirm('Are you sure you want to delete this EoIP tunnel?')) return;
  6757. try {
  6758. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6759. if (res.ok) {
  6760. showToast('Deleted', 'EoIP tunnel removed', 'success');
  6761. loadEoIP(false);
  6762. fetchData(false);
  6763. }
  6764. } catch (err) {
  6765. showToast('Error', err.message, 'error');
  6766. }
  6767. }
  6768. // ======================== AeroTUN (Custom Encrypted VPN with Adaptive LZ4) ========================
  6769. async function loadAeroTUN(populate = true) {
  6770. try {
  6771. const [tunnelsRes, statsRes] = await Promise.all([
  6772. fetch(`${API_BASE}/vpn/aerotun/tunnels`),
  6773. fetch(`${API_BASE}/vpn/aerotun/stats`)
  6774. ]);
  6775. if (tunnelsRes.ok) {
  6776. const data = await tunnelsRes.json();
  6777. state.aerotunTunnels = Array.isArray(data) ? data : [];
  6778. }
  6779. if (statsRes.ok) {
  6780. state.aerotunStats = await statsRes.json();
  6781. }
  6782. const countBadge = document.getElementById('aerotun-count-badge');
  6783. if (countBadge) countBadge.innerText = `${(state.aerotunTunnels || []).length} Tunnels`;
  6784. const sideBadge = document.getElementById('badge-aerotun-count');
  6785. if (sideBadge) sideBadge.innerText = (state.aerotunTunnels || []).length;
  6786. renderAeroTUN();
  6787. } catch (err) {
  6788. console.error('Failed to load AeroTUN:', err);
  6789. }
  6790. }
  6791. function renderAeroTUN() {
  6792. const tbody = document.getElementById('aerotun-table-body');
  6793. const empty = document.getElementById('aerotun-empty');
  6794. // Update summary cards
  6795. const stats = state.aerotunStats || {};
  6796. const tunnels = state.aerotunTunnels || [];
  6797. const statActive = document.getElementById('aerotun-stat-active');
  6798. if (statActive) {
  6799. const activeCount = tunnels.filter(t => t.running).length;
  6800. statActive.innerText = `${activeCount} / ${tunnels.length}`;
  6801. }
  6802. const statSaved = document.getElementById('aerotun-stat-saved');
  6803. if (statSaved) {
  6804. statSaved.innerText = formatBytes(stats.total_saved_bytes || 0);
  6805. }
  6806. const statRatio = document.getElementById('aerotun-stat-ratio');
  6807. if (statRatio) {
  6808. statRatio.innerText = stats.average_ratio || '1.00x (0% saved)';
  6809. }
  6810. const statTraffic = document.getElementById('aerotun-stat-traffic');
  6811. if (statTraffic) {
  6812. statTraffic.innerText = `↓ ${formatBytes(stats.total_rx_bytes || 0)} / ↑ ${formatBytes(stats.total_tx_bytes || 0)}`;
  6813. }
  6814. if (!tbody) return;
  6815. tbody.innerHTML = '';
  6816. if (tunnels.length === 0) {
  6817. empty?.classList.remove('hidden');
  6818. return;
  6819. }
  6820. empty?.classList.add('hidden');
  6821. tunnels.forEach(t => {
  6822. const tr = document.createElement('tr');
  6823. tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
  6824. const modeBadge = t.mode === 'server'
  6825. ? `<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>`
  6826. : `<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>`;
  6827. const endpointInfo = t.mode === 'server'
  6828. ? `<span class="text-sky-300 font-mono">Port :${t.listen_port || 51830}</span>`
  6829. : `<span class="text-indigo-300 font-mono">${escapeHtml(t.remote_endpoint || '(not set)')}</span>`;
  6830. const compBadge = t.compression
  6831. ? `<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>`
  6832. : `<span class="text-slate-500 text-[10px]">Off</span>`;
  6833. const activePeer = t.active_peer_endpoint
  6834. ? `<span class="text-emerald-400 font-mono text-[11px]" title="Last seen: ${t.last_handshake || 'just now'}">● ${escapeHtml(t.active_peer_endpoint)}</span>`
  6835. : `<span class="text-slate-500 text-[11px]">${t.mode === 'server' ? 'Waiting for peer...' : 'Connecting...'}</span>`;
  6836. const rawRx = formatBytes(t.rx_bytes || 0);
  6837. const rawTx = formatBytes(t.tx_bytes || 0);
  6838. const wireRx = formatBytes(t.wire_bytes_in || 0);
  6839. const wireTx = formatBytes(t.wire_bytes_out || 0);
  6840. tr.innerHTML = `
  6841. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.running, t.disabled)}</td>
  6842. <td class="py-2.5 px-3 font-bold text-white font-mono flex items-center gap-1.5">
  6843. <span>${escapeHtml(t.name)}</span>
  6844. ${t.default_route ? '<span class="text-[9px] px-1 rounded bg-amber-500/20 text-amber-300 border border-amber-500/30">DEF</span>' : ''}
  6845. </td>
  6846. <td class="py-2.5 px-3">${modeBadge}</td>
  6847. <td class="py-2.5 px-3 text-xs font-mono">${endpointInfo}</td>
  6848. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${escapeHtml(t.local_address || '-')}</td>
  6849. <td class="py-2.5 px-3">${compBadge}</td>
  6850. <td class="py-2.5 px-3">${activePeer}</td>
  6851. <td class="py-2.5 px-3 font-mono text-[11px]">
  6852. <span class="text-emerald-400">↓ ${rawRx}</span>
  6853. <span class="text-cyan-400 ml-1">↑ ${rawTx}</span>
  6854. </td>
  6855. <td class="py-2.5 px-3 font-mono text-[11px]">
  6856. <span class="text-slate-400">↓ ${wireRx}</span>
  6857. <span class="text-slate-400 ml-1">↑ ${wireTx}</span>
  6858. </td>
  6859. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(t.comment || '')}">${escapeHtml(t.comment || '-')}</td>
  6860. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  6861. ${t.running
  6862. ? `<button onclick="stopAeroTUNTunnel('${t.id}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Stop</button>`
  6863. : `<button onclick="startAeroTUNTunnel('${t.id}')" class="text-xs text-emerald-400 hover:text-emerald-300 font-medium">Start</button>`
  6864. }
  6865. <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>
  6866. <button onclick="openEditAeroTUNModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  6867. <button onclick="deleteAeroTUN('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  6868. </td>
  6869. `;
  6870. tbody.appendChild(tr);
  6871. });
  6872. }
  6873. function onAeroTUNModeChange() {
  6874. const mode = document.getElementById('aerotun-modal-mode').value;
  6875. const endpointInput = document.getElementById('aerotun-modal-endpoint');
  6876. const portInput = document.getElementById('aerotun-modal-port');
  6877. if (mode === 'server') {
  6878. if (!portInput.value) portInput.value = '51830';
  6879. endpointInput.placeholder = 'Optional / learned roaming peer';
  6880. } else {
  6881. endpointInput.placeholder = 'vpn.example.com:51830 (required)';
  6882. if (!portInput.value) portInput.value = '';
  6883. }
  6884. }
  6885. async function generateAeroTUNKey() {
  6886. try {
  6887. const res = await fetch(`${API_BASE}/vpn/aerotun/genkey`);
  6888. if (res.ok) {
  6889. const data = await res.json();
  6890. document.getElementById('aerotun-modal-psk').value = data.key;
  6891. showToast('Key Generated', 'Cryptographic 256-bit PSK generated', 'success');
  6892. }
  6893. } catch (err) {
  6894. const arr = new Uint8Array(32);
  6895. crypto.getRandomValues(arr);
  6896. const hex = Array.from(arr).map(b => b.toString(16).padStart(2, '0')).join('');
  6897. document.getElementById('aerotun-modal-psk').value = hex;
  6898. }
  6899. }
  6900. function openAddAeroTUNModal() {
  6901. const tunnels = state.aerotunTunnels || [];
  6902. document.getElementById('aerotun-modal-title').innerText = 'Add AeroTUN Interface';
  6903. document.getElementById('aerotun-modal-id').value = '';
  6904. document.getElementById('aerotun-modal-name').value = `aerotun${tunnels.length}`;
  6905. document.getElementById('aerotun-modal-mode').value = 'server';
  6906. document.getElementById('aerotun-modal-port').value = 51830 + tunnels.length;
  6907. document.getElementById('aerotun-modal-endpoint').value = '';
  6908. document.getElementById('aerotun-modal-local').value = `10.99.${tunnels.length}.1/24`;
  6909. document.getElementById('aerotun-modal-peer').value = `10.99.${tunnels.length}.2/24`;
  6910. document.getElementById('aerotun-modal-psk').value = '';
  6911. document.getElementById('aerotun-modal-mtu').value = '1420';
  6912. document.getElementById('aerotun-modal-comment').value = '';
  6913. document.getElementById('aerotun-modal-compression').checked = true;
  6914. document.getElementById('aerotun-modal-defroute').checked = false;
  6915. document.getElementById('aerotun-modal-disabled').checked = false;
  6916. generateAeroTUNKey();
  6917. onAeroTUNModeChange();
  6918. document.getElementById('aerotun-modal').classList.remove('hidden');
  6919. }
  6920. function openEditAeroTUNModal(id) {
  6921. const t = (state.aerotunTunnels || []).find(tun => tun.id === id);
  6922. if (!t) return;
  6923. document.getElementById('aerotun-modal-title').innerText = `Edit AeroTUN Interface (${t.name})`;
  6924. document.getElementById('aerotun-modal-id').value = t.id;
  6925. document.getElementById('aerotun-modal-name').value = t.name;
  6926. document.getElementById('aerotun-modal-mode').value = t.mode || 'server';
  6927. document.getElementById('aerotun-modal-port').value = t.listen_port || '';
  6928. document.getElementById('aerotun-modal-endpoint').value = t.remote_endpoint || '';
  6929. document.getElementById('aerotun-modal-local').value = t.local_address || '';
  6930. document.getElementById('aerotun-modal-peer').value = t.peer_address || '';
  6931. document.getElementById('aerotun-modal-psk').value = t.psk || '';
  6932. document.getElementById('aerotun-modal-mtu').value = t.mtu || 1420;
  6933. document.getElementById('aerotun-modal-comment').value = t.comment || '';
  6934. document.getElementById('aerotun-modal-compression').checked = !!t.compression;
  6935. document.getElementById('aerotun-modal-defroute').checked = !!t.default_route;
  6936. document.getElementById('aerotun-modal-disabled').checked = !!t.disabled;
  6937. onAeroTUNModeChange();
  6938. document.getElementById('aerotun-modal').classList.remove('hidden');
  6939. }
  6940. function closeAeroTUNModal() {
  6941. document.getElementById('aerotun-modal').classList.add('hidden');
  6942. }
  6943. async function submitSaveAeroTUN(e) {
  6944. e.preventDefault();
  6945. const id = document.getElementById('aerotun-modal-id').value;
  6946. const name = document.getElementById('aerotun-modal-name').value.trim();
  6947. const mode = document.getElementById('aerotun-modal-mode').value;
  6948. const port = parseInt(document.getElementById('aerotun-modal-port').value) || 0;
  6949. const endpoint = document.getElementById('aerotun-modal-endpoint').value.trim();
  6950. const local = document.getElementById('aerotun-modal-local').value.trim();
  6951. const peer = document.getElementById('aerotun-modal-peer').value.trim();
  6952. const psk = document.getElementById('aerotun-modal-psk').value.trim();
  6953. const mtu = parseInt(document.getElementById('aerotun-modal-mtu').value) || 1420;
  6954. const comment = document.getElementById('aerotun-modal-comment').value.trim();
  6955. const compression = document.getElementById('aerotun-modal-compression').checked;
  6956. const defaultRoute = document.getElementById('aerotun-modal-defroute').checked;
  6957. const disabled = document.getElementById('aerotun-modal-disabled').checked;
  6958. if (mode === 'client' && !endpoint) {
  6959. showToast('Validation Error', 'Remote endpoint (host:port) is required in client mode', 'error');
  6960. return;
  6961. }
  6962. if (!psk) {
  6963. showToast('Validation Error', 'Pre-shared key (PSK) is required', 'error');
  6964. return;
  6965. }
  6966. try {
  6967. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels`, {
  6968. method: 'POST',
  6969. headers: { 'Content-Type': 'application/json' },
  6970. body: JSON.stringify({
  6971. id,
  6972. name,
  6973. mode,
  6974. listen_port: port,
  6975. remote_endpoint: endpoint,
  6976. local_address: local,
  6977. peer_address: peer,
  6978. psk,
  6979. mtu,
  6980. compression,
  6981. default_route: defaultRoute,
  6982. comment,
  6983. disabled
  6984. })
  6985. });
  6986. if (res.ok) {
  6987. showToast('AeroTUN Saved', `Tunnel ${name} configured successfully`, 'success');
  6988. closeAeroTUNModal();
  6989. loadAeroTUN(false);
  6990. fetchData(false);
  6991. } else {
  6992. const err = await res.text();
  6993. showToast('Error Saving Tunnel', err, 'error');
  6994. }
  6995. } catch (err) {
  6996. showToast('Network Error', err.message, 'error');
  6997. }
  6998. }
  6999. async function startAeroTUNTunnel(id) {
  7000. try {
  7001. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/start`, { method: 'POST' });
  7002. if (res.ok) {
  7003. showToast('AeroTUN Started', 'Tunnel interface is active', 'success');
  7004. loadAeroTUN(false);
  7005. fetchData(false);
  7006. } else {
  7007. const err = await res.text();
  7008. showToast('Failed to Start', err, 'error');
  7009. }
  7010. } catch (err) {
  7011. showToast('Error', err.message, 'error');
  7012. }
  7013. }
  7014. async function stopAeroTUNTunnel(id) {
  7015. try {
  7016. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/stop`, { method: 'POST' });
  7017. if (res.ok) {
  7018. showToast('AeroTUN Stopped', 'Tunnel stopped', 'info');
  7019. loadAeroTUN(false);
  7020. fetchData(false);
  7021. } else {
  7022. const err = await res.text();
  7023. showToast('Failed to Stop', err, 'error');
  7024. }
  7025. } catch (err) {
  7026. showToast('Error', err.message, 'error');
  7027. }
  7028. }
  7029. async function toggleAeroTUNState(id, disabled) {
  7030. try {
  7031. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/state`, {
  7032. method: 'POST',
  7033. headers: { 'Content-Type': 'application/json' },
  7034. body: JSON.stringify({ disabled })
  7035. });
  7036. if (res.ok) {
  7037. showToast('State Updated', disabled ? 'Tunnel disabled' : 'Tunnel enabled', 'info');
  7038. loadAeroTUN(false);
  7039. fetchData(false);
  7040. }
  7041. } catch (err) {
  7042. showToast('Error', err.message, 'error');
  7043. }
  7044. }
  7045. async function deleteAeroTUN(id) {
  7046. if (!confirm('Are you sure you want to delete this AeroTUN tunnel?')) return;
  7047. try {
  7048. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7049. if (res.ok) {
  7050. showToast('Deleted', 'AeroTUN tunnel removed', 'success');
  7051. loadAeroTUN(false);
  7052. fetchData(false);
  7053. }
  7054. } catch (err) {
  7055. showToast('Error', err.message, 'error');
  7056. }
  7057. }
  7058. // ======================== PPP Central Hub & Servers ========================
  7059. function switchPPPSubTab(tab) {
  7060. state.pppSubTab = tab;
  7061. const tabs = ['secrets', 'profiles', 'pppoe', 'pptp', 'l2tp', 'active'];
  7062. tabs.forEach(t => {
  7063. const panel = document.getElementById(`ppp-subtab-${t}`);
  7064. const btn = document.getElementById(`ppp-subtab-btn-${t}`);
  7065. if (panel) {
  7066. if (t === tab) panel.classList.remove('hidden');
  7067. else panel.classList.add('hidden');
  7068. }
  7069. if (btn) {
  7070. if (t === tab) {
  7071. 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';
  7072. } else {
  7073. 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';
  7074. }
  7075. }
  7076. });
  7077. const addBtn = document.getElementById('ppp-primary-add-btn');
  7078. if (addBtn) {
  7079. if (tab === 'secrets') addBtn.innerHTML = '<span>+ Add User (Secret)</span>';
  7080. else if (tab === 'profiles') addBtn.innerHTML = '<span>+ Add Profile</span>';
  7081. else if (tab === 'active') addBtn.innerHTML = '<span>Refresh Sessions</span>';
  7082. else addBtn.innerHTML = '<span>Save Config</span>';
  7083. }
  7084. if (tab === 'active') loadPPPSessions();
  7085. }
  7086. function openCurrentPPPModal() {
  7087. if (state.pppSubTab === 'secrets') openAddPPPSecretModal();
  7088. else if (state.pppSubTab === 'profiles') openAddPPPProfileModal();
  7089. else if (state.pppSubTab === 'active') loadPPPSessions();
  7090. else if (state.pppSubTab === 'pppoe') document.querySelector('#ppp-subtab-pppoe form')?.requestSubmit();
  7091. else if (state.pppSubTab === 'pptp') document.querySelector('#ppp-subtab-pptp form')?.requestSubmit();
  7092. else if (state.pppSubTab === 'l2tp') document.querySelector('#ppp-subtab-l2tp form')?.requestSubmit();
  7093. }
  7094. async function loadPPP(populateDropdowns = true) {
  7095. await Promise.all([
  7096. loadPPPSecrets(),
  7097. loadPPPProfiles(),
  7098. loadPPPServers(),
  7099. loadPPPSessions()
  7100. ]);
  7101. }
  7102. async function loadPPPSecrets() {
  7103. try {
  7104. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`);
  7105. const data = await res.json();
  7106. state.pppSecrets = Array.isArray(data) ? data : [];
  7107. const b = document.getElementById('ppp-badge-secrets');
  7108. if (b) b.innerText = state.pppSecrets.length;
  7109. const b2 = document.getElementById('secrets-count-badge');
  7110. if (b2) b2.innerText = `${state.pppSecrets.length} Users`;
  7111. renderPPPSecrets();
  7112. } catch (err) {
  7113. console.error('Failed to load PPP secrets:', err);
  7114. }
  7115. }
  7116. function renderPPPSecrets() {
  7117. const tbody = document.getElementById('secrets-table-body');
  7118. const empty = document.getElementById('secrets-empty');
  7119. if (!tbody) return;
  7120. tbody.innerHTML = '';
  7121. const secrets = state.pppSecrets || [];
  7122. if (secrets.length === 0) {
  7123. empty?.classList.remove('hidden');
  7124. return;
  7125. }
  7126. empty?.classList.add('hidden');
  7127. secrets.forEach(s => {
  7128. const tr = document.createElement('tr');
  7129. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  7130. tr.innerHTML = `
  7131. <td class="py-2.5 px-3 text-center">${renderRuleFlag(s.disabled, !!s.comment)}</td>
  7132. <td class="py-2.5 px-3 font-bold text-white font-mono">${s.name}</td>
  7133. <td class="py-2.5 px-3 text-purple-300 font-mono font-semibold">${s.service}</td>
  7134. <td class="py-2.5 px-3 text-amber-300 font-mono">${s.profile}</td>
  7135. <td class="py-2.5 px-3 text-slate-400 font-mono">${s.local_address || '(profile)'}</td>
  7136. <td class="py-2.5 px-3 text-cyan-400 font-mono font-bold">${s.remote_address || '(profile)'}</td>
  7137. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]">${s.comment || '-'}</td>
  7138. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  7139. <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>
  7140. <button onclick="openEditPPPSecretModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  7141. <button onclick="deletePPPSecret('${s.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  7142. </td>
  7143. `;
  7144. tbody.appendChild(tr);
  7145. });
  7146. }
  7147. async function loadPPPProfiles() {
  7148. try {
  7149. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`);
  7150. const data = await res.json();
  7151. state.pppProfiles = Array.isArray(data) ? data : [];
  7152. const b = document.getElementById('ppp-badge-profiles');
  7153. if (b) b.innerText = state.pppProfiles.length;
  7154. const b2 = document.getElementById('profiles-count-badge');
  7155. if (b2) b2.innerText = `${state.pppProfiles.length} Profiles`;
  7156. // Populate profile selects across modals
  7157. const selects = ['secret-modal-profile', 'pppoe-server-profile', 'pptp-server-profile', 'l2tp-server-profile'];
  7158. selects.forEach(sid => {
  7159. const el = document.getElementById(sid);
  7160. if (!el) return;
  7161. const cur = el.value;
  7162. el.innerHTML = '';
  7163. state.pppProfiles.forEach(p => {
  7164. const opt = document.createElement('option');
  7165. opt.value = p.name;
  7166. opt.innerText = `${p.name} (${p.remote_address})`;
  7167. if (p.name === cur) opt.selected = true;
  7168. el.appendChild(opt);
  7169. });
  7170. });
  7171. renderPPPProfiles();
  7172. } catch (err) {
  7173. console.error('Failed to load PPP profiles:', err);
  7174. }
  7175. }
  7176. function renderPPPProfiles() {
  7177. const tbody = document.getElementById('profiles-table-body');
  7178. if (!tbody) return;
  7179. tbody.innerHTML = '';
  7180. (state.pppProfiles || []).forEach(p => {
  7181. const isDefault = p.name.startsWith('default');
  7182. const tr = document.createElement('tr');
  7183. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  7184. tr.innerHTML = `
  7185. <td class="py-2.5 px-3 font-bold text-white">${p.name}</td>
  7186. <td class="py-2.5 px-3 text-slate-300">${p.local_address}</td>
  7187. <td class="py-2.5 px-3 text-cyan-400 font-bold">${p.remote_address}</td>
  7188. <td class="py-2.5 px-3 text-slate-400">${p.dns_servers || '-'}</td>
  7189. <td class="py-2.5 px-3 text-purple-300 font-semibold">${p.use_encryption}</td>
  7190. <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>
  7191. <td class="py-2.5 px-3 text-slate-400 italic">${p.comment || '-'}</td>
  7192. <td class="py-2.5 px-3 text-right font-sans whitespace-nowrap">
  7193. ${!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>`}
  7194. </td>
  7195. `;
  7196. tbody.appendChild(tr);
  7197. });
  7198. }
  7199. async function loadPPPServers() {
  7200. try {
  7201. const [pppoeRes, pptpRes, l2tpRes, ipsecRes] = await Promise.all([
  7202. fetch(`${API_BASE}/vpn/servers/pppoe`),
  7203. fetch(`${API_BASE}/vpn/servers/pptp`),
  7204. fetch(`${API_BASE}/vpn/servers/l2tp`),
  7205. fetch(`${API_BASE}/vpn/servers/ipsec`)
  7206. ]);
  7207. if (pppoeRes.ok) {
  7208. state.pppoeServer = await pppoeRes.json();
  7209. const s = state.pppoeServer;
  7210. document.getElementById('pppoe-server-enabled').checked = !!s.enabled;
  7211. document.getElementById('pppoe-server-name').value = s.service_name || 'proxmox-pppoe';
  7212. populateInterfaceSelect('pppoe-server-iface', s.interface || 'eth0');
  7213. document.getElementById('pppoe-server-profile').value = s.default_profile || 'default';
  7214. document.getElementById('pppoe-server-mtu').value = s.max_mtu || 1480;
  7215. document.getElementById('pppoe-server-onesession').checked = !!s.one_session_per_host;
  7216. const pill = document.getElementById('pppoe-server-status-pill');
  7217. if (pill) {
  7218. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  7219. 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';
  7220. }
  7221. setDotBadge('ppp-badge-pppoe-state', s.running);
  7222. }
  7223. if (pptpRes.ok) {
  7224. state.pptpServer = await pptpRes.json();
  7225. const s = state.pptpServer;
  7226. document.getElementById('pptp-server-enabled').checked = !!s.enabled;
  7227. document.getElementById('pptp-server-port').value = s.port || 1723;
  7228. document.getElementById('pptp-server-profile').value = s.default_profile || 'default-encryption';
  7229. document.getElementById('pptp-server-mppe').checked = s.require_mppe !== false;
  7230. const pill = document.getElementById('pptp-server-status-pill');
  7231. if (pill) {
  7232. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  7233. 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';
  7234. }
  7235. setDotBadge('ppp-badge-pptp-state', s.running);
  7236. }
  7237. if (l2tpRes.ok) {
  7238. state.l2tpServer = await l2tpRes.json();
  7239. const s = state.l2tpServer;
  7240. document.getElementById('l2tp-server-enabled').checked = !!s.enabled;
  7241. document.getElementById('l2tp-server-port').value = s.port || 1701;
  7242. document.getElementById('l2tp-server-profile').value = s.default_profile || 'default';
  7243. document.getElementById('l2tp-server-useipsec').value = s.use_ipsec || 'no';
  7244. document.getElementById('l2tp-server-ipsecsecret').value = s.ipsec_secret || '';
  7245. const pill = document.getElementById('l2tp-server-status-pill');
  7246. if (pill) {
  7247. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  7248. 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';
  7249. }
  7250. setDotBadge('ppp-badge-l2tp-state', s.running);
  7251. }
  7252. if (ipsecRes.ok) {
  7253. state.ipsecServer = await ipsecRes.json();
  7254. const s = state.ipsecServer;
  7255. const modalEn = document.getElementById('modal-ipsec-server-enabled');
  7256. if (modalEn) modalEn.checked = !!s.enabled;
  7257. const modalPsk = document.getElementById('modal-ipsec-server-psk');
  7258. if (modalPsk) modalPsk.value = s.preshared_key || '';
  7259. const modalPool = document.getElementById('modal-ipsec-server-pool');
  7260. if (modalPool) modalPool.value = s.pool_address || '10.10.30.0/24';
  7261. const modalDns = document.getElementById('modal-ipsec-server-dns');
  7262. if (modalDns) modalDns.value = s.dns_servers || '1.1.1.1,8.8.8.8';
  7263. const modalSubnet = document.getElementById('modal-ipsec-server-subnet');
  7264. if (modalSubnet) modalSubnet.value = s.local_subnet || '0.0.0.0/0';
  7265. const pill = document.getElementById('modal-ipsec-server-status');
  7266. if (pill) {
  7267. pill.innerText = s.running ? 'ACTIVE RESPONDER' : 'STOPPED';
  7268. 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';
  7269. }
  7270. }
  7271. } catch (err) {
  7272. console.error('Failed to load VPN servers:', err);
  7273. }
  7274. }
  7275. async function loadPPPSessions() {
  7276. try {
  7277. const res = await fetch(`${API_BASE}/vpn/ppp/active`);
  7278. const data = await res.json();
  7279. state.pppActiveSessions = Array.isArray(data) ? data : [];
  7280. const b = document.getElementById('ppp-badge-active');
  7281. if (b) b.innerText = state.pppActiveSessions.length;
  7282. const sideB = document.getElementById('badge-ppp-sessions');
  7283. if (sideB) sideB.innerText = state.pppActiveSessions.length;
  7284. renderPPPSessions();
  7285. } catch (err) {
  7286. console.error('Failed to load active PPP sessions:', err);
  7287. }
  7288. }
  7289. function renderPPPSessions() {
  7290. const tbody = document.getElementById('active-ppp-table-body');
  7291. const empty = document.getElementById('active-ppp-empty');
  7292. if (!tbody) return;
  7293. tbody.innerHTML = '';
  7294. const list = state.pppActiveSessions || [];
  7295. if (list.length === 0) {
  7296. empty?.classList.remove('hidden');
  7297. return;
  7298. }
  7299. empty?.classList.add('hidden');
  7300. list.forEach(s => {
  7301. const tr = document.createElement('tr');
  7302. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  7303. tr.innerHTML = `
  7304. <td class="py-2.5 px-3 font-bold text-white">${s.interface}</td>
  7305. <td class="py-2.5 px-3 font-semibold text-violet-300">${s.username}</td>
  7306. <td class="py-2.5 px-3 text-cyan-400 uppercase">${s.service}</td>
  7307. <td class="py-2.5 px-3 text-emerald-400 font-bold">${s.address || '-'}</td>
  7308. <td class="py-2.5 px-3 text-slate-400">${s.uptime}</td>
  7309. <td class="py-2.5 px-3 text-[11px]">
  7310. <span class="text-emerald-400">↓ ${s.rx_human || '0 B'}</span>
  7311. <span class="text-cyan-400 ml-1">↑ ${s.tx_human || '0 B'}</span>
  7312. </td>
  7313. <td class="py-2.5 px-3 text-right font-sans">
  7314. <button onclick="disconnectPPPSession('${s.interface}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  7315. </td>
  7316. `;
  7317. tbody.appendChild(tr);
  7318. });
  7319. }
  7320. async function disconnectPPPSession(iface) {
  7321. if (!confirm(`Disconnect session ${iface}?`)) return;
  7322. try {
  7323. const res = await fetch(`${API_BASE}/vpn/ppp/active/${encodeURIComponent(iface)}`, { method: 'DELETE' });
  7324. if (res.ok) {
  7325. showToast('Disconnected', `Session ${iface} terminated`, 'info');
  7326. loadPPPSessions();
  7327. }
  7328. } catch (err) {
  7329. showToast('Error', err.message, 'error');
  7330. }
  7331. }
  7332. // PPP Secret Modal handlers
  7333. function openAddPPPSecretModal() {
  7334. document.getElementById('secret-modal-title').innerText = 'Add PPP Secret';
  7335. document.getElementById('secret-modal-id').value = '';
  7336. document.getElementById('secret-modal-name').value = '';
  7337. document.getElementById('secret-modal-password').value = '';
  7338. document.getElementById('secret-modal-service').value = 'any';
  7339. document.getElementById('secret-modal-profile').value = 'default';
  7340. document.getElementById('secret-modal-local').value = '';
  7341. document.getElementById('secret-modal-remote').value = '';
  7342. document.getElementById('secret-modal-comment').value = '';
  7343. document.getElementById('secret-modal-disabled').checked = false;
  7344. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  7345. }
  7346. function openEditPPPSecretModal(id) {
  7347. const s = (state.pppSecrets || []).find(sec => sec.id === id);
  7348. if (!s) return;
  7349. document.getElementById('secret-modal-title').innerText = `Edit PPP Secret (${s.name})`;
  7350. document.getElementById('secret-modal-id').value = s.id;
  7351. document.getElementById('secret-modal-name').value = s.name;
  7352. document.getElementById('secret-modal-password').value = s.password;
  7353. document.getElementById('secret-modal-service').value = s.service || 'any';
  7354. document.getElementById('secret-modal-profile').value = s.profile || 'default';
  7355. document.getElementById('secret-modal-local').value = s.local_address || '';
  7356. document.getElementById('secret-modal-remote').value = s.remote_address || '';
  7357. document.getElementById('secret-modal-comment').value = s.comment || '';
  7358. document.getElementById('secret-modal-disabled').checked = !!s.disabled;
  7359. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  7360. }
  7361. function closePPPSecretModal() {
  7362. document.getElementById('ppp-secret-modal').classList.add('hidden');
  7363. }
  7364. async function submitSavePPPSecret(e) {
  7365. e.preventDefault();
  7366. const id = document.getElementById('secret-modal-id').value;
  7367. const name = document.getElementById('secret-modal-name').value.trim();
  7368. const password = document.getElementById('secret-modal-password').value.trim();
  7369. const service = document.getElementById('secret-modal-service').value;
  7370. const profile = document.getElementById('secret-modal-profile').value;
  7371. const local = document.getElementById('secret-modal-local').value.trim();
  7372. const remote = document.getElementById('secret-modal-remote').value.trim();
  7373. const comment = document.getElementById('secret-modal-comment').value.trim();
  7374. const disabled = document.getElementById('secret-modal-disabled').checked;
  7375. try {
  7376. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`, {
  7377. method: 'POST',
  7378. headers: { 'Content-Type': 'application/json' },
  7379. body: JSON.stringify({
  7380. id,
  7381. name,
  7382. password,
  7383. service,
  7384. profile,
  7385. local_address: local,
  7386. remote_address: remote,
  7387. comment,
  7388. disabled
  7389. })
  7390. });
  7391. if (res.ok) {
  7392. showToast('Secret Saved', `User ${name} saved to PPP database`, 'success');
  7393. closePPPSecretModal();
  7394. loadPPPSecrets();
  7395. } else {
  7396. const err = await res.json();
  7397. showToast('Error', err.message, 'error');
  7398. }
  7399. } catch (err) {
  7400. showToast('Error', err.message, 'error');
  7401. }
  7402. }
  7403. async function togglePPPSecretState(id, disabled) {
  7404. try {
  7405. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}/state`, {
  7406. method: 'POST',
  7407. headers: { 'Content-Type': 'application/json' },
  7408. body: JSON.stringify({ disabled })
  7409. });
  7410. if (res.ok) {
  7411. showToast(disabled ? 'Disabled' : 'Enabled', 'Secret user state updated', 'info');
  7412. loadPPPSecrets();
  7413. }
  7414. } catch (err) {
  7415. showToast('Error', err.message, 'error');
  7416. }
  7417. }
  7418. async function deletePPPSecret(id) {
  7419. if (!confirm('Are you sure you want to delete this secret account?')) return;
  7420. try {
  7421. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7422. if (res.ok) {
  7423. showToast('Deleted', 'Secret account removed', 'success');
  7424. loadPPPSecrets();
  7425. }
  7426. } catch (err) {
  7427. showToast('Error', err.message, 'error');
  7428. }
  7429. }
  7430. // PPP Profile Modal handlers
  7431. function openAddPPPProfileModal() {
  7432. document.getElementById('profile-modal-name').value = '';
  7433. document.getElementById('profile-modal-local').value = '10.10.10.1';
  7434. document.getElementById('profile-modal-remote').value = '10.10.10.10-10.10.10.50';
  7435. document.getElementById('profile-modal-dns').value = '1.1.1.1,8.8.8.8';
  7436. document.getElementById('profile-modal-encryption').value = 'required';
  7437. document.getElementById('profile-modal-onlyone').checked = true;
  7438. document.getElementById('profile-modal-comment').value = '';
  7439. document.getElementById('ppp-profile-modal').classList.remove('hidden');
  7440. }
  7441. function closePPPProfileModal() {
  7442. document.getElementById('ppp-profile-modal').classList.add('hidden');
  7443. }
  7444. async function submitSavePPPProfile(e) {
  7445. e.preventDefault();
  7446. const name = document.getElementById('profile-modal-name').value.trim();
  7447. const local = document.getElementById('profile-modal-local').value.trim();
  7448. const remote = document.getElementById('profile-modal-remote').value.trim();
  7449. const dns = document.getElementById('profile-modal-dns').value.trim();
  7450. const enc = document.getElementById('profile-modal-encryption').value;
  7451. const onlyone = document.getElementById('profile-modal-onlyone').checked;
  7452. const comment = document.getElementById('profile-modal-comment').value.trim();
  7453. try {
  7454. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`, {
  7455. method: 'POST',
  7456. headers: { 'Content-Type': 'application/json' },
  7457. body: JSON.stringify({
  7458. id: name,
  7459. name,
  7460. local_address: local,
  7461. remote_address: remote,
  7462. dns_servers: dns,
  7463. use_encryption: enc,
  7464. only_one: onlyone,
  7465. comment
  7466. })
  7467. });
  7468. if (res.ok) {
  7469. showToast('Profile Saved', `PPP profile ${name} created`, 'success');
  7470. closePPPProfileModal();
  7471. loadPPPProfiles();
  7472. } else {
  7473. const err = await res.json();
  7474. showToast('Error', err.message, 'error');
  7475. }
  7476. } catch (err) {
  7477. showToast('Error', err.message, 'error');
  7478. }
  7479. }
  7480. async function deletePPPProfile(name) {
  7481. if (!confirm(`Delete PPP profile ${name}?`)) return;
  7482. try {
  7483. const res = await fetch(`${API_BASE}/vpn/ppp/profiles/${encodeURIComponent(name)}`, { method: 'DELETE' });
  7484. if (res.ok) {
  7485. showToast('Deleted', 'Profile removed', 'success');
  7486. loadPPPProfiles();
  7487. } else {
  7488. const err = await res.json();
  7489. showToast('Error', err.message, 'error');
  7490. }
  7491. } catch (err) {
  7492. showToast('Error', err.message, 'error');
  7493. }
  7494. }
  7495. // Server Config submissions
  7496. async function savePPPoEServerConfig(e) {
  7497. e.preventDefault();
  7498. const enabled = document.getElementById('pppoe-server-enabled').checked;
  7499. const name = document.getElementById('pppoe-server-name').value.trim();
  7500. const iface = document.getElementById('pppoe-server-iface').value;
  7501. const profile = document.getElementById('pppoe-server-profile').value;
  7502. const mtu = parseInt(document.getElementById('pppoe-server-mtu').value) || 1480;
  7503. const onesession = document.getElementById('pppoe-server-onesession').checked;
  7504. try {
  7505. const res = await fetch(`${API_BASE}/vpn/servers/pppoe`, {
  7506. method: 'POST',
  7507. headers: { 'Content-Type': 'application/json' },
  7508. body: JSON.stringify({
  7509. enabled,
  7510. service_name: name,
  7511. interface: iface,
  7512. default_profile: profile,
  7513. max_mtu: mtu,
  7514. max_mru: mtu,
  7515. one_session_per_host: onesession
  7516. })
  7517. });
  7518. if (res.ok) {
  7519. showToast('PPPoE Server', enabled ? 'PPPoE Server started' : 'PPPoE Server stopped', 'success');
  7520. loadPPPServers();
  7521. fetchData(false);
  7522. } else {
  7523. const err = await res.json();
  7524. showToast('Error', err.message, 'error');
  7525. }
  7526. } catch (err) {
  7527. showToast('Error', err.message, 'error');
  7528. }
  7529. }
  7530. async function savePPTPServerConfig(e) {
  7531. e.preventDefault();
  7532. const enabled = document.getElementById('pptp-server-enabled').checked;
  7533. const port = parseInt(document.getElementById('pptp-server-port').value) || 1723;
  7534. const profile = document.getElementById('pptp-server-profile').value;
  7535. const mppe = document.getElementById('pptp-server-mppe').checked;
  7536. try {
  7537. const res = await fetch(`${API_BASE}/vpn/servers/pptp`, {
  7538. method: 'POST',
  7539. headers: { 'Content-Type': 'application/json' },
  7540. body: JSON.stringify({
  7541. enabled,
  7542. port,
  7543. default_profile: profile,
  7544. require_mppe: mppe
  7545. })
  7546. });
  7547. if (res.ok) {
  7548. showToast('PPTP Server', enabled ? 'PPTP Server started' : 'PPTP Server stopped', 'success');
  7549. loadPPPServers();
  7550. fetchData(false);
  7551. } else {
  7552. const err = await res.json();
  7553. showToast('Error', err.message, 'error');
  7554. }
  7555. } catch (err) {
  7556. showToast('Error', err.message, 'error');
  7557. }
  7558. }
  7559. async function saveL2TPServerConfig(e) {
  7560. e.preventDefault();
  7561. const enabled = document.getElementById('l2tp-server-enabled').checked;
  7562. const port = parseInt(document.getElementById('l2tp-server-port').value) || 1701;
  7563. const profile = document.getElementById('l2tp-server-profile').value;
  7564. const useipsec = document.getElementById('l2tp-server-useipsec').value;
  7565. const psk = document.getElementById('l2tp-server-ipsecsecret').value.trim();
  7566. try {
  7567. const res = await fetch(`${API_BASE}/vpn/servers/l2tp`, {
  7568. method: 'POST',
  7569. headers: { 'Content-Type': 'application/json' },
  7570. body: JSON.stringify({
  7571. enabled,
  7572. port,
  7573. default_profile: profile,
  7574. use_ipsec: useipsec,
  7575. ipsec_secret: psk
  7576. })
  7577. });
  7578. if (res.ok) {
  7579. showToast('L2TP Server', enabled ? 'L2TP Server started' : 'L2TP Server stopped', 'success');
  7580. loadPPPServers();
  7581. fetchData(false);
  7582. } else {
  7583. const err = await res.json();
  7584. showToast('Error', err.message, 'error');
  7585. }
  7586. } catch (err) {
  7587. showToast('Error', err.message, 'error');
  7588. }
  7589. }
  7590. // IPSec Server Modal
  7591. function openIPSecServerModal() {
  7592. loadPPPServers();
  7593. document.getElementById('ipsec-server-modal').classList.remove('hidden');
  7594. }
  7595. function closeIPSecServerModal() {
  7596. document.getElementById('ipsec-server-modal').classList.add('hidden');
  7597. }
  7598. async function submitSaveIPSecServer(e) {
  7599. e.preventDefault();
  7600. const enabled = document.getElementById('modal-ipsec-server-enabled').checked;
  7601. const psk = document.getElementById('modal-ipsec-server-psk').value.trim();
  7602. const pool = document.getElementById('modal-ipsec-server-pool').value.trim();
  7603. const dns = document.getElementById('modal-ipsec-server-dns').value.trim();
  7604. const subnet = document.getElementById('modal-ipsec-server-subnet').value.trim();
  7605. try {
  7606. const res = await fetch(`${API_BASE}/vpn/servers/ipsec`, {
  7607. method: 'POST',
  7608. headers: { 'Content-Type': 'application/json' },
  7609. body: JSON.stringify({
  7610. enabled,
  7611. preshared_key: psk,
  7612. pool_address: pool,
  7613. dns_servers: dns,
  7614. local_subnet: subnet
  7615. })
  7616. });
  7617. if (res.ok) {
  7618. showToast('IPSec Server', enabled ? 'IKEv2 Roadwarrior responder active' : 'IPSec Server stopped', 'success');
  7619. closeIPSecServerModal();
  7620. loadPPPServers();
  7621. fetchData(false);
  7622. } else {
  7623. const err = await res.json();
  7624. showToast('Error', err.message, 'error');
  7625. }
  7626. } catch (err) {
  7627. showToast('Error', err.message, 'error');
  7628. }
  7629. }
  7630. // WireGuard Client Config Viewer
  7631. let currentWGClientConf = '';
  7632. async function openWGClientConfModal(iface, clientIP) {
  7633. try {
  7634. const res = await fetch(`${API_BASE}/vpn/wireguard/client-config`, {
  7635. method: 'POST',
  7636. headers: { 'Content-Type': 'application/json' },
  7637. body: JSON.stringify({
  7638. interface: iface,
  7639. address: clientIP || '10.10.0.2/32',
  7640. dns: '1.1.1.1, 8.8.8.8'
  7641. })
  7642. });
  7643. if (res.ok) {
  7644. const data = await res.json();
  7645. currentWGClientConf = data.config;
  7646. document.getElementById('wg-client-conf-text').value = currentWGClientConf;
  7647. document.getElementById('wg-client-conf-modal').classList.remove('hidden');
  7648. } else {
  7649. const err = await res.json();
  7650. showToast('Error', err.message, 'error');
  7651. }
  7652. } catch (err) {
  7653. showToast('Error', err.message, 'error');
  7654. }
  7655. }
  7656. function closeWGClientConfModal() {
  7657. document.getElementById('wg-client-conf-modal').classList.add('hidden');
  7658. }
  7659. function copyWGClientConf() {
  7660. if (!currentWGClientConf) return;
  7661. copyToClipboard(currentWGClientConf, 'WireGuard Client Profile');
  7662. }
  7663. function downloadWGClientConf() {
  7664. if (!currentWGClientConf) return;
  7665. const blob = new Blob([currentWGClientConf], { type: 'text/plain;charset=utf-8' });
  7666. const a = document.createElement('a');
  7667. a.href = URL.createObjectURL(blob);
  7668. a.download = 'wireguard-client.conf';
  7669. document.body.appendChild(a);
  7670. a.click();
  7671. document.body.removeChild(a);
  7672. showToast('Downloaded', 'wireguard-client.conf saved', 'success');
  7673. }
  7674. // =========================================================================
  7675. // DYNAMIC ROUTING (FRRouting BGP & OSPFv2)
  7676. // =========================================================================
  7677. state.activeDynSubTab = 'bgp-peers';
  7678. state.activeBgpSubTab = 'bgp-peers';
  7679. state.activeOspfTab = 'instances';
  7680. state.bgpInstance = null;
  7681. state.bgpPeers = [];
  7682. state.bgpNets = [];
  7683. state.bgpRoutes = [];
  7684. state.ospfInstance = null;
  7685. state.ospfInstances = [];
  7686. state.ospfAreas = [];
  7687. state.ospfAreaRanges = [];
  7688. state.ospfTemplates = [];
  7689. state.ospfLiveInterfaces = [];
  7690. state.ospfStaticNbrs = [];
  7691. state.ospfNeighbors = [];
  7692. state.ospfLSA = [];
  7693. state.ospfRoutes = [];
  7694. state.selectedOspfRow = {
  7695. instances: null,
  7696. areas: null,
  7697. 'area-ranges': null,
  7698. templates: null,
  7699. interfaces: null,
  7700. 'static-nbrs': null,
  7701. neighbors: null,
  7702. lsa: null,
  7703. };
  7704. state.ospfSort = {
  7705. instances: { col: 'name', asc: true },
  7706. areas: { col: 'name', asc: true },
  7707. ranges: { col: 'area', asc: true },
  7708. templates: { col: 'interfaces', asc: true },
  7709. live_ifaces: { col: 'interface', asc: true },
  7710. snbrs: { col: 'address', asc: true },
  7711. neighbors: { col: 'address', asc: true },
  7712. lsa: { col: 'instance', asc: true },
  7713. };
  7714. function switchBgpSubTab(subTab) {
  7715. state.activeBgpSubTab = subTab;
  7716. const tabs = ['bgp-peers', 'bgp-nets', 'bgp-routes'];
  7717. tabs.forEach(t => {
  7718. const el = document.getElementById(`dyn-subtab-${t}`);
  7719. const btn = document.getElementById(`bgp-subtab-btn-${t}`);
  7720. if (el) el.classList.toggle('hidden', t !== subTab);
  7721. if (btn) {
  7722. if (t === subTab) {
  7723. 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';
  7724. } else {
  7725. 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';
  7726. }
  7727. }
  7728. });
  7729. }
  7730. function switchOspfTab(tabName) {
  7731. state.activeOspfTab = tabName;
  7732. const tabs = ['instances', 'areas', 'area-ranges', 'templates', 'interfaces', 'static-nbrs', 'neighbors', 'lsa'];
  7733. tabs.forEach(t => {
  7734. const pane = document.getElementById(`ospf-pane-${t}`);
  7735. const btn = document.getElementById(`ospf-tab-btn-${t}`);
  7736. if (pane) pane.classList.toggle('hidden', t !== tabName);
  7737. if (btn) {
  7738. if (t === tabName) {
  7739. 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';
  7740. } else {
  7741. 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';
  7742. }
  7743. }
  7744. });
  7745. }
  7746. function switchOspfSubTab(tab) {
  7747. // Legacy alias
  7748. if (tab === 'ospf-ifaces') switchOspfTab('templates');
  7749. else if (tab === 'ospf-areas') switchOspfTab('areas');
  7750. else if (tab === 'ospf-nbrs') switchOspfTab('neighbors');
  7751. else switchOspfTab('instances');
  7752. }
  7753. function switchDynSubTab(subTab) {
  7754. if (subTab.startsWith('bgp')) {
  7755. if (state.activeTab !== 'bgp') navigate('bgp');
  7756. switchBgpSubTab(subTab);
  7757. } else if (subTab.startsWith('ospf')) {
  7758. if (state.activeTab !== 'ospf') navigate('ospf');
  7759. switchOspfTab('instances');
  7760. }
  7761. }
  7762. async function loadDynamicRouting(showToastMsg = false) {
  7763. try {
  7764. const fetchSafeJson = async (url) => {
  7765. try {
  7766. const r = await fetch(url);
  7767. return r.ok ? await r.json() : null;
  7768. } catch (e) {
  7769. return null;
  7770. }
  7771. };
  7772. const [
  7773. sum, bgpInst, bgpPeers, bgpNets, bgpRoutes,
  7774. ospfInsts, ospfAreas, ospfRanges, ospfTemplates, ospfLiveIfaces, ospfStaticNbrs, ospfNbrs, ospfLsa, filters,
  7775. selectRules, commLists, asLists
  7776. ] = await Promise.all([
  7777. fetchSafeJson(`${API_BASE}/routing/dynamic/summary`),
  7778. fetchSafeJson(`${API_BASE}/routing/bgp/instance`),
  7779. fetchSafeJson(`${API_BASE}/routing/bgp/peers`),
  7780. fetchSafeJson(`${API_BASE}/routing/bgp/networks`),
  7781. fetchSafeJson(`${API_BASE}/routing/bgp/routes`),
  7782. fetchSafeJson(`${API_BASE}/routing/ospf/instances`),
  7783. fetchSafeJson(`${API_BASE}/routing/ospf/areas`),
  7784. fetchSafeJson(`${API_BASE}/routing/ospf/area-ranges`),
  7785. fetchSafeJson(`${API_BASE}/routing/ospf/templates`),
  7786. fetchSafeJson(`${API_BASE}/routing/ospf/interfaces-live`),
  7787. fetchSafeJson(`${API_BASE}/routing/ospf/static-neighbors`),
  7788. fetchSafeJson(`${API_BASE}/routing/ospf/neighbors`),
  7789. fetchSafeJson(`${API_BASE}/routing/ospf/lsa`),
  7790. fetchSafeJson(`${API_BASE}/routing/filters`),
  7791. fetchSafeJson(`${API_BASE}/routing/filters/select-rules`),
  7792. fetchSafeJson(`${API_BASE}/routing/filters/community-lists`),
  7793. fetchSafeJson(`${API_BASE}/routing/filters/as-lists`)
  7794. ]);
  7795. if (sum) state.dynSummary = sum;
  7796. if (bgpInst) state.bgpInstance = bgpInst;
  7797. if (bgpPeers) state.bgpPeers = bgpPeers;
  7798. if (bgpNets) state.bgpNets = bgpNets;
  7799. if (bgpRoutes) state.bgpRoutes = bgpRoutes;
  7800. if (ospfInsts) state.ospfInstances = ospfInsts;
  7801. if (ospfAreas) state.ospfAreas = ospfAreas;
  7802. if (ospfRanges) state.ospfAreaRanges = ospfRanges;
  7803. if (ospfTemplates) state.ospfTemplates = ospfTemplates;
  7804. if (ospfLiveIfaces) state.ospfLiveInterfaces = ospfLiveIfaces;
  7805. if (ospfStaticNbrs) state.ospfStaticNbrs = ospfStaticNbrs;
  7806. if (ospfNbrs) state.ospfNeighbors = ospfNbrs;
  7807. if (ospfLsa) state.ospfLSA = ospfLsa;
  7808. if (filters) state.routingFilters = filters;
  7809. if (selectRules) state.routingSelectRules = selectRules;
  7810. if (commLists) state.routingCommunityLists = commLists;
  7811. if (asLists) state.routingASLists = asLists;
  7812. try { renderBgpStatusPill(); } catch(e) { console.error('renderBgpStatusPill error:', e); }
  7813. try { renderBgpPeers(); } catch(e) { console.error('renderBgpPeers error:', e); }
  7814. try { renderBgpNetworks(); } catch(e) { console.error('renderBgpNetworks error:', e); }
  7815. try { renderBgpRoutes(); } catch(e) { console.error('renderBgpRoutes error:', e); }
  7816. try { renderOspfInstances(); } catch(e) { console.error('renderOspfInstances error:', e); }
  7817. try { renderOspfAreas(); } catch(e) { console.error('renderOspfAreas error:', e); }
  7818. try { renderOspfAreaRanges(); } catch(e) { console.error('renderOspfAreaRanges error:', e); }
  7819. try { renderOspfTemplates(); } catch(e) { console.error('renderOspfTemplates error:', e); }
  7820. try { renderOspfLiveInterfaces(); } catch(e) { console.error('renderOspfLiveInterfaces error:', e); }
  7821. try { renderOspfStaticNbrs(); } catch(e) { console.error('renderOspfStaticNbrs error:', e); }
  7822. try { renderOspfNeighbors(); } catch(e) { console.error('renderOspfNeighbors error:', e); }
  7823. try { renderOspfLSA(); } catch(e) { console.error('renderOspfLSA error:', e); }
  7824. try { renderRoutingFilters(); } catch(e) { console.error('renderRoutingFilters error:', e); }
  7825. try { updateBadges(); } catch(e) { console.error('updateBadges error:', e); }
  7826. if (showToastMsg) showToast('Refreshed', 'Dynamic routing telemetry updated', 'info');
  7827. } catch (err) {
  7828. console.error('Failed to load dynamic routing:', err);
  7829. if (showToastMsg) showToast('Notice', 'Unable to refresh dynamic routing telemetry', 'warning');
  7830. }
  7831. }
  7832. async function loadOspfAll() {
  7833. await loadDynamicRouting(true);
  7834. }
  7835. function renderBgpStatusPill() {
  7836. const pill = document.getElementById('bgp-live-status-pill');
  7837. if (!pill) return;
  7838. const inst = state.bgpInstance;
  7839. if (!inst || !inst.enabled) {
  7840. pill.className = 'text-[10px] px-2 py-0.5 rounded font-mono bg-slate-800 text-slate-400 border border-slate-700';
  7841. pill.innerText = 'BGP DISABLED';
  7842. } else if (inst.running) {
  7843. 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';
  7844. pill.innerText = `BGP ACTIVE (AS ${inst.as})`;
  7845. } else {
  7846. 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';
  7847. pill.innerText = 'BGP STARTING...';
  7848. }
  7849. }
  7850. function renderBgpPeers() {
  7851. const tbody = document.getElementById('bgp-peers-table-body');
  7852. if (!tbody) return;
  7853. const empty = document.getElementById('bgp-peers-empty');
  7854. const countBadge = document.getElementById('bgp-peers-count-badge');
  7855. const navBadge = document.getElementById('dyn-badge-bgp-peers');
  7856. const peers = state.bgpPeers || [];
  7857. if (countBadge) countBadge.innerText = `${peers.length} Peers`;
  7858. if (navBadge) navBadge.innerText = peers.length;
  7859. if (peers.length === 0) {
  7860. tbody.innerHTML = '';
  7861. if (empty) empty.classList.remove('hidden');
  7862. return;
  7863. }
  7864. if (empty) empty.classList.add('hidden');
  7865. const sig = peers.map(p => `${p.name}:${p.state}:${p.uptime}:${p.prefix_received}:${p.prefix_sent}:${p.disabled}`).join(';');
  7866. if (tbody.dataset.sig === sig) return;
  7867. tbody.dataset.sig = sig;
  7868. tbody.innerHTML = peers.map(p => {
  7869. let flagA = !p.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  7870. let flagE = p.state === 'Established' ? '<span class="text-emerald-400 font-bold ml-1" title="Established">E</span>' : '';
  7871. let flagX = p.disabled ? '<span class="text-rose-400 font-bold ml-1" title="Disabled">X</span>' : '';
  7872. let stateBadge = '';
  7873. if (p.disabled) {
  7874. 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>';
  7875. } else if (p.state === 'Established') {
  7876. 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>';
  7877. } else if (p.state === 'Connect' || p.state === 'Active') {
  7878. 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>`;
  7879. } else {
  7880. 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>`;
  7881. }
  7882. return `
  7883. <tr class="hover:bg-slate-800/40 transition">
  7884. <td class="py-2.5 px-3 text-center tracking-wider">${flagA}${flagE}${flagX}</td>
  7885. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(p.name)}</td>
  7886. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(p.remote_address)}</td>
  7887. <td class="py-2.5 px-3">
  7888. <div class="font-bold text-slate-200">AS ${p.remote_as}</div>
  7889. ${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>`}
  7890. </td>
  7891. <td class="py-2.5 px-3">${stateBadge}</td>
  7892. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(p.uptime || '-')}</td>
  7893. <td class="py-2.5 px-3 text-slate-300">
  7894. <span class="text-emerald-400 font-bold">↓ ${p.prefix_received || 0}</span> /
  7895. <span class="text-blue-400 font-bold">↑ ${p.prefix_sent || 0}</span>
  7896. </td>
  7897. <td class="py-2.5 px-3 font-mono text-[11px] whitespace-nowrap">
  7898. ${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> ` : ''}
  7899. ${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>` : ''}
  7900. ${!p.in_filter && !p.out_filter ? '<span class="text-slate-600">-</span>' : ''}
  7901. </td>
  7902. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(p.comment || '')}</td>
  7903. <td class="py-2.5 px-3 text-right space-x-1.5 whitespace-nowrap font-sans">
  7904. <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'}">
  7905. ${p.disabled ? 'Enable' : 'Disable'}
  7906. </button>
  7907. <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">
  7908. Edit
  7909. </button>
  7910. <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">
  7911. Delete
  7912. </button>
  7913. </td>
  7914. </tr>
  7915. `;
  7916. }).join('');
  7917. }
  7918. function renderBgpNetworks() {
  7919. const tbody = document.getElementById('bgp-nets-table-body');
  7920. if (!tbody) return;
  7921. const empty = document.getElementById('bgp-nets-empty');
  7922. const countBadge = document.getElementById('bgp-nets-count-badge');
  7923. const navBadge = document.getElementById('dyn-badge-bgp-nets');
  7924. const nets = state.bgpNets || [];
  7925. if (countBadge) countBadge.innerText = `${nets.length} Networks`;
  7926. if (navBadge) navBadge.innerText = nets.length;
  7927. if (nets.length === 0) {
  7928. tbody.innerHTML = '';
  7929. if (empty) empty.classList.remove('hidden');
  7930. return;
  7931. }
  7932. if (empty) empty.classList.add('hidden');
  7933. const sig = nets.map(n => `${n.network}:${n.disabled}:${n.comment}`).join(';');
  7934. if (tbody.dataset.sig === sig) return;
  7935. tbody.dataset.sig = sig;
  7936. tbody.innerHTML = nets.map(n => `
  7937. <tr class="hover:bg-slate-800/40 transition">
  7938. <td class="py-2.5 px-3 font-semibold text-purple-300 font-mono">${escapeHtml(n.network)}</td>
  7939. <td class="py-2.5 px-3">
  7940. ${n.disabled
  7941. ? '<span class="px-2 py-0.5 rounded-full text-[10px] bg-slate-800 text-slate-400 border border-slate-700">Disabled</span>'
  7942. : '<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>'}
  7943. </td>
  7944. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(n.comment || '')}</td>
  7945. <td class="py-2.5 px-3 text-right space-x-1 font-sans">
  7946. <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">
  7947. Delete
  7948. </button>
  7949. </td>
  7950. </tr>
  7951. `).join('');
  7952. }
  7953. function renderBgpRoutes() {
  7954. const tbody = document.getElementById('bgp-routes-table-body');
  7955. if (!tbody) return;
  7956. const empty = document.getElementById('bgp-routes-empty');
  7957. const countBadge = document.getElementById('bgp-routes-count-badge');
  7958. const navBadge = document.getElementById('dyn-badge-bgp-routes');
  7959. const routes = state.bgpRoutes || [];
  7960. if (countBadge) countBadge.innerText = `${routes.length} Routes`;
  7961. if (navBadge) navBadge.innerText = routes.length;
  7962. if (routes.length === 0) {
  7963. tbody.innerHTML = '';
  7964. if (empty) empty.classList.remove('hidden');
  7965. return;
  7966. }
  7967. if (empty) empty.classList.add('hidden');
  7968. const sig = routes.map(r => `${r.prefix}:${r.next_hop}:${r.metric}:${r.path}`).join(';');
  7969. if (tbody.dataset.sig === sig) return;
  7970. tbody.dataset.sig = sig;
  7971. tbody.innerHTML = routes.map(r => `
  7972. <tr class="hover:bg-slate-800/40 transition">
  7973. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.prefix)}</td>
  7974. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(r.next_hop || '-')}</td>
  7975. <td class="py-2.5 px-3 text-slate-300">${r.metric}</td>
  7976. <td class="py-2.5 px-3 text-slate-300">${r.weight}</td>
  7977. <td class="py-2.5 px-3 text-amber-300">${escapeHtml(r.path || 'i')}</td>
  7978. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.origin || 'IGP')}</td>
  7979. </tr>
  7980. `).join('');
  7981. }
  7982. // =========================================================================
  7983. // ROUTEROS v7 OSPF TABLE RENDERING & SORTING
  7984. // =========================================================================
  7985. function sortOspfTable(tab, col) {
  7986. if (!state.ospfSort) state.ospfSort = {};
  7987. if (!state.ospfSort[tab]) state.ospfSort[tab] = { col: col, asc: true };
  7988. if (state.ospfSort[tab].col === col) {
  7989. state.ospfSort[tab].asc = !state.ospfSort[tab].asc;
  7990. } else {
  7991. state.ospfSort[tab].col = col;
  7992. state.ospfSort[tab].asc = true;
  7993. }
  7994. const asc = state.ospfSort[tab].asc;
  7995. let list = [];
  7996. if (tab === 'instances') list = state.ospfInstances || [];
  7997. else if (tab === 'areas') list = state.ospfAreas || [];
  7998. else if (tab === 'ranges') list = state.ospfAreaRanges || [];
  7999. else if (tab === 'templates') list = state.ospfTemplates || [];
  8000. else if (tab === 'live_ifaces') list = state.ospfLiveInterfaces || [];
  8001. else if (tab === 'snbrs') list = state.ospfStaticNbrs || [];
  8002. else if (tab === 'neighbors') list = state.ospfNeighbors || [];
  8003. else if (tab === 'lsa') list = state.ospfLSA || [];
  8004. list.sort((a, b) => {
  8005. let valA = a[col] ?? '';
  8006. let valB = b[col] ?? '';
  8007. if (typeof valA === 'number' && typeof valB === 'number') {
  8008. return asc ? valA - valB : valB - valA;
  8009. }
  8010. return asc ? String(valA).localeCompare(String(valB)) : String(valB).localeCompare(String(valA));
  8011. });
  8012. if (tab === 'instances') renderOspfInstances();
  8013. else if (tab === 'areas') renderOspfAreas();
  8014. else if (tab === 'ranges') renderOspfAreaRanges();
  8015. else if (tab === 'templates') renderOspfTemplates();
  8016. else if (tab === 'live_ifaces') renderOspfLiveInterfaces();
  8017. else if (tab === 'snbrs') renderOspfStaticNbrs();
  8018. else if (tab === 'neighbors') renderOspfNeighbors();
  8019. else if (tab === 'lsa') renderOspfLSA();
  8020. }
  8021. function selectOspfRow(tab, id) {
  8022. if (!state.selectedOspfRow) state.selectedOspfRow = {};
  8023. state.selectedOspfRow[tab] = id;
  8024. if (tab === 'instances') {
  8025. renderOspfInstances();
  8026. const btnEn = document.getElementById('btn-ospf-inst-enable');
  8027. const btnDis = document.getElementById('btn-ospf-inst-disable');
  8028. const btnRem = document.getElementById('btn-ospf-inst-remove');
  8029. const btnCom = document.getElementById('btn-ospf-inst-comment');
  8030. if (btnEn) btnEn.disabled = false;
  8031. if (btnDis) btnDis.disabled = false;
  8032. if (btnRem) btnRem.disabled = false;
  8033. if (btnCom) btnCom.disabled = false;
  8034. } else if (tab === 'areas') {
  8035. renderOspfAreas();
  8036. const btnEn = document.getElementById('btn-ospf-area-enable');
  8037. const btnDis = document.getElementById('btn-ospf-area-disable');
  8038. const btnRem = document.getElementById('btn-ospf-area-remove');
  8039. const btnCom = document.getElementById('btn-ospf-area-comment');
  8040. if (btnEn) btnEn.disabled = false;
  8041. if (btnDis) btnDis.disabled = false;
  8042. if (btnRem) btnRem.disabled = false;
  8043. if (btnCom) btnCom.disabled = false;
  8044. } else if (tab === 'ranges') {
  8045. renderOspfAreaRanges();
  8046. const btnEn = document.getElementById('btn-ospf-range-enable');
  8047. const btnDis = document.getElementById('btn-ospf-range-disable');
  8048. const btnRem = document.getElementById('btn-ospf-range-remove');
  8049. const btnCom = document.getElementById('btn-ospf-range-comment');
  8050. if (btnEn) btnEn.disabled = false;
  8051. if (btnDis) btnDis.disabled = false;
  8052. if (btnRem) btnRem.disabled = false;
  8053. if (btnCom) btnCom.disabled = false;
  8054. } else if (tab === 'templates') {
  8055. renderOspfTemplates();
  8056. const btnEn = document.getElementById('btn-ospf-tmpl-enable');
  8057. const btnDis = document.getElementById('btn-ospf-tmpl-disable');
  8058. const btnRem = document.getElementById('btn-ospf-tmpl-remove');
  8059. const btnCom = document.getElementById('btn-ospf-tmpl-comment');
  8060. if (btnEn) btnEn.disabled = false;
  8061. if (btnDis) btnDis.disabled = false;
  8062. if (btnRem) btnRem.disabled = false;
  8063. if (btnCom) btnCom.disabled = false;
  8064. } else if (tab === 'snbrs') {
  8065. renderOspfStaticNbrs();
  8066. const btnEn = document.getElementById('btn-ospf-snbr-enable');
  8067. const btnDis = document.getElementById('btn-ospf-snbr-disable');
  8068. const btnRem = document.getElementById('btn-ospf-snbr-remove');
  8069. const btnCom = document.getElementById('btn-ospf-snbr-comment');
  8070. if (btnEn) btnEn.disabled = false;
  8071. if (btnDis) btnDis.disabled = false;
  8072. if (btnRem) btnRem.disabled = false;
  8073. if (btnCom) btnCom.disabled = false;
  8074. }
  8075. }
  8076. // TAB 1: INSTANCES
  8077. function renderOspfInstances() {
  8078. const tbody = document.getElementById('ospf-instances-table-body');
  8079. if (!tbody) return;
  8080. const countEl = document.getElementById('ospf-instances-footer-count');
  8081. const filter = (document.getElementById('filter-ospf-instances')?.value || '').toLowerCase();
  8082. let list = state.ospfInstances || [];
  8083. if (filter) {
  8084. list = list.filter(i => (i.name || '').toLowerCase().includes(filter) || (i.router_id || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  8085. }
  8086. if (countEl) countEl.innerText = list.length;
  8087. const selId = state.selectedOspfRow?.instances;
  8088. tbody.innerHTML = list.map((inst, idx) => {
  8089. const isSel = inst.id === selId;
  8090. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  8091. const flagD = inst.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  8092. return `
  8093. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('instances', '${inst.id}')" ondblclick="openEditOspfInstanceModal('${inst.id}')">
  8094. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  8095. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🔀'}</td>
  8096. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(inst.comment || '')}</td>
  8097. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  8098. <span class="text-sky-400">↳</span> <span>${escapeHtml(inst.name || 'Default')}</span>
  8099. </td>
  8100. <td class="py-1.5 px-3">${inst.version || 2}</td>
  8101. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(inst.vrf || 'main')}</td>
  8102. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(inst.router_id || '192.168.131.56')}</td>
  8103. </tr>
  8104. `;
  8105. }).join('');
  8106. }
  8107. // TAB 2: AREAS
  8108. function renderOspfAreas() {
  8109. const tbody = document.getElementById('ospf-areas-table-body');
  8110. if (!tbody) return;
  8111. const countEl = document.getElementById('ospf-areas-footer-count');
  8112. const filter = (document.getElementById('filter-ospf-areas')?.value || '').toLowerCase();
  8113. let list = state.ospfAreas || [];
  8114. if (filter) {
  8115. list = list.filter(a => (a.name || '').toLowerCase().includes(filter) || (a.area_id || '').toLowerCase().includes(filter) || (a.comment || '').toLowerCase().includes(filter));
  8116. }
  8117. if (countEl) countEl.innerText = list.length;
  8118. const selId = state.selectedOspfRow?.areas;
  8119. tbody.innerHTML = list.map((a, idx) => {
  8120. const isSel = a.id === selId;
  8121. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  8122. const flagD = a.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  8123. return `
  8124. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('areas', '${a.id}')" ondblclick="openEditOspfAreaModal('${a.id}')">
  8125. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  8126. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🌐'}</td>
  8127. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(a.comment || '')}</td>
  8128. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  8129. <span class="text-sky-400">↳</span> <span>${escapeHtml(a.name || 'Default')}</span>
  8130. </td>
  8131. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(a.instance || 'Default')}</td>
  8132. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(a.area_id || '0.0.0.0')}</td>
  8133. <td class="py-1.5 px-3 font-mono text-slate-400">${escapeHtml(a.area_type || 'default')}</td>
  8134. </tr>
  8135. `;
  8136. }).join('');
  8137. }
  8138. // TAB 3: AREA RANGES
  8139. function renderOspfAreaRanges() {
  8140. const tbody = document.getElementById('ospf-ranges-table-body');
  8141. if (!tbody) return;
  8142. const countEl = document.getElementById('ospf-ranges-footer-count');
  8143. const filter = (document.getElementById('filter-ospf-area-ranges')?.value || '').toLowerCase();
  8144. let list = state.ospfAreaRanges || [];
  8145. if (filter) {
  8146. list = list.filter(r => (r.prefix || '').toLowerCase().includes(filter) || (r.area || '').toLowerCase().includes(filter) || (r.comment || '').toLowerCase().includes(filter));
  8147. }
  8148. if (countEl) countEl.innerText = list.length;
  8149. const selId = state.selectedOspfRow?.['area-ranges'];
  8150. tbody.innerHTML = list.map((r, idx) => {
  8151. const isSel = r.id === selId;
  8152. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  8153. const flagD = r.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  8154. return `
  8155. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('ranges', '${r.id}')" ondblclick="openEditOspfAreaRangeModal('${r.id}')">
  8156. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  8157. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🏷'}</td>
  8158. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(r.comment || '')}</td>
  8159. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(r.area || 'Default')}</td>
  8160. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(r.prefix || '')}</td>
  8161. <td class="py-1.5 px-3">${r.cost || 1}</td>
  8162. <td class="py-1.5 px-3">${r.advertise !== false ? 'yes' : 'no'}</td>
  8163. </tr>
  8164. `;
  8165. }).join('');
  8166. }
  8167. // TAB 4: INTERFACE TEMPLATES
  8168. function renderOspfTemplates() {
  8169. const tbody = document.getElementById('ospf-templates-table-body');
  8170. if (!tbody) return;
  8171. const countEl = document.getElementById('ospf-templates-footer-count');
  8172. const filter = (document.getElementById('filter-ospf-templates')?.value || '').toLowerCase();
  8173. let list = state.ospfTemplates || [];
  8174. if (filter) {
  8175. list = list.filter(t => (t.interfaces || t.interface || '').toLowerCase().includes(filter) || (t.networks || t.network || '').toLowerCase().includes(filter) || (t.comment || '').toLowerCase().includes(filter));
  8176. }
  8177. if (countEl) countEl.innerText = list.length;
  8178. const selId = state.selectedOspfRow?.templates;
  8179. tbody.innerHTML = list.map((t, idx) => {
  8180. const isSel = t.id === selId;
  8181. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  8182. const ifaces = t.interfaces || t.interface || 'all';
  8183. const nets = t.networks || t.network || '';
  8184. const flagD = t.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  8185. return `
  8186. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('templates', '${t.id}')" ondblclick="openEditOspfTemplateModal('${t.id}')">
  8187. <td class="py-1.5 px-3 w-8 text-center text-slate-500 font-bold">${idx}</td>
  8188. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🔀'}</td>
  8189. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(t.comment || '')}</td>
  8190. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  8191. <span class="text-sky-400">↳</span> <span>${escapeHtml(ifaces)}</span>
  8192. </td>
  8193. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(t.area || 'Default')}</td>
  8194. <td class="py-1.5 px-3 font-mono text-sky-300">${escapeHtml(nets)}</td>
  8195. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(t.network_type || 'broadcast')}</td>
  8196. <td class="py-1.5 px-3">${t.cost || 1}</td>
  8197. <td class="py-1.5 px-3">${t.priority || 128}</td>
  8198. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(t.auth || t.auth_type || '')}</td>
  8199. </tr>
  8200. `;
  8201. }).join('');
  8202. }
  8203. // TAB 5: LIVE INTERFACES
  8204. function renderOspfLiveInterfaces() {
  8205. const tbody = document.getElementById('ospf-live-interfaces-table-body');
  8206. if (!tbody) return;
  8207. const countEl = document.getElementById('ospf-live-interfaces-footer-count');
  8208. const filter = (document.getElementById('filter-ospf-interfaces')?.value || '').toLowerCase();
  8209. let list = state.ospfLiveInterfaces || [];
  8210. if (filter) {
  8211. list = list.filter(i => (i.interface || '').toLowerCase().includes(filter) || (i.address || '').toLowerCase().includes(filter) || (i.state || '').toLowerCase().includes(filter));
  8212. }
  8213. if (countEl) countEl.innerText = list.length;
  8214. tbody.innerHTML = list.map(i => `
  8215. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  8216. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(i.flags || 'D')}</td>
  8217. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(i.interface || '')}</td>
  8218. <td class="py-1.5 px-3 font-mono text-sky-300 font-medium">${escapeHtml(i.address || '')}</td>
  8219. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(i.area || 'Default')}</td>
  8220. <td class="py-1.5 px-3 text-center text-slate-400">${i.instance_id || 0}</td>
  8221. <td class="py-1.5 px-3 font-mono text-amber-300 lowercase">${escapeHtml(i.state || 'waiting')}</td>
  8222. <td class="py-1.5 px-3">${i.cost || 1}</td>
  8223. <td class="py-1.5 px-3">${i.priority || 128}</td>
  8224. </tr>
  8225. `).join('');
  8226. }
  8227. // TAB 6: STATIC NEIGHBORS
  8228. function renderOspfStaticNbrs() {
  8229. const tbody = document.getElementById('ospf-snbrs-table-body');
  8230. if (!tbody) return;
  8231. const countEl = document.getElementById('ospf-snbrs-footer-count');
  8232. const filter = (document.getElementById('filter-ospf-static-nbrs')?.value || '').toLowerCase();
  8233. let list = state.ospfStaticNbrs || [];
  8234. if (filter) {
  8235. list = list.filter(n => (n.address || '').toLowerCase().includes(filter) || (n.area || '').toLowerCase().includes(filter) || (n.comment || '').toLowerCase().includes(filter));
  8236. }
  8237. if (countEl) countEl.innerText = list.length;
  8238. const selId = state.selectedOspfRow?.['static-nbrs'];
  8239. tbody.innerHTML = list.map((n, idx) => {
  8240. const isSel = n.id === selId;
  8241. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  8242. const flagD = n.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  8243. return `
  8244. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('snbrs', '${n.id}')" ondblclick="openEditOspfStaticNbrModal('${n.id}')">
  8245. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  8246. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '📡'}</td>
  8247. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(n.comment || '')}</td>
  8248. <td class="py-1.5 px-3 font-semibold font-mono text-sky-300">${escapeHtml(n.address || '')}</td>
  8249. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(n.area || 'Default')}</td>
  8250. <td class="py-1.5 px-3">${n.poll_interval || 120}s</td>
  8251. <td class="py-1.5 px-3">${n.cost || 1}</td>
  8252. </tr>
  8253. `;
  8254. }).join('');
  8255. }
  8256. // TAB 7: LIVE NEIGHBORS
  8257. function renderOspfNeighbors() {
  8258. const tbody = document.getElementById('ospf-neighbors-table-body');
  8259. if (!tbody) return;
  8260. const countEl = document.getElementById('ospf-neighbors-footer-count');
  8261. const filter = (document.getElementById('filter-ospf-neighbors')?.value || '').toLowerCase();
  8262. let list = state.ospfNeighbors || [];
  8263. if (filter) {
  8264. list = list.filter(n => (n.address || '').toLowerCase().includes(filter) || (n.state || '').toLowerCase().includes(filter) || (n.instance || '').toLowerCase().includes(filter));
  8265. }
  8266. if (countEl) countEl.innerText = list.length;
  8267. tbody.innerHTML = list.map(n => `
  8268. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  8269. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(n.flags || 'D')}</td>
  8270. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(n.comment || '')}</td>
  8271. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  8272. <span class="text-sky-400">↳</span> <span>${escapeHtml(n.instance || 'Default')}</span>
  8273. </td>
  8274. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(n.area || 'Default')}</td>
  8275. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(n.address || '')}</td>
  8276. <td class="py-1.5 px-3 font-mono font-bold text-emerald-400">${escapeHtml(n.state || 'Full')}</td>
  8277. <td class="py-1.5 px-3 text-slate-400">${n.state_changes ?? 6}</td>
  8278. </tr>
  8279. `).join('');
  8280. }
  8281. // TAB 8: LINK-STATE DATABASE (LSA)
  8282. function renderOspfLSA() {
  8283. const tbody = document.getElementById('ospf-lsa-table-body');
  8284. if (!tbody) return;
  8285. const countEl = document.getElementById('ospf-lsa-footer-count');
  8286. const filter = (document.getElementById('filter-ospf-lsa')?.value || '').toLowerCase();
  8287. let list = state.ospfLSA || [];
  8288. if (filter) {
  8289. list = list.filter(l => (l.type || '').toLowerCase().includes(filter) || (l.originator || '').toLowerCase().includes(filter) || (l.id || '').toLowerCase().includes(filter));
  8290. }
  8291. if (countEl) countEl.innerText = list.length;
  8292. tbody.innerHTML = list.map(l => `
  8293. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  8294. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(l.flags || 'D')}</td>
  8295. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  8296. <span class="text-sky-400">↳</span> <span>${escapeHtml(l.instance || 'Default')}</span>
  8297. </td>
  8298. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(l.area || 'Default')}</td>
  8299. <td class="py-1.5 px-3 font-mono text-amber-300">${escapeHtml(l.type || 'router')}</td>
  8300. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(l.originator || '')}</td>
  8301. <td class="py-1.5 px-3 font-mono text-sky-300 font-medium">${escapeHtml(l.id || '')}</td>
  8302. <td class="py-1.5 px-3 text-slate-500">${escapeHtml(l.link || '')}</td>
  8303. <td class="py-1.5 px-3 text-slate-500">${l.link_index ?? 0}</td>
  8304. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(l.sequence || '')}</td>
  8305. <td class="py-1.5 px-3 text-slate-400">${l.age ?? 0}</td>
  8306. </tr>
  8307. `).join('');
  8308. }
  8309. function renderOspfStatusPill() {
  8310. // Maintained for backward compatibility
  8311. const pill = document.getElementById('ospf-live-status-pill');
  8312. if (!pill) return;
  8313. 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';
  8314. pill.innerText = 'OSPF ACTIVE';
  8315. }
  8316. function renderOspfInterfaces() {
  8317. renderOspfTemplates();
  8318. }
  8319. function renderOspfRoutes() {
  8320. // Routes retained in background
  8321. }
  8322. // BGP Modals & Actions
  8323. function openBgpInstanceModal() {
  8324. const inst = state.bgpInstance || { enabled: false, as: 65001, router_id: '192.168.131.56', hold_time: 180, keepalive_time: 60 };
  8325. document.getElementById('modal-bgp-enabled').checked = !!inst.enabled;
  8326. document.getElementById('modal-bgp-as').value = inst.as || 65001;
  8327. document.getElementById('modal-bgp-router-id').value = inst.router_id || '';
  8328. document.getElementById('modal-bgp-keepalive').value = inst.keepalive_time || 60;
  8329. document.getElementById('modal-bgp-holdtime').value = inst.hold_time || 180;
  8330. document.getElementById('modal-bgp-redist-conn').checked = !!inst.redistribute_connected;
  8331. document.getElementById('modal-bgp-redist-static').checked = !!inst.redistribute_static;
  8332. document.getElementById('modal-bgp-redist-ospf').checked = !!inst.redistribute_ospf;
  8333. document.getElementById('bgp-instance-modal').classList.remove('hidden');
  8334. }
  8335. function closeBgpInstanceModal() {
  8336. document.getElementById('bgp-instance-modal').classList.add('hidden');
  8337. }
  8338. async function submitBgpInstance(e) {
  8339. e.preventDefault();
  8340. const payload = {
  8341. enabled: document.getElementById('modal-bgp-enabled').checked,
  8342. as: parseInt(document.getElementById('modal-bgp-as').value, 10),
  8343. router_id: document.getElementById('modal-bgp-router-id').value.trim(),
  8344. keepalive_time: parseInt(document.getElementById('modal-bgp-keepalive').value, 10),
  8345. hold_time: parseInt(document.getElementById('modal-bgp-holdtime').value, 10),
  8346. redistribute_connected: document.getElementById('modal-bgp-redist-conn').checked,
  8347. redistribute_static: document.getElementById('modal-bgp-redist-static').checked,
  8348. redistribute_ospf: document.getElementById('modal-bgp-redist-ospf').checked
  8349. };
  8350. try {
  8351. const res = await fetch(`${API_BASE}/routing/bgp/instance`, {
  8352. method: 'POST',
  8353. headers: { 'Content-Type': 'application/json' },
  8354. body: JSON.stringify(payload)
  8355. });
  8356. if (res.ok) {
  8357. closeBgpInstanceModal();
  8358. showToast('Success', 'BGP instance configuration updated', 'success');
  8359. loadDynamicRouting();
  8360. } else {
  8361. const err = await res.json();
  8362. showToast('Error', err.error || 'Failed to update BGP instance', 'error');
  8363. }
  8364. } catch (err) {
  8365. showToast('Error', err.message, 'error');
  8366. }
  8367. }
  8368. // ----------------- BGP Peer Connection Modal (RouterOS v7) -----------------
  8369. function switchBgpPeerModalTab(tab) {
  8370. const tabs = ['general', 'extra', 'attributes', 'filter'];
  8371. tabs.forEach(t => {
  8372. const pane = document.getElementById(`bgp-peer-tab-${t}`);
  8373. const btn = document.getElementById(`bgp-peer-tab-btn-${t}`);
  8374. if (t === tab) {
  8375. if (pane) pane.classList.remove('hidden');
  8376. if (btn) btn.className = 'px-4 py-2 text-xs font-bold border-b-2 border-cyan-500 text-white transition';
  8377. } else {
  8378. if (pane) pane.classList.add('hidden');
  8379. 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';
  8380. }
  8381. });
  8382. }
  8383. function addOutputNetworkRow(val = '') {
  8384. const container = document.getElementById('modal-bgp-output-networks-container');
  8385. if (!container) return;
  8386. const row = document.createElement('div');
  8387. row.className = 'flex items-center gap-2 output-net-row';
  8388. row.innerHTML = `
  8389. <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">
  8390. <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>
  8391. `;
  8392. container.appendChild(row);
  8393. }
  8394. function parseBgpTime(val) {
  8395. if (!val) return 0;
  8396. val = String(val).trim();
  8397. if (val.includes(':')) {
  8398. const parts = val.split(':').map(x => parseInt(x, 10) || 0);
  8399. if (parts.length === 3) return parts[0] * 3600 + parts[1] * 60 + parts[2];
  8400. if (parts.length === 2) return parts[0] * 60 + parts[1];
  8401. }
  8402. return parseInt(val, 10) || 0;
  8403. }
  8404. function formatBgpTime(secs) {
  8405. if (!secs || secs <= 0) return '00:00:00';
  8406. const h = Math.floor(secs / 3600);
  8407. const m = Math.floor((secs % 3600) / 60);
  8408. const s = secs % 60;
  8409. return `${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`;
  8410. }
  8411. function populateBgpRoutingTables() {
  8412. const sel = document.getElementById('modal-bgp-peer-routing-table');
  8413. if (!sel) return;
  8414. const cur = sel.value || 'main';
  8415. sel.innerHTML = '<option value="main">main</option>';
  8416. (state.routingTables || []).forEach(t => {
  8417. if (t.name !== 'main') {
  8418. const opt = document.createElement('option');
  8419. opt.value = t.name;
  8420. opt.innerText = t.name;
  8421. sel.appendChild(opt);
  8422. }
  8423. });
  8424. sel.value = cur;
  8425. }
  8426. function openAddBgpPeerModal() {
  8427. document.getElementById('bgp-peer-form').reset();
  8428. document.getElementById('modal-bgp-peer-id').value = '';
  8429. document.getElementById('bgp-peer-modal-title').innerText = 'New...';
  8430. // General Tab
  8431. document.getElementById('modal-bgp-peer-enabled').checked = true;
  8432. document.getElementById('modal-bgp-peer-comment').value = '';
  8433. document.getElementById('modal-bgp-peer-name').value = '';
  8434. if (document.getElementById('modal-bgp-peer-instance')) document.getElementById('modal-bgp-peer-instance').value = 'bgp-instance-1';
  8435. if (document.getElementById('modal-bgp-peer-template')) document.getElementById('modal-bgp-peer-template').value = '';
  8436. document.getElementById('modal-bgp-peer-local-as').value = '';
  8437. document.getElementById('modal-bgp-peer-afi-ip').checked = true;
  8438. document.getElementById('modal-bgp-peer-afi-ipv6').checked = false;
  8439. if (document.getElementById('modal-bgp-peer-afi-l2vpn')) document.getElementById('modal-bgp-peer-afi-l2vpn').checked = false;
  8440. if (document.getElementById('modal-bgp-peer-afi-vpnv4')) document.getElementById('modal-bgp-peer-afi-vpnv4').checked = false;
  8441. if (document.getElementById('modal-bgp-peer-afi-l2vpn-cisco')) document.getElementById('modal-bgp-peer-afi-l2vpn-cisco').checked = false;
  8442. document.getElementById('modal-bgp-peer-router-id').value = '';
  8443. document.getElementById('modal-bgp-peer-remote-addr').value = '';
  8444. document.getElementById('modal-bgp-peer-remote-port').value = '';
  8445. document.getElementById('modal-bgp-peer-remote-as').value = '';
  8446. if (document.getElementById('modal-bgp-peer-remote-allow-as')) document.getElementById('modal-bgp-peer-remote-allow-as').value = '';
  8447. document.getElementById('modal-bgp-peer-local-addr').value = '';
  8448. document.getElementById('modal-bgp-peer-local-port').value = '';
  8449. document.getElementById('modal-bgp-peer-local-role').value = 'ebgp';
  8450. document.getElementById('modal-bgp-peer-password').value = '';
  8451. document.getElementById('modal-bgp-peer-multihop').checked = false;
  8452. if (document.getElementById('modal-bgp-peer-tx-ttl')) document.getElementById('modal-bgp-peer-tx-ttl').value = '';
  8453. if (document.getElementById('modal-bgp-peer-rx-min-ttl')) document.getElementById('modal-bgp-peer-rx-min-ttl').value = '';
  8454. document.getElementById('modal-bgp-peer-connect').checked = true;
  8455. document.getElementById('modal-bgp-peer-listen').checked = true;
  8456. // Extra Tab
  8457. document.getElementById('modal-bgp-peer-holdtime').value = '00:00:30';
  8458. document.getElementById('modal-bgp-peer-keepalive').value = '00:00:10';
  8459. if (document.getElementById('modal-bgp-peer-use-bfd')) document.getElementById('modal-bgp-peer-use-bfd').checked = false;
  8460. if (document.getElementById('modal-bgp-peer-vrf')) document.getElementById('modal-bgp-peer-vrf').value = 'main';
  8461. if (document.getElementById('modal-bgp-peer-no-client-reflect')) document.getElementById('modal-bgp-peer-no-client-reflect').checked = true;
  8462. document.getElementById('modal-bgp-peer-redist-conn').checked = false;
  8463. document.getElementById('modal-bgp-peer-redist-static').checked = true;
  8464. if (document.getElementById('modal-bgp-peer-redist-rip')) document.getElementById('modal-bgp-peer-redist-rip').checked = false;
  8465. document.getElementById('modal-bgp-peer-redist-ospf').checked = false;
  8466. document.getElementById('modal-bgp-peer-redist-bgp').checked = false;
  8467. if (document.getElementById('modal-bgp-peer-redist-vpn')) document.getElementById('modal-bgp-peer-redist-vpn').checked = false;
  8468. if (document.getElementById('modal-bgp-peer-redist-dhcp')) document.getElementById('modal-bgp-peer-redist-dhcp').checked = false;
  8469. if (document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn')) document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn').checked = false;
  8470. if (document.getElementById('modal-bgp-peer-redist-slaac')) document.getElementById('modal-bgp-peer-redist-slaac').checked = false;
  8471. document.getElementById('modal-bgp-peer-default-orig').checked = false;
  8472. if (document.getElementById('modal-bgp-peer-network-blackhole')) document.getElementById('modal-bgp-peer-network-blackhole').checked = false;
  8473. if (document.getElementById('modal-bgp-peer-no-early-cut')) document.getElementById('modal-bgp-peer-no-early-cut').checked = false;
  8474. if (document.getElementById('modal-bgp-peer-keep-sent-attrs')) document.getElementById('modal-bgp-peer-keep-sent-attrs').checked = false;
  8475. if (document.getElementById('modal-bgp-peer-input-affinity')) document.getElementById('modal-bgp-peer-input-affinity').value = '';
  8476. if (document.getElementById('modal-bgp-peer-output-affinity')) document.getElementById('modal-bgp-peer-output-affinity').value = '';
  8477. // Attributes Tab
  8478. document.getElementById('modal-bgp-peer-nexthop-choice').value = 'force-self';
  8479. document.getElementById('modal-bgp-peer-default-prepend').value = 0;
  8480. document.getElementById('modal-bgp-peer-allow-as-in').value = 0;
  8481. if (document.getElementById('modal-bgp-peer-ignore-as-path-len')) document.getElementById('modal-bgp-peer-ignore-as-path-len').checked = false;
  8482. document.getElementById('modal-bgp-peer-remove-priv-as').checked = false;
  8483. document.getElementById('modal-bgp-peer-as-override').checked = false;
  8484. // Filter Tab
  8485. populateFilterChainsDatalist();
  8486. document.getElementById('modal-bgp-peer-in-filter').value = '';
  8487. if (document.getElementById('modal-bgp-peer-in-accept-nlri')) document.getElementById('modal-bgp-peer-in-accept-nlri').value = '';
  8488. if (document.getElementById('modal-bgp-peer-in-accept-comm')) document.getElementById('modal-bgp-peer-in-accept-comm').value = '';
  8489. if (document.getElementById('modal-bgp-peer-in-accept-ext-comm')) document.getElementById('modal-bgp-peer-in-accept-ext-comm').value = '';
  8490. if (document.getElementById('modal-bgp-peer-in-accept-large-comm')) document.getElementById('modal-bgp-peer-in-accept-large-comm').value = '';
  8491. if (document.getElementById('modal-bgp-peer-in-filter-comm')) document.getElementById('modal-bgp-peer-in-filter-comm').value = '';
  8492. if (document.getElementById('modal-bgp-peer-in-filter-ext-comm')) document.getElementById('modal-bgp-peer-in-filter-ext-comm').value = '';
  8493. if (document.getElementById('modal-bgp-peer-in-filter-large-comm')) document.getElementById('modal-bgp-peer-in-filter-large-comm').value = '';
  8494. if (document.getElementById('modal-bgp-peer-in-filter-unknown')) document.getElementById('modal-bgp-peer-in-filter-unknown').checked = false;
  8495. document.getElementById('modal-bgp-peer-out-filter').value = '';
  8496. if (document.getElementById('modal-bgp-peer-out-selection-policy')) document.getElementById('modal-bgp-peer-out-selection-policy').value = 'disabled';
  8497. if (document.getElementById('modal-bgp-peer-out-network-name')) document.getElementById('modal-bgp-peer-out-network-name').value = '';
  8498. populateBgpRoutingTables();
  8499. const container = document.getElementById('modal-bgp-output-networks-container');
  8500. if (container) {
  8501. container.innerHTML = '';
  8502. addOutputNetworkRow('');
  8503. }
  8504. const removeBtn = document.getElementById('modal-btn-remove-peer');
  8505. if (removeBtn) removeBtn.classList.add('hidden');
  8506. switchBgpPeerModalTab('general');
  8507. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  8508. }
  8509. function populateFilterChainsDatalist() {
  8510. const dl = document.getElementById('filter-chains-list');
  8511. if (!dl) return;
  8512. const chains = new Set();
  8513. (state.routingFilters || []).forEach(f => {
  8514. if (f.chain) chains.add(f.chain);
  8515. });
  8516. if (chains.size === 0) {
  8517. chains.add('awmn');
  8518. chains.add('bgp-in');
  8519. chains.add('bgp-out');
  8520. }
  8521. dl.innerHTML = '';
  8522. chains.forEach(c => {
  8523. const opt = document.createElement('option');
  8524. opt.value = c;
  8525. dl.appendChild(opt);
  8526. });
  8527. }
  8528. function openEditBgpPeerModal(id) {
  8529. const p = (state.bgpPeers || []).find(item => item.id === id);
  8530. if (!p) return;
  8531. populateBgpRoutingTables();
  8532. populateFilterChainsDatalist();
  8533. document.getElementById('modal-bgp-peer-id').value = p.id;
  8534. document.getElementById('bgp-peer-modal-title').innerText = p.name || p.id;
  8535. // General Tab
  8536. document.getElementById('modal-bgp-peer-enabled').checked = p.enabled !== false && !p.disabled;
  8537. document.getElementById('modal-bgp-peer-comment').value = p.comment || '';
  8538. document.getElementById('modal-bgp-peer-name').value = p.name || '';
  8539. if (document.getElementById('modal-bgp-peer-instance')) document.getElementById('modal-bgp-peer-instance').value = p.instance || 'bgp-instance-1';
  8540. if (document.getElementById('modal-bgp-peer-template')) document.getElementById('modal-bgp-peer-template').value = p.template || '';
  8541. document.getElementById('modal-bgp-peer-local-as').value = p.local_as || '';
  8542. document.getElementById('modal-bgp-peer-router-id').value = p.router_id || '';
  8543. document.getElementById('modal-bgp-peer-afi-ip').checked = true;
  8544. document.getElementById('modal-bgp-peer-afi-ipv6').checked = p.afi === 'ipv6';
  8545. document.getElementById('modal-bgp-peer-remote-addr').value = p.remote_address || '';
  8546. document.getElementById('modal-bgp-peer-remote-port').value = p.remote_port || '';
  8547. document.getElementById('modal-bgp-peer-remote-as').value = p.remote_as || '';
  8548. if (document.getElementById('modal-bgp-peer-remote-allow-as')) document.getElementById('modal-bgp-peer-remote-allow-as').value = p.remote_allow_as || '';
  8549. document.getElementById('modal-bgp-peer-local-addr').value = p.local_address || '';
  8550. document.getElementById('modal-bgp-peer-local-port').value = p.local_port || '';
  8551. document.getElementById('modal-bgp-peer-local-role').value = p.local_role || 'ebgp';
  8552. document.getElementById('modal-bgp-peer-password').value = p.password || '';
  8553. document.getElementById('modal-bgp-peer-multihop').checked = !!p.multihop;
  8554. if (document.getElementById('modal-bgp-peer-tx-ttl')) document.getElementById('modal-bgp-peer-tx-ttl').value = p.tx_ttl || '';
  8555. if (document.getElementById('modal-bgp-peer-rx-min-ttl')) document.getElementById('modal-bgp-peer-rx-min-ttl').value = p.rx_min_ttl || '';
  8556. document.getElementById('modal-bgp-peer-connect').checked = p.connect !== false;
  8557. document.getElementById('modal-bgp-peer-listen').checked = p.listen !== false;
  8558. // Extra Tab
  8559. document.getElementById('modal-bgp-peer-holdtime').value = p.hold_time ? formatBgpTime(p.hold_time) : '00:00:30';
  8560. document.getElementById('modal-bgp-peer-keepalive').value = p.keepalive_time ? formatBgpTime(p.keepalive_time) : '00:00:10';
  8561. if (document.getElementById('modal-bgp-peer-use-bfd')) document.getElementById('modal-bgp-peer-use-bfd').checked = !!p.use_bfd;
  8562. document.getElementById('modal-bgp-peer-routing-table').value = p.routing_table || 'main';
  8563. if (document.getElementById('modal-bgp-peer-vrf')) document.getElementById('modal-bgp-peer-vrf').value = p.vrf || 'main';
  8564. if (document.getElementById('modal-bgp-peer-no-client-reflect')) document.getElementById('modal-bgp-peer-no-client-reflect').checked = p.no_client_reflect !== false;
  8565. document.getElementById('modal-bgp-peer-redist-conn').checked = !!p.redist_connected;
  8566. document.getElementById('modal-bgp-peer-redist-static').checked = p.redist_static !== false;
  8567. if (document.getElementById('modal-bgp-peer-redist-rip')) document.getElementById('modal-bgp-peer-redist-rip').checked = !!p.redist_rip;
  8568. document.getElementById('modal-bgp-peer-redist-ospf').checked = !!p.redist_ospf;
  8569. document.getElementById('modal-bgp-peer-redist-bgp').checked = !!p.redist_bgp;
  8570. if (document.getElementById('modal-bgp-peer-redist-vpn')) document.getElementById('modal-bgp-peer-redist-vpn').checked = !!p.redist_vpn;
  8571. if (document.getElementById('modal-bgp-peer-redist-dhcp')) document.getElementById('modal-bgp-peer-redist-dhcp').checked = !!p.redist_dhcp;
  8572. 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;
  8573. if (document.getElementById('modal-bgp-peer-redist-slaac')) document.getElementById('modal-bgp-peer-redist-slaac').checked = !!p.redist_slaac;
  8574. document.getElementById('modal-bgp-peer-default-orig').checked = !!p.default_originate;
  8575. if (document.getElementById('modal-bgp-peer-network-blackhole')) document.getElementById('modal-bgp-peer-network-blackhole').checked = !!p.network_blackhole;
  8576. if (document.getElementById('modal-bgp-peer-no-early-cut')) document.getElementById('modal-bgp-peer-no-early-cut').checked = !!p.no_early_cut;
  8577. if (document.getElementById('modal-bgp-peer-keep-sent-attrs')) document.getElementById('modal-bgp-peer-keep-sent-attrs').checked = !!p.keep_sent_attrs;
  8578. if (document.getElementById('modal-bgp-peer-input-affinity')) document.getElementById('modal-bgp-peer-input-affinity').value = p.input_affinity || '';
  8579. if (document.getElementById('modal-bgp-peer-output-affinity')) document.getElementById('modal-bgp-peer-output-affinity').value = p.output_affinity || '';
  8580. // Attributes Tab
  8581. document.getElementById('modal-bgp-peer-nexthop-choice').value = p.nexthop_choice || (p.nexthop_self ? 'force-self' : 'default');
  8582. document.getElementById('modal-bgp-peer-default-prepend').value = p.default_prepend || 0;
  8583. document.getElementById('modal-bgp-peer-allow-as-in').value = p.allow_as_in || 0;
  8584. 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;
  8585. document.getElementById('modal-bgp-peer-remove-priv-as').checked = !!p.remove_private_as;
  8586. document.getElementById('modal-bgp-peer-as-override').checked = !!p.as_override;
  8587. // Filter Tab
  8588. document.getElementById('modal-bgp-peer-in-filter').value = p.in_filter || '';
  8589. if (document.getElementById('modal-bgp-peer-in-accept-nlri')) document.getElementById('modal-bgp-peer-in-accept-nlri').value = p.in_accept_nlri || '';
  8590. if (document.getElementById('modal-bgp-peer-in-accept-comm')) document.getElementById('modal-bgp-peer-in-accept-comm').value = p.in_accept_communities || '';
  8591. 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 || '';
  8592. 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 || '';
  8593. if (document.getElementById('modal-bgp-peer-in-filter-comm')) document.getElementById('modal-bgp-peer-in-filter-comm').value = p.in_filter_communities || '';
  8594. 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 || '';
  8595. 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 || '';
  8596. if (document.getElementById('modal-bgp-peer-in-filter-unknown')) document.getElementById('modal-bgp-peer-in-filter-unknown').checked = !!p.in_filter_unknown;
  8597. document.getElementById('modal-bgp-peer-out-filter').value = p.out_filter || '';
  8598. if (document.getElementById('modal-bgp-peer-out-selection-policy')) document.getElementById('modal-bgp-peer-out-selection-policy').value = p.out_selection_policy || 'disabled';
  8599. if (document.getElementById('modal-bgp-peer-out-network-name')) document.getElementById('modal-bgp-peer-out-network-name').value = p.output_network || '';
  8600. // Output Networks
  8601. const container = document.getElementById('modal-bgp-output-networks-container');
  8602. if (container) {
  8603. container.innerHTML = '';
  8604. if (p.output_networks && p.output_networks.length > 0) {
  8605. p.output_networks.forEach(net => addOutputNetworkRow(net));
  8606. } else {
  8607. addOutputNetworkRow('');
  8608. }
  8609. }
  8610. const removeBtn = document.getElementById('modal-btn-remove-peer');
  8611. if (removeBtn) removeBtn.classList.remove('hidden');
  8612. switchBgpPeerModalTab('general');
  8613. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  8614. }
  8615. function copyCurrentBgpPeer() {
  8616. document.getElementById('modal-bgp-peer-id').value = '';
  8617. const nameEl = document.getElementById('modal-bgp-peer-name');
  8618. if (nameEl) nameEl.value = (nameEl.value || 'peer') + '-copy';
  8619. document.getElementById('bgp-peer-modal-title').innerText = 'New...';
  8620. const removeBtn = document.getElementById('modal-btn-remove-peer');
  8621. if (removeBtn) removeBtn.classList.add('hidden');
  8622. showToast('Cloned', 'BGP connection copied to new draft', 'info');
  8623. }
  8624. function removeCurrentBgpPeer() {
  8625. const id = document.getElementById('modal-bgp-peer-id')?.value;
  8626. if (!id) return;
  8627. deleteBgpPeer(id);
  8628. closeBgpPeerModal();
  8629. }
  8630. function closeBgpPeerModal() {
  8631. document.getElementById('bgp-peer-modal').classList.add('hidden');
  8632. }
  8633. function getBgpPeerFormData() {
  8634. const netInputs = document.querySelectorAll('#modal-bgp-output-networks-container .output-net-row input');
  8635. const outputNetworks = [];
  8636. netInputs.forEach(inp => {
  8637. const v = inp.value.trim();
  8638. if (v) outputNetworks.push(v);
  8639. });
  8640. const enabled = document.getElementById('modal-bgp-peer-enabled').checked;
  8641. return {
  8642. id: document.getElementById('modal-bgp-peer-id').value,
  8643. name: document.getElementById('modal-bgp-peer-name').value.trim(),
  8644. enabled: enabled,
  8645. disabled: !enabled,
  8646. comment: document.getElementById('modal-bgp-peer-comment').value.trim(),
  8647. instance: document.getElementById('modal-bgp-peer-instance')?.value.trim() || 'bgp-instance-1',
  8648. template: document.getElementById('modal-bgp-peer-template')?.value.trim() || '',
  8649. local_as: parseInt(document.getElementById('modal-bgp-peer-local-as')?.value, 10) || 0,
  8650. router_id: document.getElementById('modal-bgp-peer-router-id').value.trim(),
  8651. afi: document.getElementById('modal-bgp-peer-afi-ipv6').checked ? 'ipv6' : 'ip',
  8652. remote_address: document.getElementById('modal-bgp-peer-remote-addr').value.trim(),
  8653. remote_port: parseInt(document.getElementById('modal-bgp-peer-remote-port').value, 10) || 0,
  8654. remote_as: parseInt(document.getElementById('modal-bgp-peer-remote-as').value, 10) || 0,
  8655. remote_allow_as: document.getElementById('modal-bgp-peer-remote-allow-as')?.value.trim() || '',
  8656. local_address: document.getElementById('modal-bgp-peer-local-addr').value.trim(),
  8657. local_port: parseInt(document.getElementById('modal-bgp-peer-local-port').value, 10) || 0,
  8658. local_role: document.getElementById('modal-bgp-peer-local-role').value,
  8659. password: document.getElementById('modal-bgp-peer-password').value,
  8660. multihop: document.getElementById('modal-bgp-peer-multihop').checked,
  8661. tx_ttl: parseInt(document.getElementById('modal-bgp-peer-tx-ttl')?.value, 10) || 0,
  8662. rx_min_ttl: parseInt(document.getElementById('modal-bgp-peer-rx-min-ttl')?.value, 10) || 0,
  8663. connect: document.getElementById('modal-bgp-peer-connect').checked,
  8664. listen: document.getElementById('modal-bgp-peer-listen').checked,
  8665. hold_time: parseBgpTime(document.getElementById('modal-bgp-peer-holdtime').value),
  8666. keepalive_time: parseBgpTime(document.getElementById('modal-bgp-peer-keepalive').value),
  8667. use_bfd: document.getElementById('modal-bgp-peer-use-bfd')?.checked || false,
  8668. routing_table: document.getElementById('modal-bgp-peer-routing-table').value,
  8669. vrf: document.getElementById('modal-bgp-peer-vrf')?.value.trim() || 'main',
  8670. no_client_reflect: document.getElementById('modal-bgp-peer-no-client-reflect')?.checked || false,
  8671. redist_connected: document.getElementById('modal-bgp-peer-redist-conn').checked,
  8672. redist_static: document.getElementById('modal-bgp-peer-redist-static').checked,
  8673. redist_rip: document.getElementById('modal-bgp-peer-redist-rip')?.checked || false,
  8674. redist_ospf: document.getElementById('modal-bgp-peer-redist-ospf').checked,
  8675. redist_bgp: document.getElementById('modal-bgp-peer-redist-bgp').checked,
  8676. redist_vpn: document.getElementById('modal-bgp-peer-redist-vpn')?.checked || false,
  8677. redist_dhcp: document.getElementById('modal-bgp-peer-redist-dhcp')?.checked || false,
  8678. redist_bgp_mpls_vpn: document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn')?.checked || false,
  8679. redist_slaac: document.getElementById('modal-bgp-peer-redist-slaac')?.checked || false,
  8680. default_originate: document.getElementById('modal-bgp-peer-default-orig').checked,
  8681. network_blackhole: document.getElementById('modal-bgp-peer-network-blackhole')?.checked || false,
  8682. no_early_cut: document.getElementById('modal-bgp-peer-no-early-cut')?.checked || false,
  8683. keep_sent_attrs: document.getElementById('modal-bgp-peer-keep-sent-attrs')?.checked || false,
  8684. input_affinity: (document.getElementById('modal-bgp-peer-input-affinity')?.value || '').trim(),
  8685. output_affinity: (document.getElementById('modal-bgp-peer-output-affinity')?.value || '').trim(),
  8686. nexthop_choice: document.getElementById('modal-bgp-peer-nexthop-choice').value,
  8687. nexthop_self: document.getElementById('modal-bgp-peer-nexthop-choice').value === 'force-self',
  8688. default_prepend: parseInt(document.getElementById('modal-bgp-peer-default-prepend').value, 10) || 0,
  8689. allow_as_in: parseInt(document.getElementById('modal-bgp-peer-allow-as-in').value, 10) || 0,
  8690. ignore_as_path_len: document.getElementById('modal-bgp-peer-ignore-as-path-len')?.checked || false,
  8691. remove_private_as: document.getElementById('modal-bgp-peer-remove-priv-as').checked,
  8692. as_override: document.getElementById('modal-bgp-peer-as-override').checked,
  8693. in_filter: (document.getElementById('modal-bgp-peer-in-filter')?.value || '').trim(),
  8694. in_accept_nlri: (document.getElementById('modal-bgp-peer-in-accept-nlri')?.value || '').trim(),
  8695. in_accept_communities: (document.getElementById('modal-bgp-peer-in-accept-comm')?.value || '').trim(),
  8696. in_accept_ext_communities: (document.getElementById('modal-bgp-peer-in-accept-ext-comm')?.value || '').trim(),
  8697. in_accept_large_communities: (document.getElementById('modal-bgp-peer-in-accept-large-comm')?.value || '').trim(),
  8698. in_filter_communities: (document.getElementById('modal-bgp-peer-in-filter-comm')?.value || '').trim(),
  8699. in_filter_ext_communities: (document.getElementById('modal-bgp-peer-in-filter-ext-comm')?.value || '').trim(),
  8700. in_filter_large_communities: (document.getElementById('modal-bgp-peer-in-filter-large-comm')?.value || '').trim(),
  8701. in_filter_unknown: document.getElementById('modal-bgp-peer-in-filter-unknown')?.checked || false,
  8702. out_filter: (document.getElementById('modal-bgp-peer-out-filter')?.value || '').trim(),
  8703. out_selection_policy: document.getElementById('modal-bgp-peer-out-selection-policy')?.value || 'disabled',
  8704. output_network: (document.getElementById('modal-bgp-peer-out-network-name')?.value || '').trim(),
  8705. output_networks: outputNetworks
  8706. };
  8707. }
  8708. async function submitBgpPeer(e) {
  8709. if (e) e.preventDefault();
  8710. const payload = getBgpPeerFormData();
  8711. try {
  8712. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  8713. method: 'POST',
  8714. headers: { 'Content-Type': 'application/json' },
  8715. body: JSON.stringify(payload)
  8716. });
  8717. if (res.ok) {
  8718. closeBgpPeerModal();
  8719. showToast('Success', 'BGP Connection saved', 'success');
  8720. loadDynamicRouting();
  8721. } else {
  8722. const err = await res.json();
  8723. showToast('Error', err.error || 'Failed to save peer', 'error');
  8724. }
  8725. } catch (err) {
  8726. showToast('Error', err.message, 'error');
  8727. }
  8728. }
  8729. async function applyBgpPeerModal(e) {
  8730. if (e) e.preventDefault();
  8731. const payload = getBgpPeerFormData();
  8732. try {
  8733. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  8734. method: 'POST',
  8735. headers: { 'Content-Type': 'application/json' },
  8736. body: JSON.stringify(payload)
  8737. });
  8738. if (res.ok) {
  8739. const data = await res.json();
  8740. if (data.peer && data.peer.id) {
  8741. document.getElementById('modal-bgp-peer-id').value = data.peer.id;
  8742. document.getElementById('bgp-peer-modal-title').innerText = data.peer.name || data.peer.id;
  8743. document.getElementById('modal-btn-remove-peer')?.classList.remove('hidden');
  8744. }
  8745. showToast('Applied', 'BGP Connection applied', 'success');
  8746. loadDynamicRouting();
  8747. } else {
  8748. const err = await res.json();
  8749. showToast('Error', err.error || 'Failed to apply peer', 'error');
  8750. }
  8751. } catch (err) {
  8752. showToast('Error', err.message, 'error');
  8753. }
  8754. }
  8755. async function deleteBgpPeer(id) {
  8756. if (!confirm('Are you sure you want to delete this BGP peer connection?')) return;
  8757. try {
  8758. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8759. if (res.ok) {
  8760. showToast('Deleted', 'BGP peer removed', 'success');
  8761. loadDynamicRouting();
  8762. }
  8763. } catch (err) {
  8764. showToast('Error', err.message, 'error');
  8765. }
  8766. }
  8767. async function toggleBgpPeerState(id, disabled) {
  8768. try {
  8769. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}/state`, {
  8770. method: 'POST',
  8771. headers: { 'Content-Type': 'application/json' },
  8772. body: JSON.stringify({ disabled })
  8773. });
  8774. if (res.ok) {
  8775. showToast('Updated', `Peer ${disabled ? 'disabled' : 'enabled'}`, 'success');
  8776. loadDynamicRouting();
  8777. }
  8778. } catch (err) {
  8779. showToast('Error', err.message, 'error');
  8780. }
  8781. }
  8782. function openAddBgpNetworkModal() {
  8783. document.getElementById('bgp-network-form').reset();
  8784. document.getElementById('modal-bgp-net-id').value = '';
  8785. document.getElementById('bgp-network-modal').classList.remove('hidden');
  8786. }
  8787. function closeBgpNetworkModal() {
  8788. document.getElementById('bgp-network-modal').classList.add('hidden');
  8789. }
  8790. async function submitBgpNetwork(e) {
  8791. e.preventDefault();
  8792. const payload = {
  8793. id: document.getElementById('modal-bgp-net-id').value,
  8794. network: document.getElementById('modal-bgp-net-cidr').value.trim(),
  8795. comment: document.getElementById('modal-bgp-net-comment').value.trim(),
  8796. disabled: document.getElementById('modal-bgp-net-disabled').checked
  8797. };
  8798. try {
  8799. const res = await fetch(`${API_BASE}/routing/bgp/networks`, {
  8800. method: 'POST',
  8801. headers: { 'Content-Type': 'application/json' },
  8802. body: JSON.stringify(payload)
  8803. });
  8804. if (res.ok) {
  8805. closeBgpNetworkModal();
  8806. showToast('Success', 'BGP network advertisement saved', 'success');
  8807. loadDynamicRouting();
  8808. } else {
  8809. const err = await res.json();
  8810. showToast('Error', err.error || 'Failed to save network', 'error');
  8811. }
  8812. } catch (err) {
  8813. showToast('Error', err.message, 'error');
  8814. }
  8815. }
  8816. async function deleteBgpNetwork(id) {
  8817. if (!confirm('Are you sure you want to stop announcing this network?')) return;
  8818. try {
  8819. const res = await fetch(`${API_BASE}/routing/bgp/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8820. if (res.ok) {
  8821. showToast('Deleted', 'Network advertisement removed', 'success');
  8822. loadDynamicRouting();
  8823. }
  8824. } catch (err) {
  8825. showToast('Error', err.message, 'error');
  8826. }
  8827. }
  8828. // =========================================================================
  8829. // ROUTEROS v7 OSPF MODALS & ACTIONS
  8830. // =========================================================================
  8831. // --- 1. OSPF INSTANCE ---
  8832. function openOspfInstanceModal(id = null) {
  8833. const isEdit = !!id;
  8834. const inst = (state.ospfInstances || []).find(i => i.id === id) || {
  8835. id: '',
  8836. name: 'Default',
  8837. version: 2,
  8838. vrf: 'main',
  8839. router_id: '192.168.131.56',
  8840. routing_table: 'main',
  8841. enabled: true,
  8842. redistribute_connected: false,
  8843. redistribute_static: true,
  8844. redistribute_bgp: false,
  8845. comment: ''
  8846. };
  8847. document.getElementById('ospf-instance-modal-title').innerText = isEdit ? inst.name : 'New...';
  8848. document.getElementById('modal-ospf-inst-id').value = isEdit ? inst.id : '';
  8849. document.getElementById('modal-ospf-inst-enabled').checked = !inst.disabled;
  8850. document.getElementById('modal-ospf-inst-comment').value = inst.comment || '';
  8851. document.getElementById('modal-ospf-inst-name').value = inst.name || 'Default';
  8852. document.getElementById('modal-ospf-inst-version').value = inst.version || 2;
  8853. document.getElementById('modal-ospf-inst-vrf').value = inst.vrf || 'main';
  8854. document.getElementById('modal-ospf-inst-router-id').value = inst.router_id || '';
  8855. document.getElementById('modal-ospf-inst-routing-table').value = inst.routing_table || 'main';
  8856. document.getElementById('modal-ospf-inst-redist-conn').checked = !!inst.redistribute_connected;
  8857. document.getElementById('modal-ospf-inst-redist-static').checked = inst.redistribute_static !== false;
  8858. document.getElementById('modal-ospf-inst-redist-bgp').checked = !!inst.redistribute_bgp;
  8859. const btnRem = document.getElementById('btn-ospf-inst-modal-remove');
  8860. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  8861. document.getElementById('ospf-instance-modal').classList.remove('hidden');
  8862. }
  8863. function openEditOspfInstanceModal(id) {
  8864. openOspfInstanceModal(id);
  8865. }
  8866. function closeOspfInstanceModal() {
  8867. document.getElementById('ospf-instance-modal').classList.add('hidden');
  8868. }
  8869. async function submitOspfInstance(e) {
  8870. if (e) e.preventDefault();
  8871. const payload = {
  8872. id: document.getElementById('modal-ospf-inst-id').value,
  8873. name: document.getElementById('modal-ospf-inst-name').value.trim() || 'Default',
  8874. version: parseInt(document.getElementById('modal-ospf-inst-version').value, 10) || 2,
  8875. vrf: document.getElementById('modal-ospf-inst-vrf').value.trim() || 'main',
  8876. router_id: document.getElementById('modal-ospf-inst-router-id').value.trim(),
  8877. routing_table: document.getElementById('modal-ospf-inst-routing-table').value.trim() || 'main',
  8878. enabled: document.getElementById('modal-ospf-inst-enabled').checked,
  8879. disabled: !document.getElementById('modal-ospf-inst-enabled').checked,
  8880. comment: document.getElementById('modal-ospf-inst-comment').value.trim(),
  8881. redistribute_connected: document.getElementById('modal-ospf-inst-redist-conn').checked,
  8882. redistribute_static: document.getElementById('modal-ospf-inst-redist-static').checked,
  8883. redistribute_bgp: document.getElementById('modal-ospf-inst-redist-bgp').checked
  8884. };
  8885. try {
  8886. const res = await fetch(`${API_BASE}/routing/ospf/instances`, {
  8887. method: 'POST',
  8888. headers: { 'Content-Type': 'application/json' },
  8889. body: JSON.stringify(payload)
  8890. });
  8891. if (res.ok) {
  8892. closeOspfInstanceModal();
  8893. showToast('Saved', 'OSPF instance updated', 'success');
  8894. loadDynamicRouting();
  8895. } else {
  8896. const err = await res.json();
  8897. showToast('Error', err.error || 'Failed to save OSPF instance', 'error');
  8898. }
  8899. } catch (err) {
  8900. showToast('Error', err.message, 'error');
  8901. }
  8902. }
  8903. function applyOspfInstanceForm() {
  8904. submitOspfInstance(null);
  8905. }
  8906. function copyOspfInstance() {
  8907. document.getElementById('modal-ospf-inst-id').value = '';
  8908. document.getElementById('modal-ospf-inst-name').value += '-copy';
  8909. document.getElementById('ospf-instance-modal-title').innerText = 'New...';
  8910. showToast('Copied', 'Duplicated as new OSPF instance', 'info');
  8911. }
  8912. async function deleteCurrentOspfInstance() {
  8913. const id = document.getElementById('modal-ospf-inst-id').value;
  8914. if (!id) return;
  8915. if (!confirm('Are you sure you want to remove this OSPF instance?')) return;
  8916. try {
  8917. const res = await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8918. if (res.ok) {
  8919. closeOspfInstanceModal();
  8920. showToast('Removed', 'OSPF instance deleted', 'success');
  8921. loadDynamicRouting();
  8922. }
  8923. } catch (err) {
  8924. showToast('Error', err.message, 'error');
  8925. }
  8926. }
  8927. async function enableSelectedOspfInstance() {
  8928. const id = state.selectedOspfRow?.instances;
  8929. if (!id) return;
  8930. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}/state`, {
  8931. method: 'POST',
  8932. headers: { 'Content-Type': 'application/json' },
  8933. body: JSON.stringify({ disabled: false })
  8934. });
  8935. loadDynamicRouting();
  8936. }
  8937. async function disableSelectedOspfInstance() {
  8938. const id = state.selectedOspfRow?.instances;
  8939. if (!id) return;
  8940. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}/state`, {
  8941. method: 'POST',
  8942. headers: { 'Content-Type': 'application/json' },
  8943. body: JSON.stringify({ disabled: true })
  8944. });
  8945. loadDynamicRouting();
  8946. }
  8947. async function removeSelectedOspfInstance() {
  8948. const id = state.selectedOspfRow?.instances;
  8949. if (!id) return;
  8950. if (!confirm('Delete selected OSPF instance?')) return;
  8951. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8952. loadDynamicRouting();
  8953. }
  8954. async function promptCommentOspfInstance() {
  8955. const id = state.selectedOspfRow?.instances;
  8956. if (!id) return;
  8957. const inst = (state.ospfInstances || []).find(i => i.id === id);
  8958. if (!inst) return;
  8959. const comment = prompt('Enter comment for OSPF instance:', inst.comment || '');
  8960. if (comment === null) return;
  8961. inst.comment = comment;
  8962. await fetch(`${API_BASE}/routing/ospf/instances`, {
  8963. method: 'POST',
  8964. headers: { 'Content-Type': 'application/json' },
  8965. body: JSON.stringify(inst)
  8966. });
  8967. loadDynamicRouting();
  8968. }
  8969. // --- 2. OSPF AREA ---
  8970. function populateOspfAreaDropdowns() {
  8971. const instSelect = document.getElementById('modal-ospf-area-instance');
  8972. if (instSelect) {
  8973. const cur = instSelect.value;
  8974. instSelect.innerHTML = (state.ospfInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)}</option>`).join('');
  8975. if (instSelect.innerHTML === '') instSelect.innerHTML = '<option value="Default">Default</option>';
  8976. if (cur) instSelect.value = cur;
  8977. }
  8978. }
  8979. function openOspfAreaModal(id = null) {
  8980. const isEdit = !!id;
  8981. populateOspfAreaDropdowns();
  8982. const area = (state.ospfAreas || []).find(a => a.id === id) || {
  8983. id: '',
  8984. name: 'Default',
  8985. instance: 'Default',
  8986. area_id: '0.0.0.0',
  8987. area_type: 'default',
  8988. default_cost: 1,
  8989. no_summaries: false,
  8990. disabled: false,
  8991. comment: ''
  8992. };
  8993. document.getElementById('ospf-area-modal-title').innerText = isEdit ? area.name : 'New...';
  8994. document.getElementById('modal-ospf-area-id').value = isEdit ? area.id : '';
  8995. document.getElementById('modal-ospf-area-enabled').checked = !area.disabled;
  8996. document.getElementById('modal-ospf-area-comment').value = area.comment || '';
  8997. document.getElementById('modal-ospf-area-name').value = area.name || 'Default';
  8998. document.getElementById('modal-ospf-area-instance').value = area.instance || 'Default';
  8999. document.getElementById('modal-ospf-area-areaid').value = area.area_id || '0.0.0.0';
  9000. document.getElementById('modal-ospf-area-type').value = area.area_type || 'default';
  9001. document.getElementById('modal-ospf-area-default-cost').value = area.default_cost || 1;
  9002. document.getElementById('modal-ospf-area-no-summaries').checked = !!area.no_summaries;
  9003. const btnRem = document.getElementById('btn-ospf-area-modal-remove');
  9004. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  9005. document.getElementById('ospf-area-modal').classList.remove('hidden');
  9006. }
  9007. function openEditOspfAreaModal(id) {
  9008. openOspfAreaModal(id);
  9009. }
  9010. function closeOspfAreaModal() {
  9011. document.getElementById('ospf-area-modal').classList.add('hidden');
  9012. }
  9013. async function submitOspfArea(e) {
  9014. if (e) e.preventDefault();
  9015. const payload = {
  9016. id: document.getElementById('modal-ospf-area-id').value,
  9017. name: document.getElementById('modal-ospf-area-name').value.trim() || 'Default',
  9018. instance: document.getElementById('modal-ospf-area-instance').value.trim() || 'Default',
  9019. area_id: document.getElementById('modal-ospf-area-areaid').value.trim() || '0.0.0.0',
  9020. area_type: document.getElementById('modal-ospf-area-type').value,
  9021. default_cost: parseInt(document.getElementById('modal-ospf-area-default-cost').value, 10) || 1,
  9022. no_summaries: document.getElementById('modal-ospf-area-no-summaries').checked,
  9023. disabled: !document.getElementById('modal-ospf-area-enabled').checked,
  9024. comment: document.getElementById('modal-ospf-area-comment').value.trim()
  9025. };
  9026. try {
  9027. const res = await fetch(`${API_BASE}/routing/ospf/areas`, {
  9028. method: 'POST',
  9029. headers: { 'Content-Type': 'application/json' },
  9030. body: JSON.stringify(payload)
  9031. });
  9032. if (res.ok) {
  9033. closeOspfAreaModal();
  9034. showToast('Saved', 'OSPF area saved', 'success');
  9035. loadDynamicRouting();
  9036. } else {
  9037. const err = await res.json();
  9038. showToast('Error', err.error || 'Failed to save area', 'error');
  9039. }
  9040. } catch (err) {
  9041. showToast('Error', err.message, 'error');
  9042. }
  9043. }
  9044. function applyOspfAreaForm() {
  9045. submitOspfArea(null);
  9046. }
  9047. function copyOspfArea() {
  9048. document.getElementById('modal-ospf-area-id').value = '';
  9049. document.getElementById('modal-ospf-area-name').value += '-copy';
  9050. document.getElementById('ospf-area-modal-title').innerText = 'New...';
  9051. showToast('Copied', 'Duplicated as new OSPF area', 'info');
  9052. }
  9053. async function deleteCurrentOspfArea() {
  9054. const id = document.getElementById('modal-ospf-area-id').value;
  9055. if (!id) return;
  9056. if (!confirm('Are you sure you want to remove this OSPF area?')) return;
  9057. try {
  9058. const res = await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9059. if (res.ok) {
  9060. closeOspfAreaModal();
  9061. showToast('Removed', 'OSPF area deleted', 'success');
  9062. loadDynamicRouting();
  9063. }
  9064. } catch (err) {
  9065. showToast('Error', err.message, 'error');
  9066. }
  9067. }
  9068. async function enableSelectedOspfArea() {
  9069. const id = state.selectedOspfRow?.areas;
  9070. if (!id) return;
  9071. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}/state`, {
  9072. method: 'POST',
  9073. headers: { 'Content-Type': 'application/json' },
  9074. body: JSON.stringify({ disabled: false })
  9075. });
  9076. loadDynamicRouting();
  9077. }
  9078. async function disableSelectedOspfArea() {
  9079. const id = state.selectedOspfRow?.areas;
  9080. if (!id) return;
  9081. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}/state`, {
  9082. method: 'POST',
  9083. headers: { 'Content-Type': 'application/json' },
  9084. body: JSON.stringify({ disabled: true })
  9085. });
  9086. loadDynamicRouting();
  9087. }
  9088. async function removeSelectedOspfArea() {
  9089. const id = state.selectedOspfRow?.areas;
  9090. if (!id) return;
  9091. if (!confirm('Delete selected OSPF area?')) return;
  9092. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9093. loadDynamicRouting();
  9094. }
  9095. async function promptCommentOspfArea() {
  9096. const id = state.selectedOspfRow?.areas;
  9097. if (!id) return;
  9098. const area = (state.ospfAreas || []).find(a => a.id === id);
  9099. if (!area) return;
  9100. const comment = prompt('Enter comment for OSPF area:', area.comment || '');
  9101. if (comment === null) return;
  9102. area.comment = comment;
  9103. await fetch(`${API_BASE}/routing/ospf/areas`, {
  9104. method: 'POST',
  9105. headers: { 'Content-Type': 'application/json' },
  9106. body: JSON.stringify(area)
  9107. });
  9108. loadDynamicRouting();
  9109. }
  9110. // --- 3. OSPF AREA RANGE ---
  9111. function populateAreaRangeDropdowns() {
  9112. const select = document.getElementById('modal-ospf-range-area');
  9113. if (select) {
  9114. const cur = select.value;
  9115. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  9116. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  9117. if (cur) select.value = cur;
  9118. }
  9119. }
  9120. function openOspfAreaRangeModal(id = null) {
  9121. const isEdit = !!id;
  9122. populateAreaRangeDropdowns();
  9123. const r = (state.ospfAreaRanges || []).find(it => it.id === id) || {
  9124. id: '',
  9125. area: 'Default',
  9126. prefix: '',
  9127. cost: 1,
  9128. advertise: true,
  9129. disabled: false,
  9130. comment: ''
  9131. };
  9132. document.getElementById('ospf-area-range-modal-title').innerText = isEdit ? r.prefix : 'New...';
  9133. document.getElementById('modal-ospf-range-id').value = isEdit ? r.id : '';
  9134. document.getElementById('modal-ospf-range-enabled').checked = !r.disabled;
  9135. document.getElementById('modal-ospf-range-comment').value = r.comment || '';
  9136. document.getElementById('modal-ospf-range-area').value = r.area || 'Default';
  9137. document.getElementById('modal-ospf-range-prefix').value = r.prefix || '';
  9138. document.getElementById('modal-ospf-range-cost').value = r.cost || 1;
  9139. document.getElementById('modal-ospf-range-advertise').checked = r.advertise !== false;
  9140. const btnRem = document.getElementById('btn-ospf-range-modal-remove');
  9141. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  9142. document.getElementById('ospf-area-range-modal').classList.remove('hidden');
  9143. }
  9144. function openEditOspfAreaRangeModal(id) {
  9145. openOspfAreaRangeModal(id);
  9146. }
  9147. function closeOspfAreaRangeModal() {
  9148. document.getElementById('ospf-area-range-modal').classList.add('hidden');
  9149. }
  9150. async function submitOspfAreaRange(e) {
  9151. if (e) e.preventDefault();
  9152. const payload = {
  9153. id: document.getElementById('modal-ospf-range-id').value,
  9154. area: document.getElementById('modal-ospf-range-area').value,
  9155. prefix: document.getElementById('modal-ospf-range-prefix').value.trim(),
  9156. cost: parseInt(document.getElementById('modal-ospf-range-cost').value, 10) || 1,
  9157. advertise: document.getElementById('modal-ospf-range-advertise').checked,
  9158. disabled: !document.getElementById('modal-ospf-range-enabled').checked,
  9159. comment: document.getElementById('modal-ospf-range-comment').value.trim()
  9160. };
  9161. try {
  9162. const res = await fetch(`${API_BASE}/routing/ospf/area-ranges`, {
  9163. method: 'POST',
  9164. headers: { 'Content-Type': 'application/json' },
  9165. body: JSON.stringify(payload)
  9166. });
  9167. if (res.ok) {
  9168. closeOspfAreaRangeModal();
  9169. showToast('Saved', 'Area range saved', 'success');
  9170. loadDynamicRouting();
  9171. } else {
  9172. const err = await res.json();
  9173. showToast('Error', err.error || 'Failed to save area range', 'error');
  9174. }
  9175. } catch (err) {
  9176. showToast('Error', err.message, 'error');
  9177. }
  9178. }
  9179. function applyOspfAreaRangeForm() {
  9180. submitOspfAreaRange(null);
  9181. }
  9182. async function deleteCurrentOspfAreaRange() {
  9183. const id = document.getElementById('modal-ospf-range-id').value;
  9184. if (!id) return;
  9185. if (!confirm('Delete this area range?')) return;
  9186. try {
  9187. await fetch(`${API_BASE}/routing/ospf/area-ranges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9188. closeOspfAreaRangeModal();
  9189. showToast('Removed', 'Area range removed', 'success');
  9190. loadDynamicRouting();
  9191. } catch (err) {
  9192. showToast('Error', err.message, 'error');
  9193. }
  9194. }
  9195. async function enableSelectedOspfAreaRange() {
  9196. const id = state.selectedOspfRow?.['area-ranges'];
  9197. if (!id) return;
  9198. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  9199. if (!r) return;
  9200. r.disabled = false;
  9201. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  9202. loadDynamicRouting();
  9203. }
  9204. async function disableSelectedOspfAreaRange() {
  9205. const id = state.selectedOspfRow?.['area-ranges'];
  9206. if (!id) return;
  9207. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  9208. if (!r) return;
  9209. r.disabled = true;
  9210. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  9211. loadDynamicRouting();
  9212. }
  9213. async function removeSelectedOspfAreaRange() {
  9214. const id = state.selectedOspfRow?.['area-ranges'];
  9215. if (!id) return;
  9216. if (!confirm('Delete selected area range?')) return;
  9217. await fetch(`${API_BASE}/routing/ospf/area-ranges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9218. loadDynamicRouting();
  9219. }
  9220. async function promptCommentOspfAreaRange() {
  9221. const id = state.selectedOspfRow?.['area-ranges'];
  9222. if (!id) return;
  9223. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  9224. if (!r) return;
  9225. const comment = prompt('Enter comment for area range:', r.comment || '');
  9226. if (comment === null) return;
  9227. r.comment = comment;
  9228. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  9229. loadDynamicRouting();
  9230. }
  9231. // --- 4. OSPF INTERFACE TEMPLATE ---
  9232. function switchOspfTemplateTab(tab) {
  9233. const tabGen = document.getElementById('ospf-tmpl-tab-general');
  9234. const tabAuth = document.getElementById('ospf-tmpl-tab-auth');
  9235. const btnGen = document.getElementById('ospf-tmpl-tab-btn-general');
  9236. const btnAuth = document.getElementById('ospf-tmpl-tab-btn-auth');
  9237. if (tab === 'general') {
  9238. if (tabGen) tabGen.classList.remove('hidden');
  9239. if (tabAuth) tabAuth.classList.add('hidden');
  9240. if (btnGen) btnGen.className = 'px-4 py-2 text-xs font-bold border-b-2 border-sky-500 text-white transition';
  9241. 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';
  9242. } else {
  9243. if (tabGen) tabGen.classList.add('hidden');
  9244. if (tabAuth) tabAuth.classList.remove('hidden');
  9245. 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';
  9246. if (btnAuth) btnAuth.className = 'px-4 py-2 text-xs font-bold border-b-2 border-sky-500 text-white transition';
  9247. }
  9248. }
  9249. function populateTemplateAreaDropdowns() {
  9250. const select = document.getElementById('modal-ospf-tmpl-area');
  9251. if (select) {
  9252. const cur = select.value;
  9253. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  9254. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  9255. if (cur) select.value = cur;
  9256. }
  9257. }
  9258. function openOspfTemplateModal(id = null) {
  9259. const isEdit = !!id;
  9260. populateTemplateAreaDropdowns();
  9261. switchOspfTemplateTab('general');
  9262. const tmpl = (state.ospfTemplates || []).find(t => t.id === id) || {
  9263. id: '',
  9264. interfaces: '',
  9265. area: 'Default',
  9266. networks: '',
  9267. network_type: 'broadcast',
  9268. cost: 1,
  9269. priority: 128,
  9270. passive: false,
  9271. hello_interval: 10,
  9272. dead_interval: 40,
  9273. auth: 'none',
  9274. auth_key: '',
  9275. disabled: false,
  9276. comment: ''
  9277. };
  9278. document.getElementById('ospf-template-modal-title').innerText = isEdit ? (tmpl.interfaces || tmpl.networks || 'Template') : 'New...';
  9279. document.getElementById('modal-ospf-tmpl-id').value = isEdit ? tmpl.id : '';
  9280. document.getElementById('modal-ospf-tmpl-enabled').checked = !tmpl.disabled;
  9281. document.getElementById('modal-ospf-tmpl-comment').value = tmpl.comment || '';
  9282. document.getElementById('modal-ospf-tmpl-interfaces').value = tmpl.interfaces || tmpl.interface || '';
  9283. document.getElementById('modal-ospf-tmpl-area').value = tmpl.area || 'Default';
  9284. document.getElementById('modal-ospf-tmpl-networks').value = tmpl.networks || tmpl.network || '';
  9285. document.getElementById('modal-ospf-tmpl-net-type').value = tmpl.network_type || 'broadcast';
  9286. document.getElementById('modal-ospf-tmpl-cost').value = tmpl.cost || 1;
  9287. document.getElementById('modal-ospf-tmpl-priority').value = tmpl.priority || 128;
  9288. document.getElementById('modal-ospf-tmpl-passive').checked = !!tmpl.passive;
  9289. document.getElementById('modal-ospf-tmpl-hello').value = tmpl.hello_interval || 10;
  9290. document.getElementById('modal-ospf-tmpl-dead').value = tmpl.dead_interval || 40;
  9291. document.getElementById('modal-ospf-tmpl-auth').value = tmpl.auth || tmpl.auth_type || 'none';
  9292. document.getElementById('modal-ospf-tmpl-auth-key').value = tmpl.auth_key || '';
  9293. const btnRem = document.getElementById('btn-ospf-tmpl-modal-remove');
  9294. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  9295. document.getElementById('ospf-template-modal').classList.remove('hidden');
  9296. }
  9297. function openEditOspfTemplateModal(id) {
  9298. openOspfTemplateModal(id);
  9299. }
  9300. function closeOspfTemplateModal() {
  9301. document.getElementById('ospf-template-modal').classList.add('hidden');
  9302. }
  9303. async function submitOspfTemplate(e) {
  9304. if (e) e.preventDefault();
  9305. const payload = {
  9306. id: document.getElementById('modal-ospf-tmpl-id').value,
  9307. interfaces: document.getElementById('modal-ospf-tmpl-interfaces').value.trim(),
  9308. interface: document.getElementById('modal-ospf-tmpl-interfaces').value.trim(),
  9309. area: document.getElementById('modal-ospf-tmpl-area').value,
  9310. networks: document.getElementById('modal-ospf-tmpl-networks').value.trim(),
  9311. network: document.getElementById('modal-ospf-tmpl-networks').value.trim(),
  9312. network_type: document.getElementById('modal-ospf-tmpl-net-type').value,
  9313. cost: parseInt(document.getElementById('modal-ospf-tmpl-cost').value, 10) || 1,
  9314. priority: parseInt(document.getElementById('modal-ospf-tmpl-priority').value, 10) || 128,
  9315. passive: document.getElementById('modal-ospf-tmpl-passive').checked,
  9316. hello_interval: parseInt(document.getElementById('modal-ospf-tmpl-hello').value, 10) || 10,
  9317. dead_interval: parseInt(document.getElementById('modal-ospf-tmpl-dead').value, 10) || 40,
  9318. auth: document.getElementById('modal-ospf-tmpl-auth').value,
  9319. auth_type: document.getElementById('modal-ospf-tmpl-auth').value,
  9320. auth_key: document.getElementById('modal-ospf-tmpl-auth-key').value,
  9321. disabled: !document.getElementById('modal-ospf-tmpl-enabled').checked,
  9322. comment: document.getElementById('modal-ospf-tmpl-comment').value.trim()
  9323. };
  9324. try {
  9325. const res = await fetch(`${API_BASE}/routing/ospf/templates`, {
  9326. method: 'POST',
  9327. headers: { 'Content-Type': 'application/json' },
  9328. body: JSON.stringify(payload)
  9329. });
  9330. if (res.ok) {
  9331. closeOspfTemplateModal();
  9332. showToast('Saved', 'Interface template saved', 'success');
  9333. loadDynamicRouting();
  9334. } else {
  9335. const err = await res.json();
  9336. showToast('Error', err.error || 'Failed to save interface template', 'error');
  9337. }
  9338. } catch (err) {
  9339. showToast('Error', err.message, 'error');
  9340. }
  9341. }
  9342. function applyOspfTemplateForm() {
  9343. submitOspfTemplate(null);
  9344. }
  9345. function copyOspfTemplate() {
  9346. document.getElementById('modal-ospf-tmpl-id').value = '';
  9347. document.getElementById('ospf-template-modal-title').innerText = 'New...';
  9348. showToast('Copied', 'Duplicated as new template', 'info');
  9349. }
  9350. async function deleteCurrentOspfTemplate() {
  9351. const id = document.getElementById('modal-ospf-tmpl-id').value;
  9352. if (!id) return;
  9353. if (!confirm('Delete this interface template?')) return;
  9354. try {
  9355. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9356. closeOspfTemplateModal();
  9357. showToast('Removed', 'Interface template deleted', 'success');
  9358. loadDynamicRouting();
  9359. } catch (err) {
  9360. showToast('Error', err.message, 'error');
  9361. }
  9362. }
  9363. async function enableSelectedOspfTemplate() {
  9364. const id = state.selectedOspfRow?.templates;
  9365. if (!id) return;
  9366. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  9367. method: 'POST',
  9368. headers: { 'Content-Type': 'application/json' },
  9369. body: JSON.stringify({ disabled: false })
  9370. });
  9371. loadDynamicRouting();
  9372. }
  9373. async function disableSelectedOspfTemplate() {
  9374. const id = state.selectedOspfRow?.templates;
  9375. if (!id) return;
  9376. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  9377. method: 'POST',
  9378. headers: { 'Content-Type': 'application/json' },
  9379. body: JSON.stringify({ disabled: true })
  9380. });
  9381. loadDynamicRouting();
  9382. }
  9383. async function removeSelectedOspfTemplate() {
  9384. const id = state.selectedOspfRow?.templates;
  9385. if (!id) return;
  9386. if (!confirm('Delete selected interface template?')) return;
  9387. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9388. loadDynamicRouting();
  9389. }
  9390. async function promptCommentOspfTemplate() {
  9391. const id = state.selectedOspfRow?.templates;
  9392. if (!id) return;
  9393. const tmpl = (state.ospfTemplates || []).find(t => t.id === id);
  9394. if (!tmpl) return;
  9395. const comment = prompt('Enter comment for template:', tmpl.comment || '');
  9396. if (comment === null) return;
  9397. tmpl.comment = comment;
  9398. await fetch(`${API_BASE}/routing/ospf/templates`, {
  9399. method: 'POST',
  9400. headers: { 'Content-Type': 'application/json' },
  9401. body: JSON.stringify(tmpl)
  9402. });
  9403. loadDynamicRouting();
  9404. }
  9405. // --- 5. OSPF STATIC NEIGHBOR ---
  9406. function populateStaticNbrAreaDropdowns() {
  9407. const select = document.getElementById('modal-ospf-snbr-area');
  9408. if (select) {
  9409. const cur = select.value;
  9410. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  9411. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  9412. if (cur) select.value = cur;
  9413. }
  9414. }
  9415. function openOspfStaticNbrModal(id = null) {
  9416. const isEdit = !!id;
  9417. populateStaticNbrAreaDropdowns();
  9418. const nbr = (state.ospfStaticNbrs || []).find(n => n.id === id) || {
  9419. id: '',
  9420. address: '',
  9421. area: 'Default',
  9422. poll_interval: 120,
  9423. cost: 1,
  9424. disabled: false,
  9425. comment: ''
  9426. };
  9427. document.getElementById('ospf-static-nbr-modal-title').innerText = isEdit ? nbr.address : 'New...';
  9428. document.getElementById('modal-ospf-snbr-id').value = isEdit ? nbr.id : '';
  9429. document.getElementById('modal-ospf-snbr-enabled').checked = !nbr.disabled;
  9430. document.getElementById('modal-ospf-snbr-comment').value = nbr.comment || '';
  9431. document.getElementById('modal-ospf-snbr-address').value = nbr.address || '';
  9432. document.getElementById('modal-ospf-snbr-area').value = nbr.area || 'Default';
  9433. document.getElementById('modal-ospf-snbr-poll').value = nbr.poll_interval || 120;
  9434. document.getElementById('modal-ospf-snbr-cost').value = nbr.cost || 1;
  9435. const btnRem = document.getElementById('btn-ospf-snbr-modal-remove');
  9436. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  9437. document.getElementById('ospf-static-nbr-modal').classList.remove('hidden');
  9438. }
  9439. function openEditOspfStaticNbrModal(id) {
  9440. openOspfStaticNbrModal(id);
  9441. }
  9442. function closeOspfStaticNbrModal() {
  9443. document.getElementById('ospf-static-nbr-modal').classList.add('hidden');
  9444. }
  9445. async function submitOspfStaticNbr(e) {
  9446. if (e) e.preventDefault();
  9447. const payload = {
  9448. id: document.getElementById('modal-ospf-snbr-id').value,
  9449. address: document.getElementById('modal-ospf-snbr-address').value.trim(),
  9450. area: document.getElementById('modal-ospf-snbr-area').value,
  9451. poll_interval: parseInt(document.getElementById('modal-ospf-snbr-poll').value, 10) || 120,
  9452. cost: parseInt(document.getElementById('modal-ospf-snbr-cost').value, 10) || 1,
  9453. disabled: !document.getElementById('modal-ospf-snbr-enabled').checked,
  9454. comment: document.getElementById('modal-ospf-snbr-comment').value.trim()
  9455. };
  9456. try {
  9457. const res = await fetch(`${API_BASE}/routing/ospf/static-neighbors`, {
  9458. method: 'POST',
  9459. headers: { 'Content-Type': 'application/json' },
  9460. body: JSON.stringify(payload)
  9461. });
  9462. if (res.ok) {
  9463. closeOspfStaticNbrModal();
  9464. showToast('Saved', 'Static neighbor saved', 'success');
  9465. loadDynamicRouting();
  9466. } else {
  9467. const err = await res.json();
  9468. showToast('Error', err.error || 'Failed to save static neighbor', 'error');
  9469. }
  9470. } catch (err) {
  9471. showToast('Error', err.message, 'error');
  9472. }
  9473. }
  9474. function applyOspfStaticNbrForm() {
  9475. submitOspfStaticNbr(null);
  9476. }
  9477. async function deleteCurrentOspfStaticNbr() {
  9478. const id = document.getElementById('modal-ospf-snbr-id').value;
  9479. if (!id) return;
  9480. if (!confirm('Delete this static neighbor?')) return;
  9481. try {
  9482. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9483. closeOspfStaticNbrModal();
  9484. showToast('Removed', 'Static neighbor removed', 'success');
  9485. loadDynamicRouting();
  9486. } catch (err) {
  9487. showToast('Error', err.message, 'error');
  9488. }
  9489. }
  9490. async function enableSelectedOspfStaticNbr() {
  9491. const id = state.selectedOspfRow?.['static-nbrs'];
  9492. if (!id) return;
  9493. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  9494. if (!n) return;
  9495. n.disabled = false;
  9496. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  9497. loadDynamicRouting();
  9498. }
  9499. async function disableSelectedOspfStaticNbr() {
  9500. const id = state.selectedOspfRow?.['static-nbrs'];
  9501. if (!id) return;
  9502. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  9503. if (!n) return;
  9504. n.disabled = true;
  9505. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  9506. loadDynamicRouting();
  9507. }
  9508. async function removeSelectedOspfStaticNbr() {
  9509. const id = state.selectedOspfRow?.['static-nbrs'];
  9510. if (!id) return;
  9511. if (!confirm('Delete selected static neighbor?')) return;
  9512. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9513. loadDynamicRouting();
  9514. }
  9515. async function promptCommentOspfStaticNbr() {
  9516. const id = state.selectedOspfRow?.['static-nbrs'];
  9517. if (!id) return;
  9518. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  9519. if (!n) return;
  9520. const comment = prompt('Enter comment for static neighbor:', n.comment || '');
  9521. if (comment === null) return;
  9522. n.comment = comment;
  9523. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  9524. loadDynamicRouting();
  9525. }
  9526. // Backward-compat aliases
  9527. function openAddOspfInterfaceModal() { openOspfTemplateModal(); }
  9528. function openEditOspfInterfaceModal(id) { openEditOspfTemplateModal(id); }
  9529. function closeOspfInterfaceModal() { closeOspfTemplateModal(); }
  9530. function submitOspfInterface(e) { submitOspfTemplate(e); }
  9531. function deleteOspfInterface(id) {
  9532. fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' }).then(() => loadDynamicRouting());
  9533. }
  9534. function toggleOspfInterfaceState(id, disabled) {
  9535. fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  9536. method: 'POST',
  9537. headers: { 'Content-Type': 'application/json' },
  9538. body: JSON.stringify({ disabled })
  9539. }).then(() => loadDynamicRouting());
  9540. }
  9541. function openAddOspfAreaModal() { openOspfAreaModal(); }
  9542. function deleteOspfArea(id) {
  9543. fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' }).then(() => loadDynamicRouting());
  9544. }
  9545. // ============================================================================
  9546. // ==================== MIKROTIK BRIDGE SUBSYSTEM ==============================
  9547. // ============================================================================
  9548. function switchBridgeSubTab(tab) {
  9549. state.bridgeSubTab = tab;
  9550. const tabs = ['bridges', 'ports', 'vlans', 'hosts'];
  9551. tabs.forEach(t => {
  9552. const panel = document.getElementById(`bridge-subtab-${t}`);
  9553. const btn = document.getElementById(`bridge-subtab-btn-${t}`);
  9554. if (panel) {
  9555. if (t === tab) panel.classList.remove('hidden');
  9556. else panel.classList.add('hidden');
  9557. }
  9558. if (btn) {
  9559. if (t === tab) {
  9560. 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';
  9561. } else {
  9562. 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';
  9563. }
  9564. }
  9565. });
  9566. const addBtn = document.getElementById('bridge-top-action-btn');
  9567. if (addBtn) {
  9568. if (tab === 'bridges') addBtn.innerHTML = '<span>+ Add Bridge</span>';
  9569. else if (tab === 'ports') addBtn.innerHTML = '<span>+ Add Port</span>';
  9570. else if (tab === 'vlans') addBtn.innerHTML = '<span>+ Add VLAN Entry</span>';
  9571. else if (tab === 'hosts') addBtn.innerHTML = '<span>🔄 Refresh MACs</span>';
  9572. }
  9573. if (tab === 'hosts') loadBridgeHosts();
  9574. setTimeout(initTableSorting, 50);
  9575. }
  9576. function openCurrentBridgeModal() {
  9577. if (state.bridgeSubTab === 'bridges') openAddBridgeModal();
  9578. else if (state.bridgeSubTab === 'ports') openAddBridgePortModal();
  9579. else if (state.bridgeSubTab === 'vlans') openAddBridgeVLANModal();
  9580. else if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  9581. }
  9582. async function loadBridge() {
  9583. try {
  9584. const [bridgesRes, portsRes, vlansRes, summaryRes, eoipRes, vlanIfacesRes] = await Promise.all([
  9585. fetch(`${API_BASE}/bridge/bridges`),
  9586. fetch(`${API_BASE}/bridge/ports`),
  9587. fetch(`${API_BASE}/bridge/vlans`),
  9588. fetch(`${API_BASE}/bridge/summary`),
  9589. fetch(`${API_BASE}/vpn/eoip`),
  9590. fetch(`${API_BASE}/vlans`)
  9591. ]);
  9592. if (bridgesRes.ok) state.bridges = await bridgesRes.json();
  9593. if (portsRes.ok) state.bridgePorts = await portsRes.json();
  9594. if (vlansRes.ok) state.bridgeVLANs = await vlansRes.json();
  9595. if (summaryRes.ok) state.bridgeSummary = await summaryRes.json();
  9596. if (eoipRes && eoipRes.ok) state.eoipTunnels = await eoipRes.json();
  9597. if (vlanIfacesRes && vlanIfacesRes.ok) state.vlans = await vlanIfacesRes.json();
  9598. // Badges & Stats
  9599. const bBridges = document.getElementById('bridge-badge-bridges');
  9600. if (bBridges) bBridges.innerText = (state.bridges || []).length;
  9601. const bPorts = document.getElementById('bridge-badge-ports');
  9602. if (bPorts) bPorts.innerText = (state.bridgePorts || []).length;
  9603. const bVlans = document.getElementById('bridge-badge-vlans');
  9604. if (bVlans) bVlans.innerText = (state.bridgeVLANs || []).length;
  9605. const bHosts = document.getElementById('bridge-badge-hosts');
  9606. if (bHosts) bHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  9607. const sBr = document.getElementById('bridge-stat-bridges');
  9608. if (sBr) sBr.innerText = (state.bridges || []).length;
  9609. const sPorts = document.getElementById('bridge-stat-ports');
  9610. if (sPorts) sPorts.innerText = (state.bridgePorts || []).length;
  9611. const sHosts = document.getElementById('bridge-stat-hosts');
  9612. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  9613. renderBridges();
  9614. renderBridgePorts();
  9615. renderBridgeVLANs();
  9616. if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  9617. } catch (err) {
  9618. console.error('Failed to load bridge subsystem:', err);
  9619. }
  9620. }
  9621. // ----------------- Bridges -----------------
  9622. function renderBridges() {
  9623. const tbody = document.getElementById('bridge-table-body');
  9624. const empty = document.getElementById('bridge-empty-bridges');
  9625. const countBadge = document.getElementById('bridge-count-badge');
  9626. if (!tbody) return;
  9627. tbody.innerHTML = '';
  9628. const bridges = state.bridges || [];
  9629. if (countBadge) countBadge.innerText = `${bridges.length} Bridges`;
  9630. if (bridges.length === 0) {
  9631. empty?.classList.remove('hidden');
  9632. return;
  9633. }
  9634. empty?.classList.add('hidden');
  9635. bridges.forEach((b, idx) => {
  9636. const tr = document.createElement('tr');
  9637. tr.className = `hover:bg-slate-800/40 transition text-xs ${b.disabled ? 'opacity-50' : ''}`;
  9638. // Format IP addresses pill list
  9639. let ipsHtml = '<span class="text-slate-600 font-sans">None</span>';
  9640. if (b.ip_addresses && b.ip_addresses.length > 0) {
  9641. ipsHtml = b.ip_addresses.map(ip => `
  9642. <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">
  9643. <span>${ip}</span>
  9644. <button onclick="deleteBridgeIP('${b.id}', '${ip}')" class="text-slate-500 hover:text-rose-400 font-bold ml-0.5">×</button>
  9645. </span>
  9646. `).join(' ');
  9647. }
  9648. const runningFlag = b.running ? '<span class="text-emerald-400 font-bold" title="Running (R)">R</span>' : '<span class="text-slate-600">-</span>';
  9649. const disabledFlag = b.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '';
  9650. const flagDisplay = `${runningFlag}${disabledFlag ? ' ' + disabledFlag : ''}`;
  9651. tr.innerHTML = `
  9652. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  9653. <td class="py-2.5 px-3 text-center font-mono">${flagDisplay}</td>
  9654. <td class="py-2.5 px-3 font-bold text-white text-sm">
  9655. <span class="text-sky-400 mr-1.5">🌉</span>${b.name}
  9656. </td>
  9657. <td class="py-2.5 px-3 text-slate-300">${b.mtu}</td>
  9658. <td class="py-2.5 px-3 font-mono text-slate-300 text-[11px]">${b.mac_address || '-'}</td>
  9659. <td class="py-2.5 px-3">
  9660. <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>
  9661. </td>
  9662. <td class="py-2.5 px-3 text-center">
  9663. ${b.vlan_filtering ? '<span class="text-emerald-400 font-bold">yes</span>' : '<span class="text-slate-500">no</span>'}
  9664. </td>
  9665. <td class="py-2.5 px-3 font-mono">${b.pvid || 1}</td>
  9666. <td class="py-2.5 px-3">
  9667. <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>
  9668. </td>
  9669. <td class="py-2.5 px-3">
  9670. <div class="flex items-center gap-1.5 flex-wrap">
  9671. ${ipsHtml}
  9672. <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>
  9673. </div>
  9674. </td>
  9675. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  9676. <span class="text-emerald-400">↓ ${b.rx_human || '0 B'}</span> / <span class="text-cyan-400">↑ ${b.tx_human || '0 B'}</span>
  9677. </td>
  9678. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${b.comment || ''}">${b.comment || '-'}</td>
  9679. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  9680. <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>
  9681. <button onclick="openEditBridgeModal('${b.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  9682. <button onclick="deleteBridge('${b.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  9683. </td>
  9684. `;
  9685. tbody.appendChild(tr);
  9686. });
  9687. }
  9688. function openAddBridgeModal() {
  9689. document.getElementById('bridge-modal-title').innerText = 'Add Bridge Interface';
  9690. document.getElementById('bridge-modal-id').value = '';
  9691. document.getElementById('bridge-modal-name').value = 'bridge1';
  9692. document.getElementById('bridge-modal-name').disabled = false;
  9693. document.getElementById('bridge-modal-mtu').value = '1500';
  9694. document.getElementById('bridge-modal-mac').value = '';
  9695. document.getElementById('bridge-modal-stp').value = 'rstp';
  9696. document.getElementById('bridge-modal-priority').value = '32768';
  9697. document.getElementById('bridge-modal-vlanfiltering').checked = false;
  9698. document.getElementById('bridge-modal-pvid').value = '1';
  9699. document.getElementById('bridge-modal-fastforward').checked = true;
  9700. document.getElementById('bridge-modal-comment').value = '';
  9701. document.getElementById('bridge-modal-disabled').checked = false;
  9702. toggleBridgeModalVlanFiltering();
  9703. document.getElementById('bridge-modal').classList.remove('hidden');
  9704. }
  9705. function openEditBridgeModal(id) {
  9706. const b = (state.bridges || []).find(x => x.id === id);
  9707. if (!b) return;
  9708. document.getElementById('bridge-modal-title').innerText = `Edit Bridge (${b.name})`;
  9709. document.getElementById('bridge-modal-id').value = b.id;
  9710. document.getElementById('bridge-modal-name').value = b.name;
  9711. document.getElementById('bridge-modal-name').disabled = true;
  9712. document.getElementById('bridge-modal-mtu').value = b.mtu || 1500;
  9713. document.getElementById('bridge-modal-mac').value = b.mac_address || '';
  9714. document.getElementById('bridge-modal-stp').value = b.stp || 'rstp';
  9715. document.getElementById('bridge-modal-priority').value = b.priority || 32768;
  9716. document.getElementById('bridge-modal-vlanfiltering').checked = !!b.vlan_filtering;
  9717. document.getElementById('bridge-modal-pvid').value = b.pvid || 1;
  9718. document.getElementById('bridge-modal-fastforward').checked = b.fast_forward !== false;
  9719. document.getElementById('bridge-modal-comment').value = b.comment || '';
  9720. document.getElementById('bridge-modal-disabled').checked = !!b.disabled;
  9721. toggleBridgeModalVlanFiltering();
  9722. document.getElementById('bridge-modal').classList.remove('hidden');
  9723. }
  9724. function closeBridgeModal() {
  9725. document.getElementById('bridge-modal').classList.add('hidden');
  9726. }
  9727. function toggleBridgeModalVlanFiltering() {
  9728. const chk = document.getElementById('bridge-modal-vlanfiltering').checked;
  9729. const pvidBox = document.getElementById('bridge-modal-pvid-box');
  9730. if (pvidBox) {
  9731. if (chk) pvidBox.classList.remove('opacity-40');
  9732. else pvidBox.classList.add('opacity-40');
  9733. }
  9734. }
  9735. async function submitSaveBridge(e) {
  9736. e.preventDefault();
  9737. const id = document.getElementById('bridge-modal-id').value;
  9738. const name = document.getElementById('bridge-modal-name').value.trim();
  9739. const mtu = parseInt(document.getElementById('bridge-modal-mtu').value, 10) || 1500;
  9740. const mac = document.getElementById('bridge-modal-mac').value.trim();
  9741. const stp = document.getElementById('bridge-modal-stp').value;
  9742. const priority = parseInt(document.getElementById('bridge-modal-priority').value, 10) || 32768;
  9743. const vlanFiltering = document.getElementById('bridge-modal-vlanfiltering').checked;
  9744. const pvid = parseInt(document.getElementById('bridge-modal-pvid').value, 10) || 1;
  9745. const fastForward = document.getElementById('bridge-modal-fastforward').checked;
  9746. const comment = document.getElementById('bridge-modal-comment').value.trim();
  9747. const disabled = document.getElementById('bridge-modal-disabled').checked;
  9748. try {
  9749. const res = await fetch(`${API_BASE}/bridge/bridges`, {
  9750. method: 'POST',
  9751. headers: { 'Content-Type': 'application/json' },
  9752. body: JSON.stringify({
  9753. id,
  9754. name,
  9755. mtu,
  9756. mac_address: mac,
  9757. stp,
  9758. priority,
  9759. vlan_filtering: vlanFiltering,
  9760. pvid,
  9761. fast_forward: fastForward,
  9762. comment,
  9763. disabled
  9764. })
  9765. });
  9766. if (res.ok) {
  9767. showToast('Bridge Saved', `Bridge ${name} configured`, 'success');
  9768. closeBridgeModal();
  9769. loadBridge();
  9770. fetchData(false);
  9771. } else {
  9772. const err = await res.json();
  9773. showToast('Error', err.error || err.message || 'Failed to save bridge', 'error');
  9774. }
  9775. } catch (err) {
  9776. showToast('Error', err.message, 'error');
  9777. }
  9778. }
  9779. async function toggleBridgeState(id, disabled) {
  9780. try {
  9781. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/state`, {
  9782. method: 'POST',
  9783. headers: { 'Content-Type': 'application/json' },
  9784. body: JSON.stringify({ disabled })
  9785. });
  9786. if (res.ok) {
  9787. loadBridge();
  9788. fetchData(false);
  9789. }
  9790. } catch (err) {
  9791. showToast('Error', err.message, 'error');
  9792. }
  9793. }
  9794. async function deleteBridge(id) {
  9795. const b = (state.bridges || []).find(x => x.id === id);
  9796. const name = b ? b.name : id;
  9797. if (!confirm(`Are you sure you want to delete bridge '${name}'? All member ports will be detached.`)) return;
  9798. try {
  9799. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9800. if (res.ok) {
  9801. showToast('Deleted', `Bridge ${name} deleted`, 'success');
  9802. loadBridge();
  9803. fetchData(false);
  9804. } else {
  9805. const err = await res.json();
  9806. showToast('Error', err.error || err.message || 'Failed to delete bridge', 'error');
  9807. }
  9808. } catch (err) {
  9809. showToast('Error', err.message, 'error');
  9810. }
  9811. }
  9812. // ----------------- Bridge IP Assignments -----------------
  9813. function openAddBridgeIPModal(id, name) {
  9814. document.getElementById('bridge-ip-modal-id').value = id;
  9815. document.getElementById('bridge-ip-modal-sub').innerText = name;
  9816. document.getElementById('bridge-ip-modal-cidr').value = '';
  9817. document.getElementById('bridge-ip-modal').classList.remove('hidden');
  9818. }
  9819. function closeBridgeIPModal() {
  9820. document.getElementById('bridge-ip-modal').classList.add('hidden');
  9821. }
  9822. async function submitAddBridgeIP(e) {
  9823. e.preventDefault();
  9824. const id = document.getElementById('bridge-ip-modal-id').value;
  9825. const ip = document.getElementById('bridge-ip-modal-cidr').value.trim();
  9826. try {
  9827. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  9828. method: 'POST',
  9829. headers: { 'Content-Type': 'application/json' },
  9830. body: JSON.stringify({ ip })
  9831. });
  9832. if (res.ok) {
  9833. showToast('IP Assigned', `${ip} assigned to bridge`, 'success');
  9834. closeBridgeIPModal();
  9835. loadBridge();
  9836. fetchData(false);
  9837. } else {
  9838. const err = await res.json();
  9839. showToast('Error', err.error || err.message || 'Failed to add IP', 'error');
  9840. }
  9841. } catch (err) {
  9842. showToast('Error', err.message, 'error');
  9843. }
  9844. }
  9845. async function deleteBridgeIP(id, ip) {
  9846. if (!confirm(`Remove IP address ${ip} from bridge?`)) return;
  9847. try {
  9848. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  9849. method: 'DELETE',
  9850. headers: { 'Content-Type': 'application/json' },
  9851. body: JSON.stringify({ ip })
  9852. });
  9853. if (res.ok) {
  9854. showToast('IP Removed', `${ip} removed from bridge`, 'success');
  9855. loadBridge();
  9856. fetchData(false);
  9857. }
  9858. } catch (err) {
  9859. showToast('Error', err.message, 'error');
  9860. }
  9861. }
  9862. // ----------------- Bridge Ports -----------------
  9863. function renderBridgePorts() {
  9864. const tbody = document.getElementById('bridge-ports-table-body');
  9865. const empty = document.getElementById('bridge-empty-ports');
  9866. const countBadge = document.getElementById('bridge-ports-count-badge');
  9867. const filterBridge = document.getElementById('bridge-ports-filter-bridge')?.value || '';
  9868. if (!tbody) return;
  9869. tbody.innerHTML = '';
  9870. // Update filter select
  9871. populateBridgeSelect('bridge-ports-filter-bridge', filterBridge, true);
  9872. const ports = (state.bridgePorts || []).filter(p => !filterBridge || p.bridge === filterBridge);
  9873. if (countBadge) countBadge.innerText = `${ports.length} Ports`;
  9874. if (ports.length === 0) {
  9875. empty?.classList.remove('hidden');
  9876. return;
  9877. }
  9878. empty?.classList.add('hidden');
  9879. ports.forEach((p, idx) => {
  9880. const tr = document.createElement('tr');
  9881. tr.className = `hover:bg-slate-800/40 transition text-xs ${p.disabled ? 'opacity-50' : ''}`;
  9882. const disabledFlag = p.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  9883. tr.innerHTML = `
  9884. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  9885. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  9886. <td class="py-2.5 px-3 font-bold text-white text-sm">
  9887. <span class="text-emerald-400 mr-1.5">🔌</span>${p.interface}
  9888. </td>
  9889. <td class="py-2.5 px-3 font-semibold text-sky-400">${p.bridge}</td>
  9890. <td class="py-2.5 px-3 font-mono">${p.pvid || 1}</td>
  9891. <td class="py-2.5 px-3 text-slate-300">${p.frame_types}</td>
  9892. <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>
  9893. <td class="py-2.5 px-3">
  9894. ${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>'}
  9895. </td>
  9896. <td class="py-2.5 px-3">
  9897. <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>
  9898. </td>
  9899. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${p.comment || ''}">${p.comment || '-'}</td>
  9900. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  9901. <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>
  9902. <button onclick="openEditBridgePortModal('${p.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  9903. <button onclick="deleteBridgePort('${p.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  9904. </td>
  9905. `;
  9906. tbody.appendChild(tr);
  9907. });
  9908. }
  9909. function openAddBridgePortModal() {
  9910. document.getElementById('bridge-port-modal-title').innerText = 'Add Port to Bridge';
  9911. document.getElementById('bridge-port-modal-id').value = '';
  9912. populateBridgeSelect('bridge-port-modal-bridge');
  9913. populateBridgePortCandidateSelect('bridge-port-modal-interface');
  9914. document.getElementById('bridge-port-modal-pvid').value = '1';
  9915. document.getElementById('bridge-port-modal-frametypes').value = 'admit-all';
  9916. document.getElementById('bridge-port-modal-ingressfiltering').checked = false;
  9917. document.getElementById('bridge-port-modal-horizon').value = '0';
  9918. document.getElementById('bridge-port-modal-pathcost').value = '10';
  9919. document.getElementById('bridge-port-modal-priority').value = '128';
  9920. document.getElementById('bridge-port-modal-learn').checked = true;
  9921. document.getElementById('bridge-port-modal-comment').value = '';
  9922. document.getElementById('bridge-port-modal-disabled').checked = false;
  9923. document.getElementById('bridge-port-modal').classList.remove('hidden');
  9924. }
  9925. function openEditBridgePortModal(id) {
  9926. const p = (state.bridgePorts || []).find(x => x.id === id);
  9927. if (!p) return;
  9928. document.getElementById('bridge-port-modal-title').innerText = `Edit Bridge Port (${p.interface})`;
  9929. document.getElementById('bridge-port-modal-id').value = p.id;
  9930. populateBridgeSelect('bridge-port-modal-bridge', p.bridge);
  9931. populateBridgePortCandidateSelect('bridge-port-modal-interface', p.interface);
  9932. document.getElementById('bridge-port-modal-pvid').value = p.pvid || 1;
  9933. document.getElementById('bridge-port-modal-frametypes').value = p.frame_types || 'admit-all';
  9934. document.getElementById('bridge-port-modal-ingressfiltering').checked = !!p.ingress_filtering;
  9935. document.getElementById('bridge-port-modal-horizon').value = p.horizon || 0;
  9936. document.getElementById('bridge-port-modal-pathcost').value = p.path_cost || 10;
  9937. document.getElementById('bridge-port-modal-priority').value = p.priority || 128;
  9938. document.getElementById('bridge-port-modal-learn').checked = p.learn !== false;
  9939. document.getElementById('bridge-port-modal-comment').value = p.comment || '';
  9940. document.getElementById('bridge-port-modal-disabled').checked = !!p.disabled;
  9941. document.getElementById('bridge-port-modal').classList.remove('hidden');
  9942. }
  9943. function closeBridgePortModal() {
  9944. document.getElementById('bridge-port-modal').classList.add('hidden');
  9945. }
  9946. async function submitSaveBridgePort(e) {
  9947. e.preventDefault();
  9948. const id = document.getElementById('bridge-port-modal-id').value;
  9949. const bridge = document.getElementById('bridge-port-modal-bridge').value;
  9950. const iface = document.getElementById('bridge-port-modal-interface').value;
  9951. const pvid = parseInt(document.getElementById('bridge-port-modal-pvid').value, 10) || 1;
  9952. const frameTypes = document.getElementById('bridge-port-modal-frametypes').value;
  9953. const ingressFiltering = document.getElementById('bridge-port-modal-ingressfiltering').checked;
  9954. const horizon = parseInt(document.getElementById('bridge-port-modal-horizon').value, 10) || 0;
  9955. const pathCost = parseInt(document.getElementById('bridge-port-modal-pathcost').value, 10) || 10;
  9956. const priority = parseInt(document.getElementById('bridge-port-modal-priority').value, 10) || 128;
  9957. const learn = document.getElementById('bridge-port-modal-learn').checked;
  9958. const comment = document.getElementById('bridge-port-modal-comment').value.trim();
  9959. const disabled = document.getElementById('bridge-port-modal-disabled').checked;
  9960. try {
  9961. const res = await fetch(`${API_BASE}/bridge/ports`, {
  9962. method: 'POST',
  9963. headers: { 'Content-Type': 'application/json' },
  9964. body: JSON.stringify({
  9965. id,
  9966. bridge,
  9967. interface: iface,
  9968. pvid,
  9969. frame_types: frameTypes,
  9970. ingress_filtering: ingressFiltering,
  9971. horizon,
  9972. path_cost: pathCost,
  9973. priority,
  9974. learn,
  9975. comment,
  9976. disabled
  9977. })
  9978. });
  9979. if (res.ok) {
  9980. showToast('Port Attached', `${iface} added to ${bridge}`, 'success');
  9981. closeBridgePortModal();
  9982. loadBridge();
  9983. fetchData(false);
  9984. } else {
  9985. const err = await res.json();
  9986. showToast('Error', err.error || err.message || 'Failed to save port', 'error');
  9987. }
  9988. } catch (err) {
  9989. showToast('Error', err.message, 'error');
  9990. }
  9991. }
  9992. async function toggleBridgePortState(id, disabled) {
  9993. try {
  9994. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}/state`, {
  9995. method: 'POST',
  9996. headers: { 'Content-Type': 'application/json' },
  9997. body: JSON.stringify({ disabled })
  9998. });
  9999. if (res.ok) {
  10000. loadBridge();
  10001. fetchData(false);
  10002. }
  10003. } catch (err) {
  10004. showToast('Error', err.message, 'error');
  10005. }
  10006. }
  10007. async function deleteBridgePort(id) {
  10008. const p = (state.bridgePorts || []).find(x => x.id === id);
  10009. const iface = p ? p.interface : id;
  10010. if (!confirm(`Detach interface '${iface}' from bridge?`)) return;
  10011. try {
  10012. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10013. if (res.ok) {
  10014. showToast('Port Detached', `${iface} removed from bridge`, 'success');
  10015. loadBridge();
  10016. fetchData(false);
  10017. }
  10018. } catch (err) {
  10019. showToast('Error', err.message, 'error');
  10020. }
  10021. }
  10022. // ----------------- Bridge VLANs -----------------
  10023. function renderBridgeVLANs() {
  10024. const tbody = document.getElementById('bridge-vlans-table-body');
  10025. const empty = document.getElementById('bridge-empty-vlans');
  10026. const countBadge = document.getElementById('bridge-vlans-count-badge');
  10027. const filterBridge = document.getElementById('bridge-vlans-filter-bridge')?.value || '';
  10028. if (!tbody) return;
  10029. tbody.innerHTML = '';
  10030. populateBridgeSelect('bridge-vlans-filter-bridge', filterBridge, true);
  10031. const vlans = (state.bridgeVLANs || []).filter(v => !filterBridge || v.bridge === filterBridge);
  10032. if (countBadge) countBadge.innerText = `${vlans.length} Entries`;
  10033. if (vlans.length === 0) {
  10034. empty?.classList.remove('hidden');
  10035. return;
  10036. }
  10037. empty?.classList.add('hidden');
  10038. vlans.forEach((v, idx) => {
  10039. const tr = document.createElement('tr');
  10040. tr.className = `hover:bg-slate-800/40 transition text-xs ${v.disabled ? 'opacity-50' : ''}`;
  10041. const taggedHtml = (v.tagged && v.tagged.length > 0)
  10042. ? 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(' ')
  10043. : '<span class="text-slate-600">none</span>';
  10044. const untaggedHtml = (v.untagged && v.untagged.length > 0)
  10045. ? 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(' ')
  10046. : '<span class="text-slate-600">none</span>';
  10047. const disabledFlag = v.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  10048. tr.innerHTML = `
  10049. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  10050. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  10051. <td class="py-2.5 px-3 font-semibold text-sky-400">${v.bridge}</td>
  10052. <td class="py-2.5 px-3 font-bold text-white font-mono text-sm">${v.vlan_ids}</td>
  10053. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${taggedHtml}</div></td>
  10054. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${untaggedHtml}</div></td>
  10055. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${v.comment || ''}">${v.comment || '-'}</td>
  10056. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  10057. <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>
  10058. <button onclick="openEditBridgeVLANModal('${v.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  10059. <button onclick="deleteBridgeVLAN('${v.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  10060. </td>
  10061. `;
  10062. tbody.appendChild(tr);
  10063. });
  10064. }
  10065. function openAddBridgeVLANModal() {
  10066. document.getElementById('bridge-vlan-modal-title').innerText = 'Add Bridge VLAN Entry';
  10067. document.getElementById('bridge-vlan-modal-id').value = '';
  10068. populateBridgeSelect('bridge-vlan-modal-bridge');
  10069. document.getElementById('bridge-vlan-modal-vlanids').value = '';
  10070. document.getElementById('bridge-vlan-modal-comment').value = '';
  10071. document.getElementById('bridge-vlan-modal-disabled').checked = false;
  10072. updateBridgeVlanPortCheckboxes();
  10073. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  10074. }
  10075. function openEditBridgeVLANModal(id) {
  10076. const v = (state.bridgeVLANs || []).find(x => x.id === id);
  10077. if (!v) return;
  10078. document.getElementById('bridge-vlan-modal-title').innerText = `Edit Bridge VLAN (${v.vlan_ids})`;
  10079. document.getElementById('bridge-vlan-modal-id').value = v.id;
  10080. populateBridgeSelect('bridge-vlan-modal-bridge', v.bridge);
  10081. document.getElementById('bridge-vlan-modal-vlanids').value = v.vlan_ids;
  10082. document.getElementById('bridge-vlan-modal-comment').value = v.comment || '';
  10083. document.getElementById('bridge-vlan-modal-disabled').checked = !!v.disabled;
  10084. updateBridgeVlanPortCheckboxes(v.tagged || [], v.untagged || []);
  10085. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  10086. }
  10087. function closeBridgeVlanModal() {
  10088. document.getElementById('bridge-vlan-modal').classList.add('hidden');
  10089. }
  10090. function updateBridgeVlanPortCheckboxes(taggedSelected = [], untaggedSelected = []) {
  10091. const selBridge = document.getElementById('bridge-vlan-modal-bridge')?.value || '';
  10092. const taggedBox = document.getElementById('bridge-vlan-tagged-ports');
  10093. const untaggedBox = document.getElementById('bridge-vlan-untagged-ports');
  10094. if (!taggedBox || !untaggedBox) return;
  10095. // Ports belonging to the selected bridge
  10096. const memberPorts = (state.bridgePorts || []).filter(p => !selBridge || p.bridge === selBridge);
  10097. if (memberPorts.length === 0) {
  10098. taggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  10099. untaggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  10100. return;
  10101. }
  10102. taggedBox.innerHTML = memberPorts.map(p => `
  10103. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  10104. <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">
  10105. <span>${p.interface}</span>
  10106. </label>
  10107. `).join('');
  10108. untaggedBox.innerHTML = memberPorts.map(p => `
  10109. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  10110. <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">
  10111. <span>${p.interface}</span>
  10112. </label>
  10113. `).join('');
  10114. }
  10115. async function submitSaveBridgeVLAN(e) {
  10116. e.preventDefault();
  10117. const id = document.getElementById('bridge-vlan-modal-id').value;
  10118. const bridge = document.getElementById('bridge-vlan-modal-bridge').value;
  10119. const vlanIDs = document.getElementById('bridge-vlan-modal-vlanids').value.trim();
  10120. const comment = document.getElementById('bridge-vlan-modal-comment').value.trim();
  10121. const disabled = document.getElementById('bridge-vlan-modal-disabled').checked;
  10122. const tagged = Array.from(document.querySelectorAll('input[name="bvlan-tagged"]:checked')).map(x => x.value);
  10123. const untagged = Array.from(document.querySelectorAll('input[name="bvlan-untagged"]:checked')).map(x => x.value);
  10124. try {
  10125. const res = await fetch(`${API_BASE}/bridge/vlans`, {
  10126. method: 'POST',
  10127. headers: { 'Content-Type': 'application/json' },
  10128. body: JSON.stringify({
  10129. id,
  10130. bridge,
  10131. vlan_ids: vlanIDs,
  10132. tagged,
  10133. untagged,
  10134. comment,
  10135. disabled
  10136. })
  10137. });
  10138. if (res.ok) {
  10139. showToast('VLAN Entry Saved', `VLAN ${vlanIDs} configured on ${bridge}`, 'success');
  10140. closeBridgeVlanModal();
  10141. loadBridge();
  10142. } else {
  10143. const err = await res.json();
  10144. showToast('Error', err.error || err.message || 'Failed to save VLAN entry', 'error');
  10145. }
  10146. } catch (err) {
  10147. showToast('Error', err.message, 'error');
  10148. }
  10149. }
  10150. async function toggleBridgeVLANState(id, disabled) {
  10151. try {
  10152. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}/state`, {
  10153. method: 'POST',
  10154. headers: { 'Content-Type': 'application/json' },
  10155. body: JSON.stringify({ disabled })
  10156. });
  10157. if (res.ok) loadBridge();
  10158. } catch (err) {
  10159. showToast('Error', err.message, 'error');
  10160. }
  10161. }
  10162. async function deleteBridgeVLAN(id) {
  10163. if (!confirm('Delete this bridge VLAN entry?')) return;
  10164. try {
  10165. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10166. if (res.ok) {
  10167. showToast('Deleted', 'VLAN entry removed from bridge', 'success');
  10168. loadBridge();
  10169. }
  10170. } catch (err) {
  10171. showToast('Error', err.message, 'error');
  10172. }
  10173. }
  10174. // ----------------- Hosts / MAC Table -----------------
  10175. async function loadBridgeHosts() {
  10176. const filterBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || '';
  10177. populateBridgeSelect('bridge-hosts-filter-bridge', filterBridge, true);
  10178. try {
  10179. const url = filterBridge ? `${API_BASE}/bridge/hosts?bridge=${encodeURIComponent(filterBridge)}` : `${API_BASE}/bridge/hosts`;
  10180. const res = await fetch(url);
  10181. if (res.ok) {
  10182. state.bridgeHosts = await res.json();
  10183. renderBridgeHosts();
  10184. }
  10185. } catch (err) {
  10186. console.error('Failed to load bridge hosts:', err);
  10187. }
  10188. }
  10189. function renderBridgeHosts() {
  10190. const tbody = document.getElementById('bridge-hosts-table-body');
  10191. const empty = document.getElementById('bridge-empty-hosts');
  10192. const countBadge = document.getElementById('bridge-hosts-count-badge');
  10193. const search = (document.getElementById('bridge-hosts-search')?.value || '').toLowerCase().trim();
  10194. if (!tbody) return;
  10195. tbody.innerHTML = '';
  10196. const hosts = (state.bridgeHosts || []).filter(h => {
  10197. if (!search) return true;
  10198. return (h.mac || '').toLowerCase().includes(search) || (h.interface || '').toLowerCase().includes(search) || (h.bridge || '').toLowerCase().includes(search);
  10199. });
  10200. if (countBadge) countBadge.innerText = `${hosts.length} Hosts`;
  10201. if (hosts.length === 0) {
  10202. empty?.classList.remove('hidden');
  10203. return;
  10204. }
  10205. empty?.classList.add('hidden');
  10206. hosts.forEach(h => {
  10207. const tr = document.createElement('tr');
  10208. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  10209. let flagBadges = '';
  10210. 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>';
  10211. 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>';
  10212. 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>';
  10213. tr.innerHTML = `
  10214. <td class="py-2.5 px-3 font-mono font-bold text-white text-sm">${h.mac}</td>
  10215. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${h.interface || '-'}</td>
  10216. <td class="py-2.5 px-3 font-mono text-sky-400">${h.bridge || '-'}</td>
  10217. <td class="py-2.5 px-3 font-mono">${h.vlan_id || 1}</td>
  10218. <td class="py-2.5 px-3 font-mono text-slate-400">${h.age ? h.age.toFixed(1) + 's' : '-'}</td>
  10219. <td class="py-2.5 px-3">${flagBadges}</td>
  10220. `;
  10221. tbody.appendChild(tr);
  10222. });
  10223. }
  10224. async function flushBridgeHosts() {
  10225. const selBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || (state.bridges[0] ? state.bridges[0].name : '');
  10226. if (!selBridge) {
  10227. showToast('Notice', 'Please select a bridge to flush dynamic MACs', 'info');
  10228. return;
  10229. }
  10230. if (!confirm(`Flush all dynamic learned MAC addresses on bridge '${selBridge}'?`)) return;
  10231. try {
  10232. const res = await fetch(`${API_BASE}/bridge/hosts/flush`, {
  10233. method: 'POST',
  10234. headers: { 'Content-Type': 'application/json' },
  10235. body: JSON.stringify({ bridge: selBridge })
  10236. });
  10237. if (res.ok) {
  10238. showToast('FDB Flushed', `Dynamic MACs flushed on ${selBridge}`, 'success');
  10239. loadBridgeHosts();
  10240. }
  10241. } catch (err) {
  10242. showToast('Error', err.message, 'error');
  10243. }
  10244. }
  10245. // ----------------- Helpers -----------------
  10246. function populateBridgeSelect(selectId, currentVal = '', includeAll = false) {
  10247. const sel = document.getElementById(selectId);
  10248. if (!sel) return;
  10249. const prevVal = currentVal || sel.value;
  10250. sel.innerHTML = includeAll ? '<option value="">All Bridges</option>' : '';
  10251. (state.bridges || []).forEach(b => {
  10252. const opt = document.createElement('option');
  10253. opt.value = b.name;
  10254. opt.innerText = `${b.name} (${b.ports_count} ports)`;
  10255. if (b.name === prevVal) opt.selected = true;
  10256. sel.appendChild(opt);
  10257. });
  10258. }
  10259. function populateBridgePortCandidateSelect(selectId, currentVal = '') {
  10260. const sel = document.getElementById(selectId);
  10261. if (!sel) return;
  10262. sel.innerHTML = '<option value="">(Select Interface...)</option>';
  10263. // 1. Physical Interfaces
  10264. const grpPhys = document.createElement('optgroup');
  10265. grpPhys.label = 'Physical Interfaces';
  10266. (state.interfaces || []).filter(i => i.type !== 'bridge' && i.type !== 'vlan' && i.type !== 'loopback').forEach(i => {
  10267. const opt = document.createElement('option');
  10268. opt.value = i.name;
  10269. opt.innerText = `${i.name} (${i.role || i.type})`;
  10270. if (i.name === currentVal) opt.selected = true;
  10271. grpPhys.appendChild(opt);
  10272. });
  10273. if (grpPhys.children.length > 0) sel.appendChild(grpPhys);
  10274. // 2. VLAN Sub-interfaces
  10275. const grpVlans = document.createElement('optgroup');
  10276. grpVlans.label = 'VLAN Sub-interfaces (802.1Q)';
  10277. (state.vlans || []).forEach(v => {
  10278. const opt = document.createElement('option');
  10279. opt.value = v.name;
  10280. opt.innerText = `${v.name} (VLAN ${v.vlan_id})`;
  10281. if (v.name === currentVal) opt.selected = true;
  10282. grpVlans.appendChild(opt);
  10283. });
  10284. if (grpVlans.children.length > 0) sel.appendChild(grpVlans);
  10285. // 3. EoIP Tunnels (MikroTik EoIP bridging!)
  10286. const grpEoip = document.createElement('optgroup');
  10287. grpEoip.label = 'EoIP Tunnels (Layer 2 VPN)';
  10288. (state.eoipTunnels || []).forEach(t => {
  10289. const opt = document.createElement('option');
  10290. opt.value = t.name;
  10291. opt.innerText = `${t.name} (Tunnel ID: ${t.tunnel_id} -> ${t.remote_address})`;
  10292. if (t.name === currentVal) opt.selected = true;
  10293. grpEoip.appendChild(opt);
  10294. });
  10295. if (grpEoip.children.length > 0) sel.appendChild(grpEoip);
  10296. }
  10297. // -------------------------------------------------------------
  10298. // RouterOS v7 Routing Filters Management (/routing filter)
  10299. // -------------------------------------------------------------
  10300. if (!state.activeRoutingFilterTab) state.activeRoutingFilterTab = 'rules';
  10301. if (!state.selectedFilterRow) state.selectedFilterRow = {};
  10302. if (!state.rfSort) state.rfSort = {};
  10303. function switchRoutingFilterTab(tab) {
  10304. state.activeRoutingFilterTab = tab;
  10305. const tabs = ['rules', 'select-rules', 'community-lists', 'as-lists'];
  10306. tabs.forEach(t => {
  10307. const btn = document.getElementById(`tab-rf-${t}`);
  10308. const content = document.getElementById(`tab-content-rf-${t}`);
  10309. if (btn) {
  10310. if (t === tab) {
  10311. 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';
  10312. } else {
  10313. btn.className = 'px-3 py-1 text-xs font-semibold rounded text-slate-400 hover:text-white hover:bg-slate-800 transition';
  10314. }
  10315. }
  10316. if (content) {
  10317. if (t === tab) content.classList.remove('hidden');
  10318. else content.classList.add('hidden');
  10319. }
  10320. });
  10321. const chainContainer = document.getElementById('rf-chain-filter-container');
  10322. if (chainContainer) {
  10323. if (tab === 'rules' || tab === 'select-rules') chainContainer.classList.remove('hidden');
  10324. else chainContainer.classList.add('hidden');
  10325. }
  10326. renderRoutingFilters();
  10327. }
  10328. function selectFilterRow(tab, id) {
  10329. if (state.selectedFilterRow[tab] === id) {
  10330. delete state.selectedFilterRow[tab];
  10331. } else {
  10332. state.selectedFilterRow[tab] = id;
  10333. }
  10334. if (tab === 'rules') renderRoutingFilterRules();
  10335. else if (tab === 'select-rules') renderRoutingFilterSelectRules();
  10336. else if (tab === 'community-lists') renderRoutingFilterCommunityLists();
  10337. else if (tab === 'as-lists') renderRoutingFilterASLists();
  10338. }
  10339. function openRoutingFilterNewModal() {
  10340. const tab = state.activeRoutingFilterTab || 'rules';
  10341. if (tab === 'rules') openAddRoutingFilterModal();
  10342. else if (tab === 'select-rules') openAddSelectRuleModal();
  10343. else if (tab === 'community-lists') openAddCommunityListModal();
  10344. else if (tab === 'as-lists') openAddASListModal();
  10345. }
  10346. function toggleSelectedRoutingFilter(disabled) {
  10347. const tab = state.activeRoutingFilterTab || 'rules';
  10348. const id = state.selectedFilterRow[tab];
  10349. if (!id) {
  10350. showToast('Select Row', 'Please click on a row to select it first', 'info');
  10351. return;
  10352. }
  10353. if (tab === 'rules') toggleRoutingFilterState(id, disabled);
  10354. else if (tab === 'select-rules') toggleSelectRuleState(id, disabled);
  10355. else if (tab === 'community-lists') toggleCommunityListState(id, disabled);
  10356. else if (tab === 'as-lists') toggleASListState(id, disabled);
  10357. }
  10358. function removeSelectedRoutingFilter() {
  10359. const tab = state.activeRoutingFilterTab || 'rules';
  10360. const id = state.selectedFilterRow[tab];
  10361. if (!id) {
  10362. showToast('Select Row', 'Please click on a row to select it first', 'info');
  10363. return;
  10364. }
  10365. if (tab === 'rules') deleteRoutingFilter(id);
  10366. else if (tab === 'select-rules') deleteSelectRule(id);
  10367. else if (tab === 'community-lists') deleteCommunityList(id);
  10368. else if (tab === 'as-lists') deleteASList(id);
  10369. }
  10370. function searchRoutingFilters(q) {
  10371. state.rfSearchQuery = (q || '').trim().toLowerCase();
  10372. renderRoutingFilters();
  10373. }
  10374. function sortFilterTable(tab, col) {
  10375. if (!state.rfSort) state.rfSort = {};
  10376. if (!state.rfSort[tab]) state.rfSort[tab] = { col: col, asc: true };
  10377. if (state.rfSort[tab].col === col) {
  10378. state.rfSort[tab].asc = !state.rfSort[tab].asc;
  10379. } else {
  10380. state.rfSort[tab].col = col;
  10381. state.rfSort[tab].asc = true;
  10382. }
  10383. const asc = state.rfSort[tab].asc;
  10384. let list = [];
  10385. if (tab === 'rules') list = state.routingFilters || [];
  10386. else if (tab === 'select-rules') list = state.routingSelectRules || [];
  10387. else if (tab === 'community-lists') list = state.routingCommunityLists || [];
  10388. else if (tab === 'as-lists') list = state.routingASLists || [];
  10389. list.sort((a, b) => {
  10390. let valA = a[col] ?? '';
  10391. let valB = b[col] ?? '';
  10392. if (col === 'flags') {
  10393. valA = a.disabled ? 'X' : 'A';
  10394. valB = b.disabled ? 'X' : 'A';
  10395. }
  10396. if (typeof valA === 'number' && typeof valB === 'number') {
  10397. return asc ? valA - valB : valB - valA;
  10398. }
  10399. return asc ? String(valA).localeCompare(String(valB)) : String(valB).localeCompare(String(valA));
  10400. });
  10401. const allCols = ['flags', 'rule_order', 'chain', 'rule', 'name', 'communities', 'range', 'regexp', 'comment'];
  10402. allCols.forEach(c => {
  10403. const el = document.getElementById(`sort-icon-${tab}-${c}`);
  10404. if (el) el.innerText = (c === col) ? (asc ? '▲' : '▼') : '';
  10405. });
  10406. if (tab === 'rules') renderRoutingFilterRules();
  10407. else if (tab === 'select-rules') renderRoutingFilterSelectRules();
  10408. else if (tab === 'community-lists') renderRoutingFilterCommunityLists();
  10409. else if (tab === 'as-lists') renderRoutingFilterASLists();
  10410. }
  10411. function renderRoutingFilters() {
  10412. const navBadge = document.getElementById('badge-filters-count');
  10413. const allRules = state.routingFilters || [];
  10414. if (navBadge) navBadge.innerText = allRules.length;
  10415. // Populate chain filter select options and datalist
  10416. const chainSelect = document.getElementById('routing-filter-chain-select');
  10417. const chainDatalist = document.getElementById('dl-routing-chains');
  10418. const uniqueChains = Array.from(new Set(allRules.map(r => r.chain).filter(Boolean))).sort();
  10419. if (chainSelect) {
  10420. const currentVal = state.filterChainSelected || 'all';
  10421. chainSelect.innerHTML = `<option value="all">All Chains (${allRules.length})</option>` +
  10422. uniqueChains.map(ch => {
  10423. const count = allRules.filter(r => r.chain === ch).length;
  10424. return `<option value="${escapeHtml(ch)}"${currentVal === ch ? ' selected' : ''}>${escapeHtml(ch)} (${count})</option>`;
  10425. }).join('');
  10426. chainSelect.value = currentVal;
  10427. }
  10428. if (chainDatalist) {
  10429. chainDatalist.innerHTML = uniqueChains.map(ch => `<option value="${escapeHtml(ch)}">`).join('');
  10430. }
  10431. renderRoutingFilterRules();
  10432. renderRoutingFilterSelectRules();
  10433. renderRoutingFilterCommunityLists();
  10434. renderRoutingFilterASLists();
  10435. }
  10436. function filterRoutingFiltersByChain(chain) {
  10437. state.filterChainSelected = chain;
  10438. renderRoutingFilters();
  10439. }
  10440. // -------------------------------------------------------------
  10441. // TAB 1: RULES (/routing filter rule)
  10442. // -------------------------------------------------------------
  10443. function renderRoutingFilterRules() {
  10444. const tbody = document.getElementById('routing-filter-rules-tbody');
  10445. if (!tbody) return;
  10446. const empty = document.getElementById('rf-rules-empty');
  10447. const statusCount = document.getElementById('rf-status-count');
  10448. let list = (state.routingFilters || []).slice();
  10449. if (state.filterChainSelected && state.filterChainSelected !== 'all') {
  10450. list = list.filter(r => r.chain === state.filterChainSelected);
  10451. }
  10452. const q = state.rfSearchQuery;
  10453. if (q) {
  10454. list = list.filter(r =>
  10455. (r.chain && r.chain.toLowerCase().includes(q)) ||
  10456. (r.rule && r.rule.toLowerCase().includes(q)) ||
  10457. (r.prefix && r.prefix.toLowerCase().includes(q)) ||
  10458. (r.comment && r.comment.toLowerCase().includes(q))
  10459. );
  10460. }
  10461. if (!state.rfSort?.['rules']) {
  10462. list.sort((a, b) => {
  10463. if (a.chain !== b.chain) return (a.chain || '').localeCompare(b.chain || '');
  10464. return (a.rule_order || 0) - (b.rule_order || 0);
  10465. });
  10466. }
  10467. if (statusCount && (state.activeRoutingFilterTab === 'rules' || !state.activeRoutingFilterTab)) {
  10468. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  10469. }
  10470. if (list.length === 0) {
  10471. tbody.innerHTML = '';
  10472. if (empty) empty.classList.remove('hidden');
  10473. return;
  10474. }
  10475. if (empty) empty.classList.add('hidden');
  10476. tbody.innerHTML = list.map(r => {
  10477. const isSelected = state.selectedFilterRow?.['rules'] === r.id;
  10478. const flagA = !r.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  10479. const flagX = r.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  10480. const flagC = r.comment ? '<span class="text-amber-400 font-bold ml-1" title="Comment">C</span>' : '';
  10481. let ruleDisplay = '';
  10482. if (r.rule && r.rule.trim() !== '') {
  10483. ruleDisplay = `<span class="text-emerald-400 font-mono font-medium">${escapeHtml(r.rule)}</span>`;
  10484. } else {
  10485. let conds = [];
  10486. if (r.prefix) conds.push(`dst in ${escapeHtml(r.prefix)}`);
  10487. if (r.match_protocol && r.match_protocol !== 'any') conds.push(`protocol ${escapeHtml(r.match_protocol)}`);
  10488. let act = r.action || 'accept';
  10489. ruleDisplay = `<span class="text-slate-300 font-mono">if (${conds.length ? conds.join(' && ') : 'true'}) { ${escapeHtml(act)}; }</span>`;
  10490. }
  10491. return `
  10492. <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'}">
  10493. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}${flagC}</td>
  10494. <td class="py-2 px-2 font-mono text-slate-400 font-bold">${r.rule_order || 10}</td>
  10495. <td class="py-2 px-3">
  10496. <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>
  10497. </td>
  10498. <td class="py-2 px-3 break-all max-w-xl">${ruleDisplay}</td>
  10499. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(r.comment || '')}</td>
  10500. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  10501. <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>
  10502. <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>
  10503. <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'}">
  10504. ${r.disabled ? 'Enable' : 'Disable'}
  10505. </button>
  10506. <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">
  10507. Edit
  10508. </button>
  10509. <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">
  10510. ✕
  10511. </button>
  10512. </td>
  10513. </tr>
  10514. `;
  10515. }).join('');
  10516. }
  10517. // -------------------------------------------------------------
  10518. // TAB 2: SELECT RULES (/routing filter select-rule)
  10519. // -------------------------------------------------------------
  10520. function renderRoutingFilterSelectRules() {
  10521. const tbody = document.getElementById('routing-filter-select-rules-tbody');
  10522. if (!tbody) return;
  10523. const empty = document.getElementById('rf-select-rules-empty');
  10524. const statusCount = document.getElementById('rf-status-count');
  10525. let list = (state.routingSelectRules || []).slice();
  10526. if (state.filterChainSelected && state.filterChainSelected !== 'all') {
  10527. list = list.filter(r => r.chain === state.filterChainSelected);
  10528. }
  10529. const q = state.rfSearchQuery;
  10530. if (q) {
  10531. list = list.filter(r =>
  10532. (r.chain && r.chain.toLowerCase().includes(q)) ||
  10533. (r.rule && r.rule.toLowerCase().includes(q)) ||
  10534. (r.comment && r.comment.toLowerCase().includes(q))
  10535. );
  10536. }
  10537. if (statusCount && state.activeRoutingFilterTab === 'select-rules') {
  10538. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  10539. }
  10540. if (list.length === 0) {
  10541. tbody.innerHTML = '';
  10542. if (empty) empty.classList.remove('hidden');
  10543. return;
  10544. }
  10545. if (empty) empty.classList.add('hidden');
  10546. tbody.innerHTML = list.map(r => {
  10547. const isSelected = state.selectedFilterRow?.['select-rules'] === r.id;
  10548. const flagA = !r.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  10549. const flagX = r.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  10550. return `
  10551. <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'}">
  10552. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  10553. <td class="py-2 px-2 font-mono text-slate-400 font-bold">${r.rule_order || 10}</td>
  10554. <td class="py-2 px-3">
  10555. <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>
  10556. </td>
  10557. <td class="py-2 px-3 break-all max-w-xl font-mono text-emerald-400">${escapeHtml(r.rule || '')}</td>
  10558. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(r.comment || '')}</td>
  10559. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  10560. <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'}">
  10561. ${r.disabled ? 'Enable' : 'Disable'}
  10562. </button>
  10563. <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">
  10564. Edit
  10565. </button>
  10566. <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">
  10567. ✕
  10568. </button>
  10569. </td>
  10570. </tr>
  10571. `;
  10572. }).join('');
  10573. }
  10574. // -------------------------------------------------------------
  10575. // TAB 3: COMMUNITY LISTS (/routing filter community-list)
  10576. // -------------------------------------------------------------
  10577. function renderRoutingFilterCommunityLists() {
  10578. const tbody = document.getElementById('routing-filter-comm-lists-tbody');
  10579. if (!tbody) return;
  10580. const empty = document.getElementById('rf-comm-lists-empty');
  10581. const statusCount = document.getElementById('rf-status-count');
  10582. let list = (state.routingCommunityLists || []).slice();
  10583. const q = state.rfSearchQuery;
  10584. if (q) {
  10585. list = list.filter(cl =>
  10586. (cl.name && cl.name.toLowerCase().includes(q)) ||
  10587. (cl.comment && cl.comment.toLowerCase().includes(q)) ||
  10588. (cl.communities && cl.communities.some(c => c.toLowerCase().includes(q)))
  10589. );
  10590. }
  10591. if (statusCount && state.activeRoutingFilterTab === 'community-lists') {
  10592. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  10593. }
  10594. if (list.length === 0) {
  10595. tbody.innerHTML = '';
  10596. if (empty) empty.classList.remove('hidden');
  10597. return;
  10598. }
  10599. if (empty) empty.classList.add('hidden');
  10600. tbody.innerHTML = list.map(cl => {
  10601. const isSelected = state.selectedFilterRow?.['community-lists'] === cl.id;
  10602. const flagA = !cl.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  10603. const flagX = cl.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  10604. const commBadges = (cl.communities || []).map(c =>
  10605. `<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>`
  10606. ).join(' ');
  10607. return `
  10608. <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'}">
  10609. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  10610. <td class="py-2 px-3 font-mono font-bold text-white">${escapeHtml(cl.name)}</td>
  10611. <td class="py-2 px-3 space-x-1">${commBadges || '<span class="text-slate-600">-</span>'}</td>
  10612. <td class="py-2 px-3 font-mono text-slate-400">${escapeHtml(cl.regexp || '-')}</td>
  10613. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(cl.comment || '')}</td>
  10614. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  10615. <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'}">
  10616. ${cl.disabled ? 'Enable' : 'Disable'}
  10617. </button>
  10618. <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">
  10619. Edit
  10620. </button>
  10621. <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">
  10622. ✕
  10623. </button>
  10624. </td>
  10625. </tr>
  10626. `;
  10627. }).join('');
  10628. }
  10629. // -------------------------------------------------------------
  10630. // TAB 4: AS LISTS (/routing filter num-list)
  10631. // -------------------------------------------------------------
  10632. function renderRoutingFilterASLists() {
  10633. const tbody = document.getElementById('routing-filter-as-lists-tbody');
  10634. if (!tbody) return;
  10635. const empty = document.getElementById('rf-as-lists-empty');
  10636. const statusCount = document.getElementById('rf-status-count');
  10637. let list = (state.routingASLists || []).slice();
  10638. const q = state.rfSearchQuery;
  10639. if (q) {
  10640. list = list.filter(al =>
  10641. (al.name && al.name.toLowerCase().includes(q)) ||
  10642. (al.range && al.range.toLowerCase().includes(q)) ||
  10643. (al.comment && al.comment.toLowerCase().includes(q))
  10644. );
  10645. }
  10646. if (statusCount && state.activeRoutingFilterTab === 'as-lists') {
  10647. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  10648. }
  10649. if (list.length === 0) {
  10650. tbody.innerHTML = '';
  10651. if (empty) empty.classList.remove('hidden');
  10652. return;
  10653. }
  10654. if (empty) empty.classList.add('hidden');
  10655. tbody.innerHTML = list.map(al => {
  10656. const isSelected = state.selectedFilterRow?.['as-lists'] === al.id;
  10657. const flagA = !al.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  10658. const flagX = al.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  10659. return `
  10660. <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'}">
  10661. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  10662. <td class="py-2 px-3 font-mono font-bold text-white">${escapeHtml(al.name)}</td>
  10663. <td class="py-2 px-3 font-mono text-purple-300">${escapeHtml(al.range)}</td>
  10664. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(al.comment || '')}</td>
  10665. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  10666. <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'}">
  10667. ${al.disabled ? 'Enable' : 'Disable'}
  10668. </button>
  10669. <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">
  10670. Edit
  10671. </button>
  10672. <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">
  10673. ✕
  10674. </button>
  10675. </td>
  10676. </tr>
  10677. `;
  10678. }).join('');
  10679. }
  10680. // -------------------------------------------------------------
  10681. // SNIPPETS & WIZARD HELPERS
  10682. // -------------------------------------------------------------
  10683. function insertRuleSnippet(type) {
  10684. const textarea = document.getElementById('modal-rf-rule');
  10685. if (!textarea) return;
  10686. let snippet = '';
  10687. switch (type) {
  10688. case 'accept-default':
  10689. snippet = 'if (dst in 0.0.0.0/0) { accept; }';
  10690. break;
  10691. case 'drop-rfc1918':
  10692. snippet = 'if (dst in 10.0.0.0/8 || dst in 172.16.0.0/12 || dst in 192.168.0.0/16) { reject; }';
  10693. break;
  10694. case 'len-24':
  10695. snippet = 'if (dst-len > 24) { reject; }';
  10696. break;
  10697. case 'local-pref-150':
  10698. snippet = 'if (dst in 10.0.0.0/8) { set bgp-local-pref 150; accept; }';
  10699. break;
  10700. case 'as-prepend-2':
  10701. snippet = 'set bgp-path-prepend 2; accept;';
  10702. break;
  10703. case 'set-comm':
  10704. snippet = 'set bgp-communities.add 65000:100; accept;';
  10705. break;
  10706. case 'match-comm':
  10707. snippet = 'if (bgp-communities includes 65000:100) { accept; }';
  10708. break;
  10709. case 'reject-all':
  10710. snippet = 'reject;';
  10711. break;
  10712. }
  10713. if (!snippet) return;
  10714. if (!textarea.value.trim()) {
  10715. textarea.value = snippet;
  10716. } else {
  10717. textarea.value = textarea.value.trim() + '\n' + snippet;
  10718. }
  10719. }
  10720. function generateScriptFromWizard() {
  10721. const pfx = (document.getElementById('modal-rf-prefix')?.value || '').trim();
  10722. const pfxLen = (document.getElementById('modal-rf-prefix-len')?.value || '').trim();
  10723. const proto = document.getElementById('modal-rf-protocol')?.value || 'any';
  10724. const asp = (document.getElementById('modal-rf-as-path')?.value || '').trim();
  10725. const comm = (document.getElementById('modal-rf-community')?.value || '').trim();
  10726. const act = document.getElementById('modal-rf-action')?.value || 'accept';
  10727. const lp = parseInt(document.getElementById('modal-rf-set-local-pref')?.value, 10) || 0;
  10728. const prep = parseInt(document.getElementById('modal-rf-set-as-prepend')?.value, 10) || 0;
  10729. const conds = [];
  10730. if (pfx) {
  10731. if (pfxLen) {
  10732. if (pfxLen.includes('-')) {
  10733. const parts = pfxLen.split('-');
  10734. conds.push(`dst in ${pfx}{${parts[0].trim()},${parts[1].trim()}}`);
  10735. } else {
  10736. conds.push(`dst in ${pfx} && dst-len >= ${pfxLen}`);
  10737. }
  10738. } else {
  10739. conds.push(`dst in ${pfx}`);
  10740. }
  10741. }
  10742. if (proto && proto !== 'any') {
  10743. conds.push(`protocol ${proto}`);
  10744. }
  10745. if (asp) {
  10746. conds.push(`bgp-as-path "${asp}"`);
  10747. }
  10748. if (comm) {
  10749. conds.push(`bgp-communities includes ${comm}`);
  10750. }
  10751. const actions = [];
  10752. if (lp > 0) actions.push(`set bgp-local-pref ${lp};`);
  10753. if (prep > 0) actions.push(`set bgp-path-prepend ${prep};`);
  10754. actions.push(`${act};`);
  10755. let code = '';
  10756. if (conds.length > 0) {
  10757. code = `if (${conds.join(' && ')}) {\n ${actions.join(' ')}\n}`;
  10758. } else {
  10759. code = actions.join(' ');
  10760. }
  10761. const textarea = document.getElementById('modal-rf-rule');
  10762. if (textarea) textarea.value = code;
  10763. }
  10764. // -------------------------------------------------------------
  10765. // MODAL CRUD: RULES (/routing filter rule)
  10766. // -------------------------------------------------------------
  10767. function openAddRoutingFilterModal(defaultChain = '') {
  10768. const form = document.getElementById('routing-filter-form');
  10769. if (form) form.reset();
  10770. const idEl = document.getElementById('modal-rf-id');
  10771. if (idEl) idEl.value = '';
  10772. const titleEl = document.getElementById('modal-rf-title');
  10773. if (titleEl) titleEl.innerText = 'Add Routing Filter Rule';
  10774. const chainEl = document.getElementById('modal-rf-chain');
  10775. if (chainEl) chainEl.value = defaultChain || (state.filterChainSelected && state.filterChainSelected !== 'all' ? state.filterChainSelected : 'bgp-in');
  10776. const orderEl = document.getElementById('modal-rf-order');
  10777. if (orderEl) orderEl.value = ((state.routingFilters || []).length + 1) * 10;
  10778. const ruleEl = document.getElementById('modal-rf-rule');
  10779. if (ruleEl) ruleEl.value = 'if (dst in 10.0.0.0/8) { set bgp-local-pref 150; accept; }';
  10780. const disEl = document.getElementById('modal-rf-disabled');
  10781. if (disEl) disEl.checked = false;
  10782. const modal = document.getElementById('modal-routing-filter');
  10783. if (modal) modal.classList.remove('hidden');
  10784. }
  10785. function openEditRoutingFilterModal(id) {
  10786. const r = (state.routingFilters || []).find(item => item.id === id);
  10787. if (!r) return;
  10788. const idEl = document.getElementById('modal-rf-id');
  10789. if (idEl) idEl.value = r.id;
  10790. const titleEl = document.getElementById('modal-rf-title');
  10791. if (titleEl) titleEl.innerText = 'Edit Routing Filter Rule';
  10792. const chainEl = document.getElementById('modal-rf-chain');
  10793. if (chainEl) chainEl.value = r.chain || '';
  10794. const orderEl = document.getElementById('modal-rf-order');
  10795. if (orderEl) orderEl.value = r.rule_order || 10;
  10796. const ruleEl = document.getElementById('modal-rf-rule');
  10797. if (ruleEl) {
  10798. if (r.rule) {
  10799. ruleEl.value = r.rule;
  10800. } else {
  10801. let conds = [];
  10802. if (r.prefix) conds.push(`dst in ${r.prefix}`);
  10803. if (r.match_protocol && r.match_protocol !== 'any') conds.push(`protocol ${r.match_protocol}`);
  10804. let act = r.action || 'accept';
  10805. ruleEl.value = `if (${conds.length ? conds.join(' && ') : 'true'}) { ${act}; }`;
  10806. }
  10807. }
  10808. const comEl = document.getElementById('modal-rf-comment');
  10809. if (comEl) comEl.value = r.comment || '';
  10810. const disEl = document.getElementById('modal-rf-disabled');
  10811. if (disEl) disEl.checked = !!r.disabled;
  10812. const modal = document.getElementById('modal-routing-filter');
  10813. if (modal) modal.classList.remove('hidden');
  10814. }
  10815. function closeRoutingFilterModal() {
  10816. const modal = document.getElementById('modal-routing-filter');
  10817. if (modal) modal.classList.add('hidden');
  10818. }
  10819. async function submitRoutingFilter(e) {
  10820. if (e) e.preventDefault();
  10821. const payload = {
  10822. id: document.getElementById('modal-rf-id').value,
  10823. chain: document.getElementById('modal-rf-chain').value.trim(),
  10824. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  10825. rule: document.getElementById('modal-rf-rule').value.trim(),
  10826. comment: document.getElementById('modal-rf-comment').value.trim(),
  10827. disabled: document.getElementById('modal-rf-disabled').checked
  10828. };
  10829. try {
  10830. const res = await fetch(`${API_BASE}/routing/filters`, {
  10831. method: 'POST',
  10832. headers: { 'Content-Type': 'application/json' },
  10833. body: JSON.stringify(payload)
  10834. });
  10835. if (res.ok) {
  10836. closeRoutingFilterModal();
  10837. showToast('Success', 'Routing filter rule saved', 'success');
  10838. loadDynamicRouting();
  10839. } else {
  10840. const err = await res.json();
  10841. showToast('Error', err.error || 'Failed to save filter rule', 'error');
  10842. }
  10843. } catch (err) {
  10844. showToast('Error', err.message, 'error');
  10845. }
  10846. }
  10847. async function applyRoutingFilterForm() {
  10848. const payload = {
  10849. id: document.getElementById('modal-rf-id').value,
  10850. chain: document.getElementById('modal-rf-chain').value.trim(),
  10851. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  10852. rule: document.getElementById('modal-rf-rule').value.trim(),
  10853. comment: document.getElementById('modal-rf-comment').value.trim(),
  10854. disabled: document.getElementById('modal-rf-disabled').checked
  10855. };
  10856. try {
  10857. const res = await fetch(`${API_BASE}/routing/filters`, {
  10858. method: 'POST',
  10859. headers: { 'Content-Type': 'application/json' },
  10860. body: JSON.stringify(payload)
  10861. });
  10862. if (res.ok) {
  10863. const data = await res.json();
  10864. if (data.id) document.getElementById('modal-rf-id').value = data.id;
  10865. showToast('Applied', 'Routing filter configuration applied', 'success');
  10866. loadDynamicRouting();
  10867. } else {
  10868. const err = await res.json();
  10869. showToast('Error', err.error || 'Failed to apply filter rule', 'error');
  10870. }
  10871. } catch (err) {
  10872. showToast('Error', err.message, 'error');
  10873. }
  10874. }
  10875. async function moveRoutingFilterOrder(id, delta) {
  10876. const list = state.routingFilters || [];
  10877. const idx = list.findIndex(r => r.id === id);
  10878. if (idx < 0) return;
  10879. const targetIdx = idx + delta;
  10880. if (targetIdx < 0 || targetIdx >= list.length) return;
  10881. const currentOrder = list[idx].rule_order || 10;
  10882. const targetOrder = list[targetIdx].rule_order || 20;
  10883. list[idx].rule_order = targetOrder;
  10884. list[targetIdx].rule_order = currentOrder;
  10885. try {
  10886. await fetch(`${API_BASE}/routing/filters`, {
  10887. method: 'POST',
  10888. headers: { 'Content-Type': 'application/json' },
  10889. body: JSON.stringify(list[idx])
  10890. });
  10891. await fetch(`${API_BASE}/routing/filters`, {
  10892. method: 'POST',
  10893. headers: { 'Content-Type': 'application/json' },
  10894. body: JSON.stringify(list[targetIdx])
  10895. });
  10896. loadDynamicRouting();
  10897. } catch (e) {
  10898. console.error('Reorder error:', e);
  10899. }
  10900. }
  10901. async function deleteRoutingFilter(id) {
  10902. if (!confirm('Are you sure you want to delete this routing filter rule?')) return;
  10903. try {
  10904. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10905. if (res.ok) {
  10906. showToast('Deleted', 'Routing filter rule removed', 'info');
  10907. loadDynamicRouting();
  10908. } else {
  10909. const err = await res.json();
  10910. showToast('Error', err.error || 'Failed to delete rule', 'error');
  10911. }
  10912. } catch (err) {
  10913. showToast('Error', err.message, 'error');
  10914. }
  10915. }
  10916. async function toggleRoutingFilterState(id, disabled) {
  10917. try {
  10918. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}/state`, {
  10919. method: 'POST',
  10920. headers: { 'Content-Type': 'application/json' },
  10921. body: JSON.stringify({ disabled })
  10922. });
  10923. if (res.ok) {
  10924. showToast('Status Updated', `Rule ${disabled ? 'disabled' : 'enabled'}`, 'info');
  10925. loadDynamicRouting();
  10926. } else {
  10927. const err = await res.json();
  10928. showToast('Error', err.error || 'Failed to toggle rule state', 'error');
  10929. }
  10930. } catch (err) {
  10931. showToast('Error', err.message, 'error');
  10932. }
  10933. }
  10934. // -------------------------------------------------------------
  10935. // MODAL CRUD: SELECT RULES (/routing filter select-rule)
  10936. // -------------------------------------------------------------
  10937. function openAddSelectRuleModal() {
  10938. document.getElementById('modal-rf-sr-id').value = '';
  10939. document.getElementById('modal-rf-sr-title').innerText = 'Add Routing Select Rule';
  10940. document.getElementById('modal-rf-sr-chain').value = state.filterChainSelected && state.filterChainSelected !== 'all' ? state.filterChainSelected : 'bgp-out';
  10941. document.getElementById('modal-rf-sr-order').value = ((state.routingSelectRules || []).length + 1) * 10;
  10942. document.getElementById('modal-rf-sr-rule').value = 'if (protocol bgp && dst in 10.0.0.0/8) { accept; }';
  10943. document.getElementById('modal-rf-sr-comment').value = '';
  10944. document.getElementById('modal-rf-sr-disabled').checked = false;
  10945. document.getElementById('modal-rf-select-rule').classList.remove('hidden');
  10946. }
  10947. function openEditSelectRuleModal(id) {
  10948. const r = (state.routingSelectRules || []).find(item => item.id === id);
  10949. if (!r) return;
  10950. document.getElementById('modal-rf-sr-id').value = r.id;
  10951. document.getElementById('modal-rf-sr-title').innerText = 'Edit Routing Select Rule';
  10952. document.getElementById('modal-rf-sr-chain').value = r.chain || '';
  10953. document.getElementById('modal-rf-sr-order').value = r.rule_order || 10;
  10954. document.getElementById('modal-rf-sr-rule').value = r.rule || '';
  10955. document.getElementById('modal-rf-sr-comment').value = r.comment || '';
  10956. document.getElementById('modal-rf-sr-disabled').checked = !!r.disabled;
  10957. document.getElementById('modal-rf-select-rule').classList.remove('hidden');
  10958. }
  10959. function closeSelectRuleModal() {
  10960. document.getElementById('modal-rf-select-rule').classList.add('hidden');
  10961. }
  10962. async function submitSelectRule(e) {
  10963. e.preventDefault();
  10964. const payload = {
  10965. id: document.getElementById('modal-rf-sr-id').value,
  10966. chain: document.getElementById('modal-rf-sr-chain').value.trim(),
  10967. rule_order: parseInt(document.getElementById('modal-rf-sr-order').value, 10) || 10,
  10968. rule: document.getElementById('modal-rf-sr-rule').value.trim(),
  10969. comment: document.getElementById('modal-rf-sr-comment').value.trim(),
  10970. disabled: document.getElementById('modal-rf-sr-disabled').checked
  10971. };
  10972. try {
  10973. const res = await fetch(`${API_BASE}/routing/filters/select-rules`, {
  10974. method: 'POST',
  10975. headers: { 'Content-Type': 'application/json' },
  10976. body: JSON.stringify(payload)
  10977. });
  10978. if (res.ok) {
  10979. closeSelectRuleModal();
  10980. showToast('Success', 'Select rule saved', 'success');
  10981. loadDynamicRouting();
  10982. } else {
  10983. const err = await res.json();
  10984. showToast('Error', err.error || 'Failed to save select rule', 'error');
  10985. }
  10986. } catch (err) {
  10987. showToast('Error', err.message, 'error');
  10988. }
  10989. }
  10990. async function deleteSelectRule(id) {
  10991. if (!confirm('Are you sure you want to delete this select rule?')) return;
  10992. try {
  10993. const res = await fetch(`${API_BASE}/routing/filters/select-rules/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10994. if (res.ok) {
  10995. showToast('Deleted', 'Select rule removed', 'info');
  10996. loadDynamicRouting();
  10997. } else {
  10998. const err = await res.json();
  10999. showToast('Error', err.error || 'Failed to delete select rule', 'error');
  11000. }
  11001. } catch (err) {
  11002. showToast('Error', err.message, 'error');
  11003. }
  11004. }
  11005. async function toggleSelectRuleState(id, disabled) {
  11006. try {
  11007. const res = await fetch(`${API_BASE}/routing/filters/select-rules/${encodeURIComponent(id)}/state`, {
  11008. method: 'POST',
  11009. headers: { 'Content-Type': 'application/json' },
  11010. body: JSON.stringify({ disabled })
  11011. });
  11012. if (res.ok) {
  11013. showToast('Status Updated', `Select rule ${disabled ? 'disabled' : 'enabled'}`, 'info');
  11014. loadDynamicRouting();
  11015. } else {
  11016. const err = await res.json();
  11017. showToast('Error', err.error || 'Failed to update select rule state', 'error');
  11018. }
  11019. } catch (err) {
  11020. showToast('Error', err.message, 'error');
  11021. }
  11022. }
  11023. // -------------------------------------------------------------
  11024. // MODAL CRUD: COMMUNITY LISTS (/routing filter community-list)
  11025. // -------------------------------------------------------------
  11026. function openAddCommunityListModal() {
  11027. document.getElementById('modal-rf-cl-id').value = '';
  11028. document.getElementById('modal-rf-cl-title').innerText = 'Add BGP Community List';
  11029. document.getElementById('modal-rf-cl-name').value = '';
  11030. document.getElementById('modal-rf-cl-communities').value = '';
  11031. document.getElementById('modal-rf-cl-regexp').value = '';
  11032. document.getElementById('modal-rf-cl-comment').value = '';
  11033. document.getElementById('modal-rf-cl-disabled').checked = false;
  11034. document.getElementById('modal-rf-community-list').classList.remove('hidden');
  11035. }
  11036. function openEditCommunityListModal(id) {
  11037. const cl = (state.routingCommunityLists || []).find(item => item.id === id);
  11038. if (!cl) return;
  11039. document.getElementById('modal-rf-cl-id').value = cl.id;
  11040. document.getElementById('modal-rf-cl-title').innerText = 'Edit BGP Community List';
  11041. document.getElementById('modal-rf-cl-name').value = cl.name || '';
  11042. document.getElementById('modal-rf-cl-communities').value = (cl.communities || []).join(', ');
  11043. document.getElementById('modal-rf-cl-regexp').value = cl.regexp || '';
  11044. document.getElementById('modal-rf-cl-comment').value = cl.comment || '';
  11045. document.getElementById('modal-rf-cl-disabled').checked = !!cl.disabled;
  11046. document.getElementById('modal-rf-community-list').classList.remove('hidden');
  11047. }
  11048. function closeCommunityListModal() {
  11049. document.getElementById('modal-rf-community-list').classList.add('hidden');
  11050. }
  11051. async function submitCommunityList(e) {
  11052. e.preventDefault();
  11053. const rawComms = document.getElementById('modal-rf-cl-communities').value;
  11054. const comms = rawComms.split(',').map(c => c.trim()).filter(Boolean);
  11055. const payload = {
  11056. id: document.getElementById('modal-rf-cl-id').value,
  11057. name: document.getElementById('modal-rf-cl-name').value.trim(),
  11058. communities: comms,
  11059. regexp: document.getElementById('modal-rf-cl-regexp').value.trim(),
  11060. comment: document.getElementById('modal-rf-cl-comment').value.trim(),
  11061. disabled: document.getElementById('modal-rf-cl-disabled').checked
  11062. };
  11063. try {
  11064. const res = await fetch(`${API_BASE}/routing/filters/community-lists`, {
  11065. method: 'POST',
  11066. headers: { 'Content-Type': 'application/json' },
  11067. body: JSON.stringify(payload)
  11068. });
  11069. if (res.ok) {
  11070. closeCommunityListModal();
  11071. showToast('Success', 'Community list saved', 'success');
  11072. loadDynamicRouting();
  11073. } else {
  11074. const err = await res.json();
  11075. showToast('Error', err.error || 'Failed to save community list', 'error');
  11076. }
  11077. } catch (err) {
  11078. showToast('Error', err.message, 'error');
  11079. }
  11080. }
  11081. async function deleteCommunityList(id) {
  11082. if (!confirm('Are you sure you want to delete this community list?')) return;
  11083. try {
  11084. const res = await fetch(`${API_BASE}/routing/filters/community-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11085. if (res.ok) {
  11086. showToast('Deleted', 'Community list removed', 'info');
  11087. loadDynamicRouting();
  11088. } else {
  11089. const err = await res.json();
  11090. showToast('Error', err.error || 'Failed to delete community list', 'error');
  11091. }
  11092. } catch (err) {
  11093. showToast('Error', err.message, 'error');
  11094. }
  11095. }
  11096. async function toggleCommunityListState(id, disabled) {
  11097. try {
  11098. const res = await fetch(`${API_BASE}/routing/filters/community-lists/${encodeURIComponent(id)}/state`, {
  11099. method: 'POST',
  11100. headers: { 'Content-Type': 'application/json' },
  11101. body: JSON.stringify({ disabled })
  11102. });
  11103. if (res.ok) {
  11104. showToast('Status Updated', `Community list ${disabled ? 'disabled' : 'enabled'}`, 'info');
  11105. loadDynamicRouting();
  11106. } else {
  11107. const err = await res.json();
  11108. showToast('Error', err.error || 'Failed to update community list state', 'error');
  11109. }
  11110. } catch (err) {
  11111. showToast('Error', err.message, 'error');
  11112. }
  11113. }
  11114. // -------------------------------------------------------------
  11115. // MODAL CRUD: AS LISTS (/routing filter num-list)
  11116. // -------------------------------------------------------------
  11117. function openAddASListModal() {
  11118. document.getElementById('modal-rf-al-id').value = '';
  11119. document.getElementById('modal-rf-al-title').innerText = 'Add AS Number List';
  11120. document.getElementById('modal-rf-al-name').value = '';
  11121. document.getElementById('modal-rf-al-range').value = '';
  11122. document.getElementById('modal-rf-al-comment').value = '';
  11123. document.getElementById('modal-rf-al-disabled').checked = false;
  11124. document.getElementById('modal-rf-as-list').classList.remove('hidden');
  11125. }
  11126. function openEditASListModal(id) {
  11127. const al = (state.routingASLists || []).find(item => item.id === id);
  11128. if (!al) return;
  11129. document.getElementById('modal-rf-al-id').value = al.id;
  11130. document.getElementById('modal-rf-al-title').innerText = 'Edit AS Number List';
  11131. document.getElementById('modal-rf-al-name').value = al.name || '';
  11132. document.getElementById('modal-rf-al-range').value = al.range || '';
  11133. document.getElementById('modal-rf-al-comment').value = al.comment || '';
  11134. document.getElementById('modal-rf-al-disabled').checked = !!al.disabled;
  11135. document.getElementById('modal-rf-as-list').classList.remove('hidden');
  11136. }
  11137. function closeASListModal() {
  11138. document.getElementById('modal-rf-as-list').classList.add('hidden');
  11139. }
  11140. async function submitASList(e) {
  11141. e.preventDefault();
  11142. const payload = {
  11143. id: document.getElementById('modal-rf-al-id').value,
  11144. name: document.getElementById('modal-rf-al-name').value.trim(),
  11145. range: document.getElementById('modal-rf-al-range').value.trim(),
  11146. comment: document.getElementById('modal-rf-al-comment').value.trim(),
  11147. disabled: document.getElementById('modal-rf-al-disabled').checked
  11148. };
  11149. try {
  11150. const res = await fetch(`${API_BASE}/routing/filters/as-lists`, {
  11151. method: 'POST',
  11152. headers: { 'Content-Type': 'application/json' },
  11153. body: JSON.stringify(payload)
  11154. });
  11155. if (res.ok) {
  11156. closeASListModal();
  11157. showToast('Success', 'AS number list saved', 'success');
  11158. loadDynamicRouting();
  11159. } else {
  11160. const err = await res.json();
  11161. showToast('Error', err.error || 'Failed to save AS list', 'error');
  11162. }
  11163. } catch (err) {
  11164. showToast('Error', err.message, 'error');
  11165. }
  11166. }
  11167. async function deleteASList(id) {
  11168. if (!confirm('Are you sure you want to delete this AS list?')) return;
  11169. try {
  11170. const res = await fetch(`${API_BASE}/routing/filters/as-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11171. if (res.ok) {
  11172. showToast('Deleted', 'AS list removed', 'info');
  11173. loadDynamicRouting();
  11174. } else {
  11175. const err = await res.json();
  11176. showToast('Error', err.error || 'Failed to delete AS list', 'error');
  11177. }
  11178. } catch (err) {
  11179. showToast('Error', err.message, 'error');
  11180. }
  11181. }
  11182. async function toggleASListState(id, disabled) {
  11183. try {
  11184. const res = await fetch(`${API_BASE}/routing/filters/as-lists/${encodeURIComponent(id)}/state`, {
  11185. method: 'POST',
  11186. headers: { 'Content-Type': 'application/json' },
  11187. body: JSON.stringify({ disabled })
  11188. });
  11189. if (res.ok) {
  11190. showToast('Status Updated', `AS list ${disabled ? 'disabled' : 'enabled'}`, 'info');
  11191. loadDynamicRouting();
  11192. } else {
  11193. const err = await res.json();
  11194. showToast('Error', err.error || 'Failed to update AS list state', 'error');
  11195. }
  11196. } catch (err) {
  11197. showToast('Error', err.message, 'error');
  11198. }
  11199. }
  11200. // ==========================================
  11201. // TROUBLESHOOT & DIAGNOSTIC TOOLS (/tool)
  11202. // ==========================================
  11203. function loadToolsView() {
  11204. populateToolsInterfaces();
  11205. switchToolsSubTab(state.activeToolsSubTab || 'ping');
  11206. }
  11207. function populateToolsInterfaces() {
  11208. const pingSel = document.getElementById('tools-ping-iface');
  11209. const traceSel = document.getElementById('tools-tr-iface');
  11210. let opts = '<option value="">Auto (Default Route)</option>';
  11211. if (Array.isArray(state.interfaces)) {
  11212. state.interfaces.forEach(iface => {
  11213. if (iface.name) {
  11214. opts += `<option value="${escapeHtml(iface.name)}">${escapeHtml(iface.name)}${iface.ip_address ? ' (' + escapeHtml(iface.ip_address) + ')' : ''}</option>`;
  11215. }
  11216. });
  11217. }
  11218. if (pingSel) {
  11219. const cur = pingSel.value;
  11220. pingSel.innerHTML = opts;
  11221. if (cur) pingSel.value = cur;
  11222. }
  11223. if (traceSel) {
  11224. const cur = traceSel.value;
  11225. traceSel.innerHTML = opts;
  11226. if (cur) traceSel.value = cur;
  11227. }
  11228. }
  11229. function switchToolsSubTab(subTab) {
  11230. state.activeToolsSubTab = subTab;
  11231. const tabs = ['ping', 'traceroute', 'mtr', 'dns', 'port'];
  11232. tabs.forEach(t => {
  11233. const btn = document.getElementById(`tools-subtab-btn-${t}`);
  11234. const view = document.getElementById(`tools-view-${t}`);
  11235. if (btn) {
  11236. if (t === subTab) {
  11237. 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';
  11238. } else {
  11239. 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';
  11240. }
  11241. }
  11242. if (view) {
  11243. if (t === subTab) {
  11244. view.classList.remove('hidden');
  11245. } else {
  11246. view.classList.add('hidden');
  11247. }
  11248. }
  11249. });
  11250. }
  11251. function setPortPreset(port) {
  11252. const input = document.getElementById('tools-port-num');
  11253. if (input) input.value = port;
  11254. }
  11255. let pingAbortController = null;
  11256. let tracerouteAbortController = null;
  11257. function clearPingTable() {
  11258. const tbody = document.getElementById('tools-ping-tbody');
  11259. if (tbody) tbody.innerHTML = '';
  11260. const rawEl = document.getElementById('tools-ping-raw');
  11261. if (rawEl) rawEl.innerText = '';
  11262. const sentEl = document.getElementById('tools-ping-stat-sent');
  11263. if (sentEl) sentEl.innerText = '0';
  11264. const recvEl = document.getElementById('tools-ping-stat-recv');
  11265. if (recvEl) recvEl.innerText = '0';
  11266. const lossEl = document.getElementById('tools-ping-stat-loss');
  11267. if (lossEl) lossEl.innerText = '0%';
  11268. const avgEl = document.getElementById('tools-ping-stat-avg');
  11269. if (avgEl) avgEl.innerText = '0 ms';
  11270. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  11271. if (minMaxEl) minMaxEl.innerText = '-';
  11272. const badge = document.getElementById('tools-ping-status-badge');
  11273. if (badge) {
  11274. badge.className = '';
  11275. badge.innerText = '';
  11276. }
  11277. }
  11278. function clearTracerouteTable() {
  11279. const tbody = document.getElementById('tools-tr-tbody');
  11280. if (tbody) tbody.innerHTML = '';
  11281. const rawEl = document.getElementById('tools-tr-raw');
  11282. if (rawEl) rawEl.innerText = '';
  11283. const statHops = document.getElementById('tools-tr-hops-count');
  11284. if (statHops) statHops.innerText = '0 Hops';
  11285. }
  11286. function resetPingButton() {
  11287. const btn = document.getElementById('tools-ping-btn');
  11288. const btnText = document.getElementById('tools-ping-btn-text');
  11289. const spinner = document.getElementById('tools-ping-spinner');
  11290. if (btn) {
  11291. btn.disabled = false;
  11292. 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';
  11293. }
  11294. if (btnText) btnText.innerText = 'Start Ping';
  11295. if (spinner) spinner.classList.add('hidden');
  11296. }
  11297. function setPingRunningButton() {
  11298. const btn = document.getElementById('tools-ping-btn');
  11299. const btnText = document.getElementById('tools-ping-btn-text');
  11300. const spinner = document.getElementById('tools-ping-spinner');
  11301. if (btn) {
  11302. btn.disabled = false;
  11303. 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';
  11304. }
  11305. if (btnText) btnText.innerText = 'Stop Ping';
  11306. if (spinner) spinner.classList.remove('hidden');
  11307. }
  11308. function resetTracerouteButton() {
  11309. const btn = document.getElementById('tools-tr-btn');
  11310. const btnText = document.getElementById('tools-tr-btn-text');
  11311. const spinner = document.getElementById('tools-tr-spinner');
  11312. if (btn) {
  11313. btn.disabled = false;
  11314. 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';
  11315. }
  11316. if (btnText) btnText.innerText = 'Start Traceroute';
  11317. if (spinner) spinner.classList.add('hidden');
  11318. }
  11319. function setTracerouteRunningButton() {
  11320. const btn = document.getElementById('tools-tr-btn');
  11321. const btnText = document.getElementById('tools-tr-btn-text');
  11322. const spinner = document.getElementById('tools-tr-spinner');
  11323. if (btn) {
  11324. btn.disabled = false;
  11325. 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';
  11326. }
  11327. if (btnText) btnText.innerText = 'Stop Traceroute';
  11328. if (spinner) spinner.classList.remove('hidden');
  11329. }
  11330. async function executePing(e) {
  11331. if (e) e.preventDefault();
  11332. // If already running, clicking the button stops the stream!
  11333. if (pingAbortController) {
  11334. pingAbortController.abort();
  11335. pingAbortController = null;
  11336. resetPingButton();
  11337. showToast('Ping Stopped', 'Live ping stopped by user', 'info');
  11338. return;
  11339. }
  11340. const target = document.getElementById('tools-ping-target')?.value?.trim();
  11341. const count = parseInt(document.getElementById('tools-ping-count')?.value || '4', 10);
  11342. const size = parseInt(document.getElementById('tools-ping-size')?.value || '56', 10);
  11343. const timeout = parseInt(document.getElementById('tools-ping-timeout')?.value || '3', 10);
  11344. const iface = document.getElementById('tools-ping-iface')?.value || '';
  11345. const dontFrag = document.getElementById('tools-ping-df')?.checked || false;
  11346. if (!target) {
  11347. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  11348. return;
  11349. }
  11350. clearPingTable();
  11351. const resCard = document.getElementById('tools-ping-results');
  11352. if (resCard) resCard.classList.remove('hidden');
  11353. pingAbortController = new AbortController();
  11354. setPingRunningButton();
  11355. try {
  11356. const res = await fetch(`${API_BASE}/tools/ping/stream`, {
  11357. method: 'POST',
  11358. headers: { 'Content-Type': 'application/json' },
  11359. body: JSON.stringify({
  11360. target,
  11361. count,
  11362. size,
  11363. timeout,
  11364. interface: iface,
  11365. dont_frag: dontFrag
  11366. }),
  11367. signal: pingAbortController.signal
  11368. });
  11369. if (!res.ok) {
  11370. const errText = await res.text();
  11371. showToast('Ping Error', errText || 'Failed to start live ping', 'error');
  11372. resetPingButton();
  11373. pingAbortController = null;
  11374. return;
  11375. }
  11376. const reader = res.body.getReader();
  11377. const decoder = new TextDecoder('utf-8');
  11378. let buffer = '';
  11379. while (true) {
  11380. const { done, value } = await reader.read();
  11381. if (done) break;
  11382. buffer += decoder.decode(value, { stream: true });
  11383. const blocks = buffer.split('\n\n');
  11384. buffer = blocks.pop() || '';
  11385. for (const block of blocks) {
  11386. const trimmed = block.trim();
  11387. if (!trimmed) continue;
  11388. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  11389. try {
  11390. const evt = JSON.parse(line);
  11391. handleLivePingEvent(evt);
  11392. } catch (parseErr) {
  11393. console.warn('Ping SSE parse error:', parseErr, line);
  11394. }
  11395. }
  11396. }
  11397. } catch (err) {
  11398. if (err.name === 'AbortError') {
  11399. // User aborted normally
  11400. } else {
  11401. showToast('Ping Error', err.message, 'error');
  11402. }
  11403. } finally {
  11404. pingAbortController = null;
  11405. resetPingButton();
  11406. }
  11407. }
  11408. function handleLivePingEvent(evt) {
  11409. const sentEl = document.getElementById('tools-ping-stat-sent');
  11410. const recvEl = document.getElementById('tools-ping-stat-recv');
  11411. const lossEl = document.getElementById('tools-ping-stat-loss');
  11412. const avgEl = document.getElementById('tools-ping-stat-avg');
  11413. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  11414. const badge = document.getElementById('tools-ping-status-badge');
  11415. const tbody = document.getElementById('tools-ping-tbody');
  11416. const rawEl = document.getElementById('tools-ping-raw');
  11417. if (evt.raw && rawEl) {
  11418. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  11419. rawEl.scrollTop = rawEl.scrollHeight;
  11420. }
  11421. if (evt.type === 'reply') {
  11422. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  11423. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  11424. if (lossEl && evt.packet_loss_pct !== undefined) {
  11425. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  11426. lossEl.className = evt.packet_loss_pct === 0
  11427. ? 'text-base font-bold font-mono text-emerald-400 mt-1'
  11428. : (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');
  11429. }
  11430. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  11431. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  11432. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  11433. }
  11434. if (badge) {
  11435. if (evt.packet_loss_pct === 0) {
  11436. 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';
  11437. badge.innerText = '100% OK';
  11438. } else {
  11439. 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';
  11440. badge.innerText = `${evt.packet_loss_pct.toFixed(0)}% LOSS`;
  11441. }
  11442. }
  11443. if (tbody) {
  11444. const tr = document.createElement('tr');
  11445. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  11446. tr.innerHTML = `
  11447. <td class="py-2 px-3 text-slate-300">#${evt.seq}</td>
  11448. <td class="py-2 px-3 font-semibold text-white">${escapeHtml(evt.from)}</td>
  11449. <td class="py-2 px-3 text-slate-400">${evt.bytes} bytes</td>
  11450. <td class="py-2 px-3 text-slate-300">${evt.ttl}</td>
  11451. <td class="py-2 px-3 font-bold text-amber-300">${evt.time_ms.toFixed(2)} ms</td>
  11452. <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>
  11453. `;
  11454. tbody.appendChild(tr);
  11455. }
  11456. } else if (evt.type === 'timeout') {
  11457. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  11458. if (lossEl && evt.packet_loss_pct !== undefined) {
  11459. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  11460. 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';
  11461. }
  11462. if (badge) {
  11463. 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';
  11464. badge.innerText = `${evt.packet_loss_pct?.toFixed(0) || 100}% LOSS`;
  11465. }
  11466. if (tbody) {
  11467. const tr = document.createElement('tr');
  11468. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs opacity-75';
  11469. tr.innerHTML = `
  11470. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  11471. <td class="py-2 px-3 font-semibold text-slate-500 italic">Request timed out</td>
  11472. <td class="py-2 px-3 text-slate-600">--</td>
  11473. <td class="py-2 px-3 text-slate-600">--</td>
  11474. <td class="py-2 px-3 font-bold text-slate-500">* * *</td>
  11475. <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>
  11476. `;
  11477. tbody.appendChild(tr);
  11478. }
  11479. } else if (evt.type === 'unreach') {
  11480. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  11481. if (lossEl && evt.packet_loss_pct !== undefined) {
  11482. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  11483. lossEl.className = 'text-base font-bold font-mono text-rose-400 mt-1';
  11484. }
  11485. if (badge) {
  11486. 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';
  11487. badge.innerText = 'UNREACHABLE';
  11488. }
  11489. if (tbody) {
  11490. const tr = document.createElement('tr');
  11491. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  11492. tr.innerHTML = `
  11493. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  11494. <td class="py-2 px-3 font-semibold text-rose-400">${escapeHtml(evt.from || 'Gateway')}</td>
  11495. <td class="py-2 px-3 text-slate-600">--</td>
  11496. <td class="py-2 px-3 text-slate-600">--</td>
  11497. <td class="py-2 px-3 font-bold text-rose-400 text-xs">${escapeHtml(evt.message || 'Unreachable')}</td>
  11498. <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>
  11499. `;
  11500. tbody.appendChild(tr);
  11501. }
  11502. } else if (evt.type === 'stats') {
  11503. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  11504. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  11505. if (lossEl && evt.packet_loss_pct !== undefined) lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  11506. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  11507. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  11508. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  11509. }
  11510. } else if (evt.type === 'done') {
  11511. 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');
  11512. }
  11513. }
  11514. async function executeTraceroute(e) {
  11515. if (e) e.preventDefault();
  11516. if (tracerouteAbortController) {
  11517. tracerouteAbortController.abort();
  11518. tracerouteAbortController = null;
  11519. resetTracerouteButton();
  11520. showToast('Traceroute Stopped', 'Traceroute stopped by user', 'info');
  11521. return;
  11522. }
  11523. const target = document.getElementById('tools-tr-target')?.value?.trim();
  11524. const maxHops = parseInt(document.getElementById('tools-tr-maxhops')?.value || '15', 10);
  11525. const protocol = document.getElementById('tools-tr-proto')?.value || 'icmp';
  11526. const iface = document.getElementById('tools-tr-iface')?.value || '';
  11527. const resolve = document.getElementById('tools-tr-resolve')?.checked || false;
  11528. if (!target) {
  11529. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  11530. return;
  11531. }
  11532. clearTracerouteTable();
  11533. const resCard = document.getElementById('tools-tr-results');
  11534. if (resCard) resCard.classList.remove('hidden');
  11535. tracerouteAbortController = new AbortController();
  11536. setTracerouteRunningButton();
  11537. try {
  11538. const res = await fetch(`${API_BASE}/tools/traceroute/stream`, {
  11539. method: 'POST',
  11540. headers: { 'Content-Type': 'application/json' },
  11541. body: JSON.stringify({
  11542. target,
  11543. max_hops: maxHops,
  11544. protocol,
  11545. interface: iface,
  11546. resolve
  11547. }),
  11548. signal: tracerouteAbortController.signal
  11549. });
  11550. if (!res.ok) {
  11551. const errText = await res.text();
  11552. showToast('Traceroute Error', errText || 'Failed to start traceroute', 'error');
  11553. resetTracerouteButton();
  11554. tracerouteAbortController = null;
  11555. return;
  11556. }
  11557. const reader = res.body.getReader();
  11558. const decoder = new TextDecoder('utf-8');
  11559. let buffer = '';
  11560. while (true) {
  11561. const { done, value } = await reader.read();
  11562. if (done) break;
  11563. buffer += decoder.decode(value, { stream: true });
  11564. const blocks = buffer.split('\n\n');
  11565. buffer = blocks.pop() || '';
  11566. for (const block of blocks) {
  11567. const trimmed = block.trim();
  11568. if (!trimmed) continue;
  11569. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  11570. try {
  11571. const evt = JSON.parse(line);
  11572. handleLiveTracerouteEvent(evt);
  11573. } catch (parseErr) {
  11574. console.warn('Traceroute SSE parse error:', parseErr, line);
  11575. }
  11576. }
  11577. }
  11578. } catch (err) {
  11579. if (err.name === 'AbortError') {
  11580. // User aborted normally
  11581. } else {
  11582. showToast('Traceroute Error', err.message, 'error');
  11583. }
  11584. } finally {
  11585. tracerouteAbortController = null;
  11586. resetTracerouteButton();
  11587. }
  11588. }
  11589. function handleLiveTracerouteEvent(evt) {
  11590. const statHops = document.getElementById('tools-tr-hops-count');
  11591. const tbody = document.getElementById('tools-tr-tbody');
  11592. const rawEl = document.getElementById('tools-tr-raw');
  11593. if (evt.raw && rawEl) {
  11594. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  11595. rawEl.scrollTop = rawEl.scrollHeight;
  11596. }
  11597. if (evt.hops_count !== undefined && statHops) {
  11598. statHops.innerText = `${evt.hops_count} Hops`;
  11599. }
  11600. if (evt.type === 'hop' && evt.hop && tbody) {
  11601. const h = evt.hop;
  11602. const isTimeout = h.status === 'timeout' || (!h.ip && !h.host);
  11603. const rtt1 = Array.isArray(h.times_ms) && h.times_ms[0] ? `${h.times_ms[0]} ms` : (isTimeout ? '*' : '--');
  11604. const rtt2 = Array.isArray(h.times_ms) && h.times_ms[1] ? `${h.times_ms[1]} ms` : (isTimeout ? '*' : '--');
  11605. const displayHost = h.host && h.host !== h.ip ? `${escapeHtml(h.host)} (${escapeHtml(h.ip || '')})` : escapeHtml(h.ip || (isTimeout ? 'Request timed out' : '--'));
  11606. const tr = document.createElement('tr');
  11607. tr.className = `hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs ${isTimeout ? 'opacity-60' : ''}`;
  11608. tr.innerHTML = `
  11609. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  11610. <td class="py-2.5 px-3 font-semibold ${isTimeout ? 'text-slate-500 italic' : 'text-cyan-300'}">${displayHost}</td>
  11611. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt1)}</td>
  11612. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt2)}</td>
  11613. <td class="py-2.5 px-3 text-right">
  11614. ${isTimeout
  11615. ? '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-slate-800 text-slate-400 border border-slate-700">TIMEOUT</span>'
  11616. : '<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>'}
  11617. </td>
  11618. `;
  11619. tbody.appendChild(tr);
  11620. } else if (evt.type === 'done') {
  11621. showToast('Traceroute Finished', `Traced ${evt.hops_count || 0} hops`, 'info');
  11622. }
  11623. }
  11624. async function executeMTR(e) {
  11625. if (e) e.preventDefault();
  11626. const target = document.getElementById('tools-mtr-target')?.value?.trim();
  11627. const cycles = parseInt(document.getElementById('tools-mtr-count')?.value || '3', 10);
  11628. if (!target) {
  11629. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  11630. return;
  11631. }
  11632. const btn = document.getElementById('tools-mtr-btn');
  11633. const spinner = document.getElementById('tools-mtr-spinner');
  11634. if (btn) btn.disabled = true;
  11635. if (spinner) spinner.classList.remove('hidden');
  11636. try {
  11637. const res = await fetch(`${API_BASE}/tools/mtr`, {
  11638. method: 'POST',
  11639. headers: { 'Content-Type': 'application/json' },
  11640. body: JSON.stringify({ target, count: cycles })
  11641. });
  11642. const data = await res.json();
  11643. if (!res.ok) {
  11644. showToast('MTR Error', data.error || 'Failed to execute MTR', 'error');
  11645. return;
  11646. }
  11647. const resCard = document.getElementById('tools-mtr-results');
  11648. if (resCard) resCard.classList.remove('hidden');
  11649. const hopsCount = Array.isArray(data.hops) ? data.hops.length : 0;
  11650. const statHops = document.getElementById('tools-mtr-hops-count');
  11651. if (statHops) statHops.innerText = `${hopsCount} Hops`;
  11652. const tbody = document.getElementById('tools-mtr-tbody');
  11653. if (tbody) {
  11654. if (hopsCount > 0) {
  11655. tbody.innerHTML = data.hops.map(h => {
  11656. 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');
  11657. return `
  11658. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  11659. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  11660. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(h.host || '--')}</td>
  11661. <td class="py-2.5 px-3 ${lossClass}">${h.loss_pct.toFixed(1)}%</td>
  11662. <td class="py-2.5 px-3 text-slate-300">${h.sent}</td>
  11663. <td class="py-2.5 px-3 text-slate-300">${h.last_ms.toFixed(1)}</td>
  11664. <td class="py-2.5 px-3 font-bold text-amber-300">${h.avg_ms.toFixed(1)}</td>
  11665. <td class="py-2.5 px-3 text-emerald-400">${h.best_ms.toFixed(1)}</td>
  11666. <td class="py-2.5 px-3 text-rose-400">${h.wrst_ms.toFixed(1)}</td>
  11667. <td class="py-2.5 px-3 text-slate-400">${h.stdev_ms.toFixed(1)}</td>
  11668. </tr>
  11669. `;
  11670. }).join('');
  11671. } else {
  11672. tbody.innerHTML = `<tr><td colspan="9" class="p-4 text-center text-xs text-rose-400 font-mono">No MTR data collected</td></tr>`;
  11673. }
  11674. }
  11675. const rawEl = document.getElementById('tools-mtr-raw');
  11676. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  11677. showToast('MTR Finished', `Report completed (${hopsCount} hops discovered)`, 'info');
  11678. } catch (err) {
  11679. showToast('MTR Error', err.message, 'error');
  11680. } finally {
  11681. if (btn) btn.disabled = false;
  11682. if (spinner) spinner.classList.add('hidden');
  11683. }
  11684. }
  11685. async function executeDNS(e) {
  11686. if (e) e.preventDefault();
  11687. const domain = document.getElementById('tools-dns-domain')?.value?.trim();
  11688. const type = document.getElementById('tools-dns-type')?.value || 'A';
  11689. const server = document.getElementById('tools-dns-server')?.value?.trim() || '';
  11690. if (!domain) {
  11691. showToast('Input Required', 'Please enter a hostname or domain', 'warning');
  11692. return;
  11693. }
  11694. const btn = document.getElementById('tools-dns-btn');
  11695. const spinner = document.getElementById('tools-dns-spinner');
  11696. if (btn) btn.disabled = true;
  11697. if (spinner) spinner.classList.remove('hidden');
  11698. try {
  11699. const res = await fetch(`${API_BASE}/tools/dns`, {
  11700. method: 'POST',
  11701. headers: { 'Content-Type': 'application/json' },
  11702. body: JSON.stringify({ domain, type, server })
  11703. });
  11704. const data = await res.json();
  11705. if (!res.ok) {
  11706. showToast('DNS Error', data.error || 'Failed to resolve DNS query', 'error');
  11707. return;
  11708. }
  11709. const resCard = document.getElementById('tools-dns-results');
  11710. if (resCard) resCard.classList.remove('hidden');
  11711. const metaEl = document.getElementById('tools-dns-meta');
  11712. if (metaEl) metaEl.innerText = `Resolved in ${data.query_time_ms ?? 0} ms via ${escapeHtml(data.server || 'System DNS')}`;
  11713. const tbody = document.getElementById('tools-dns-tbody');
  11714. if (tbody) {
  11715. if (Array.isArray(data.records) && data.records.length > 0) {
  11716. tbody.innerHTML = data.records.map(r => `
  11717. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  11718. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.name)}</td>
  11719. <td class="py-2.5 px-3 text-slate-400">${r.ttl}s</td>
  11720. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.class || 'IN')}</td>
  11721. <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>
  11722. <td class="py-2.5 px-3 font-bold text-amber-300 break-all">${escapeHtml(r.value)}</td>
  11723. </tr>
  11724. `).join('');
  11725. } else {
  11726. 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>`;
  11727. }
  11728. }
  11729. const rawEl = document.getElementById('tools-dns-raw');
  11730. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  11731. showToast('DNS Lookup Done', `Resolved ${domain} in ${data.query_time_ms} ms`, 'success');
  11732. } catch (err) {
  11733. showToast('DNS Error', err.message, 'error');
  11734. } finally {
  11735. if (btn) btn.disabled = false;
  11736. if (spinner) spinner.classList.add('hidden');
  11737. }
  11738. }
  11739. async function executePortProbe(e) {
  11740. if (e) e.preventDefault();
  11741. const target = document.getElementById('tools-port-target')?.value?.trim();
  11742. const port = parseInt(document.getElementById('tools-port-num')?.value || '80', 10);
  11743. const timeout = parseInt(document.getElementById('tools-port-timeout')?.value || '3', 10);
  11744. if (!target || !port) {
  11745. showToast('Input Required', 'Please enter a target host and TCP port', 'warning');
  11746. return;
  11747. }
  11748. const btn = document.getElementById('tools-port-btn');
  11749. const spinner = document.getElementById('tools-port-spinner');
  11750. if (btn) btn.disabled = true;
  11751. if (spinner) spinner.classList.remove('hidden');
  11752. try {
  11753. const res = await fetch(`${API_BASE}/tools/port-probe`, {
  11754. method: 'POST',
  11755. headers: { 'Content-Type': 'application/json' },
  11756. body: JSON.stringify({ target, port, timeout })
  11757. });
  11758. const data = await res.json();
  11759. if (!res.ok) {
  11760. showToast('Probe Error', data.error || 'Failed to probe TCP port', 'error');
  11761. return;
  11762. }
  11763. const resCard = document.getElementById('tools-port-results');
  11764. if (resCard) resCard.classList.remove('hidden');
  11765. const banner = document.getElementById('tools-port-banner');
  11766. const icon = document.getElementById('tools-port-icon');
  11767. const title = document.getElementById('tools-port-title');
  11768. const sub = document.getElementById('tools-port-sub');
  11769. const latency = document.getElementById('tools-port-latency');
  11770. if (data.open) {
  11771. if (banner) banner.className = 'rounded-xl p-5 border bg-emerald-950/30 border-emerald-800/50 flex items-center justify-between';
  11772. if (icon) {
  11773. 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';
  11774. icon.innerText = '✓';
  11775. }
  11776. if (title) {
  11777. title.className = 'text-sm font-bold text-emerald-300';
  11778. title.innerText = `PORT ${port} OPEN / LISTENING`;
  11779. }
  11780. if (sub) {
  11781. sub.className = 'text-xs mt-0.5 font-mono text-emerald-400/80';
  11782. sub.innerText = `TCP 3-way handshake established with ${escapeHtml(target)}:${port}${data.service ? ' (' + escapeHtml(data.service) + ')' : ''}`;
  11783. }
  11784. if (latency) {
  11785. latency.className = 'text-base font-bold font-mono text-emerald-300';
  11786. latency.innerText = `${data.latency_ms.toFixed(2)} ms`;
  11787. }
  11788. } else {
  11789. if (banner) banner.className = 'rounded-xl p-5 border bg-rose-950/30 border-rose-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-rose-500/20 text-rose-400 border border-rose-500/40';
  11792. icon.innerText = '✕';
  11793. }
  11794. if (title) {
  11795. title.className = 'text-sm font-bold text-rose-300';
  11796. title.innerText = `PORT ${port} CLOSED / FILTERED`;
  11797. }
  11798. if (sub) {
  11799. sub.className = 'text-xs mt-0.5 font-mono text-rose-400/80';
  11800. sub.innerText = `Connection failed or timed out to ${escapeHtml(target)}:${port}`;
  11801. }
  11802. if (latency) {
  11803. latency.className = 'text-base font-bold font-mono text-slate-500';
  11804. latency.innerText = '--';
  11805. }
  11806. }
  11807. const rawEl = document.getElementById('tools-port-raw');
  11808. 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'}`);
  11809. showToast('Probe Complete', `Port ${port} is ${data.open ? 'OPEN' : 'CLOSED'}`, data.open ? 'success' : 'warning');
  11810. } catch (err) {
  11811. showToast('Probe Error', err.message, 'error');
  11812. } finally {
  11813. if (btn) btn.disabled = false;
  11814. if (spinner) spinner.classList.add('hidden');
  11815. }
  11816. }
  11817. // ==========================================
  11818. // DHCP CLIENT (/ip dhcp-client) CONTROLLER
  11819. // ==========================================
  11820. async function loadDHCPClients(showToastMsg = false) {
  11821. try {
  11822. const [clientsRes, sumRes] = await Promise.all([
  11823. fetch(`${API_BASE}/dhcp/clients`),
  11824. fetch(`${API_BASE}/dhcp/clients/summary`)
  11825. ]);
  11826. if (clientsRes.ok) {
  11827. state.dhcpClients = await clientsRes.json();
  11828. }
  11829. if (sumRes.ok) {
  11830. state.dhcpSummary = await sumRes.json();
  11831. }
  11832. renderDHCPClients();
  11833. updateDHCPSummaryCards();
  11834. const bDhcp = document.getElementById('badge-dhcp-client-count');
  11835. if (bDhcp && state.dhcpSummary) {
  11836. bDhcp.innerText = state.dhcpSummary.total_clients || 0;
  11837. }
  11838. if (showToastMsg) {
  11839. showToast('Refreshed', 'DHCP Client telemetry updated', 'info');
  11840. }
  11841. } catch (err) {
  11842. console.error('Failed to load DHCP clients:', err);
  11843. if (showToastMsg) {
  11844. showToast('Notice', 'Unable to fetch DHCP client status', 'warning');
  11845. }
  11846. }
  11847. }
  11848. function updateDHCPSummaryCards() {
  11849. const sum = state.dhcpSummary || {
  11850. total_clients: (state.dhcpClients || []).length,
  11851. bound_clients: (state.dhcpClients || []).filter(c => c.status === 'bound').length,
  11852. searching_clients: (state.dhcpClients || []).filter(c => c.status === 'searching').length,
  11853. disabled_clients: (state.dhcpClients || []).filter(c => !c.enabled).length
  11854. };
  11855. const totalEl = document.getElementById('dhcp-stat-total');
  11856. const boundEl = document.getElementById('dhcp-stat-bound');
  11857. const searchEl = document.getElementById('dhcp-stat-searching');
  11858. const disEl = document.getElementById('dhcp-stat-disabled');
  11859. if (totalEl) totalEl.innerText = sum.total_clients ?? 0;
  11860. if (boundEl) boundEl.innerText = sum.bound_clients ?? 0;
  11861. if (searchEl) searchEl.innerText = sum.searching_clients ?? 0;
  11862. if (disEl) disEl.innerText = sum.disabled_clients ?? 0;
  11863. }
  11864. function renderDHCPClients() {
  11865. const tbody = document.getElementById('dhcp-clients-tbody');
  11866. const emptyState = document.getElementById('dhcp-clients-empty');
  11867. if (!tbody) return;
  11868. const clients = Array.isArray(state.dhcpClients) ? state.dhcpClients : [];
  11869. if (clients.length === 0) {
  11870. tbody.innerHTML = '';
  11871. if (emptyState) emptyState.classList.remove('hidden');
  11872. return;
  11873. }
  11874. if (emptyState) emptyState.classList.add('hidden');
  11875. const sig = clients.map(c => `${c.id}:${c.status}:${c.ip_address}:${c.gateway}:${c.enabled}`).join(';');
  11876. if (tbody.dataset.sig === sig) return;
  11877. tbody.dataset.sig = sig;
  11878. tbody.innerHTML = clients.map(c => {
  11879. let statusBadge = '';
  11880. if (!c.enabled) {
  11881. 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>';
  11882. } else if (c.status === 'bound') {
  11883. 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>';
  11884. } else if (c.status === 'searching') {
  11885. 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>';
  11886. } else if (c.status === 'stopped') {
  11887. 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>';
  11888. } else {
  11889. 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>`;
  11890. }
  11891. 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>';
  11892. const gwDisplay = c.gateway ? `<span class="text-slate-300">${escapeHtml(c.gateway)}</span>` : '<span class="text-slate-600">--</span>';
  11893. const srvDisplay = c.dhcp_server ? `<span class="text-slate-300">${escapeHtml(c.dhcp_server)}</span>` : '<span class="text-slate-600">--</span>';
  11894. 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>';
  11895. const expDisplay = c.expires_in ? `<span class="text-purple-300">${escapeHtml(c.expires_in)}</span>` : '<span class="text-slate-600">--</span>';
  11896. // Option flags
  11897. const flags = [];
  11898. 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>');
  11899. 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>');
  11900. 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>');
  11901. 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>`);
  11902. return `
  11903. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 text-xs transition">
  11904. <td class="py-3 px-4">
  11905. <div class="flex items-center gap-2">
  11906. <span class="font-bold text-white text-sm">${escapeHtml(c.interface)}</span>
  11907. ${c.comment ? `<span class="text-[11px] text-slate-400 font-sans italic">(${escapeHtml(c.comment)})</span>` : ''}
  11908. </div>
  11909. </td>
  11910. <td class="py-3 px-4">${statusBadge}</td>
  11911. <td class="py-3 px-4 font-mono">${ipDisplay}</td>
  11912. <td class="py-3 px-4 font-mono">${gwDisplay}</td>
  11913. <td class="py-3 px-4 font-mono">${srvDisplay}</td>
  11914. <td class="py-3 px-4 font-mono text-[11px]">${dnsDisplay}</td>
  11915. <td class="py-3 px-4 font-mono text-[11px]">${expDisplay}</td>
  11916. <td class="py-3 px-4">
  11917. <div class="flex flex-wrap gap-1 font-mono">${flags.join('')}</div>
  11918. </td>
  11919. <td class="py-3 px-4 text-right space-x-1.5 font-sans whitespace-nowrap">
  11920. ${c.enabled ? `
  11921. <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>
  11922. <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>
  11923. <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>
  11924. ` : `
  11925. <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>
  11926. `}
  11927. <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>
  11928. <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>
  11929. </td>
  11930. </tr>
  11931. `;
  11932. }).join('');
  11933. }
  11934. function openDHCPClientModal(clientId = null) {
  11935. const modal = document.getElementById('modal-dhcp-client');
  11936. if (!modal) return;
  11937. const title = document.getElementById('modal-dhcp-title');
  11938. const idInput = document.getElementById('modal-dhcp-id');
  11939. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  11940. const distInput = document.getElementById('modal-dhcp-distance');
  11941. const commentInput = document.getElementById('modal-dhcp-comment');
  11942. const defRouteCheck = document.getElementById('modal-dhcp-def-route');
  11943. const peerDnsCheck = document.getElementById('modal-dhcp-peer-dns');
  11944. const peerNtpCheck = document.getElementById('modal-dhcp-peer-ntp');
  11945. const enabledCheck = document.getElementById('modal-dhcp-enabled');
  11946. // Populate interfaces
  11947. if (ifaceSelect) {
  11948. let opts = '<option value="">Select interface...</option>';
  11949. const allIfaces = state.interfaces || [];
  11950. const allVlans = state.vlans || [];
  11951. const usedIfaces = new Set((state.dhcpClients || []).map(c => c.interface));
  11952. // Group 1: Physical & Bridge Interfaces
  11953. opts += '<optgroup label="Physical & Bridge Interfaces">';
  11954. allIfaces.filter(i => supportsDHCPClient(i)).forEach(i => {
  11955. const isConfigured = usedIfaces.has(i.name) ? ' (Configured)' : '';
  11956. opts += `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)} [${escapeHtml(i.role || i.type)}]${isConfigured}</option>`;
  11957. });
  11958. opts += '</optgroup>';
  11959. // Group 2: VLAN Interfaces
  11960. if (allVlans.length > 0) {
  11961. opts += '<optgroup label="802.1Q VLAN Sub-interfaces">';
  11962. allVlans.forEach(v => {
  11963. const isConfigured = usedIfaces.has(v.name) ? ' (Configured)' : '';
  11964. opts += `<option value="${escapeHtml(v.name)}">${escapeHtml(v.name)} (VLAN ${v.vlan_id})${isConfigured}</option>`;
  11965. });
  11966. opts += '</optgroup>';
  11967. }
  11968. ifaceSelect.innerHTML = opts;
  11969. }
  11970. if (clientId) {
  11971. const client = (state.dhcpClients || []).find(c => c.id === clientId);
  11972. if (client) {
  11973. if (title) title.innerText = `Edit DHCP Client: ${client.interface}`;
  11974. if (idInput) idInput.value = client.id;
  11975. if (ifaceSelect) {
  11976. ifaceSelect.value = client.interface;
  11977. ifaceSelect.disabled = true; // interface cannot be changed on edit
  11978. }
  11979. if (distInput) distInput.value = client.default_route_distance || 1;
  11980. if (commentInput) commentInput.value = client.comment || '';
  11981. if (defRouteCheck) defRouteCheck.checked = client.add_default_route !== false;
  11982. if (peerDnsCheck) peerDnsCheck.checked = client.use_peer_dns !== false;
  11983. if (peerNtpCheck) peerNtpCheck.checked = client.use_peer_ntp !== false;
  11984. if (enabledCheck) enabledCheck.checked = client.enabled !== false;
  11985. }
  11986. } else {
  11987. if (title) title.innerText = 'Add DHCP Client';
  11988. if (idInput) idInput.value = '';
  11989. if (ifaceSelect) {
  11990. ifaceSelect.value = '';
  11991. ifaceSelect.disabled = false;
  11992. }
  11993. if (distInput) distInput.value = 1;
  11994. if (commentInput) commentInput.value = '';
  11995. if (defRouteCheck) defRouteCheck.checked = true;
  11996. if (peerDnsCheck) peerDnsCheck.checked = true;
  11997. if (peerNtpCheck) peerNtpCheck.checked = true;
  11998. if (enabledCheck) enabledCheck.checked = true;
  11999. }
  12000. modal.classList.remove('hidden');
  12001. }
  12002. function openDHCPClientModalForIface(ifaceName) {
  12003. openDHCPClientModal();
  12004. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  12005. if (ifaceSelect && ifaceName) {
  12006. ifaceSelect.value = ifaceName;
  12007. }
  12008. }
  12009. function closeDHCPClientModal() {
  12010. const modal = document.getElementById('modal-dhcp-client');
  12011. if (modal) modal.classList.add('hidden');
  12012. }
  12013. async function submitSaveDHCPClient(e) {
  12014. if (e) e.preventDefault();
  12015. const id = document.getElementById('modal-dhcp-id')?.value;
  12016. const iface = document.getElementById('modal-dhcp-iface')?.value?.trim();
  12017. const distance = parseInt(document.getElementById('modal-dhcp-distance')?.value || '1', 10);
  12018. const comment = document.getElementById('modal-dhcp-comment')?.value?.trim() || '';
  12019. const defRoute = document.getElementById('modal-dhcp-def-route')?.checked ?? true;
  12020. const peerDns = document.getElementById('modal-dhcp-peer-dns')?.checked ?? true;
  12021. const peerNtp = document.getElementById('modal-dhcp-peer-ntp')?.checked ?? true;
  12022. const enabled = document.getElementById('modal-dhcp-enabled')?.checked ?? true;
  12023. if (!id && !iface) {
  12024. showToast('Input Required', 'Please select an interface for the DHCP client', 'warning');
  12025. return;
  12026. }
  12027. try {
  12028. let res;
  12029. if (id) {
  12030. // PUT update
  12031. res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  12032. method: 'PUT',
  12033. headers: { 'Content-Type': 'application/json' },
  12034. body: JSON.stringify({
  12035. enabled,
  12036. add_default_route: defRoute,
  12037. default_route_distance: distance,
  12038. use_peer_dns: peerDns,
  12039. use_peer_ntp: peerNtp,
  12040. comment
  12041. })
  12042. });
  12043. } else {
  12044. // POST create
  12045. res = await fetch(`${API_BASE}/dhcp/clients`, {
  12046. method: 'POST',
  12047. headers: { 'Content-Type': 'application/json' },
  12048. body: JSON.stringify({
  12049. interface: iface,
  12050. enabled,
  12051. add_default_route: defRoute,
  12052. default_route_distance: distance,
  12053. use_peer_dns: peerDns,
  12054. use_peer_ntp: peerNtp,
  12055. comment
  12056. })
  12057. });
  12058. }
  12059. const data = await res.json();
  12060. if (!res.ok) {
  12061. showToast('Error', data.error || 'Failed to save DHCP client', 'error');
  12062. return;
  12063. }
  12064. closeDHCPClientModal();
  12065. showToast('Success', id ? 'DHCP Client updated successfully' : `DHCP Client activated on ${iface}`, 'success');
  12066. await loadDHCPClients();
  12067. fetchData(); // refresh interfaces list with new lease/status
  12068. } catch (err) {
  12069. showToast('Error', err.message, 'error');
  12070. }
  12071. }
  12072. async function toggleDHCPClientState(id, enabled) {
  12073. try {
  12074. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/state`, {
  12075. method: 'POST',
  12076. headers: { 'Content-Type': 'application/json' },
  12077. body: JSON.stringify({ enabled })
  12078. });
  12079. const data = await res.json();
  12080. if (!res.ok) {
  12081. showToast('Error', data.error || 'Failed to toggle client state', 'error');
  12082. return;
  12083. }
  12084. showToast('Updated', `DHCP client ${enabled ? 'enabled' : 'disabled'}`, 'info');
  12085. await loadDHCPClients();
  12086. fetchData();
  12087. } catch (err) {
  12088. showToast('Error', err.message, 'error');
  12089. }
  12090. }
  12091. async function renewDHCPClient(id) {
  12092. try {
  12093. showToast('Renewing...', 'Requesting DHCP lease renewal from upstream server', 'info');
  12094. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/renew`, {
  12095. method: 'POST'
  12096. });
  12097. const data = await res.json();
  12098. if (!res.ok) {
  12099. showToast('Error', data.error || 'Failed to renew lease', 'error');
  12100. return;
  12101. }
  12102. showToast('Lease Renewed', 'DHCP renewal signal sent successfully', 'success');
  12103. setTimeout(() => {
  12104. loadDHCPClients();
  12105. fetchData();
  12106. }, 1500);
  12107. } catch (err) {
  12108. showToast('Error', err.message, 'error');
  12109. }
  12110. }
  12111. async function releaseDHCPClient(id) {
  12112. try {
  12113. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/release`, {
  12114. method: 'POST'
  12115. });
  12116. const data = await res.json();
  12117. if (!res.ok) {
  12118. showToast('Error', data.error || 'Failed to release lease', 'error');
  12119. return;
  12120. }
  12121. showToast('Lease Released', 'DHCP lease released from upstream server', 'info');
  12122. await loadDHCPClients();
  12123. fetchData();
  12124. } catch (err) {
  12125. showToast('Error', err.message, 'error');
  12126. }
  12127. }
  12128. async function deleteDHCPClient(id, ifaceName) {
  12129. if (!confirm(`Are you sure you want to remove the DHCP Client on ${ifaceName}? The interface will release its dynamic IP.`)) {
  12130. return;
  12131. }
  12132. try {
  12133. const res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  12134. method: 'DELETE'
  12135. });
  12136. const data = await res.json();
  12137. if (!res.ok) {
  12138. showToast('Error', data.error || 'Failed to delete DHCP client', 'error');
  12139. return;
  12140. }
  12141. showToast('Deleted', `DHCP client removed from ${ifaceName}`, 'info');
  12142. await loadDHCPClients();
  12143. fetchData();
  12144. } catch (err) {
  12145. showToast('Error', err.message, 'error');
  12146. }
  12147. }
  12148. // ==================== DHCP SERVER (/ip dhcp-server) ====================
  12149. async function loadDHCPServer(populate = true) {
  12150. try {
  12151. const [sumRes, srvRes, netRes, leaseRes, optRes] = await Promise.all([
  12152. fetch(`${API_BASE}/dhcp-server/summary`),
  12153. fetch(`${API_BASE}/dhcp-server/servers`),
  12154. fetch(`${API_BASE}/dhcp-server/networks`),
  12155. fetch(`${API_BASE}/dhcp-server/leases`),
  12156. fetch(`${API_BASE}/dhcp-server/options`)
  12157. ]);
  12158. if (sumRes.ok) state.dhcpServerSummary = await sumRes.json();
  12159. if (srvRes.ok) state.dhcpServers = await srvRes.json();
  12160. if (netRes.ok) state.dhcpNetworks = await netRes.json();
  12161. if (leaseRes.ok) state.dhcpLeases = await leaseRes.json();
  12162. if (optRes.ok) state.dhcpOptions = await optRes.json();
  12163. const sum = state.dhcpServerSummary || {};
  12164. const srvs = state.dhcpServers || [];
  12165. const nets = state.dhcpNetworks || [];
  12166. const leases = state.dhcpLeases || [];
  12167. const opts = state.dhcpOptions || [];
  12168. // KPI Cards
  12169. const statActive = document.getElementById('dhcp-server-stat-active');
  12170. if (statActive) {
  12171. const activeCount = srvs.filter(s => s.running).length;
  12172. statActive.innerText = `${activeCount} / ${srvs.length}`;
  12173. }
  12174. const statLeases = document.getElementById('dhcp-server-stat-leases');
  12175. if (statLeases) {
  12176. statLeases.innerText = leases.length;
  12177. }
  12178. const statLeasesSub = document.getElementById('dhcp-server-stat-leases-sub');
  12179. if (statLeasesSub) {
  12180. const dyn = leases.filter(l => l.dynamic).length;
  12181. const st = leases.filter(l => !l.dynamic).length;
  12182. statLeasesSub.innerText = `${dyn} dynamic, ${st} static`;
  12183. }
  12184. const statNetworks = document.getElementById('dhcp-server-stat-networks');
  12185. if (statNetworks) {
  12186. statNetworks.innerText = nets.length;
  12187. }
  12188. // Subtab Badges
  12189. const bSrv = document.getElementById('dhcp-server-tab-badge-servers');
  12190. if (bSrv) bSrv.innerText = srvs.length;
  12191. const bNet = document.getElementById('dhcp-server-tab-badge-networks');
  12192. if (bNet) bNet.innerText = nets.length;
  12193. const bLease = document.getElementById('dhcp-server-tab-badge-leases');
  12194. if (bLease) bLease.innerText = leases.length;
  12195. const bOpt = document.getElementById('dhcp-server-tab-badge-options');
  12196. if (bOpt) bOpt.innerText = opts.length;
  12197. // Sidebar Badge
  12198. const sideBadge = document.getElementById('badge-dhcp-server-count');
  12199. if (sideBadge) sideBadge.innerText = leases.length || srvs.length;
  12200. renderCurrentDHCPServerTab();
  12201. } catch (err) {
  12202. console.error('Failed to load DHCP Server:', err);
  12203. }
  12204. }
  12205. function switchDHCPServerTab(tab) {
  12206. state.dhcpServerTab = tab;
  12207. const tabs = ['servers', 'networks', 'leases', 'options'];
  12208. tabs.forEach(t => {
  12209. const panel = document.getElementById(`dhcp-server-subtab-${t}`);
  12210. const btn = document.getElementById(`dhcp-server-tab-btn-${t}`);
  12211. if (panel) {
  12212. if (t === tab) panel.classList.remove('hidden');
  12213. else panel.classList.add('hidden');
  12214. }
  12215. if (btn) {
  12216. if (t === tab) {
  12217. 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';
  12218. } else {
  12219. 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';
  12220. }
  12221. }
  12222. });
  12223. const addBtn = document.getElementById('dhcp-server-primary-add-btn');
  12224. if (addBtn) {
  12225. if (tab === 'servers') addBtn.innerHTML = '<span>+ Add Server</span>';
  12226. else if (tab === 'networks') addBtn.innerHTML = '<span>+ Add Network</span>';
  12227. else if (tab === 'leases') addBtn.innerHTML = '<span>+ Add Static Lease</span>';
  12228. else if (tab === 'options') addBtn.innerHTML = '<span>+ Add Option</span>';
  12229. }
  12230. renderCurrentDHCPServerTab();
  12231. }
  12232. function handleDHCPServerPrimaryAdd() {
  12233. const tab = state.dhcpServerTab || 'servers';
  12234. if (tab === 'servers') openAddDHCPServerModal();
  12235. else if (tab === 'networks') openAddDHCPNetworkModal();
  12236. else if (tab === 'leases') openAddDHCPStaticLeaseModal();
  12237. else if (tab === 'options') openAddDHCPOptionModal();
  12238. }
  12239. function renderCurrentDHCPServerTab() {
  12240. const tab = state.dhcpServerTab || 'servers';
  12241. if (tab === 'servers') renderDHCPServers();
  12242. else if (tab === 'networks') renderDHCPNetworks();
  12243. else if (tab === 'leases') renderDHCPLeases();
  12244. else if (tab === 'options') renderDHCPOptions();
  12245. }
  12246. function renderDHCPServers() {
  12247. const tbody = document.getElementById('dhcp-server-tbody');
  12248. const empty = document.getElementById('dhcp-server-empty');
  12249. if (!tbody) return;
  12250. const servers = state.dhcpServers || [];
  12251. if (servers.length === 0) {
  12252. tbody.innerHTML = '';
  12253. empty?.classList.remove('hidden');
  12254. return;
  12255. }
  12256. empty?.classList.add('hidden');
  12257. const sig = servers.map(s => `${s.id}:${s.running}:${s.disabled}:${s.active_leases}:${s.interface}`).join(';');
  12258. if (tbody.dataset.sig === sig) return;
  12259. tbody.dataset.sig = sig;
  12260. tbody.innerHTML = '';
  12261. servers.forEach(s => {
  12262. const tr = document.createElement('tr');
  12263. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  12264. tr.innerHTML = `
  12265. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(s.running, s.disabled)}</td>
  12266. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(s.name)}</td>
  12267. <td class="py-2.5 px-3 font-mono text-cyan-400 font-semibold">${escapeHtml(s.interface)}</td>
  12268. <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>
  12269. <td class="py-2.5 px-3 font-mono text-emerald-400">${escapeHtml(s.address_pool)}</td>
  12270. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(s.lease_time || '12h')}</td>
  12271. <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>
  12272. <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>
  12273. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]" title="${escapeHtml(s.comment || '')}">${escapeHtml(s.comment || '-')}</td>
  12274. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  12275. <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>
  12276. <button onclick="openEditDHCPServerModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  12277. <button onclick="deleteDHCPServer('${s.id}', '${escapeHtml(s.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  12278. </td>
  12279. `;
  12280. tbody.appendChild(tr);
  12281. });
  12282. }
  12283. function renderDHCPNetworks() {
  12284. const tbody = document.getElementById('dhcp-networks-tbody');
  12285. const empty = document.getElementById('dhcp-networks-empty');
  12286. if (!tbody) return;
  12287. tbody.innerHTML = '';
  12288. const networks = state.dhcpNetworks || [];
  12289. if (networks.length === 0) {
  12290. empty?.classList.remove('hidden');
  12291. return;
  12292. }
  12293. empty?.classList.add('hidden');
  12294. networks.forEach(n => {
  12295. const tr = document.createElement('tr');
  12296. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  12297. const dnsStr = (n.dns_servers || []).join(', ') || '-';
  12298. const optionsChips = (n.dhcp_options || []).map(optId => {
  12299. const opt = (state.dhcpOptions || []).find(o => o.id === optId);
  12300. if (!opt) return '';
  12301. 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>`;
  12302. }).filter(Boolean).join('');
  12303. tr.innerHTML = `
  12304. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${escapeHtml(n.address)}</td>
  12305. <td class="py-2.5 px-3 font-mono text-cyan-300 font-semibold">${escapeHtml(n.gateway || '-')}</td>
  12306. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(n.netmask || '-')}</td>
  12307. <td class="py-2.5 px-3 font-mono text-slate-300 truncate max-w-[140px]" title="${escapeHtml(dnsStr)}">${escapeHtml(dnsStr)}</td>
  12308. <td class="py-2.5 px-3 font-mono text-slate-400">${escapeHtml(n.domain || '-')}</td>
  12309. <td class="py-2.5 px-3 font-mono">${optionsChips || '<span class="text-slate-600 font-sans">-</span>'}</td>
  12310. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(n.comment || '')}">${escapeHtml(n.comment || '-')}</td>
  12311. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  12312. <button onclick="openEditDHCPNetworkModal('${n.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  12313. <button onclick="deleteDHCPNetwork('${n.id}', '${escapeHtml(n.address)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  12314. </td>
  12315. `;
  12316. tbody.appendChild(tr);
  12317. });
  12318. }
  12319. function renderDHCPLeases() {
  12320. const tbody = document.getElementById('dhcp-leases-tbody');
  12321. const empty = document.getElementById('dhcp-leases-empty');
  12322. if (!tbody) return;
  12323. tbody.innerHTML = '';
  12324. const leases = state.dhcpLeases || [];
  12325. if (leases.length === 0) {
  12326. empty?.classList.remove('hidden');
  12327. return;
  12328. }
  12329. empty?.classList.add('hidden');
  12330. leases.forEach(l => {
  12331. const tr = document.createElement('tr');
  12332. tr.className = `hover:bg-slate-800/40 transition text-xs ${l.disabled ? 'opacity-50' : ''}`;
  12333. 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>';
  12334. const statusBadge = l.status === 'bound'
  12335. ? '<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>'
  12336. : l.status === 'static'
  12337. ? '<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>'
  12338. : '<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>';
  12339. const makeStaticBtn = l.dynamic
  12340. ? `<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>`
  12341. : `<button onclick="deleteDHCPStaticLease('${l.id}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Remove</button>`;
  12342. tr.innerHTML = `
  12343. <td class="py-2.5 px-3 text-center">${flag}</td>
  12344. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(l.address)}</td>
  12345. <td class="py-2.5 px-3 font-mono text-cyan-300">${escapeHtml(l.mac_address)}</td>
  12346. <td class="py-2.5 px-3 font-sans text-slate-200 font-medium">${escapeHtml(l.hostname || '*')}</td>
  12347. <td class="py-2.5 px-3 font-mono text-slate-400">${escapeHtml(l.server || 'all')}</td>
  12348. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(l.expires_in || 'never')}</td>
  12349. <td class="py-2.5 px-3">${statusBadge}</td>
  12350. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(l.comment || '')}">${escapeHtml(l.comment || '-')}</td>
  12351. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  12352. ${makeStaticBtn}
  12353. </td>
  12354. `;
  12355. tbody.appendChild(tr);
  12356. });
  12357. }
  12358. function renderDHCPOptions() {
  12359. const tbody = document.getElementById('dhcp-options-tbody');
  12360. const empty = document.getElementById('dhcp-options-empty');
  12361. if (!tbody) return;
  12362. tbody.innerHTML = '';
  12363. const options = state.dhcpOptions || [];
  12364. if (options.length === 0) {
  12365. empty?.classList.remove('hidden');
  12366. return;
  12367. }
  12368. empty?.classList.add('hidden');
  12369. options.forEach(o => {
  12370. const tr = document.createElement('tr');
  12371. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  12372. tr.innerHTML = `
  12373. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(o.name)}</td>
  12374. <td class="py-2.5 px-3 font-bold text-cyan-400 font-mono">${o.code}</td>
  12375. <td class="py-2.5 px-3 font-mono text-emerald-400 break-all max-w-xs">${escapeHtml(o.value)}</td>
  12376. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-xs" title="${escapeHtml(o.comment || '')}">${escapeHtml(o.comment || '-')}</td>
  12377. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  12378. <button onclick="openEditDHCPOptionModal('${o.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  12379. <button onclick="deleteDHCPOption('${o.id}', '${escapeHtml(o.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  12380. </td>
  12381. `;
  12382. tbody.appendChild(tr);
  12383. });
  12384. }
  12385. // ==================== MODALS & ACTIONS: SERVER ====================
  12386. function populateDHCPNetworkSelect(elemId, selectedVal) {
  12387. const sel = document.getElementById(elemId);
  12388. if (!sel) return;
  12389. sel.innerHTML = '<option value="">Select network subnet...</option>';
  12390. const networks = state.dhcpNetworks || [];
  12391. networks.forEach(n => {
  12392. const opt = document.createElement('option');
  12393. opt.value = n.address;
  12394. opt.innerText = `${n.address} (Gateway: ${n.gateway || 'None'}${n.comment ? ' - ' + n.comment : ''})`;
  12395. if (selectedVal && (selectedVal === n.address || selectedVal === n.id)) {
  12396. opt.selected = true;
  12397. }
  12398. sel.appendChild(opt);
  12399. });
  12400. }
  12401. function onDHCPServerNetworkChange() {
  12402. const netSel = document.getElementById('dhcp-server-modal-network');
  12403. if (!netSel) return;
  12404. const netVal = netSel.value;
  12405. if (!netVal) return;
  12406. const poolInput = document.getElementById('dhcp-server-modal-pool');
  12407. if (!poolInput) return;
  12408. // Auto-calculate suggested address pool based on subnet CIDR
  12409. const parts = netVal.split('/');
  12410. const ip = parts[0];
  12411. const cidr = parseInt(parts[1] || '24', 10);
  12412. if (cidr === 24) {
  12413. const octets = ip.split('.');
  12414. if (octets.length === 4) {
  12415. const base = `${octets[0]}.${octets[1]}.${octets[2]}`;
  12416. poolInput.value = `${base}.10-${base}.254`;
  12417. }
  12418. }
  12419. }
  12420. function openAddDHCPServerModal() {
  12421. document.getElementById('dhcp-server-modal-title').innerText = 'Add DHCP Server';
  12422. document.getElementById('dhcp-server-modal-id').value = '';
  12423. document.getElementById('dhcp-server-modal-name').value = `dhcp${(state.dhcpServers || []).length + 1}`;
  12424. document.getElementById('dhcp-server-modal-pool').value = '192.168.88.10-192.168.88.254';
  12425. document.getElementById('dhcp-server-modal-leasetime').value = '12h';
  12426. document.getElementById('dhcp-server-modal-comment').value = '';
  12427. document.getElementById('dhcp-server-modal-authoritative').checked = true;
  12428. document.getElementById('dhcp-server-modal-disabled').checked = false;
  12429. populateDHCPIfaceSelect('dhcp-server-modal-iface', '');
  12430. const networks = state.dhcpNetworks || [];
  12431. const defaultNet = networks.length > 0 ? networks[0].address : '';
  12432. populateDHCPNetworkSelect('dhcp-server-modal-network', defaultNet);
  12433. if (defaultNet) {
  12434. onDHCPServerNetworkChange();
  12435. }
  12436. document.getElementById('dhcp-server-instance-modal').classList.remove('hidden');
  12437. }
  12438. function openEditDHCPServerModal(id) {
  12439. const s = (state.dhcpServers || []).find(item => item.id === id);
  12440. if (!s) return;
  12441. document.getElementById('dhcp-server-modal-title').innerText = `Edit DHCP Server (${s.name})`;
  12442. document.getElementById('dhcp-server-modal-id').value = s.id;
  12443. document.getElementById('dhcp-server-modal-name').value = s.name;
  12444. document.getElementById('dhcp-server-modal-pool').value = s.address_pool;
  12445. document.getElementById('dhcp-server-modal-leasetime').value = s.lease_time || '12h';
  12446. document.getElementById('dhcp-server-modal-comment').value = s.comment || '';
  12447. document.getElementById('dhcp-server-modal-authoritative').checked = s.authoritative !== false;
  12448. document.getElementById('dhcp-server-modal-disabled').checked = !!s.disabled;
  12449. populateDHCPIfaceSelect('dhcp-server-modal-iface', s.interface);
  12450. populateDHCPNetworkSelect('dhcp-server-modal-network', s.network || '');
  12451. document.getElementById('dhcp-server-instance-modal').classList.remove('hidden');
  12452. }
  12453. function closeDHCPServerModal() {
  12454. document.getElementById('dhcp-server-instance-modal').classList.add('hidden');
  12455. }
  12456. async function submitSaveDHCPServer(e) {
  12457. e.preventDefault();
  12458. const id = document.getElementById('dhcp-server-modal-id').value;
  12459. const name = document.getElementById('dhcp-server-modal-name').value.trim();
  12460. const iface = document.getElementById('dhcp-server-modal-iface').value;
  12461. const network = document.getElementById('dhcp-server-modal-network').value.trim();
  12462. const pool = document.getElementById('dhcp-server-modal-pool').value.trim();
  12463. const leaseTime = document.getElementById('dhcp-server-modal-leasetime').value.trim() || '12h';
  12464. const comment = document.getElementById('dhcp-server-modal-comment').value.trim();
  12465. const authoritative = document.getElementById('dhcp-server-modal-authoritative').checked;
  12466. const disabled = document.getElementById('dhcp-server-modal-disabled').checked;
  12467. try {
  12468. const res = await fetch(`${API_BASE}/dhcp-server/servers`, {
  12469. method: 'POST',
  12470. headers: { 'Content-Type': 'application/json' },
  12471. body: JSON.stringify({
  12472. id,
  12473. name,
  12474. interface: iface,
  12475. network,
  12476. address_pool: pool,
  12477. lease_time: leaseTime,
  12478. authoritative,
  12479. disabled,
  12480. comment
  12481. })
  12482. });
  12483. if (res.ok) {
  12484. showToast('DHCP Server Saved', `Server ${name} configured successfully`, 'success');
  12485. closeDHCPServerModal();
  12486. loadDHCPServer(false);
  12487. fetchData(false);
  12488. } else {
  12489. const err = await res.text();
  12490. showToast('Error', err, 'error');
  12491. }
  12492. } catch (err) {
  12493. showToast('Error', err.message, 'error');
  12494. }
  12495. }
  12496. async function toggleDHCPServerState(id, disabled) {
  12497. try {
  12498. const res = await fetch(`${API_BASE}/dhcp-server/servers/${encodeURIComponent(id)}/state`, {
  12499. method: 'POST',
  12500. headers: { 'Content-Type': 'application/json' },
  12501. body: JSON.stringify({ disabled })
  12502. });
  12503. if (res.ok) {
  12504. showToast('State Updated', disabled ? 'Server disabled' : 'Server enabled', 'info');
  12505. loadDHCPServer(false);
  12506. fetchData(false);
  12507. }
  12508. } catch (err) {
  12509. showToast('Error', err.message, 'error');
  12510. }
  12511. }
  12512. async function deleteDHCPServer(id, name) {
  12513. if (!confirm(`Are you sure you want to delete DHCP Server "${name}"?`)) return;
  12514. try {
  12515. const res = await fetch(`${API_BASE}/dhcp-server/servers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12516. if (res.ok) {
  12517. showToast('Deleted', `DHCP Server ${name} removed`, 'success');
  12518. loadDHCPServer(false);
  12519. fetchData(false);
  12520. }
  12521. } catch (err) {
  12522. showToast('Error', err.message, 'error');
  12523. }
  12524. }
  12525. // ==================== MODALS & ACTIONS: NETWORKS ====================
  12526. function openAddDHCPNetworkModal() {
  12527. document.getElementById('dhcp-network-modal-title').innerText = 'Add DHCP Network';
  12528. document.getElementById('dhcp-network-modal-id').value = '';
  12529. document.getElementById('dhcp-network-modal-address').value = '192.168.88.0/24';
  12530. document.getElementById('dhcp-network-modal-gateway').value = '192.168.88.1';
  12531. document.getElementById('dhcp-network-modal-dns').value = '192.168.88.1, 1.1.1.1, 8.8.8.8';
  12532. document.getElementById('dhcp-network-modal-domain').value = 'lan';
  12533. document.getElementById('dhcp-network-modal-netmask').value = '';
  12534. document.getElementById('dhcp-network-modal-comment').value = '';
  12535. renderDHCPNetworkOptionsCheckboxes([]);
  12536. document.getElementById('dhcp-network-modal').classList.remove('hidden');
  12537. }
  12538. function openEditDHCPNetworkModal(id) {
  12539. const n = (state.dhcpNetworks || []).find(item => item.id === id);
  12540. if (!n) return;
  12541. document.getElementById('dhcp-network-modal-title').innerText = `Edit DHCP Network (${n.address})`;
  12542. document.getElementById('dhcp-network-modal-id').value = n.id;
  12543. document.getElementById('dhcp-network-modal-address').value = n.address;
  12544. document.getElementById('dhcp-network-modal-gateway').value = n.gateway || '';
  12545. document.getElementById('dhcp-network-modal-dns').value = (n.dns_servers || []).join(', ');
  12546. document.getElementById('dhcp-network-modal-domain').value = n.domain || '';
  12547. document.getElementById('dhcp-network-modal-netmask').value = n.netmask || '';
  12548. document.getElementById('dhcp-network-modal-comment').value = n.comment || '';
  12549. renderDHCPNetworkOptionsCheckboxes(n.dhcp_options || []);
  12550. document.getElementById('dhcp-network-modal').classList.remove('hidden');
  12551. }
  12552. function renderDHCPNetworkOptionsCheckboxes(selectedIds) {
  12553. const container = document.getElementById('dhcp-network-modal-options-list');
  12554. if (!container) return;
  12555. container.innerHTML = '';
  12556. const opts = state.dhcpOptions || [];
  12557. if (opts.length === 0) {
  12558. container.innerHTML = '<span class="text-slate-500 text-[11px] col-span-2">No custom options configured. Add some in the "Options" tab.</span>';
  12559. return;
  12560. }
  12561. opts.forEach(o => {
  12562. const isChecked = selectedIds.includes(o.id);
  12563. const label = document.createElement('label');
  12564. label.className = 'flex items-center space-x-2 text-slate-300 hover:text-white cursor-pointer';
  12565. label.innerHTML = `
  12566. <input type="checkbox" name="dhcp-net-opt" value="${o.id}" ${isChecked ? 'checked' : ''} class="rounded bg-slate-800 border-slate-700 text-emerald-600">
  12567. <span class="truncate" title="${escapeHtml(o.name)} (Code ${o.code})">${escapeHtml(o.name)} <span class="text-cyan-400">#${o.code}</span></span>
  12568. `;
  12569. container.appendChild(label);
  12570. });
  12571. }
  12572. function closeDHCPNetworkModal() {
  12573. document.getElementById('dhcp-network-modal').classList.add('hidden');
  12574. }
  12575. async function submitSaveDHCPNetwork(e) {
  12576. e.preventDefault();
  12577. const id = document.getElementById('dhcp-network-modal-id').value;
  12578. const address = document.getElementById('dhcp-network-modal-address').value.trim();
  12579. const gateway = document.getElementById('dhcp-network-modal-gateway').value.trim();
  12580. const dnsStr = document.getElementById('dhcp-network-modal-dns').value.trim();
  12581. const domain = document.getElementById('dhcp-network-modal-domain').value.trim();
  12582. const netmask = document.getElementById('dhcp-network-modal-netmask').value.trim();
  12583. const comment = document.getElementById('dhcp-network-modal-comment').value.trim();
  12584. const selectedOpts = [];
  12585. document.querySelectorAll('input[name="dhcp-net-opt"]:checked').forEach(cb => selectedOpts.push(cb.value));
  12586. const dnsServers = dnsStr ? dnsStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  12587. try {
  12588. const res = await fetch(`${API_BASE}/dhcp-server/networks`, {
  12589. method: 'POST',
  12590. headers: { 'Content-Type': 'application/json' },
  12591. body: JSON.stringify({
  12592. id,
  12593. address,
  12594. gateway,
  12595. netmask,
  12596. dns_servers: dnsServers,
  12597. domain,
  12598. dhcp_options: selectedOpts,
  12599. comment
  12600. })
  12601. });
  12602. if (res.ok) {
  12603. showToast('Network Saved', `Subnet ${address} configured successfully`, 'success');
  12604. closeDHCPNetworkModal();
  12605. loadDHCPServer(false);
  12606. fetchData(false);
  12607. } else {
  12608. const err = await res.text();
  12609. showToast('Error', err, 'error');
  12610. }
  12611. } catch (err) {
  12612. showToast('Error', err.message, 'error');
  12613. }
  12614. }
  12615. async function deleteDHCPNetwork(id, addr) {
  12616. if (!confirm(`Are you sure you want to delete DHCP Network "${addr}"?`)) return;
  12617. try {
  12618. const res = await fetch(`${API_BASE}/dhcp-server/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12619. if (res.ok) {
  12620. showToast('Deleted', `Network ${addr} removed`, 'success');
  12621. loadDHCPServer(false);
  12622. fetchData(false);
  12623. }
  12624. } catch (err) {
  12625. showToast('Error', err.message, 'error');
  12626. }
  12627. }
  12628. // ==================== MODALS & ACTIONS: LEASES ====================
  12629. function openAddDHCPStaticLeaseModal() {
  12630. document.getElementById('dhcp-static-lease-modal-title').innerText = 'Add Static Lease Reservation';
  12631. document.getElementById('dhcp-static-lease-modal-id').value = '';
  12632. document.getElementById('dhcp-static-lease-modal-mac').value = '';
  12633. document.getElementById('dhcp-static-lease-modal-ip').value = '';
  12634. document.getElementById('dhcp-static-lease-modal-hostname').value = '';
  12635. document.getElementById('dhcp-static-lease-modal-server').value = 'all';
  12636. document.getElementById('dhcp-static-lease-modal-comment').value = '';
  12637. document.getElementById('dhcp-static-lease-modal-disabled').checked = false;
  12638. document.getElementById('dhcp-static-lease-modal').classList.remove('hidden');
  12639. }
  12640. function closeDHCPStaticLeaseModal() {
  12641. document.getElementById('dhcp-static-lease-modal').classList.add('hidden');
  12642. }
  12643. async function submitSaveDHCPStaticLease(e) {
  12644. e.preventDefault();
  12645. const id = document.getElementById('dhcp-static-lease-modal-id').value;
  12646. const mac = document.getElementById('dhcp-static-lease-modal-mac').value.trim();
  12647. const ip = document.getElementById('dhcp-static-lease-modal-ip').value.trim();
  12648. const hostname = document.getElementById('dhcp-static-lease-modal-hostname').value.trim();
  12649. const server = document.getElementById('dhcp-static-lease-modal-server').value.trim() || 'all';
  12650. const comment = document.getElementById('dhcp-static-lease-modal-comment').value.trim();
  12651. const disabled = document.getElementById('dhcp-static-lease-modal-disabled').checked;
  12652. try {
  12653. const res = await fetch(`${API_BASE}/dhcp-server/leases/static`, {
  12654. method: 'POST',
  12655. headers: { 'Content-Type': 'application/json' },
  12656. body: JSON.stringify({
  12657. id,
  12658. mac_address: mac,
  12659. address: ip,
  12660. hostname,
  12661. server,
  12662. comment,
  12663. disabled
  12664. })
  12665. });
  12666. if (res.ok) {
  12667. showToast('Static Lease Saved', `IP ${ip} reserved for ${mac}`, 'success');
  12668. closeDHCPStaticLeaseModal();
  12669. loadDHCPServer(false);
  12670. fetchData(false);
  12671. } else {
  12672. const err = await res.text();
  12673. showToast('Error', err, 'error');
  12674. }
  12675. } catch (err) {
  12676. showToast('Error', err.message, 'error');
  12677. }
  12678. }
  12679. async function deleteDHCPStaticLease(id) {
  12680. if (!confirm('Are you sure you want to remove this static reservation?')) return;
  12681. try {
  12682. const res = await fetch(`${API_BASE}/dhcp-server/leases/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12683. if (res.ok) {
  12684. showToast('Deleted', 'Static lease removed', 'success');
  12685. loadDHCPServer(false);
  12686. fetchData(false);
  12687. }
  12688. } catch (err) {
  12689. showToast('Error', err.message, 'error');
  12690. }
  12691. }
  12692. async function makeDHCPLeaseStatic(mac, ip, hostname, comment) {
  12693. try {
  12694. const res = await fetch(`${API_BASE}/dhcp-server/leases/make-static`, {
  12695. method: 'POST',
  12696. headers: { 'Content-Type': 'application/json' },
  12697. body: JSON.stringify({
  12698. mac_address: mac,
  12699. address: ip,
  12700. hostname,
  12701. comment: comment || 'Converted to static'
  12702. })
  12703. });
  12704. if (res.ok) {
  12705. showToast('Lease Made Static', `IP ${ip} permanently reserved for ${mac}`, 'success');
  12706. loadDHCPServer(false);
  12707. fetchData(false);
  12708. } else {
  12709. const err = await res.text();
  12710. showToast('Error', err, 'error');
  12711. }
  12712. } catch (err) {
  12713. showToast('Error', err.message, 'error');
  12714. }
  12715. }
  12716. // ==================== MODALS & ACTIONS: OPTIONS ====================
  12717. function openAddDHCPOptionModal() {
  12718. document.getElementById('dhcp-option-modal-title').innerText = 'Add DHCP Option';
  12719. document.getElementById('dhcp-option-modal-id').value = '';
  12720. document.getElementById('dhcp-option-modal-name').value = '';
  12721. document.getElementById('dhcp-option-modal-code').value = '';
  12722. document.getElementById('dhcp-option-modal-value').value = '';
  12723. document.getElementById('dhcp-option-modal-comment').value = '';
  12724. document.getElementById('dhcp-option-modal').classList.remove('hidden');
  12725. }
  12726. function openEditDHCPOptionModal(id) {
  12727. const o = (state.dhcpOptions || []).find(item => item.id === id);
  12728. if (!o) return;
  12729. document.getElementById('dhcp-option-modal-title').innerText = `Edit DHCP Option (${o.name})`;
  12730. document.getElementById('dhcp-option-modal-id').value = o.id;
  12731. document.getElementById('dhcp-option-modal-name').value = o.name;
  12732. document.getElementById('dhcp-option-modal-code').value = o.code;
  12733. document.getElementById('dhcp-option-modal-value').value = o.value;
  12734. document.getElementById('dhcp-option-modal-comment').value = o.comment || '';
  12735. document.getElementById('dhcp-option-modal').classList.remove('hidden');
  12736. }
  12737. function closeDHCPOptionModal() {
  12738. document.getElementById('dhcp-option-modal').classList.add('hidden');
  12739. }
  12740. async function submitSaveDHCPOption(e) {
  12741. e.preventDefault();
  12742. const id = document.getElementById('dhcp-option-modal-id').value;
  12743. const name = document.getElementById('dhcp-option-modal-name').value.trim();
  12744. const code = parseInt(document.getElementById('dhcp-option-modal-code').value);
  12745. const value = document.getElementById('dhcp-option-modal-value').value.trim();
  12746. const comment = document.getElementById('dhcp-option-modal-comment').value.trim();
  12747. try {
  12748. const res = await fetch(`${API_BASE}/dhcp-server/options`, {
  12749. method: 'POST',
  12750. headers: { 'Content-Type': 'application/json' },
  12751. body: JSON.stringify({ id, name, code, value, comment })
  12752. });
  12753. if (res.ok) {
  12754. showToast('Option Saved', `DHCP option ${name} (#${code}) configured`, 'success');
  12755. closeDHCPOptionModal();
  12756. loadDHCPServer(false);
  12757. fetchData(false);
  12758. } else {
  12759. const err = await res.text();
  12760. showToast('Error', err, 'error');
  12761. }
  12762. } catch (err) {
  12763. showToast('Error', err.message, 'error');
  12764. }
  12765. }
  12766. async function deleteDHCPOption(id, name) {
  12767. if (!confirm(`Are you sure you want to delete DHCP Option "${name}"?`)) return;
  12768. try {
  12769. const res = await fetch(`${API_BASE}/dhcp-server/options/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12770. if (res.ok) {
  12771. showToast('Deleted', `Option ${name} removed`, 'success');
  12772. loadDHCPServer(false);
  12773. fetchData(false);
  12774. }
  12775. } catch (err) {
  12776. showToast('Error', err.message, 'error');
  12777. }
  12778. }
  12779. // ==================== WIZARD: DHCP SETUP (MikroTik style) ====================
  12780. function openDHCPServerSetupModal() {
  12781. populateDHCPIfaceSelect('dhcp-wizard-iface', '');
  12782. onDHCPWizardIfaceChange();
  12783. document.getElementById('dhcp-setup-wizard-modal').classList.remove('hidden');
  12784. }
  12785. function closeDHCPServerSetupModal() {
  12786. document.getElementById('dhcp-setup-wizard-modal').classList.add('hidden');
  12787. }
  12788. function onDHCPWizardIfaceChange() {
  12789. const ifaceName = document.getElementById('dhcp-wizard-iface').value;
  12790. const iface = (state.interfaces || []).find(i => i.name === ifaceName);
  12791. let ip = '192.168.88.1';
  12792. let prefix = '24';
  12793. if (iface && iface.ip_address) {
  12794. const parts = iface.ip_address.split('/');
  12795. ip = parts[0];
  12796. if (parts.length > 1) prefix = parts[1];
  12797. }
  12798. // Calculate subnet base (e.g. 192.168.88.0/24)
  12799. const ipParts = ip.split('.');
  12800. if (ipParts.length === 4) {
  12801. const baseSpace = `${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.0/${prefix}`;
  12802. const pool = `${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.10-${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.254`;
  12803. document.getElementById('dhcp-wizard-space').value = baseSpace;
  12804. document.getElementById('dhcp-wizard-gateway').value = ip;
  12805. document.getElementById('dhcp-wizard-pool').value = pool;
  12806. document.getElementById('dhcp-wizard-dns').value = `${ip}, 1.1.1.1, 8.8.8.8`;
  12807. document.getElementById('dhcp-wizard-ntp').value = `${ip}`;
  12808. }
  12809. }
  12810. async function submitDHCPServerSetupWizard(e) {
  12811. e.preventDefault();
  12812. const iface = document.getElementById('dhcp-wizard-iface').value;
  12813. const space = document.getElementById('dhcp-wizard-space').value.trim();
  12814. const gw = document.getElementById('dhcp-wizard-gateway').value.trim();
  12815. const pool = document.getElementById('dhcp-wizard-pool').value.trim();
  12816. const dnsStr = document.getElementById('dhcp-wizard-dns').value.trim();
  12817. const leaseTime = document.getElementById('dhcp-wizard-leasetime').value.trim() || '12h';
  12818. const ntpStr = document.getElementById('dhcp-wizard-ntp').value.trim();
  12819. const tftp = document.getElementById('dhcp-wizard-tftp').value.trim();
  12820. const dnsServers = dnsStr ? dnsStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  12821. const ntpServers = ntpStr ? ntpStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  12822. try {
  12823. const res = await fetch(`${API_BASE}/dhcp-server/setup`, {
  12824. method: 'POST',
  12825. headers: { 'Content-Type': 'application/json' },
  12826. body: JSON.stringify({
  12827. interface: iface,
  12828. address_space: space,
  12829. gateway: gw,
  12830. address_pool: pool,
  12831. dns_servers: dnsServers,
  12832. lease_time: leaseTime,
  12833. ntp_servers: ntpServers,
  12834. next_server: tftp
  12835. })
  12836. });
  12837. if (res.ok) {
  12838. showToast('DHCP Setup Complete', `DHCP Server setup finished on ${iface}`, 'success');
  12839. closeDHCPServerSetupModal();
  12840. loadDHCPServer(false);
  12841. fetchData(false);
  12842. } else {
  12843. const err = await res.text();
  12844. showToast('Error', err, 'error');
  12845. }
  12846. } catch (err) {
  12847. showToast('Error', err.message, 'error');
  12848. }
  12849. }
  12850. function populateDHCPIfaceSelect(elemId, selectedVal) {
  12851. const sel = document.getElementById(elemId);
  12852. if (!sel) return;
  12853. sel.innerHTML = '<option value="">Select interface...</option>';
  12854. const ifaces = state.interfaces || [];
  12855. ifaces.forEach(i => {
  12856. if (i.name === 'lo') return;
  12857. const opt = document.createElement('option');
  12858. opt.value = i.name;
  12859. const ipStr = i.ip_address ? ` (${i.ip_address})` : '';
  12860. opt.textContent = `${i.name}${ipStr} [${i.role || i.type || 'interface'}]`;
  12861. if (i.name === selectedVal) opt.selected = true;
  12862. sel.appendChild(opt);
  12863. });
  12864. }
  12865. // ==================== UNIVERSAL TABLE ORDERING / SORTING (WINBOX / WEBFIG STYLE) ====================
  12866. function initTableSorting() {
  12867. document.querySelectorAll('table').forEach(setupSortableTable);
  12868. }
  12869. function setupSortableTable(table) {
  12870. const thead = table.querySelector('thead');
  12871. const tbody = table.querySelector('tbody');
  12872. if (!thead || !tbody) return;
  12873. const headerRows = thead.querySelectorAll('tr');
  12874. if (headerRows.length === 0) return;
  12875. const ths = headerRows[headerRows.length - 1].querySelectorAll('th');
  12876. ths.forEach((th, colIdx) => {
  12877. if (th._sortBound) return;
  12878. th._sortBound = true;
  12879. const rawText = th.innerText.trim().toLowerCase();
  12880. const isActionsCol = rawText === 'actions' || (rawText === 'action' && th.classList.contains('text-right'));
  12881. const isCheckboxCol = !!th.querySelector('input[type="checkbox"]');
  12882. const isExpandCol = (th.classList.contains('w-8') || th.classList.contains('w-6')) && !rawText;
  12883. const isExplicitNoSort = th.classList.contains('no-sort') || th.getAttribute('data-sortable') === 'false';
  12884. if (isActionsCol || isCheckboxCol || isExpandCol || isExplicitNoSort) {
  12885. return;
  12886. }
  12887. th.classList.add('table-sortable', 'group');
  12888. if (!th.title) th.title = 'Click to sort (Ascending / Descending / Default)';
  12889. let icon = th.querySelector('.table-sort-icon');
  12890. if (!icon) {
  12891. icon = document.createElement('span');
  12892. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  12893. icon.innerHTML = '⇅';
  12894. th.appendChild(icon);
  12895. }
  12896. th.addEventListener('click', (e) => {
  12897. if (e.target.tagName === 'INPUT' || e.target.tagName === 'BUTTON' || e.target.closest('button, input')) return;
  12898. handleHeaderClick(table, th, colIdx);
  12899. });
  12900. });
  12901. if (!tbody._sortObserved) {
  12902. tbody._sortObserved = true;
  12903. let sortDebounceTimer = null;
  12904. const observer = new MutationObserver((mutations) => {
  12905. if (tbody._isSorting) return;
  12906. const hasChildChanges = mutations.some(m => m.type === 'childList' && m.addedNodes.length > 0);
  12907. if (!hasChildChanges) return;
  12908. clearTimeout(sortDebounceTimer);
  12909. sortDebounceTimer = setTimeout(() => {
  12910. if (tbody._isSorting) return;
  12911. if (table._activeSort && table._activeSort.dir !== 'none') {
  12912. applyTableSort(table, table._activeSort.colIdx, table._activeSort.dir, false);
  12913. } else {
  12914. tagOriginalRowOrder(tbody);
  12915. }
  12916. }, 50);
  12917. });
  12918. tbody._sortObserver = observer;
  12919. observer.observe(tbody, { childList: true });
  12920. }
  12921. tagOriginalRowOrder(tbody);
  12922. }
  12923. function tagOriginalRowOrder(tbody) {
  12924. let idx = 0;
  12925. Array.from(tbody.children).forEach(tr => {
  12926. if (!tr.querySelector('td[colspan]')) {
  12927. if (!tr.hasAttribute('data-orig-idx')) {
  12928. tr.setAttribute('data-orig-idx', idx++);
  12929. }
  12930. }
  12931. });
  12932. }
  12933. function handleHeaderClick(table, th, colIdx) {
  12934. const currentSort = table._activeSort || { colIdx: -1, dir: 'none' };
  12935. let newDir = 'asc';
  12936. if (currentSort.colIdx === colIdx) {
  12937. if (currentSort.dir === 'asc') newDir = 'desc';
  12938. else if (currentSort.dir === 'desc') newDir = 'none';
  12939. else newDir = 'asc';
  12940. } else {
  12941. newDir = 'asc';
  12942. }
  12943. table._activeSort = { colIdx, dir: newDir };
  12944. updateHeaderIcons(table, colIdx, newDir);
  12945. applyTableSort(table, colIdx, newDir, true);
  12946. }
  12947. function updateHeaderIcons(table, activeColIdx, dir) {
  12948. const thead = table.querySelector('thead');
  12949. if (!thead) return;
  12950. const ths = thead.querySelectorAll('th');
  12951. ths.forEach((th, idx) => {
  12952. const icon = th.querySelector('.table-sort-icon');
  12953. if (!icon) return;
  12954. if (idx === activeColIdx && dir !== 'none') {
  12955. icon.innerHTML = dir === 'asc' ? '▲' : '▼';
  12956. icon.className = 'table-sort-icon text-cyan-400 font-bold opacity-100';
  12957. th.classList.add('table-sorted-active');
  12958. } else {
  12959. icon.innerHTML = '⇅';
  12960. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  12961. th.classList.remove('table-sorted-active');
  12962. }
  12963. });
  12964. }
  12965. function applyTableSort(table, colIdx, dir, userInitiated) {
  12966. const tbody = table.querySelector('tbody');
  12967. if (!tbody || tbody.children.length <= 1) return;
  12968. tbody._isSorting = true;
  12969. tagOriginalRowOrder(tbody);
  12970. // Group parent rows and any attached drawer/sub-rows
  12971. const groups = [];
  12972. let currentGroup = null;
  12973. Array.from(tbody.children).forEach(tr => {
  12974. if (tr.querySelector('td[colspan]')) {
  12975. if (currentGroup) {
  12976. currentGroup.subRows.push(tr);
  12977. } else {
  12978. groups.push({ mainRow: tr, subRows: [] });
  12979. }
  12980. } else {
  12981. currentGroup = { mainRow: tr, subRows: [] };
  12982. groups.push(currentGroup);
  12983. }
  12984. });
  12985. if (dir === 'none') {
  12986. groups.sort((a, b) => {
  12987. const idxA = parseInt(a.mainRow.getAttribute('data-orig-idx') || '0', 10);
  12988. const idxB = parseInt(b.mainRow.getAttribute('data-orig-idx') || '0', 10);
  12989. return idxA - idxB;
  12990. });
  12991. } else {
  12992. groups.sort((a, b) => {
  12993. const cellA = a.mainRow.children[colIdx];
  12994. const cellB = b.mainRow.children[colIdx];
  12995. const res = compareTableCells(cellA, cellB);
  12996. return dir === 'asc' ? res : -res;
  12997. });
  12998. }
  12999. // Check if rows are already in correct order to avoid modifying DOM
  13000. let alreadyOrdered = true;
  13001. let childIdx = 0;
  13002. for (const g of groups) {
  13003. if (tbody.children[childIdx] !== g.mainRow) {
  13004. alreadyOrdered = false;
  13005. break;
  13006. }
  13007. childIdx++;
  13008. for (const sub of g.subRows) {
  13009. if (tbody.children[childIdx] !== sub) {
  13010. alreadyOrdered = false;
  13011. break;
  13012. }
  13013. childIdx++;
  13014. }
  13015. }
  13016. if (alreadyOrdered) {
  13017. tbody._isSorting = false;
  13018. return;
  13019. }
  13020. // Disconnect observer while re-ordering to prevent recursion and thrashing
  13021. if (tbody._sortObserver) {
  13022. tbody._sortObserver.disconnect();
  13023. }
  13024. // Re-append rows in sorted order
  13025. groups.forEach(g => {
  13026. tbody.appendChild(g.mainRow);
  13027. g.subRows.forEach(sub => tbody.appendChild(sub));
  13028. });
  13029. // Drain any queued mutations and re-connect observer
  13030. if (tbody._sortObserver) {
  13031. tbody._sortObserver.takeRecords();
  13032. tbody._sortObserver.observe(tbody, { childList: true });
  13033. }
  13034. tbody._isSorting = false;
  13035. }
  13036. function getCellRawText(cell) {
  13037. if (!cell) return '';
  13038. if (cell.hasAttribute('data-sort-value')) return cell.getAttribute('data-sort-value');
  13039. const input = cell.querySelector('input, select');
  13040. if (input) {
  13041. if (input.type === 'checkbox') return input.checked ? '1' : '0';
  13042. return input.value;
  13043. }
  13044. return cell.innerText.trim();
  13045. }
  13046. function parseTrafficToNumber(str) {
  13047. const m = str.match(/^([\d.,]+)\s*([KMGTkmgt]?[iI]?[Bb](?:ps|\/s)?)/);
  13048. if (!m) return null;
  13049. const num = parseFloat(m[1].replace(/,/g, ''));
  13050. if (isNaN(num)) return null;
  13051. const unit = m[2].toUpperCase();
  13052. let mult = 1;
  13053. if (unit.startsWith('K')) mult = 1024;
  13054. else if (unit.startsWith('M')) mult = 1024 * 1024;
  13055. else if (unit.startsWith('G')) mult = 1024 * 1024 * 1024;
  13056. else if (unit.startsWith('T')) mult = 1024 * 1024 * 1024 * 1024;
  13057. return num * mult;
  13058. }
  13059. function parseIpToNumber(str) {
  13060. const clean = str.replace(/^[!~]/, '').trim();
  13061. const m = clean.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(?:\/(\d{1,2}))?/);
  13062. if (!m) return null;
  13063. const o1 = parseInt(m[1], 10);
  13064. const o2 = parseInt(m[2], 10);
  13065. const o3 = parseInt(m[3], 10);
  13066. const o4 = parseInt(m[4], 10);
  13067. if (o1 > 255 || o2 > 255 || o3 > 255 || o4 > 255) return null;
  13068. return ((o1 * 256 + o2) * 256 + o3) * 256 + o4;
  13069. }
  13070. function parseCompoundPackets(str) {
  13071. const m = str.match(/^([\d,]+)p/);
  13072. if (!m) return null;
  13073. return parseInt(m[1].replace(/,/g, ''), 10);
  13074. }
  13075. function compareTableCells(cellA, cellB) {
  13076. const a = getCellRawText(cellA);
  13077. const b = getCellRawText(cellB);
  13078. if (a === '' && b !== '') return 1;
  13079. if (b === '' && a !== '') return -1;
  13080. if (a === b) return 0;
  13081. // 1. IP Addresses / CIDR
  13082. const ipA = parseIpToNumber(a);
  13083. const ipB = parseIpToNumber(b);
  13084. if (ipA !== null && ipB !== null) return ipA - ipB;
  13085. // 2. Packet counts (e.g. "1,250p / 45 KB")
  13086. const pktA = parseCompoundPackets(a);
  13087. const pktB = parseCompoundPackets(b);
  13088. if (pktA !== null && pktB !== null) return pktA - pktB;
  13089. // 3. Traffic / Throughput / Bytes (e.g. "1.2 MB", "500 KiB", "10 Gbps")
  13090. const trafA = parseTrafficToNumber(a);
  13091. const trafB = parseTrafficToNumber(b);
  13092. if (trafA !== null && trafB !== null) return trafA - trafB;
  13093. // 4. Numbers with '#' or formatted with commas (e.g. "#1", "24", "1,200")
  13094. const cleanNumA = a.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  13095. const cleanNumB = b.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  13096. const numA = Number(cleanNumA);
  13097. const numB = Number(cleanNumB);
  13098. if (!isNaN(numA) && !isNaN(numB) && cleanNumA !== '' && cleanNumB !== '') {
  13099. return numA - numB;
  13100. }
  13101. // 5. Natural case-insensitive string compare
  13102. return a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' });
  13103. }
  13104. // ==================== VRRP HIGH AVAILABILITY CONTROLLER ====================
  13105. async function loadVRRP(showToastNotification = false) {
  13106. try {
  13107. const [instRes, sumRes] = await Promise.all([
  13108. fetch(`${API_BASE}/vrrp/instances`),
  13109. fetch(`${API_BASE}/vrrp/summary`)
  13110. ]);
  13111. if (instRes.ok) {
  13112. state.vrrpInstances = await instRes.json();
  13113. renderVRRP();
  13114. }
  13115. if (sumRes.ok) {
  13116. state.vrrpSummary = await sumRes.json();
  13117. renderVRRPSummary();
  13118. }
  13119. if (showToastNotification) {
  13120. showToast('Refreshed', 'VRRP telemetry refreshed', 'info');
  13121. }
  13122. } catch (err) {
  13123. console.error('Failed to load VRRP:', err);
  13124. }
  13125. }
  13126. function renderVRRPSummary() {
  13127. const s = state.vrrpSummary || { total_instances: 0, master_instances: 0, backup_instances: 0 };
  13128. const elTotal = document.getElementById('vrrp-stat-total');
  13129. if (elTotal) elTotal.innerText = s.total_instances || 0;
  13130. const elMaster = document.getElementById('vrrp-stat-master');
  13131. if (elMaster) elMaster.innerText = s.master_instances || 0;
  13132. const elBackup = document.getElementById('vrrp-stat-backup');
  13133. if (elBackup) elBackup.innerText = s.backup_instances || 0;
  13134. const bCount = document.getElementById('badge-vrrp-count');
  13135. if (bCount) bCount.innerText = s.total_instances || 0;
  13136. const dot = document.getElementById('badge-vrrp-dot');
  13137. if (dot) {
  13138. if (s.master_instances > 0) {
  13139. dot.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  13140. } else if (s.backup_instances > 0) {
  13141. dot.className = 'w-2 h-2 rounded-full bg-sky-400';
  13142. } else {
  13143. dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  13144. }
  13145. }
  13146. }
  13147. function renderVRRP() {
  13148. const tbody = document.getElementById('vrrp-table-tbody');
  13149. const empty = document.getElementById('vrrp-table-empty');
  13150. if (!tbody) return;
  13151. tbody.innerHTML = '';
  13152. const instances = state.vrrpInstances || [];
  13153. if (instances.length === 0) {
  13154. empty?.classList.remove('hidden');
  13155. return;
  13156. }
  13157. empty?.classList.add('hidden');
  13158. instances.forEach(inst => {
  13159. const tr = document.createElement('tr');
  13160. tr.className = `hover:bg-slate-800/40 transition text-xs ${inst.disabled ? 'opacity-50' : ''}`;
  13161. // Render Flag: M (Master), B (Backup), F (Fault), X (Disabled)
  13162. 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>`;
  13163. if (inst.disabled) {
  13164. 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>`;
  13165. } else if (inst.state === 'MASTER') {
  13166. 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>`;
  13167. } else if (inst.state === 'BACKUP') {
  13168. 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>`;
  13169. } else if (inst.state === 'FAULT') {
  13170. 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>`;
  13171. }
  13172. // Render State Badge
  13173. let stateBadge = `<span class="px-2 py-0.5 rounded text-[10px] bg-slate-800 text-slate-400 border border-slate-700">DISABLED</span>`;
  13174. if (!inst.disabled) {
  13175. if (inst.state === 'MASTER') {
  13176. 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>`;
  13177. } else if (inst.state === 'BACKUP') {
  13178. 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>`;
  13179. } else if (inst.state === 'FAULT') {
  13180. 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>`;
  13181. }
  13182. }
  13183. const vipsStr = (inst.virtual_ips || []).join(', ') || '-';
  13184. tr.innerHTML = `
  13185. <td class="py-2.5 px-3 text-center">${flagHtml}</td>
  13186. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(inst.name)}</td>
  13187. <td class="py-2.5 px-3 font-mono text-cyan-400 font-semibold">${escapeHtml(inst.interface)}</td>
  13188. <td class="py-2.5 px-3 font-mono font-bold text-center text-white">${inst.vrid}</td>
  13189. <td class="py-2.5 px-3 font-mono text-center text-slate-300 font-semibold">${inst.priority}</td>
  13190. <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>
  13191. <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>
  13192. <td class="py-2.5 px-3 font-mono text-slate-400 text-[11px]">${escapeHtml(inst.virtual_mac || '-')}</td>
  13193. <td class="py-2.5 px-3 text-center">${stateBadge}</td>
  13194. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]" title="${escapeHtml(inst.comment || '')}">${escapeHtml(inst.comment || '-')}</td>
  13195. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  13196. <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>
  13197. <button onclick="openEditVRRPModal('${inst.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  13198. <button onclick="deleteVRRP('${inst.id}', '${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  13199. </td>
  13200. `;
  13201. tbody.appendChild(tr);
  13202. });
  13203. }
  13204. function populateVRRPIfaceSelect(elemId, selectedIface) {
  13205. const sel = document.getElementById(elemId);
  13206. if (!sel) return;
  13207. sel.innerHTML = '<option value="">Select interface...</option>';
  13208. const ifaces = state.interfaces || [];
  13209. ifaces.forEach(i => {
  13210. const opt = document.createElement('option');
  13211. opt.value = i.name;
  13212. opt.innerText = `${i.name} (${i.type || 'net'}${i.ip ? ' - ' + i.ip : ''})`;
  13213. if (selectedIface && selectedIface === i.name) opt.selected = true;
  13214. sel.appendChild(opt);
  13215. });
  13216. }
  13217. function openAddVRRPModal() {
  13218. document.getElementById('modal-vrrp-title').innerText = 'Add VRRP Instance';
  13219. document.getElementById('modal-vrrp-id').value = '';
  13220. document.getElementById('modal-vrrp-name').value = `vrrp${(state.vrrpInstances || []).length + 1}`;
  13221. document.getElementById('modal-vrrp-vrid').value = 10 + (state.vrrpInstances || []).length;
  13222. document.getElementById('modal-vrrp-priority').value = 100;
  13223. document.getElementById('modal-vrrp-vip').value = '192.168.88.254/24';
  13224. document.getElementById('modal-vrrp-version').value = '3';
  13225. document.getElementById('modal-vrrp-interval').value = 1;
  13226. document.getElementById('modal-vrrp-authtype').value = 'none';
  13227. document.getElementById('modal-vrrp-authpass').value = '';
  13228. document.getElementById('modal-vrrp-comment').value = '';
  13229. document.getElementById('modal-vrrp-preempt').checked = true;
  13230. document.getElementById('modal-vrrp-disabled').checked = false;
  13231. populateVRRPIfaceSelect('modal-vrrp-iface', '');
  13232. document.getElementById('modal-vrrp-instance').classList.remove('hidden');
  13233. }
  13234. function openEditVRRPModal(id) {
  13235. const inst = (state.vrrpInstances || []).find(item => item.id === id);
  13236. if (!inst) return;
  13237. document.getElementById('modal-vrrp-title').innerText = `Edit VRRP Instance (${inst.name})`;
  13238. document.getElementById('modal-vrrp-id').value = inst.id;
  13239. document.getElementById('modal-vrrp-name').value = inst.name;
  13240. document.getElementById('modal-vrrp-vrid').value = inst.vrid;
  13241. document.getElementById('modal-vrrp-priority').value = inst.priority;
  13242. document.getElementById('modal-vrrp-vip').value = (inst.virtual_ips || []).join(', ');
  13243. document.getElementById('modal-vrrp-version').value = String(inst.version || 3);
  13244. document.getElementById('modal-vrrp-interval').value = inst.interval || 1;
  13245. document.getElementById('modal-vrrp-authtype').value = inst.auth_type || 'none';
  13246. document.getElementById('modal-vrrp-authpass').value = inst.auth_password || '';
  13247. document.getElementById('modal-vrrp-comment').value = inst.comment || '';
  13248. document.getElementById('modal-vrrp-preempt').checked = inst.preempt !== false;
  13249. document.getElementById('modal-vrrp-disabled').checked = !!inst.disabled;
  13250. populateVRRPIfaceSelect('modal-vrrp-iface', inst.interface);
  13251. document.getElementById('modal-vrrp-instance').classList.remove('hidden');
  13252. }
  13253. function closeVRRPModal() {
  13254. document.getElementById('modal-vrrp-instance').classList.add('hidden');
  13255. }
  13256. async function submitSaveVRRP(e) {
  13257. e.preventDefault();
  13258. const id = document.getElementById('modal-vrrp-id').value;
  13259. const name = document.getElementById('modal-vrrp-name').value.trim();
  13260. const iface = document.getElementById('modal-vrrp-iface').value;
  13261. const vrid = parseInt(document.getElementById('modal-vrrp-vrid').value, 10) || 1;
  13262. const priority = parseInt(document.getElementById('modal-vrrp-priority').value, 10) || 100;
  13263. const vipRaw = document.getElementById('modal-vrrp-vip').value.trim();
  13264. const version = parseInt(document.getElementById('modal-vrrp-version').value, 10) || 3;
  13265. const interval = parseInt(document.getElementById('modal-vrrp-interval').value, 10) || 1;
  13266. const authType = document.getElementById('modal-vrrp-authtype').value;
  13267. const authPass = document.getElementById('modal-vrrp-authpass').value.trim();
  13268. const comment = document.getElementById('modal-vrrp-comment').value.trim();
  13269. const preempt = document.getElementById('modal-vrrp-preempt').checked;
  13270. const disabled = document.getElementById('modal-vrrp-disabled').checked;
  13271. const vips = vipRaw.split(',').map(s => s.trim()).filter(Boolean);
  13272. try {
  13273. const res = await fetch(`${API_BASE}/vrrp/instances`, {
  13274. method: 'POST',
  13275. headers: { 'Content-Type': 'application/json' },
  13276. body: JSON.stringify({
  13277. id,
  13278. name,
  13279. interface: iface,
  13280. vrid,
  13281. priority,
  13282. virtual_ips: vips,
  13283. version,
  13284. interval,
  13285. auth_type: authType,
  13286. auth_password: authPass,
  13287. comment,
  13288. preempt,
  13289. disabled
  13290. })
  13291. });
  13292. if (res.ok) {
  13293. showToast('VRRP Saved', `VRRP instance ${name} configured`, 'success');
  13294. closeVRRPModal();
  13295. loadVRRP(false);
  13296. fetchData(false);
  13297. } else {
  13298. const err = await res.text();
  13299. showToast('Error', err, 'error');
  13300. }
  13301. } catch (err) {
  13302. showToast('Error', err.message, 'error');
  13303. }
  13304. }
  13305. async function deleteVRRP(id, name) {
  13306. if (!confirm(`Delete VRRP instance "${name}"?`)) return;
  13307. try {
  13308. const res = await fetch(`${API_BASE}/vrrp/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  13309. if (res.ok) {
  13310. showToast('Deleted', `VRRP instance ${name} removed`, 'info');
  13311. loadVRRP(false);
  13312. fetchData(false);
  13313. } else {
  13314. const err = await res.text();
  13315. showToast('Error', err, 'error');
  13316. }
  13317. } catch (err) {
  13318. showToast('Error', err.message, 'error');
  13319. }
  13320. }
  13321. async function toggleVRRPState(id, disabled) {
  13322. try {
  13323. const res = await fetch(`${API_BASE}/vrrp/instances/${encodeURIComponent(id)}/state`, {
  13324. method: 'POST',
  13325. headers: { 'Content-Type': 'application/json' },
  13326. body: JSON.stringify({ disabled })
  13327. });
  13328. if (res.ok) {
  13329. showToast('State Updated', disabled ? 'VRRP disabled' : 'VRRP enabled', 'info');
  13330. loadVRRP(false);
  13331. fetchData(false);
  13332. } else {
  13333. const err = await res.text();
  13334. showToast('Error', err, 'error');
  13335. }
  13336. } catch (err) {
  13337. showToast('Error', err.message, 'error');
  13338. }
  13339. }
  13340. // Global observer for dynamically injected tables (e.g. inside modals or drawers)
  13341. if (typeof MutationObserver !== 'undefined' && typeof document !== 'undefined') {
  13342. let docSortDebounce = null;
  13343. const docTableObserver = new MutationObserver((mutations) => {
  13344. let needsInit = false;
  13345. for (const m of mutations) {
  13346. for (const node of m.addedNodes) {
  13347. if (node.nodeType === 1) {
  13348. if (node.tagName === 'TABLE' && !node.closest('tbody, thead')) {
  13349. needsInit = true;
  13350. break;
  13351. } else if (node.querySelector && !node.closest('table') && node.querySelector('table')) {
  13352. needsInit = true;
  13353. break;
  13354. }
  13355. }
  13356. }
  13357. if (needsInit) break;
  13358. }
  13359. if (needsInit) {
  13360. clearTimeout(docSortDebounce);
  13361. docSortDebounce = setTimeout(initTableSorting, 100);
  13362. }
  13363. });
  13364. docTableObserver.observe(document.body || document.documentElement, { childList: true, subtree: true });
  13365. }
  13366. // =========================================================================
  13367. // BANDWIDTH TEST (BwTest) BENCHMARK ENGINE
  13368. // =========================================================================
  13369. const bwtestState = {
  13370. running: false,
  13371. pollTimer: null,
  13372. eventSource: null,
  13373. chartPoints: [],
  13374. maxChartPoints: 60,
  13375. serverConfig: null,
  13376. peakTx: 0,
  13377. peakRx: 0,
  13378. targetDuration: 10,
  13379. lastSampleIndex: 0
  13380. };
  13381. async function loadBwTestView() {
  13382. fetchBwTestServerStatus();
  13383. loadBwTestHistory();
  13384. resizeBwTestCanvas();
  13385. checkActiveBwTest();
  13386. }
  13387. async function fetchBwTestServerStatus() {
  13388. try {
  13389. const res = await fetch(`${API_BASE}/tools/bwtest/server`);
  13390. if (!res.ok) return;
  13391. const s = await res.json();
  13392. bwtestState.serverConfig = s;
  13393. // Update indicator and badges
  13394. const indicator = document.getElementById('bwtest-server-indicator');
  13395. const badge = document.getElementById('bwtest-server-badge');
  13396. const sideBadge = document.getElementById('badge-bwtest-server');
  13397. if (s.enabled && s.running) {
  13398. if (indicator) indicator.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  13399. if (badge) {
  13400. badge.innerText = `Port ${s.port} (Active)`;
  13401. badge.className = 'text-emerald-400 font-bold';
  13402. }
  13403. if (sideBadge) {
  13404. sideBadge.innerText = s.port;
  13405. 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';
  13406. }
  13407. } else {
  13408. if (indicator) indicator.className = 'w-2 h-2 rounded-full bg-slate-600';
  13409. if (badge) {
  13410. badge.innerText = `Disabled`;
  13411. badge.className = 'text-slate-500 font-bold';
  13412. }
  13413. if (sideBadge) {
  13414. sideBadge.innerText = 'Off';
  13415. sideBadge.className = 'text-[10px] bg-slate-800 text-slate-500 border border-slate-700 px-1.5 py-0.2 rounded-full font-mono';
  13416. }
  13417. }
  13418. // Modal fields
  13419. const toggle = document.getElementById('bwtest-server-enable-toggle');
  13420. if (toggle) toggle.checked = !!s.enabled;
  13421. const portInp = document.getElementById('bwtest-server-port-input');
  13422. if (portInp) portInp.value = s.port || 2000;
  13423. const actSess = document.getElementById('bwtest-modal-active-sessions');
  13424. if (actSess) actSess.innerText = s.active_sessions || 0;
  13425. const totServ = document.getElementById('bwtest-modal-total-served');
  13426. if (totServ) totServ.innerText = s.total_sessions_served || 0;
  13427. const totBytes = document.getElementById('bwtest-modal-total-bytes');
  13428. if (totBytes) totBytes.innerText = formatBytes(s.total_bytes_processed || 0);
  13429. } catch (err) {
  13430. console.error('Failed to fetch BwTest server status:', err);
  13431. }
  13432. }
  13433. function openBwTestServerModal() {
  13434. fetchBwTestServerStatus();
  13435. document.getElementById('modal-bwtest-server')?.classList.remove('hidden');
  13436. }
  13437. function closeBwTestServerModal() {
  13438. document.getElementById('modal-bwtest-server')?.classList.add('hidden');
  13439. }
  13440. async function submitBwTestServerSettings(e) {
  13441. e.preventDefault();
  13442. const enabled = document.getElementById('bwtest-server-enable-toggle').checked;
  13443. const port = parseInt(document.getElementById('bwtest-server-port-input').value, 10) || 2000;
  13444. try {
  13445. const res = await fetch(`${API_BASE}/tools/bwtest/server`, {
  13446. method: 'POST',
  13447. headers: { 'Content-Type': 'application/json' },
  13448. body: JSON.stringify({ enabled, port, listen_addr: '0.0.0.0', allow_anonymous: true })
  13449. });
  13450. if (!res.ok) {
  13451. const err = await res.json();
  13452. throw new Error(err.error || 'Failed to update server configuration');
  13453. }
  13454. showToast('BwTest Server', `Bandwidth Test server updated (Port ${port})`, 'success');
  13455. closeBwTestServerModal();
  13456. fetchBwTestServerStatus();
  13457. } catch (err) {
  13458. showToast('Server Configuration Error', err.message, 'error');
  13459. }
  13460. }
  13461. function setBwTestTarget(target) {
  13462. const inp = document.getElementById('bwtest-input-target');
  13463. if (inp) inp.value = target;
  13464. }
  13465. function setBwTestProtocol(proto) {
  13466. const hiddenInp = document.getElementById('bwtest-input-protocol');
  13467. if (hiddenInp) hiddenInp.value = proto;
  13468. const btnUdp = document.getElementById('bwtest-proto-udp');
  13469. const btnTcp = document.getElementById('bwtest-proto-tcp');
  13470. const badge = document.getElementById('bwtest-proto-badge');
  13471. const pktField = document.getElementById('bwtest-field-pktsize');
  13472. 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';
  13473. 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';
  13474. 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';
  13475. if (proto === 'udp') {
  13476. if (btnUdp) {
  13477. btnUdp.className = activeUdpCls;
  13478. const dot = btnUdp.querySelector('span');
  13479. if (dot) dot.className = 'w-2 h-2 rounded-full bg-emerald-400';
  13480. }
  13481. if (btnTcp) {
  13482. btnTcp.className = inactiveCls;
  13483. const dot = btnTcp.querySelector('span');
  13484. if (dot) dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  13485. }
  13486. if (badge) {
  13487. badge.innerText = 'UDP Mode (RFC 3550 Jitter + Loss %)';
  13488. badge.className = 'text-[10px] font-mono text-emerald-400 bg-emerald-500/10 px-2 py-0.5 rounded border border-emerald-500/20';
  13489. }
  13490. if (pktField) pktField.classList.remove('opacity-40');
  13491. } else {
  13492. if (btnUdp) {
  13493. btnUdp.className = inactiveCls;
  13494. const dot = btnUdp.querySelector('span');
  13495. if (dot) dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  13496. }
  13497. if (btnTcp) {
  13498. btnTcp.className = activeTcpCls;
  13499. const dot = btnTcp.querySelector('span');
  13500. if (dot) dot.className = 'w-2 h-2 rounded-full bg-blue-400';
  13501. }
  13502. if (badge) {
  13503. badge.innerText = 'TCP Mode (Sliding Window Throughput)';
  13504. badge.className = 'text-[10px] font-mono text-blue-400 bg-blue-500/10 px-2 py-0.5 rounded border border-blue-500/20';
  13505. }
  13506. if (pktField) pktField.classList.add('opacity-40');
  13507. }
  13508. }
  13509. function setBwTestDirection(dir) {
  13510. const hiddenInp = document.getElementById('bwtest-input-direction');
  13511. if (hiddenInp) hiddenInp.value = dir;
  13512. const btnBoth = document.getElementById('bwtest-dir-both');
  13513. const btnTx = document.getElementById('bwtest-dir-tx');
  13514. const btnRx = document.getElementById('bwtest-dir-rx');
  13515. 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';
  13516. 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';
  13517. if (btnBoth) btnBoth.className = dir === 'both' ? activeCls : inactiveCls;
  13518. if (btnTx) btnTx.className = dir === 'tx' ? activeCls : inactiveCls;
  13519. if (btnRx) btnRx.className = dir === 'rx' ? activeCls : inactiveCls;
  13520. }
  13521. function setBwTestLimit(bps) {
  13522. const sel = document.getElementById('bwtest-input-limit');
  13523. if (sel) sel.value = String(bps);
  13524. }
  13525. async function checkActiveBwTest() {
  13526. try {
  13527. const res = await fetch(`${API_BASE}/tools/bwtest/status`);
  13528. if (!res.ok) return;
  13529. const st = await res.json();
  13530. if (st.running) {
  13531. setBwTestRunningUI(true);
  13532. if (st.current_sample) handleBwTestSample(st.current_sample);
  13533. startBwTestTelemetry();
  13534. }
  13535. } catch (err) {
  13536. console.error('Failed to check active BwTest:', err);
  13537. }
  13538. }
  13539. async function startBwTest(e) {
  13540. if (e && e.preventDefault) e.preventDefault();
  13541. const target = document.getElementById('bwtest-input-target').value.trim() || '127.0.0.1';
  13542. const port = parseInt(document.getElementById('bwtest-input-port').value, 10) || 2000;
  13543. const direction = document.getElementById('bwtest-input-direction').value || 'both';
  13544. const protocol = document.getElementById('bwtest-input-protocol').value || 'udp';
  13545. const bandwidth_limit = parseInt(document.getElementById('bwtest-input-limit').value, 10) || 0;
  13546. const packet_size = parseInt(document.getElementById('bwtest-input-pktsize').value, 10) || 1472;
  13547. const streams = parseInt(document.getElementById('bwtest-input-streams').value, 10) || 1;
  13548. const duration = parseInt(document.getElementById('bwtest-input-duration').value, 10);
  13549. bwtestState.targetDuration = duration;
  13550. bwtestState.chartPoints = [];
  13551. bwtestState.peakTx = 0;
  13552. bwtestState.peakRx = 0;
  13553. bwtestState.lastSampleIndex = 0;
  13554. // Clear UI elements
  13555. document.getElementById('bwtest-stat-tx-mbps').innerText = '0.00';
  13556. document.getElementById('bwtest-stat-tx-peak').innerText = '0.00 Mbps';
  13557. document.getElementById('bwtest-stat-tx-pkts').innerText = '0';
  13558. document.getElementById('bwtest-stat-rx-mbps').innerText = '0.00';
  13559. document.getElementById('bwtest-stat-rx-peak').innerText = '0.00 Mbps';
  13560. document.getElementById('bwtest-stat-rx-pkts').innerText = '0';
  13561. document.getElementById('bwtest-stat-loss').innerText = '0.0%';
  13562. document.getElementById('bwtest-stat-jitter').innerText = '0.00 ms';
  13563. document.getElementById('bwtest-stat-time').innerText = '0.0s';
  13564. document.getElementById('bwtest-stat-data').innerText = '0.0 MB';
  13565. document.getElementById('bwtest-stat-target-dur').innerText = duration > 0 ? `/ ${duration}s` : '/ ∞';
  13566. const tbody = document.getElementById('bwtest-samples-tbody');
  13567. if (tbody) tbody.innerHTML = '';
  13568. document.getElementById('bwtest-sample-count').innerText = '0 samples';
  13569. setBwTestRunningUI(true);
  13570. try {
  13571. const res = await fetch(`${API_BASE}/tools/bwtest/start`, {
  13572. method: 'POST',
  13573. headers: { 'Content-Type': 'application/json' },
  13574. body: JSON.stringify({
  13575. target,
  13576. port,
  13577. direction,
  13578. protocol,
  13579. bandwidth_limit,
  13580. packet_size,
  13581. streams,
  13582. duration
  13583. })
  13584. });
  13585. if (!res.ok) {
  13586. const err = await res.json();
  13587. throw new Error(err.error || 'Failed to start bandwidth test');
  13588. }
  13589. showToast('Benchmark Started', `Target: ${target}:${port} (${direction.toUpperCase()}, ${protocol.toUpperCase()})`, 'info');
  13590. startBwTestTelemetry();
  13591. } catch (err) {
  13592. setBwTestRunningUI(false);
  13593. showToast('Start Failed', err.message, 'error');
  13594. }
  13595. }
  13596. function setBwTestRunningUI(running) {
  13597. bwtestState.running = running;
  13598. const startBtn = document.getElementById('bwtest-btn-start');
  13599. const stopBtn = document.getElementById('bwtest-btn-stop');
  13600. const badge = document.getElementById('bwtest-run-status-badge');
  13601. const ph = document.getElementById('bwtest-chart-placeholder');
  13602. if (running) {
  13603. if (startBtn) {
  13604. startBtn.disabled = true;
  13605. startBtn.classList.add('opacity-50', 'cursor-not-allowed');
  13606. }
  13607. if (stopBtn) {
  13608. stopBtn.disabled = false;
  13609. stopBtn.classList.remove('opacity-40');
  13610. }
  13611. if (badge) {
  13612. badge.innerText = 'TESTING...';
  13613. 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';
  13614. }
  13615. if (ph) ph.style.display = 'none';
  13616. } else {
  13617. if (startBtn) {
  13618. startBtn.disabled = false;
  13619. startBtn.classList.remove('opacity-50', 'cursor-not-allowed');
  13620. }
  13621. if (stopBtn) {
  13622. stopBtn.disabled = true;
  13623. stopBtn.classList.add('opacity-40');
  13624. }
  13625. if (badge) {
  13626. badge.innerText = 'IDLE';
  13627. badge.className = 'px-2 py-0.5 rounded text-[10px] font-mono bg-slate-800 text-slate-400 border border-slate-700 font-semibold';
  13628. }
  13629. }
  13630. }
  13631. async function stopBwTest() {
  13632. try {
  13633. await fetch(`${API_BASE}/tools/bwtest/stop`, { method: 'POST' });
  13634. showToast('Test Stopped', 'Bandwidth test terminated by user', 'info');
  13635. } catch (err) {
  13636. console.error('Failed to stop test:', err);
  13637. }
  13638. }
  13639. function startBwTestTelemetry() {
  13640. if (bwtestState.pollTimer) clearInterval(bwtestState.pollTimer);
  13641. bwtestState.pollTimer = setInterval(async () => {
  13642. try {
  13643. const res = await fetch(`${API_BASE}/tools/bwtest/status`);
  13644. if (!res.ok) return;
  13645. const st = await res.json();
  13646. if (st.recent_samples && st.recent_samples.length > 0) {
  13647. // Process new samples
  13648. const newSamples = st.recent_samples.slice(bwtestState.lastSampleIndex);
  13649. newSamples.forEach(s => handleBwTestSample(s));
  13650. bwtestState.lastSampleIndex = st.recent_samples.length;
  13651. }
  13652. if (!st.running) {
  13653. clearInterval(bwtestState.pollTimer);
  13654. bwtestState.pollTimer = null;
  13655. setBwTestRunningUI(false);
  13656. handleBwTestFinish(st.summary, st.error);
  13657. }
  13658. } catch (err) {
  13659. console.error('BwTest polling error:', err);
  13660. }
  13661. }, 400);
  13662. }
  13663. function handleBwTestSample(s) {
  13664. if (!s) return;
  13665. const txMbps = s.tx_mbps || 0;
  13666. const rxMbps = s.rx_mbps || 0;
  13667. if (txMbps > bwtestState.peakTx) bwtestState.peakTx = txMbps;
  13668. if (rxMbps > bwtestState.peakRx) bwtestState.peakRx = rxMbps;
  13669. // KPI updates
  13670. const elTx = document.getElementById('bwtest-stat-tx-mbps');
  13671. if (elTx) elTx.innerText = txMbps.toFixed(2);
  13672. const elTxPeak = document.getElementById('bwtest-stat-tx-peak');
  13673. if (elTxPeak) elTxPeak.innerText = `${bwtestState.peakTx.toFixed(2)} Mbps`;
  13674. const elTxPkts = document.getElementById('bwtest-stat-tx-pkts');
  13675. if (elTxPkts) elTxPkts.innerText = s.tx_packets || 0;
  13676. const elRx = document.getElementById('bwtest-stat-rx-mbps');
  13677. if (elRx) elRx.innerText = rxMbps.toFixed(2);
  13678. const elRxPeak = document.getElementById('bwtest-stat-rx-peak');
  13679. if (elRxPeak) elRxPeak.innerText = `${bwtestState.peakRx.toFixed(2)} Mbps`;
  13680. const elRxPkts = document.getElementById('bwtest-stat-rx-pkts');
  13681. if (elRxPkts) elRxPkts.innerText = s.rx_packets || 0;
  13682. const elLoss = document.getElementById('bwtest-stat-loss');
  13683. if (elLoss) {
  13684. elLoss.innerText = `${(s.loss_pct || 0).toFixed(1)}%`;
  13685. elLoss.className = (s.loss_pct > 1.0) ? 'text-2xl font-bold text-rose-400' : 'text-2xl font-bold text-emerald-400';
  13686. }
  13687. const elLostPkts = document.getElementById('bwtest-stat-lost-pkts');
  13688. if (elLostPkts) elLostPkts.innerText = s.lost_packets || 0;
  13689. const elJitter = document.getElementById('bwtest-stat-jitter');
  13690. if (elJitter) elJitter.innerText = `${(s.jitter_ms || 0).toFixed(2)} ms`;
  13691. const elTime = document.getElementById('bwtest-stat-time');
  13692. if (elTime) elTime.innerText = `${(s.elapsed_sec || 0).toFixed(1)}s`;
  13693. const elData = document.getElementById('bwtest-stat-data');
  13694. if (elData) elData.innerText = formatBytes((s.tx_bytes || 0) + (s.rx_bytes || 0));
  13695. const elGraphRate = document.getElementById('bwtest-graph-rate');
  13696. if (elGraphRate) elGraphRate.innerText = `TX: ${txMbps.toFixed(1)} Mbps • RX: ${rxMbps.toFixed(1)} Mbps`;
  13697. // Append point to chart buffer
  13698. bwtestState.chartPoints.push({
  13699. elapsed: s.elapsed_sec || 0,
  13700. tx: txMbps,
  13701. rx: rxMbps
  13702. });
  13703. if (bwtestState.chartPoints.length > bwtestState.maxChartPoints) {
  13704. bwtestState.chartPoints.shift();
  13705. }
  13706. drawBwTestChart();
  13707. // Add row to breakdown table
  13708. const tbody = document.getElementById('bwtest-samples-tbody');
  13709. if (tbody) {
  13710. const tr = document.createElement('tr');
  13711. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  13712. tr.innerHTML = `
  13713. <td class="py-1.5 px-3 font-semibold text-white">${(s.elapsed_sec || 0).toFixed(1)}s</td>
  13714. <td class="py-1.5 px-3 font-bold text-cyan-400">${txMbps.toFixed(2)} Mbps</td>
  13715. <td class="py-1.5 px-3 font-bold text-purple-400">${rxMbps.toFixed(2)} Mbps</td>
  13716. <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>
  13717. <td class="py-1.5 px-3 text-slate-300">${(s.jitter_ms || 0).toFixed(2)} ms</td>
  13718. <td class="py-1.5 px-3 text-slate-400">${formatBytes((s.tx_bytes || 0) + (s.rx_bytes || 0))}</td>
  13719. `;
  13720. tbody.insertBefore(tr, tbody.firstChild);
  13721. const countEl = document.getElementById('bwtest-sample-count');
  13722. if (countEl) countEl.innerText = `${tbody.children.length} samples`;
  13723. }
  13724. }
  13725. function handleBwTestFinish(summary, error) {
  13726. const badge = document.getElementById('bwtest-run-status-badge');
  13727. if (error) {
  13728. showToast('Benchmark Error', error, 'error');
  13729. if (badge) {
  13730. badge.innerText = 'ERROR';
  13731. 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';
  13732. }
  13733. } else if (summary) {
  13734. const avgTx = summary.avg_tx_mbps.toFixed(1);
  13735. const avgRx = summary.avg_rx_mbps.toFixed(1);
  13736. showToast('Benchmark Complete', `Average TX: ${avgTx} Mbps | RX: ${avgRx} Mbps (Loss: ${summary.avg_loss_pct.toFixed(1)}%)`, 'success');
  13737. if (badge) {
  13738. badge.innerText = 'COMPLETED';
  13739. 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';
  13740. }
  13741. }
  13742. loadBwTestHistory();
  13743. fetchBwTestServerStatus();
  13744. }
  13745. function resizeBwTestCanvas() {
  13746. const canvas = document.getElementById('bwtest-chart');
  13747. if (!canvas || !canvas.parentElement) return;
  13748. const rect = canvas.parentElement.getBoundingClientRect();
  13749. const dpr = window.devicePixelRatio || 1;
  13750. canvas.width = rect.width * dpr;
  13751. canvas.height = rect.height * dpr;
  13752. const ctx = canvas.getContext('2d');
  13753. ctx.scale(dpr, dpr);
  13754. drawBwTestChart();
  13755. }
  13756. window.addEventListener('resize', () => {
  13757. if (state.activeTab === 'bwtest') resizeBwTestCanvas();
  13758. });
  13759. function drawBwTestChart() {
  13760. const canvas = document.getElementById('bwtest-chart');
  13761. if (!canvas) return;
  13762. const ctx = canvas.getContext('2d');
  13763. const dpr = window.devicePixelRatio || 1;
  13764. const width = canvas.width / dpr;
  13765. const height = canvas.height / dpr;
  13766. ctx.clearRect(0, 0, width, height);
  13767. const points = bwtestState.chartPoints;
  13768. if (!points || points.length === 0) return;
  13769. // Determine scale ceiling
  13770. let maxRate = 10;
  13771. for (const p of points) {
  13772. if (p.tx > maxRate) maxRate = p.tx;
  13773. if (p.rx > maxRate) maxRate = p.rx;
  13774. }
  13775. maxRate = Math.ceil(maxRate * 1.25); // 25% headroom
  13776. const paddingLeft = 55;
  13777. const paddingBottom = 24;
  13778. const paddingTop = 12;
  13779. const paddingRight = 16;
  13780. const chartW = width - paddingLeft - paddingRight;
  13781. const chartH = height - paddingTop - paddingBottom;
  13782. // Grid Lines and Y-Axis labels
  13783. ctx.strokeStyle = 'rgba(51, 65, 85, 0.4)';
  13784. ctx.lineWidth = 1;
  13785. ctx.fillStyle = '#94a3b8';
  13786. ctx.font = '10px monospace';
  13787. ctx.textAlign = 'right';
  13788. const gridSteps = 4;
  13789. for (let i = 0; i <= gridSteps; i++) {
  13790. const val = (maxRate / gridSteps) * i;
  13791. const y = paddingTop + chartH - (i / gridSteps) * chartH;
  13792. ctx.beginPath();
  13793. ctx.moveTo(paddingLeft, y);
  13794. ctx.lineTo(width - paddingRight, y);
  13795. ctx.stroke();
  13796. ctx.fillText(`${Math.round(val)}M`, paddingLeft - 8, y + 3);
  13797. }
  13798. // Draw TX Line (Cyan #22d3ee)
  13799. drawSeries(ctx, points, p => p.tx, maxRate, paddingLeft, paddingTop, chartW, chartH, '#22d3ee', 'rgba(34, 211, 238, 0.15)');
  13800. // Draw RX Line (Purple #a855f7)
  13801. drawSeries(ctx, points, p => p.rx, maxRate, paddingLeft, paddingTop, chartW, chartH, '#a855f7', 'rgba(168, 85, 247, 0.15)');
  13802. }
  13803. function drawSeries(ctx, points, valFn, maxVal, left, top, w, h, strokeColor, fillColor) {
  13804. if (points.length < 2) return;
  13805. const stepX = w / Math.max(points.length - 1, 1);
  13806. // Gradient area fill
  13807. const grad = ctx.createLinearGradient(0, top, 0, top + h);
  13808. grad.addColorStop(0, fillColor);
  13809. grad.addColorStop(1, 'rgba(0, 0, 0, 0)');
  13810. ctx.beginPath();
  13811. points.forEach((p, idx) => {
  13812. const x = left + idx * stepX;
  13813. const val = valFn(p);
  13814. const y = top + h - (val / maxVal) * h;
  13815. if (idx === 0) {
  13816. ctx.moveTo(x, y);
  13817. } else {
  13818. ctx.lineTo(x, y);
  13819. }
  13820. });
  13821. // Complete path for fill
  13822. ctx.lineTo(left + (points.length - 1) * stepX, top + h);
  13823. ctx.lineTo(left, top + h);
  13824. ctx.closePath();
  13825. ctx.fillStyle = grad;
  13826. ctx.fill();
  13827. // Draw line stroke
  13828. ctx.beginPath();
  13829. ctx.lineWidth = 2.5;
  13830. ctx.strokeStyle = strokeColor;
  13831. points.forEach((p, idx) => {
  13832. const x = left + idx * stepX;
  13833. const val = valFn(p);
  13834. const y = top + h - (val / maxVal) * h;
  13835. if (idx === 0) {
  13836. ctx.moveTo(x, y);
  13837. } else {
  13838. ctx.lineTo(x, y);
  13839. }
  13840. });
  13841. ctx.stroke();
  13842. // Draw end point halo
  13843. const lastP = points[points.length - 1];
  13844. const lastX = left + (points.length - 1) * stepX;
  13845. const lastY = top + h - (valFn(lastP) / maxVal) * h;
  13846. ctx.fillStyle = strokeColor;
  13847. ctx.beginPath();
  13848. ctx.arc(lastX, lastY, 4, 0, 2 * Math.PI);
  13849. ctx.fill();
  13850. }
  13851. async function loadBwTestHistory() {
  13852. try {
  13853. const res = await fetch(`${API_BASE}/tools/bwtest/history`);
  13854. if (!res.ok) return;
  13855. const list = await res.json();
  13856. renderBwTestHistory(Array.isArray(list) ? list : []);
  13857. } catch (err) {
  13858. console.error('Failed to load BwTest history:', err);
  13859. }
  13860. }
  13861. function renderBwTestHistory(list) {
  13862. const tbody = document.getElementById('bwtest-history-tbody');
  13863. if (!tbody) return;
  13864. if (list.length === 0) {
  13865. 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>`;
  13866. return;
  13867. }
  13868. tbody.innerHTML = '';
  13869. list.forEach(item => {
  13870. const s = item.summary || {};
  13871. const tr = document.createElement('tr');
  13872. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  13873. const dirBadge = item.direction === 'both'
  13874. ? `<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>`
  13875. : item.direction === 'tx'
  13876. ? `<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>`
  13877. : `<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>`;
  13878. const protoBadge = item.protocol === 'tcp'
  13879. ? `<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>`
  13880. : `<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>`;
  13881. const dateStr = item.timestamp ? new Date(item.timestamp).toLocaleString() : '-';
  13882. tr.innerHTML = `
  13883. <td class="py-2.5 px-4 font-bold text-white font-mono text-[11px]">${escapeHtml(item.id || '-')}</td>
  13884. <td class="py-2.5 px-4 text-emerald-400 font-mono font-medium">${escapeHtml(item.target || '-')}</td>
  13885. <td class="py-2.5 px-4">${protoBadge}</td>
  13886. <td class="py-2.5 px-4">${dirBadge}</td>
  13887. <td class="py-2.5 px-4 text-slate-300">${(s.duration_sec || 0).toFixed(1)}s</td>
  13888. <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>
  13889. <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>
  13890. <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>
  13891. <td class="py-2.5 px-4 text-slate-300 font-mono">${(s.avg_jitter_ms || 0).toFixed(2)} ms</td>
  13892. <td class="py-2.5 px-4 text-slate-400 text-[11px] font-sans">${escapeHtml(dateStr)}</td>
  13893. `;
  13894. tbody.appendChild(tr);
  13895. });
  13896. }
  13897. // ======================== SETTINGS & ROUTER DNS ========================
  13898. state.settingsSubTab = 'dns';
  13899. state.dnsSettings = null;
  13900. state.dnsStaticRecords = [];
  13901. state.dnsStatus = null;
  13902. function switchSettingsSubTab(sub) {
  13903. state.settingsSubTab = sub;
  13904. const btnDns = document.getElementById('btn-settings-subtab-dns');
  13905. const btnSys = document.getElementById('btn-settings-subtab-system');
  13906. const tabDns = document.getElementById('settings-subtab-dns');
  13907. const tabSys = document.getElementById('settings-subtab-system');
  13908. if (sub === 'dns') {
  13909. if (btnDns) {
  13910. 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';
  13911. }
  13912. if (btnSys) {
  13913. 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';
  13914. }
  13915. tabDns?.classList.remove('hidden');
  13916. tabSys?.classList.add('hidden');
  13917. loadDNSSettings();
  13918. } else {
  13919. if (btnSys) {
  13920. 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';
  13921. }
  13922. if (btnDns) {
  13923. 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';
  13924. }
  13925. tabSys?.classList.remove('hidden');
  13926. tabDns?.classList.add('hidden');
  13927. loadSystemSettings();
  13928. }
  13929. }
  13930. async function loadSettingsData(showLoading = false) {
  13931. if (state.settingsSubTab === 'system') {
  13932. await loadSystemSettings();
  13933. } else {
  13934. await loadDNSSettings();
  13935. }
  13936. }
  13937. async function loadDNSSettings() {
  13938. try {
  13939. const [settingsRes, staticRes, statusRes] = await Promise.all([
  13940. fetch(`${API_BASE}/dns/settings`),
  13941. fetch(`${API_BASE}/dns/static`),
  13942. fetch(`${API_BASE}/dns/status`)
  13943. ]);
  13944. if (settingsRes.ok) {
  13945. state.dnsSettings = await settingsRes.json();
  13946. populateDNSSettingsForm(state.dnsSettings);
  13947. }
  13948. if (staticRes.ok) {
  13949. state.dnsStaticRecords = await staticRes.json();
  13950. renderStaticDNSList();
  13951. }
  13952. if (statusRes.ok) {
  13953. state.dnsStatus = await statusRes.json();
  13954. updateDNSStatusView(state.dnsStatus);
  13955. }
  13956. } catch (err) {
  13957. console.error('Failed to load DNS settings:', err);
  13958. }
  13959. }
  13960. function populateDNSSettingsForm(s) {
  13961. if (!s) return;
  13962. const dnsForm = document.getElementById('form-dns-settings');
  13963. const isEditing = dnsForm && (dnsForm.contains(document.activeElement) || dnsForm.dataset.dirty === 'true');
  13964. const dynamicEl = document.getElementById('dns-dynamic-servers-list');
  13965. if (dynamicEl) {
  13966. if (Array.isArray(s.dynamic_servers) && s.dynamic_servers.length > 0) {
  13967. 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(' ');
  13968. } else {
  13969. dynamicEl.innerText = 'None';
  13970. }
  13971. }
  13972. // If user is actively typing or editing in the form, do not overwrite their inputs!
  13973. if (isEditing) return;
  13974. const serversInput = document.getElementById('dns-servers-input');
  13975. if (serversInput) serversInput.value = (s.servers || []).join(', ');
  13976. const cacheSizeInput = document.getElementById('dns-cache-size-input');
  13977. if (cacheSizeInput) cacheSizeInput.value = s.cache_size || 2048;
  13978. const domainInput = document.getElementById('dns-domain-input');
  13979. if (domainInput) domainInput.value = s.domain || '';
  13980. const allowRemoteInput = document.getElementById('dns-allow-remote-input');
  13981. if (allowRemoteInput) allowRemoteInput.checked = s.allow_remote_requests !== false;
  13982. }
  13983. function updateDNSStatusView(st) {
  13984. if (!st) return;
  13985. const preview = document.getElementById('dns-resolv-preview');
  13986. if (preview) preview.innerText = st.resolv_conf_content || '(empty)';
  13987. const pillText = document.getElementById('dns-live-status-text');
  13988. const pill = document.getElementById('dns-live-status-pill');
  13989. if (pill && pillText) {
  13990. if (st.service_running) {
  13991. 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';
  13992. pillText.innerText = 'DNS Service Active';
  13993. } else {
  13994. 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';
  13995. pillText.innerText = 'DNS Service Inactive';
  13996. }
  13997. }
  13998. }
  13999. function appendDNSPreset(preset) {
  14000. const input = document.getElementById('dns-servers-input');
  14001. if (!input) return;
  14002. const dnsForm = document.getElementById('form-dns-settings');
  14003. if (dnsForm) dnsForm.dataset.dirty = 'true';
  14004. const current = input.value.trim();
  14005. if (!current) {
  14006. input.value = preset;
  14007. } else {
  14008. const existing = current.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  14009. const toAdd = preset.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  14010. toAdd.forEach(ip => {
  14011. if (!existing.includes(ip)) existing.push(ip);
  14012. });
  14013. input.value = existing.join(', ');
  14014. }
  14015. }
  14016. async function saveDNSSettings(e) {
  14017. e.preventDefault();
  14018. const rawServers = document.getElementById('dns-servers-input')?.value || '';
  14019. const servers = rawServers.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  14020. if (servers.length === 0) {
  14021. showToast('Validation Error', 'Please enter at least one upstream DNS server IP', 'error');
  14022. return;
  14023. }
  14024. const cacheSize = parseInt(document.getElementById('dns-cache-size-input')?.value || '2048', 10);
  14025. const domain = (document.getElementById('dns-domain-input')?.value || '').trim();
  14026. const allowRemote = document.getElementById('dns-allow-remote-input')?.checked ?? true;
  14027. try {
  14028. const res = await fetch(`${API_BASE}/dns/settings`, {
  14029. method: 'POST',
  14030. headers: { 'Content-Type': 'application/json' },
  14031. body: JSON.stringify({
  14032. servers: servers,
  14033. cache_size: cacheSize,
  14034. domain: domain,
  14035. allow_remote_requests: allowRemote
  14036. })
  14037. });
  14038. const data = await res.json();
  14039. if (res.ok) {
  14040. const dnsForm = document.getElementById('form-dns-settings');
  14041. if (dnsForm) dnsForm.dataset.dirty = 'false';
  14042. showToast('DNS Applied', 'Router DNS forwarders and resolver settings updated successfully', 'success');
  14043. loadDNSSettings();
  14044. } else {
  14045. showToast('Error', data.error || data.message || 'Failed to save DNS settings', 'error');
  14046. }
  14047. } catch (err) {
  14048. showToast('Error', err.message, 'error');
  14049. }
  14050. }
  14051. async function flushDNSCache() {
  14052. try {
  14053. const res = await fetch(`${API_BASE}/dns/flush`, { method: 'POST' });
  14054. if (res.ok) {
  14055. showToast('Cache Flushed', 'Router DNS cache cleared and static hosts reloaded', 'success');
  14056. loadDNSSettings();
  14057. } else {
  14058. const err = await res.json();
  14059. showToast('Error', err.error || 'Failed to flush cache', 'error');
  14060. }
  14061. } catch (err) {
  14062. showToast('Error', err.message, 'error');
  14063. }
  14064. }
  14065. function renderStaticDNSList() {
  14066. const tbody = document.getElementById('dns-static-tbody');
  14067. const empty = document.getElementById('dns-static-empty');
  14068. const badge = document.getElementById('dns-static-count-badge');
  14069. if (!tbody) return;
  14070. tbody.innerHTML = '';
  14071. const records = state.dnsStaticRecords || [];
  14072. if (badge) badge.innerText = `${records.length} Records`;
  14073. if (records.length === 0) {
  14074. empty?.classList.remove('hidden');
  14075. return;
  14076. }
  14077. empty?.classList.add('hidden');
  14078. records.forEach(rec => {
  14079. const tr = document.createElement('tr');
  14080. tr.className = `hover:bg-slate-800/40 transition text-xs ${rec.disabled ? 'opacity-50' : ''}`;
  14081. tr.innerHTML = `
  14082. <td class="py-2.5 px-4 font-bold text-white">${escapeHtml(rec.name)}</td>
  14083. <td class="py-2.5 px-4">
  14084. <span class="px-2 py-0.5 rounded text-[10px] font-bold ${
  14085. rec.type === 'CNAME' ? 'bg-purple-950 text-purple-300 border border-purple-800' :
  14086. (rec.type === 'AAAA' ? 'bg-blue-950 text-blue-300 border border-blue-800' : 'bg-cyan-950 text-cyan-300 border border-cyan-800')
  14087. }">
  14088. ${rec.type || 'A'}
  14089. </span>
  14090. </td>
  14091. <td class="py-2.5 px-4 text-emerald-400 font-mono">${escapeHtml(rec.address)}</td>
  14092. <td class="py-2.5 px-4 text-slate-400 font-mono">${rec.ttl || 3600}s</td>
  14093. <td class="py-2.5 px-4 text-slate-400 italic truncate max-w-[140px]">${escapeHtml(rec.comment || '-')}</td>
  14094. <td class="py-2.5 px-4">
  14095. <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'}">
  14096. ${rec.disabled ? 'Disabled' : 'Active'}
  14097. </span>
  14098. </td>
  14099. <td class="py-2.5 px-4 text-right space-x-2 font-sans whitespace-nowrap">
  14100. <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>
  14101. <button onclick="openStaticDNSModal('${rec.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold">Edit</button>
  14102. <button onclick="deleteStaticDNS('${rec.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  14103. </td>
  14104. `;
  14105. tbody.appendChild(tr);
  14106. });
  14107. }
  14108. function openStaticDNSModal(id = null) {
  14109. const modal = document.getElementById('modal-static-dns');
  14110. const title = document.getElementById('modal-static-dns-title');
  14111. const form = document.getElementById('form-static-dns');
  14112. if (!modal || !form) return;
  14113. form.reset();
  14114. document.getElementById('modal-static-dns-id').value = '';
  14115. if (id) {
  14116. const rec = (state.dnsStaticRecords || []).find(r => r.id === id);
  14117. if (rec) {
  14118. if (title) title.innerText = 'Edit Static DNS Record';
  14119. document.getElementById('modal-static-dns-id').value = rec.id;
  14120. document.getElementById('modal-static-dns-name').value = rec.name;
  14121. document.getElementById('modal-static-dns-type').value = rec.type || 'A';
  14122. document.getElementById('modal-static-dns-addr').value = rec.address;
  14123. document.getElementById('modal-static-dns-ttl').value = rec.ttl || 3600;
  14124. document.getElementById('modal-static-dns-comment').value = rec.comment || '';
  14125. document.getElementById('modal-static-dns-disabled').checked = !!rec.disabled;
  14126. }
  14127. } else {
  14128. if (title) title.innerText = 'Add Static DNS Record';
  14129. }
  14130. modal.classList.remove('hidden');
  14131. }
  14132. function closeStaticDNSModal() {
  14133. document.getElementById('modal-static-dns')?.classList.add('hidden');
  14134. }
  14135. async function submitSaveStaticDNS(e) {
  14136. e.preventDefault();
  14137. const id = document.getElementById('modal-static-dns-id')?.value || '';
  14138. const name = (document.getElementById('modal-static-dns-name')?.value || '').trim();
  14139. const type = document.getElementById('modal-static-dns-type')?.value || 'A';
  14140. const address = (document.getElementById('modal-static-dns-addr')?.value || '').trim();
  14141. const ttl = parseInt(document.getElementById('modal-static-dns-ttl')?.value || '3600', 10);
  14142. const comment = (document.getElementById('modal-static-dns-comment')?.value || '').trim();
  14143. const disabled = document.getElementById('modal-static-dns-disabled')?.checked ?? false;
  14144. if (!name || !address) {
  14145. showToast('Validation Error', 'Name and Target Address are required', 'error');
  14146. return;
  14147. }
  14148. try {
  14149. const res = await fetch(`${API_BASE}/dns/static`, {
  14150. method: 'POST',
  14151. headers: { 'Content-Type': 'application/json' },
  14152. body: JSON.stringify({ id, name, type, address, ttl, comment, disabled })
  14153. });
  14154. const data = await res.json();
  14155. if (res.ok) {
  14156. showToast('Static DNS Saved', `Saved record ${name} -> ${address}`, 'success');
  14157. closeStaticDNSModal();
  14158. loadDNSSettings();
  14159. } else {
  14160. showToast('Error', data.error || data.message || 'Failed to save record', 'error');
  14161. }
  14162. } catch (err) {
  14163. showToast('Error', err.message, 'error');
  14164. }
  14165. }
  14166. async function deleteStaticDNS(id) {
  14167. if (!confirm('Are you sure you want to delete this static DNS entry?')) return;
  14168. try {
  14169. const res = await fetch(`${API_BASE}/dns/static/${encodeURIComponent(id)}`, { method: 'DELETE' });
  14170. if (res.ok) {
  14171. showToast('Deleted', 'Static DNS record deleted', 'success');
  14172. loadDNSSettings();
  14173. }
  14174. } catch (err) {
  14175. showToast('Error', err.message, 'error');
  14176. }
  14177. }
  14178. async function toggleStaticDNS(id, disabled) {
  14179. try {
  14180. const res = await fetch(`${API_BASE}/dns/static/${encodeURIComponent(id)}/state`, {
  14181. method: 'POST',
  14182. headers: { 'Content-Type': 'application/json' },
  14183. body: JSON.stringify({ disabled })
  14184. });
  14185. if (res.ok) {
  14186. showToast('Updated', `Record ${disabled ? 'disabled' : 'enabled'}`, 'success');
  14187. loadDNSSettings();
  14188. }
  14189. } catch (err) {
  14190. showToast('Error', err.message, 'error');
  14191. }
  14192. }
  14193. async function loadSystemSettings() {
  14194. try {
  14195. const sysForm = document.getElementById('form-system-settings');
  14196. const isEditing = sysForm && (sysForm.contains(document.activeElement) || sysForm.dataset.dirty === 'true');
  14197. const res = await fetch(`${API_BASE}/system/settings`);
  14198. if (res.ok) {
  14199. const data = await res.json();
  14200. if (!isEditing) {
  14201. const hostInput = document.getElementById('system-hostname-input');
  14202. if (hostInput) hostInput.value = data.hostname || '';
  14203. const tzInput = document.getElementById('system-timezone-input');
  14204. if (tzInput && data.timezone) tzInput.value = data.timezone;
  14205. }
  14206. }
  14207. } catch (err) {
  14208. console.error('Failed to load system settings:', err);
  14209. }
  14210. }
  14211. async function saveSystemSettings(e) {
  14212. e.preventDefault();
  14213. const hostname = (document.getElementById('system-hostname-input')?.value || '').trim();
  14214. const timezone = document.getElementById('system-timezone-input')?.value || 'UTC';
  14215. try {
  14216. const res = await fetch(`${API_BASE}/system/settings`, {
  14217. method: 'POST',
  14218. headers: { 'Content-Type': 'application/json' },
  14219. body: JSON.stringify({ hostname, timezone })
  14220. });
  14221. const data = await res.json();
  14222. if (res.ok) {
  14223. const sysForm = document.getElementById('form-system-settings');
  14224. if (sysForm) sysForm.dataset.dirty = 'false';
  14225. showToast('System Updated', 'Hostname and timezone saved successfully', 'success');
  14226. const sideH = document.getElementById('side-hostname');
  14227. if (sideH) sideH.innerText = data.hostname;
  14228. } else {
  14229. showToast('Error', data.error || 'Failed to save system settings', 'error');
  14230. }
  14231. } catch (err) {
  14232. showToast('Error', err.message, 'error');
  14233. }
  14234. }
  14235. // =============================================================================
  14236. // AUTHENTICATION & USER MANAGER
  14237. // =============================================================================
  14238. async function checkAuthStatus() {
  14239. try {
  14240. const res = await originalFetch(`${API_BASE}/auth/me`, {
  14241. headers: {
  14242. 'Authorization': `Bearer ${localStorage.getItem('debtik_token') || ''}`
  14243. }
  14244. });
  14245. if (res.ok) {
  14246. const user = await res.json();
  14247. state.currentUser = user;
  14248. updateUserProfileHeader(user);
  14249. hideLoginScreen();
  14250. state.isPolling = true;
  14251. fetchData();
  14252. initLiveTrafficStream();
  14253. return true;
  14254. } else {
  14255. showLoginScreen(false);
  14256. return false;
  14257. }
  14258. } catch (err) {
  14259. showLoginScreen(false);
  14260. return false;
  14261. }
  14262. }
  14263. function showLoginScreen(isExpired = false) {
  14264. const el = document.getElementById('login-screen');
  14265. if (el) el.classList.remove('hidden');
  14266. const errEl = document.getElementById('login-error');
  14267. const errTxt = document.getElementById('login-error-text');
  14268. if (isExpired && errEl && errTxt) {
  14269. errTxt.innerText = 'Session expired. Please sign in again.';
  14270. errEl.classList.remove('hidden');
  14271. } else if (errEl) {
  14272. errEl.classList.add('hidden');
  14273. }
  14274. const pwInput = document.getElementById('login-password');
  14275. if (pwInput) pwInput.value = '';
  14276. const userInput = document.getElementById('login-username');
  14277. if (userInput && !userInput.value) userInput.focus();
  14278. else if (pwInput) pwInput.focus();
  14279. }
  14280. function hideLoginScreen() {
  14281. const el = document.getElementById('login-screen');
  14282. if (el) el.classList.add('hidden');
  14283. const errEl = document.getElementById('login-error');
  14284. if (errEl) errEl.classList.add('hidden');
  14285. }
  14286. async function handleLoginSubmit(event) {
  14287. event.preventDefault();
  14288. const username = (document.getElementById('login-username')?.value || '').trim();
  14289. const password = document.getElementById('login-password')?.value || '';
  14290. const errEl = document.getElementById('login-error');
  14291. const errTxt = document.getElementById('login-error-text');
  14292. const btn = document.getElementById('login-submit-btn');
  14293. const btnText = document.getElementById('login-btn-text');
  14294. const spinner = document.getElementById('login-btn-spinner');
  14295. if (!username || !password) {
  14296. if (errTxt) errTxt.innerText = 'Username and password are required.';
  14297. if (errEl) errEl.classList.remove('hidden');
  14298. return;
  14299. }
  14300. if (errEl) errEl.classList.add('hidden');
  14301. if (btn) btn.disabled = true;
  14302. if (btnText) btnText.innerText = 'Authenticating...';
  14303. if (spinner) spinner.classList.remove('hidden');
  14304. try {
  14305. const res = await originalFetch(`${API_BASE}/auth/login`, {
  14306. method: 'POST',
  14307. headers: { 'Content-Type': 'application/json' },
  14308. body: JSON.stringify({ username, password })
  14309. });
  14310. const data = await res.json();
  14311. if (res.ok && data.success) {
  14312. localStorage.setItem('debtik_token', data.token);
  14313. state.currentUser = data.user;
  14314. updateUserProfileHeader(data.user);
  14315. hideLoginScreen();
  14316. state.isPolling = true;
  14317. showToast('Authenticated', `Signed in as ${data.user.username}`, 'success');
  14318. fetchData();
  14319. initLiveTrafficStream();
  14320. } else {
  14321. if (errTxt) errTxt.innerText = data.message || 'Invalid username or password';
  14322. if (errEl) errEl.classList.remove('hidden');
  14323. }
  14324. } catch (err) {
  14325. if (errTxt) errTxt.innerText = err.message || 'Failed to connect to router';
  14326. if (errEl) errEl.classList.remove('hidden');
  14327. } finally {
  14328. if (btn) btn.disabled = false;
  14329. if (btnText) btnText.innerText = 'Sign In to Controller';
  14330. if (spinner) spinner.classList.add('hidden');
  14331. }
  14332. }
  14333. async function handleLogoutClick() {
  14334. try {
  14335. await originalFetch(`${API_BASE}/auth/logout`, {
  14336. method: 'POST',
  14337. headers: {
  14338. 'Authorization': `Bearer ${localStorage.getItem('debtik_token') || ''}`
  14339. }
  14340. });
  14341. } catch (e) {}
  14342. localStorage.removeItem('debtik_token');
  14343. state.currentUser = null;
  14344. state.isPolling = false;
  14345. if (trafficEventSource) {
  14346. trafficEventSource.close();
  14347. trafficEventSource = null;
  14348. }
  14349. if (trafficPollFallback) {
  14350. clearInterval(trafficPollFallback);
  14351. trafficPollFallback = null;
  14352. }
  14353. showLoginScreen(false);
  14354. showToast('Signed Out', 'You have been signed out successfully', 'info');
  14355. }
  14356. function togglePasswordVisibility(id) {
  14357. const input = document.getElementById(id);
  14358. if (!input) return;
  14359. input.type = input.type === 'password' ? 'text' : 'password';
  14360. }
  14361. function toggleUserMenu() {
  14362. const menu = document.getElementById('user-menu-dropdown');
  14363. if (menu) menu.classList.toggle('hidden');
  14364. }
  14365. function closeUserMenu() {
  14366. const menu = document.getElementById('user-menu-dropdown');
  14367. if (menu) menu.classList.add('hidden');
  14368. }
  14369. // Close user menu on outside click
  14370. document.addEventListener('click', (e) => {
  14371. const menu = document.getElementById('user-menu-dropdown');
  14372. if (!menu || menu.classList.contains('hidden')) return;
  14373. if (!e.target.closest('#user-menu-dropdown') && !e.target.closest('button[onclick*="toggleUserMenu"]')) {
  14374. menu.classList.add('hidden');
  14375. }
  14376. });
  14377. function updateUserProfileHeader(user) {
  14378. if (!user) return;
  14379. const navName = document.getElementById('nav-user-name');
  14380. if (navName) navName.innerText = user.username;
  14381. const dropName = document.getElementById('dropdown-user-name');
  14382. if (dropName) dropName.innerText = user.username;
  14383. const navRole = document.getElementById('nav-user-role');
  14384. if (navRole) navRole.innerText = (user.role || 'read').toUpperCase();
  14385. const navAvatar = document.getElementById('nav-user-avatar');
  14386. if (navAvatar) {
  14387. const initials = (user.username || 'AD').slice(0, 2).toUpperCase();
  14388. navAvatar.innerText = initials;
  14389. }
  14390. const statCurUser = document.getElementById('stat-current-user');
  14391. if (statCurUser) statCurUser.innerText = user.username;
  14392. const statCurRole = document.getElementById('stat-current-role');
  14393. if (statCurRole) statCurRole.innerText = (user.role || 'read').toUpperCase();
  14394. }
  14395. // ================= User Management CRUD =================
  14396. async function loadUsers(isManual = false) {
  14397. try {
  14398. const res = await fetch(`${API_BASE}/users`);
  14399. if (res.status === 403) {
  14400. const tbody = document.getElementById('users-table-tbody');
  14401. if (tbody) {
  14402. tbody.innerHTML = `
  14403. <tr>
  14404. <td colspan="6" class="p-6 text-center text-amber-400 font-sans">
  14405. <div class="inline-flex items-center gap-2">
  14406. <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>
  14407. <span>Viewing and managing users requires Super Administrator (full) permissions.</span>
  14408. </div>
  14409. </td>
  14410. </tr>
  14411. `;
  14412. }
  14413. return;
  14414. }
  14415. if (res.ok) {
  14416. state.users = await res.json();
  14417. renderUsersTable();
  14418. const totalUsers = document.getElementById('stat-total-users');
  14419. if (totalUsers) totalUsers.innerText = state.users.length;
  14420. const adminCount = state.users.filter(u => u.role === 'full' && !u.disabled).length;
  14421. const adminUsers = document.getElementById('stat-admin-users');
  14422. if (adminUsers) adminUsers.innerText = adminCount;
  14423. const badgeCount = document.getElementById('badge-users-count');
  14424. if (badgeCount) badgeCount.innerText = state.users.length;
  14425. if (isManual) showToast('Refreshed', 'User list updated', 'info');
  14426. }
  14427. } catch (err) {
  14428. console.error('Failed to load users:', err);
  14429. }
  14430. }
  14431. function renderUsersTable() {
  14432. const tbody = document.getElementById('users-table-tbody');
  14433. const emptyState = document.getElementById('users-empty-state');
  14434. if (!tbody) return;
  14435. tbody.innerHTML = '';
  14436. const query = (document.getElementById('users-search-input')?.value || '').trim().toLowerCase();
  14437. const filtered = (state.users || []).filter(u => {
  14438. if (!query) return true;
  14439. return u.username.toLowerCase().includes(query) ||
  14440. (u.role || '').toLowerCase().includes(query) ||
  14441. (u.comment || '').toLowerCase().includes(query);
  14442. });
  14443. if (filtered.length === 0) {
  14444. if (emptyState) emptyState.classList.remove('hidden');
  14445. return;
  14446. }
  14447. if (emptyState) emptyState.classList.add('hidden');
  14448. const currentAuthUser = state.currentUser?.username || '';
  14449. filtered.forEach(u => {
  14450. const isSelf = u.username === currentAuthUser;
  14451. const isFull = u.role === 'full';
  14452. const isWrite = u.role === 'write';
  14453. 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>`;
  14454. if (isFull) {
  14455. 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>`;
  14456. } else if (isWrite) {
  14457. 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>`;
  14458. }
  14459. const statusBadge = u.disabled
  14460. ? `<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>`
  14461. : `<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>`;
  14462. let lastLoginText = 'Never';
  14463. if (u.last_login_at && !u.last_login_at.startsWith('0001-01-01')) {
  14464. const dt = new Date(u.last_login_at);
  14465. lastLoginText = dt.toLocaleString();
  14466. }
  14467. const initials = u.username.slice(0, 2).toUpperCase();
  14468. const tr = document.createElement('tr');
  14469. tr.className = 'hover:bg-slate-800/40 transition group';
  14470. tr.innerHTML = `
  14471. <td class="py-3 px-4">
  14472. <div class="flex items-center gap-3">
  14473. <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">
  14474. ${initials}
  14475. </div>
  14476. <div>
  14477. <div class="font-bold text-white text-xs flex items-center gap-2">
  14478. <span>${escapeHtml(u.username)}</span>
  14479. ${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>' : ''}
  14480. </div>
  14481. <div class="text-[10px] text-slate-500 font-sans">Created: ${u.created_at ? new Date(u.created_at).toLocaleDateString() : '-'}</div>
  14482. </div>
  14483. </div>
  14484. </td>
  14485. <td class="py-3 px-4 font-sans">
  14486. ${roleBadge}
  14487. </td>
  14488. <td class="py-3 px-4 font-sans">
  14489. ${statusBadge}
  14490. </td>
  14491. <td class="py-3 px-4 text-slate-300 font-sans text-xs">
  14492. ${escapeHtml(u.comment) || '<span class="text-slate-600">-</span>'}
  14493. </td>
  14494. <td class="py-3 px-4 text-slate-400 text-xs">
  14495. ${lastLoginText}
  14496. </td>
  14497. <td class="py-3 px-4 text-right space-x-1.5 font-sans">
  14498. <button onclick="openAdminResetPasswordModal('${escapeHtml(u.username)}')"
  14499. class="p-1.5 rounded-lg text-slate-400 hover:text-amber-400 hover:bg-slate-800 transition" title="Reset User Password">
  14500. <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>
  14501. </button>
  14502. <button onclick="openEditUserModal('${escapeHtml(u.username)}')"
  14503. class="p-1.5 rounded-lg text-slate-400 hover:text-cyan-400 hover:bg-slate-800 transition" title="Edit User">
  14504. <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>
  14505. </button>
  14506. ${!isSelf ? `
  14507. <button onclick="deleteUser('${escapeHtml(u.username)}')"
  14508. class="p-1.5 rounded-lg text-slate-400 hover:text-rose-400 hover:bg-slate-800 transition" title="Delete User">
  14509. <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>
  14510. </button>
  14511. ` : ''}
  14512. </td>
  14513. `;
  14514. tbody.appendChild(tr);
  14515. });
  14516. }
  14517. function openAddUserModal() {
  14518. document.getElementById('user-add-username').value = '';
  14519. document.getElementById('user-add-password').value = '';
  14520. document.getElementById('user-add-confirm').value = '';
  14521. document.getElementById('user-add-role').value = 'full';
  14522. document.getElementById('user-add-comment').value = '';
  14523. document.getElementById('modal-add-user')?.classList.remove('hidden');
  14524. document.getElementById('user-add-username')?.focus();
  14525. }
  14526. function closeAddUserModal() {
  14527. document.getElementById('modal-add-user')?.classList.add('hidden');
  14528. }
  14529. async function submitAddUser(event) {
  14530. event.preventDefault();
  14531. const username = (document.getElementById('user-add-username')?.value || '').trim();
  14532. const password = document.getElementById('user-add-password')?.value || '';
  14533. const confirm = document.getElementById('user-add-confirm')?.value || '';
  14534. const role = document.getElementById('user-add-role')?.value || 'full';
  14535. const comment = (document.getElementById('user-add-comment')?.value || '').trim();
  14536. if (password !== confirm) {
  14537. showToast('Validation Error', 'Passwords do not match', 'warning');
  14538. return;
  14539. }
  14540. if (password.length < 4) {
  14541. showToast('Validation Error', 'Password must be at least 4 characters', 'warning');
  14542. return;
  14543. }
  14544. try {
  14545. const res = await fetch(`${API_BASE}/users`, {
  14546. method: 'POST',
  14547. headers: { 'Content-Type': 'application/json' },
  14548. body: JSON.stringify({ username, password, role, comment })
  14549. });
  14550. const data = await res.json();
  14551. if (res.ok) {
  14552. showToast('User Created', `Created user ${username} with ${role.toUpperCase()} permissions`, 'success');
  14553. closeAddUserModal();
  14554. loadUsers(false);
  14555. } else {
  14556. showToast('Error', data.message || 'Failed to create user', 'error');
  14557. }
  14558. } catch (err) {
  14559. showToast('Error', err.message, 'error');
  14560. }
  14561. }
  14562. function openEditUserModal(username) {
  14563. const user = (state.users || []).find(u => u.username === username);
  14564. if (!user) return;
  14565. document.getElementById('user-edit-username').value = user.username;
  14566. document.getElementById('user-edit-username-title').innerText = `@${user.username}`;
  14567. document.getElementById('user-edit-role').value = user.role || 'read';
  14568. document.getElementById('user-edit-comment').value = user.comment || '';
  14569. document.getElementById('user-edit-disabled').checked = !!user.disabled;
  14570. document.getElementById('modal-edit-user')?.classList.remove('hidden');
  14571. }
  14572. function closeEditUserModal() {
  14573. document.getElementById('modal-edit-user')?.classList.add('hidden');
  14574. }
  14575. async function submitEditUser(event) {
  14576. event.preventDefault();
  14577. const username = document.getElementById('user-edit-username')?.value;
  14578. const role = document.getElementById('user-edit-role')?.value || 'read';
  14579. const comment = (document.getElementById('user-edit-comment')?.value || '').trim();
  14580. const disabled = document.getElementById('user-edit-disabled')?.checked || false;
  14581. try {
  14582. const res = await fetch(`${API_BASE}/users/${encodeURIComponent(username)}`, {
  14583. method: 'PUT',
  14584. headers: { 'Content-Type': 'application/json' },
  14585. body: JSON.stringify({ role, comment, disabled })
  14586. });
  14587. const data = await res.json();
  14588. if (res.ok) {
  14589. showToast('User Updated', `Updated settings for ${username}`, 'success');
  14590. closeEditUserModal();
  14591. loadUsers(false);
  14592. // If updated own role/disabled status, refresh self profile
  14593. if (username === state.currentUser?.username) {
  14594. checkAuthStatus();
  14595. }
  14596. } else {
  14597. showToast('Error', data.message || 'Failed to update user', 'error');
  14598. }
  14599. } catch (err) {
  14600. showToast('Error', err.message, 'error');
  14601. }
  14602. }
  14603. function openAdminResetPasswordModal(username) {
  14604. document.getElementById('admin-reset-username').value = username;
  14605. document.getElementById('admin-reset-username-title').innerText = `@${username}`;
  14606. document.getElementById('admin-reset-new-pw').value = '';
  14607. document.getElementById('admin-reset-confirm-pw').value = '';
  14608. document.getElementById('modal-admin-reset-pw')?.classList.remove('hidden');
  14609. document.getElementById('admin-reset-new-pw')?.focus();
  14610. }
  14611. function closeAdminResetPasswordModal() {
  14612. document.getElementById('modal-admin-reset-pw')?.classList.add('hidden');
  14613. }
  14614. async function submitAdminResetPassword(event) {
  14615. event.preventDefault();
  14616. const username = document.getElementById('admin-reset-username')?.value;
  14617. const newPassword = document.getElementById('admin-reset-new-pw')?.value || '';
  14618. const confirm = document.getElementById('admin-reset-confirm-pw')?.value || '';
  14619. if (newPassword !== confirm) {
  14620. showToast('Validation Error', 'Passwords do not match', 'warning');
  14621. return;
  14622. }
  14623. if (newPassword.length < 4) {
  14624. showToast('Validation Error', 'Password must be at least 4 characters', 'warning');
  14625. return;
  14626. }
  14627. try {
  14628. const res = await fetch(`${API_BASE}/users/${encodeURIComponent(username)}/password`, {
  14629. method: 'POST',
  14630. headers: { 'Content-Type': 'application/json' },
  14631. body: JSON.stringify({ new_password: newPassword })
  14632. });
  14633. const data = await res.json();
  14634. if (res.ok) {
  14635. showToast('Password Reset', `Password for user ${username} updated successfully`, 'success');
  14636. closeAdminResetPasswordModal();
  14637. } else {
  14638. showToast('Error', data.message || 'Failed to reset password', 'error');
  14639. }
  14640. } catch (err) {
  14641. showToast('Error', err.message, 'error');
  14642. }
  14643. }
  14644. async function deleteUser(username) {
  14645. if (username === state.currentUser?.username) {
  14646. showToast('Action Forbidden', 'You cannot delete your own account', 'warning');
  14647. return;
  14648. }
  14649. if (!confirm(`Are you sure you want to completely remove user "${username}"?`)) {
  14650. return;
  14651. }
  14652. try {
  14653. const res = await fetch(`${API_BASE}/users/${encodeURIComponent(username)}`, {
  14654. method: 'DELETE'
  14655. });
  14656. const data = await res.json();
  14657. if (res.ok) {
  14658. showToast('User Deleted', `User ${username} has been removed`, 'success');
  14659. loadUsers(false);
  14660. } else {
  14661. showToast('Error', data.message || 'Failed to delete user', 'error');
  14662. }
  14663. } catch (err) {
  14664. showToast('Error', err.message, 'error');
  14665. }
  14666. }
  14667. function openSelfPasswordModal() {
  14668. document.getElementById('self-current-password').value = '';
  14669. document.getElementById('self-new-password').value = '';
  14670. document.getElementById('self-confirm-password').value = '';
  14671. document.getElementById('modal-self-password')?.classList.remove('hidden');
  14672. document.getElementById('self-current-password')?.focus();
  14673. }
  14674. function closeSelfPasswordModal() {
  14675. document.getElementById('modal-self-password')?.classList.add('hidden');
  14676. }
  14677. async function submitSelfPassword(event) {
  14678. event.preventDefault();
  14679. const oldPassword = document.getElementById('self-current-password')?.value || '';
  14680. const newPassword = document.getElementById('self-new-password')?.value || '';
  14681. const confirm = document.getElementById('self-confirm-password')?.value || '';
  14682. if (newPassword !== confirm) {
  14683. showToast('Validation Error', 'New passwords do not match', 'warning');
  14684. return;
  14685. }
  14686. if (newPassword.length < 4) {
  14687. showToast('Validation Error', 'Password must be at least 4 characters', 'warning');
  14688. return;
  14689. }
  14690. try {
  14691. const res = await fetch(`${API_BASE}/auth/change-password`, {
  14692. method: 'POST',
  14693. headers: { 'Content-Type': 'application/json' },
  14694. body: JSON.stringify({ old_password: oldPassword, new_password: newPassword })
  14695. });
  14696. const data = await res.json();
  14697. if (res.ok) {
  14698. showToast('Password Changed', 'Your password has been changed successfully', 'success');
  14699. closeSelfPasswordModal();
  14700. } else {
  14701. showToast('Error', data.message || 'Failed to change password', 'error');
  14702. }
  14703. } catch (err) {
  14704. showToast('Error', err.message, 'error');
  14705. }
  14706. }