app.js 698 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676
  1. // DebTik - Debian Linux Router Frontend Application Logic
  2. // ================= Interceptor: Automatic Auth Bearer & 401 Handling =================
  3. const originalFetch = window.fetch;
  4. window.fetch = async function(...args) {
  5. let [resource, config] = args;
  6. config = config || {};
  7. // Clone or init headers
  8. let headers = config.headers;
  9. if (!headers) {
  10. headers = {};
  11. config.headers = headers;
  12. }
  13. const token = localStorage.getItem('debtik_token');
  14. if (token) {
  15. if (headers instanceof Headers) {
  16. if (!headers.has('Authorization')) headers.set('Authorization', `Bearer ${token}`);
  17. } else if (Array.isArray(headers)) {
  18. if (!headers.some(([k]) => k.toLowerCase() === 'authorization')) headers.push(['Authorization', `Bearer ${token}`]);
  19. } else {
  20. if (!headers['Authorization']) headers['Authorization'] = `Bearer ${token}`;
  21. }
  22. }
  23. const response = await originalFetch(resource, config);
  24. // If 401 Unauthorized on protected API endpoint, prompt login immediately
  25. if (response.status === 401 && typeof resource === 'string' && resource.includes('/api/') && !resource.includes('/api/auth/login')) {
  26. if (state.currentUser) {
  27. if (window._telemetryInterval) {
  28. clearInterval(window._telemetryInterval);
  29. window._telemetryInterval = null;
  30. }
  31. if (trafficEventSource) {
  32. try { trafficEventSource.close(); } catch(e) {}
  33. trafficEventSource = null;
  34. }
  35. if (trafficPollFallback) {
  36. clearInterval(trafficPollFallback);
  37. trafficPollFallback = null;
  38. }
  39. state.isPolling = false;
  40. state.currentUser = null;
  41. localStorage.removeItem('debtik_token');
  42. showLoginScreen(true);
  43. }
  44. }
  45. return response;
  46. };
  47. let state = {
  48. currentUser: null,
  49. users: [],
  50. interfaces: [],
  51. vlans: [],
  52. systemStatus: null,
  53. vpnStatus: null,
  54. routes: [],
  55. activeTab: 'dashboard',
  56. fwSubTab: 'filter',
  57. bridgeSubTab: 'bridges',
  58. bridges: [],
  59. bridgePorts: [],
  60. bridgeVLANs: [],
  61. bridgeHosts: [],
  62. bridgeSummary: null,
  63. routesSubTab: 'routes',
  64. pppSubTab: 'secrets',
  65. eoipTunnels: [],
  66. pppSecrets: [],
  67. pppProfiles: [],
  68. pppActiveSessions: [],
  69. pppoeServer: null,
  70. pptpServer: null,
  71. l2tpServer: null,
  72. ipsecServer: null,
  73. ifaceFilter: 'all',
  74. currentModalIface: null,
  75. isPolling: false,
  76. expandedParents: new Set(['eth0']),
  77. pppoeData: null,
  78. wgData: null,
  79. ipsecData: null,
  80. l2tpData: null,
  81. pptpData: null,
  82. fwSummary: null,
  83. filterRules: [],
  84. natRules: [],
  85. mangleRules: [],
  86. addressLists: [],
  87. connections: [],
  88. policyRules: [],
  89. routingTables: [],
  90. routingFilters: [],
  91. filterChainSelected: 'all',
  92. activeToolsSubTab: 'ping',
  93. dhcpClients: [],
  94. dhcpSummary: null,
  95. dhcpServerTab: 'servers',
  96. dhcpServers: [],
  97. dhcpNetworks: [],
  98. dhcpLeases: [],
  99. dhcpOptions: [],
  100. dhcpServerSummary: null
  101. };
  102. const API_BASE = '/api';
  103. function escapeHtml(str) {
  104. if (str === null || str === undefined) return '';
  105. return String(str)
  106. .replace(/&/g, '&')
  107. .replace(/</g, '&lt;')
  108. .replace(/>/g, '&gt;')
  109. .replace(/"/g, '&quot;')
  110. .replace(/'/g, '&#039;');
  111. }
  112. function formatBytes(bytes) {
  113. if (bytes === undefined || bytes === null || isNaN(bytes) || bytes === 0) return '0 B';
  114. const k = 1024;
  115. const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
  116. const i = Math.floor(Math.log(bytes) / Math.log(k));
  117. if (i < 0 || i >= sizes.length) return `${bytes} B`;
  118. return `${parseFloat((bytes / Math.pow(k, i)).toFixed(2))} ${sizes[i]}`;
  119. }
  120. // Initialize on page load
  121. document.addEventListener('DOMContentLoaded', async () => {
  122. initTableSorting();
  123. // Verify authentication before bootstrapping telemetry and views
  124. const isAuthenticated = await checkAuthStatus();
  125. if (isAuthenticated) {
  126. const hash = window.location.hash.replace('#', '') || 'dashboard';
  127. navigate(hash);
  128. // Full state telemetry polling every 5 seconds (smooth & flicker-free)
  129. if (!window._telemetryInterval) {
  130. window._telemetryInterval = setInterval(() => {
  131. if (state.isPolling && state.currentUser) {
  132. fetchData(false);
  133. }
  134. }, 5000);
  135. }
  136. }
  137. });
  138. let trafficEventSource = null;
  139. let trafficPollFallback = null;
  140. function initLiveTrafficStream() {
  141. if (trafficEventSource) {
  142. try { trafficEventSource.close(); } catch(e) {}
  143. trafficEventSource = null;
  144. }
  145. if (trafficPollFallback) {
  146. clearInterval(trafficPollFallback);
  147. trafficPollFallback = null;
  148. }
  149. if (window.EventSource) {
  150. try {
  151. trafficEventSource = new EventSource(`${API_BASE}/interfaces/traffic/stream`);
  152. trafficEventSource.onmessage = (event) => {
  153. try {
  154. const data = JSON.parse(event.data);
  155. updateLiveInterfaceTraffic(data);
  156. } catch (e) {
  157. console.error('Error parsing live traffic event:', e);
  158. }
  159. };
  160. trafficEventSource.onerror = () => {
  161. // Fallback polling if SSE disconnects
  162. if (!trafficPollFallback) {
  163. trafficPollFallback = setInterval(pollLiveTrafficSnapshot, 1000);
  164. }
  165. };
  166. trafficEventSource.onopen = () => {
  167. if (trafficPollFallback) {
  168. clearInterval(trafficPollFallback);
  169. trafficPollFallback = null;
  170. }
  171. };
  172. return;
  173. } catch (e) {
  174. console.warn('EventSource failed, using 1s polling fallback:', e);
  175. }
  176. }
  177. // Fallback if EventSource is unavailable
  178. trafficPollFallback = setInterval(pollLiveTrafficSnapshot, 1000);
  179. }
  180. async function pollLiveTrafficSnapshot() {
  181. try {
  182. const res = await fetch(`${API_BASE}/interfaces/traffic/rates`);
  183. if (res.ok) {
  184. const data = await res.json();
  185. updateLiveInterfaceTraffic(data);
  186. }
  187. } catch (e) {}
  188. }
  189. function updateLiveInterfaceTraffic(data) {
  190. if (!data || !data.interfaces) return;
  191. state.latestTraffic = data;
  192. // 1. Update Top & Dashboard Total Bandwidth Indicators
  193. const rxHuman = data.total_rx_human || '0 B/s';
  194. const txHuman = data.total_tx_human || '0 B/s';
  195. const statRx = document.getElementById('stat-traffic-rx');
  196. if (statRx && statRx.innerText !== rxHuman) statRx.innerText = rxHuman;
  197. const statTx = document.getElementById('stat-traffic-tx');
  198. if (statTx && statTx.innerText !== txHuman) statTx.innerText = txHuman;
  199. // 2. Update state.interfaces rates in-memory
  200. if (Array.isArray(state.interfaces)) {
  201. state.interfaces.forEach(i => {
  202. const live = data.interfaces[i.name];
  203. if (live) {
  204. i.rate = {
  205. rx_bytes_sec: live.rx_bytes_sec,
  206. tx_bytes_sec: live.tx_bytes_sec,
  207. rx_human: live.rx_human,
  208. tx_human: live.tx_human
  209. };
  210. i.stats = {
  211. rx_bytes: live.rx_bytes,
  212. tx_bytes: live.tx_bytes,
  213. rx_packets: live.rx_packets,
  214. tx_packets: live.tx_packets,
  215. rx_errors: live.rx_errors,
  216. tx_errors: live.tx_errors,
  217. rx_dropped: live.rx_dropped,
  218. tx_dropped: live.tx_dropped
  219. };
  220. }
  221. });
  222. }
  223. // 3. Update all live UI rate spans in-place (ZERO flicker)
  224. Object.keys(data.interfaces).forEach(name => {
  225. const live = data.interfaces[name];
  226. // Dashboard Port Matrix Card
  227. const cardRate = document.getElementById(`port-card-rate-${name}`);
  228. if (cardRate && cardRate.innerText !== live.rx_human) {
  229. cardRate.innerText = live.rx_human;
  230. }
  231. // Dashboard Quick Interfaces Table
  232. const quickRx = document.getElementById(`quick-rx-${name}`);
  233. if (quickRx) quickRx.innerText = `↓ ${live.rx_human}`;
  234. const quickTx = document.getElementById(`quick-tx-${name}`);
  235. if (quickTx) quickTx.innerText = `↑ ${live.tx_human}`;
  236. // Main Interfaces Tree Table
  237. const ifaceRx = document.getElementById(`iface-rate-rx-${name}`);
  238. if (ifaceRx) ifaceRx.innerText = `↓ ${live.rx_human}`;
  239. const ifaceTx = document.getElementById(`iface-rate-tx-${name}`);
  240. if (ifaceTx) ifaceTx.innerText = `↑ ${live.tx_human}`;
  241. // VLAN Sub-interfaces Table
  242. const vlanRx = document.getElementById(`vlan-rate-rx-${name}`);
  243. if (vlanRx) vlanRx.innerText = `↓ ${live.rx_human}`;
  244. const vlanTx = document.getElementById(`vlan-rate-tx-${name}`);
  245. if (vlanTx) vlanTx.innerText = `↑ ${live.tx_human}`;
  246. // VLAN Page Table
  247. const vlanPageRx = document.getElementById(`vlan-page-rate-rx-${name}`);
  248. if (vlanPageRx) vlanPageRx.innerText = `↓ ${live.rx_human}`;
  249. const vlanPageTx = document.getElementById(`vlan-page-rate-tx-${name}`);
  250. if (vlanPageTx) vlanPageTx.innerText = `↑ ${live.tx_human}`;
  251. });
  252. }
  253. // Navigation Handler
  254. function navigate(tabName) {
  255. if (tabName === 'dynamic-routing' || tabName === 'routing') {
  256. navigate('bgp');
  257. return;
  258. }
  259. if (tabName === 'vlans') {
  260. navigate('interfaces');
  261. return;
  262. }
  263. state.activeTab = tabName;
  264. window.location.hash = tabName;
  265. // Update nav links styling
  266. document.querySelectorAll('.nav-link').forEach(link => {
  267. link.className = 'nav-link flex items-center justify-between px-3 py-2 rounded-lg text-xs font-medium transition-all group text-slate-300 hover:bg-slate-800/80 hover:text-white';
  268. });
  269. const activeNav = document.getElementById(`nav-${tabName}`);
  270. if (activeNav) {
  271. activeNav.className = 'nav-link flex items-center justify-between px-3 py-2 rounded-lg text-xs font-medium transition-all group bg-brand-500/10 text-brand-400 border border-brand-500/20';
  272. }
  273. // Update page headers
  274. const titles = {
  275. dashboard: { title: 'Dashboard Overview', sub: 'Live router performance and network telemetry' },
  276. interfaces: { title: 'Network Interfaces', sub: 'Interface Table View' },
  277. 'dhcp-client': { title: 'DHCP Client', sub: 'DHCP Client List' },
  278. 'dhcp-server': { title: 'DHCP Server & Subnets', sub: 'DHCP Server instances, subnet networks (NTP, TFTP, DNS), dynamic leases & static reservations' },
  279. bridge: { title: 'Bridge Interfaces', sub: 'IEEE 802.1D / 802.1Q VLAN-aware Layer 2 switching, RSTP & hardware forwarding (FDB)' },
  280. vlans: { title: 'VLAN Virtual Networks', sub: 'IEEE 802.1Q sub-interface segmentation and routing' },
  281. firewall: { title: 'Network Firewall', sub: 'Stateful packet inspection, NAT, traffic mangle, address lists & connection tracking' },
  282. routes: { title: 'Routing & Policy', sub: 'Routing tables, static routes (DAS/DAC), and policy routing rules' },
  283. bgp: { title: 'BGP Dynamic Routing', sub: 'BGP multi-instance peering sessions, advertised networks, and routing table (RIB)' },
  284. ospf: { title: 'OSPF Dynamic Routing', sub: 'OSPFv2 link-state routing, dynamic neighbor adjacencies, and multi-area topology' },
  285. 'routing-filters': { title: 'Routing Policy Filters', sub: 'Route filter chains, prefix matching, BGP community maps & policy-based path control' },
  286. 'dynamic-routing': { title: 'BGP Dynamic Routing', sub: 'Dynamic routing engine and peering sessions' },
  287. ppp: { title: 'PPP Servers & Secrets', sub: 'Subscriber authentication, dynamic IP pools and VPN access concentrators' },
  288. eoip: { title: 'EoIP Tunnels', sub: 'Ethernet over IP (EoIP / GRETAP) Layer 2 encapsulation & transparent network bridging' },
  289. aerotun: { title: 'AeroTUN High-Speed VPN', sub: 'Ultra-fast Layer 3 encrypted tunnel with ChaCha20-Poly1305 and live Adaptive LZ4 compression' },
  290. pppoe: { title: 'PPPoE Client WAN', sub: 'Point-to-Point Protocol over Ethernet WAN access' },
  291. wireguard: { title: 'WireGuard VPN', sub: 'High-performance cryptographic Layer 3 tunnels with ChaCha20-Poly1305 key exchange' },
  292. ipsec: { title: 'IPSec (IKEv2) strongSwan', sub: 'Enterprise Site-to-Site & Roadwarrior IPSec controller' },
  293. l2tp: { title: 'L2TP VPN Client', sub: 'Layer 2 Tunneling Protocol via xl2tpd' },
  294. pptp: { title: 'PPTP VPN Client', sub: 'Point-to-Point Tunneling Protocol with MPPE-128 encryption' },
  295. vrrp: { title: 'VRRP High Availability', sub: 'Virtual Router Redundancy Protocol, active-backup gateway failover & Virtual IP (VIP) routing' },
  296. bwtest: { title: 'Bandwidth Test Benchmark', sub: 'High-speed line-rate throughput benchmark, token-bucket rate limiting, loss & jitter telemetry' },
  297. tools: { title: 'Diagnostic & Troubleshooting Tools', sub: 'Network latency analysis, ICMP/MTR telemetry, path tracing, DNS resolution and TCP probing' },
  298. persistence: { title: 'Debian Configuration', sub: 'Native /etc/network/interfaces.d/ persistence manager' },
  299. settings: { title: 'Router Settings & DNS', sub: 'System DNS forwarder, upstream resolvers, static host mappings, and appliance identity' },
  300. users: { title: 'Local User Manager', sub: 'Manage local system administrator credentials and access permissions' },
  301. services: { title: 'RouterOS Management Services (/ip service)', sub: 'Enable or disable Web, SSH, and Telnet management listeners and listening ports' },
  302. logs: { title: 'System Activity Logs (/log)', sub: 'Real-time circular buffer log viewer and topic-based event monitoring' }
  303. };
  304. const header = titles[tabName] || titles.dashboard;
  305. const pTitle = document.getElementById('page-title');
  306. if (pTitle) pTitle.innerText = header.title;
  307. const pSub = document.getElementById('page-subtitle');
  308. if (pSub) pSub.innerText = header.sub;
  309. // Toggle sections dynamically for all section elements
  310. document.querySelectorAll('main section[id^="section-"]').forEach(el => {
  311. if (el.id === `section-${tabName}`) {
  312. el.classList.remove('hidden');
  313. } else {
  314. el.classList.add('hidden');
  315. }
  316. });
  317. if (tabName === 'interfaces') {
  318. loadRoles();
  319. if (state.activeIfaceSubTab === 'roles') switchIfaceSubTab('roles');
  320. else switchIfaceSubTab('tree');
  321. }
  322. if (tabName === 'bridge') loadBridge();
  323. if (tabName === 'firewall') loadFirewall();
  324. if (tabName === 'routes') loadRoutes();
  325. if (tabName === 'bgp') {
  326. loadDynamicRouting();
  327. switchBgpSubTab(state.activeBgpSubTab || 'bgp-peers');
  328. }
  329. if (tabName === 'ospf') {
  330. loadDynamicRouting();
  331. switchOspfTab(state.activeOspfTab || 'instances');
  332. }
  333. if (tabName === 'routing-filters') loadDynamicRouting();
  334. if (tabName === 'dynamic-routing') loadDynamicRouting();
  335. if (tabName === 'ppp') loadPPP();
  336. if (tabName === 'eoip') loadEoIP();
  337. if (tabName === 'aerotun') loadAeroTUN();
  338. if (tabName === 'persistence') loadDebianConfig();
  339. if (tabName === 'pppoe') loadPPPoE();
  340. if (tabName === 'wireguard') loadWireGuard();
  341. if (tabName === 'ipsec') loadIPSec();
  342. if (tabName === 'l2tp') loadL2TP();
  343. if (tabName === 'pptp') loadPPTP();
  344. if (tabName === 'tools') loadToolsView();
  345. if (tabName === 'dhcp-client') loadDHCPClients();
  346. if (tabName === 'dhcp-server') loadDHCPServer();
  347. if (tabName === 'vrrp') loadVRRP();
  348. if (tabName === 'bwtest') loadBwTestView();
  349. if (tabName === 'settings') loadSettingsData();
  350. if (tabName === 'users') loadUsers();
  351. if (tabName === 'services') loadServices();
  352. if (tabName === 'logs') loadLogs();
  353. setTimeout(initTableSorting, 50);
  354. }
  355. // Fetch all core system, network and VPN telemetry
  356. async function fetchData(isManual = false) {
  357. const spinner = document.getElementById('refresh-spinner');
  358. if (isManual && spinner) spinner.classList.add('animate-spin');
  359. try {
  360. const [statusRes, ifacesRes, vlansRes, vpnRes, fwRes, dynRes, brSummaryRes, dhcpSumRes, dhcpClientsRes, vrrpSumRes, rolesRes] = await Promise.all([
  361. fetch(`${API_BASE}/system/status`),
  362. fetch(`${API_BASE}/interfaces`),
  363. fetch(`${API_BASE}/vlans`),
  364. fetch(`${API_BASE}/vpn/status`),
  365. fetch(`${API_BASE}/firewall/summary`),
  366. fetch(`${API_BASE}/routing/dynamic/summary`),
  367. fetch(`${API_BASE}/bridge/summary`),
  368. fetch(`${API_BASE}/dhcp/clients/summary`),
  369. fetch(`${API_BASE}/dhcp/clients`),
  370. fetch(`${API_BASE}/vrrp/summary`).catch(() => null),
  371. fetch(`${API_BASE}/roles`).catch(() => null)
  372. ]);
  373. if (rolesRes && rolesRes.ok) {
  374. state.roles = await rolesRes.json();
  375. const countEl = document.getElementById('badge-roles-count');
  376. if (countEl) countEl.innerText = (state.roles || []).length;
  377. }
  378. if (vrrpSumRes && vrrpSumRes.ok) {
  379. state.vrrpSummary = await vrrpSumRes.json();
  380. renderVRRPSummary();
  381. }
  382. if (dhcpSumRes && dhcpSumRes.ok) {
  383. state.dhcpSummary = await dhcpSumRes.json();
  384. const bDhcp = document.getElementById('badge-dhcp-client-count');
  385. if (bDhcp) bDhcp.innerText = state.dhcpSummary?.total_clients || 0;
  386. }
  387. if (dhcpClientsRes && dhcpClientsRes.ok) {
  388. state.dhcpClients = await dhcpClientsRes.json();
  389. }
  390. if (brSummaryRes.ok) {
  391. state.bridgeSummary = await brSummaryRes.json();
  392. const bBridge = document.getElementById('badge-bridge-count');
  393. if (bBridge) bBridge.innerText = state.bridgeSummary?.bridges_count || 0;
  394. const sBr = document.getElementById('bridge-stat-bridges');
  395. if (sBr) sBr.innerText = state.bridgeSummary?.bridges_count || 0;
  396. const sPorts = document.getElementById('bridge-stat-ports');
  397. if (sPorts) sPorts.innerText = state.bridgeSummary?.ports_count || 0;
  398. const sHosts = document.getElementById('bridge-stat-hosts');
  399. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  400. }
  401. if (statusRes.ok) state.systemStatus = await statusRes.json();
  402. if (ifacesRes.ok) {
  403. const ifacesData = await ifacesRes.json();
  404. const rawIfaces = Array.isArray(ifacesData) ? ifacesData : [];
  405. state.interfaces = rawIfaces.filter(i => {
  406. if (!i.name) return false;
  407. if (i.name.startsWith('ep_')) return false;
  408. return !['gre0', 'gretap0', 'erspan0', 'sit0', 'tunl0', 'ip6tnl0', 'ip6gre0', 'ip6erspan0'].includes(i.name);
  409. });
  410. try { populateToolsInterfaces(); } catch (e) {}
  411. }
  412. if (vlansRes.ok) {
  413. const vlansData = await vlansRes.json();
  414. state.vlans = Array.isArray(vlansData) ? vlansData : [];
  415. }
  416. if (vpnRes.ok) state.vpnStatus = await vpnRes.json();
  417. if (fwRes && fwRes.ok) state.fwSummary = await fwRes.json();
  418. if (dynRes && dynRes.ok) state.dynSummary = await dynRes.json();
  419. updateSystemMetrics();
  420. updateBadges();
  421. if (state.activeTab === 'dashboard') renderDashboard();
  422. if (state.activeTab === 'interfaces') {
  423. if (state.activeIfaceSubTab === 'roles') renderRolesTable();
  424. else renderInterfacesList();
  425. }
  426. if (state.activeTab === 'vlans') renderVlansList();
  427. if (state.activeTab === 'firewall') loadFirewall(false);
  428. if (state.activeTab === 'routes') loadRoutes(false);
  429. if (state.activeTab === 'dynamic-routing' || state.activeTab === 'bgp' || state.activeTab === 'ospf') loadDynamicRouting(false);
  430. if (state.activeTab === 'ppp') loadPPP(false);
  431. if (state.activeTab === 'eoip') loadEoIP(false);
  432. if (state.activeTab === 'aerotun') loadAeroTUN(false);
  433. if (state.activeTab === 'pppoe') loadPPPoE(false);
  434. if (state.activeTab === 'wireguard') loadWireGuard(false);
  435. if (state.activeTab === 'ipsec') loadIPSec(false);
  436. if (state.activeTab === 'l2tp') loadL2TP(false);
  437. if (state.activeTab === 'pptp') loadPPTP(false);
  438. if (state.activeTab === 'dhcp-client') loadDHCPClients(false);
  439. if (state.activeTab === 'dhcp-server') loadDHCPServer(false);
  440. if (state.activeTab === 'vrrp') loadVRRP(false);
  441. if (state.activeTab === 'settings') loadSettingsData(false);
  442. if (state.activeTab === 'users') loadUsers(false);
  443. fetchBwTestServerStatus();
  444. } catch (err) {
  445. console.error('Failed to fetch router state:', err);
  446. } finally {
  447. if (isManual && spinner) {
  448. setTimeout(() => spinner.classList.remove('animate-spin'), 300);
  449. }
  450. }
  451. }
  452. // Update Top KPI and Sidebar Telemetry
  453. function updateSystemMetrics() {
  454. const s = state.systemStatus;
  455. const v = state.vpnStatus;
  456. if (!s) return;
  457. // Sidebar Host & Uptime
  458. const sideHost = document.getElementById('side-hostname');
  459. if (sideHost) sideHost.innerText = s.hostname || 'debian-lxc';
  460. const sideUp = document.getElementById('side-uptime');
  461. if (sideUp) sideUp.innerText = s.uptime_human || '0m';
  462. const sideGw = document.getElementById('side-gateway-ip');
  463. if (sideGw) sideGw.innerText = s.default_gateway ? `GW: ${s.default_gateway}` : 'GW: Isolated';
  464. // Compute CPU Metrics
  465. let cpuPct = 0;
  466. if (s.cpu_pct !== undefined) {
  467. cpuPct = s.cpu_pct;
  468. } else if (s.cpu_load && s.cpu_load.length > 0) {
  469. const cores = s.cpu_cores || 1;
  470. cpuPct = Math.min(100, Math.round((parseFloat(s.cpu_load[0]) / cores) * 100));
  471. }
  472. const cpuPctStr = `${cpuPct.toFixed(1)}%`;
  473. const cpuWidth = `${Math.max(3, Math.min(100, cpuPct))}%`;
  474. const loadStr = s.cpu_load ? s.cpu_load.join(', ') : '-';
  475. // Sidebar CPU
  476. const sideCpuVal = document.getElementById('side-cpu-val');
  477. if (sideCpuVal) sideCpuVal.innerText = cpuPctStr;
  478. const sideCpuBar = document.getElementById('side-cpu-bar');
  479. if (sideCpuBar) {
  480. sideCpuBar.style.width = cpuWidth;
  481. sideCpuBar.title = `Container: ${cpuPctStr} | Host Loadavg: ${loadStr} (${s.cpu_cores || 1} cores)`;
  482. }
  483. // Dashboard CPU Card
  484. const dashCpuVal = document.getElementById('dash-cpu-val');
  485. if (dashCpuVal) dashCpuVal.innerText = cpuPctStr;
  486. const dashCpuBar = document.getElementById('dash-cpu-bar');
  487. if (dashCpuBar) {
  488. dashCpuBar.style.width = cpuWidth;
  489. if (cpuPct > 85) {
  490. dashCpuBar.className = 'h-full rounded-full bg-rose-500 transition-all duration-500';
  491. } else if (cpuPct > 65) {
  492. dashCpuBar.className = 'h-full rounded-full bg-amber-500 transition-all duration-500';
  493. } else {
  494. dashCpuBar.className = 'h-full rounded-full bg-emerald-500 transition-all duration-500';
  495. }
  496. }
  497. const dashCpuCores = document.getElementById('dash-cpu-cores');
  498. if (dashCpuCores) dashCpuCores.innerText = `${s.cpu_cores || 1} Cores`;
  499. const dashCpuLoad = document.getElementById('dash-cpu-load');
  500. if (dashCpuLoad) dashCpuLoad.innerText = loadStr;
  501. const dashCpuStatus = document.getElementById('dash-cpu-status');
  502. if (dashCpuStatus) {
  503. if (cpuPct > 85) {
  504. dashCpuStatus.innerText = 'High';
  505. dashCpuStatus.className = 'text-[11px] font-semibold text-rose-400 uppercase px-2 py-0.5 rounded bg-rose-500/10';
  506. } else if (cpuPct > 65) {
  507. dashCpuStatus.innerText = 'Heavy';
  508. dashCpuStatus.className = 'text-[11px] font-semibold text-amber-400 uppercase px-2 py-0.5 rounded bg-amber-500/10';
  509. } else {
  510. dashCpuStatus.innerText = 'Normal';
  511. dashCpuStatus.className = 'text-[11px] font-semibold text-emerald-400 uppercase px-2 py-0.5 rounded bg-emerald-500/10';
  512. }
  513. }
  514. // Compute RAM Metrics
  515. const memPct = Math.round(s.mem_usage_pct || 0);
  516. const memPctStr = `${memPct}%`;
  517. const memWidth = `${Math.max(3, Math.min(100, memPct))}%`;
  518. const usedMB = s.mem_used_mb || 0;
  519. const totalMB = s.mem_total_mb || 0;
  520. const freeMB = totalMB > usedMB ? totalMB - usedMB : 0;
  521. function fmtMemMB(mb) {
  522. if (mb >= 1024) {
  523. return `${(mb / 1024).toFixed(1)} GB`;
  524. }
  525. return `${mb} MB`;
  526. }
  527. // Sidebar RAM
  528. const sideRamVal = document.getElementById('side-ram-val');
  529. if (sideRamVal) sideRamVal.innerText = memPctStr;
  530. const sideRamBar = document.getElementById('side-ram-bar');
  531. if (sideRamBar) sideRamBar.style.width = memWidth;
  532. // Dashboard RAM Card
  533. const dashRamVal = document.getElementById('dash-ram-val');
  534. if (dashRamVal) dashRamVal.innerText = memPctStr;
  535. const dashRamBar = document.getElementById('dash-ram-bar');
  536. if (dashRamBar) {
  537. dashRamBar.style.width = memWidth;
  538. if (memPct > 85) {
  539. dashRamBar.className = 'h-full rounded-full bg-rose-500 transition-all duration-500';
  540. } else if (memPct > 70) {
  541. dashRamBar.className = 'h-full rounded-full bg-amber-500 transition-all duration-500';
  542. } else {
  543. dashRamBar.className = 'h-full rounded-full bg-indigo-500 transition-all duration-500';
  544. }
  545. }
  546. const dashRamUsedTotal = document.getElementById('dash-ram-used-total');
  547. if (dashRamUsedTotal) {
  548. dashRamUsedTotal.innerText = `${fmtMemMB(usedMB)} / ${fmtMemMB(totalMB)}`;
  549. }
  550. const dashRamFree = document.getElementById('dash-ram-free');
  551. if (dashRamFree) {
  552. dashRamFree.innerText = fmtMemMB(freeMB);
  553. }
  554. const dashRamStatus = document.getElementById('dash-ram-status');
  555. if (dashRamStatus) {
  556. if (memPct > 85) {
  557. dashRamStatus.innerText = 'High';
  558. dashRamStatus.className = 'text-[11px] font-semibold text-rose-400 uppercase px-2 py-0.5 rounded bg-rose-500/10';
  559. } else {
  560. dashRamStatus.innerText = 'Active';
  561. dashRamStatus.className = 'text-[11px] font-semibold text-indigo-400 uppercase px-2 py-0.5 rounded bg-indigo-500/10';
  562. }
  563. }
  564. // Legacy Dashboard Stats (Safe checks)
  565. const elIfacesUp = document.getElementById('stat-ifaces-up');
  566. if (elIfacesUp) elIfacesUp.innerText = s.up_ifaces || 0;
  567. const elIfacesTot = document.getElementById('stat-ifaces-total');
  568. if (elIfacesTot) elIfacesTot.innerText = `${s.total_ifaces || 0} Total`;
  569. const elIfacesDown = document.getElementById('stat-ifaces-down');
  570. if (elIfacesDown) elIfacesDown.innerText = `${s.down_ifaces || 0} DOWN`;
  571. const elVlans = document.getElementById('stat-vlans-count');
  572. if (elVlans) elVlans.innerText = s.vlan_ifaces || 0;
  573. // VPN Status Indicators
  574. if (v) {
  575. const totalActive = v.total_active_tunnels || 0;
  576. const statVpnActive = document.getElementById('stat-vpn-active');
  577. if (statVpnActive) statVpnActive.innerText = totalActive;
  578. const tunnelsDot = document.getElementById('tunnels-dot');
  579. const tunnelsLabel = document.getElementById('tunnels-label');
  580. if (tunnelsDot && tunnelsLabel) {
  581. if (totalActive > 0) {
  582. tunnelsDot.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  583. tunnelsLabel.innerText = `${totalActive} Active VPN Tunnel${totalActive > 1 ? 's' : ''}`;
  584. } else {
  585. tunnelsDot.className = 'w-2 h-2 rounded-full bg-slate-500';
  586. tunnelsLabel.innerText = '0 Active VPN Tunnels';
  587. }
  588. }
  589. setDotBadge('badge-pppoe-status', (v.active_pppoe || 0) > 0 || v.pppoe_connected);
  590. setDotBadge('badge-wg-status', (v.active_wireguard || 0) > 0 || v.wireguard_active);
  591. setDotBadge('badge-ipsec-status', (v.active_ipsec || 0) > 0 || v.ipsec_active);
  592. setDotBadge('badge-l2tp-status', (v.active_l2tp || 0) > 0 || v.l2tp_connected);
  593. setDotBadge('badge-pptp-status', (v.active_pptp || 0) > 0 || v.pptp_connected);
  594. }
  595. // Total Live Bandwidth Rate
  596. let totalRx = 0;
  597. let totalTx = 0;
  598. (state.interfaces || []).forEach(i => {
  599. if (i.rate) {
  600. totalRx += i.rate.rx_bytes_sec || 0;
  601. totalTx += i.rate.tx_bytes_sec || 0;
  602. }
  603. });
  604. document.getElementById('stat-traffic-rx').innerText = formatTraffic(totalRx);
  605. document.getElementById('stat-traffic-tx').innerText = formatTraffic(totalTx);
  606. }
  607. function setDotBadge(id, active) {
  608. const el = document.getElementById(id);
  609. if (!el) return;
  610. if (active) {
  611. el.className = 'w-2 h-2 rounded-full bg-emerald-400 shadow-sm shadow-emerald-400/80';
  612. } else {
  613. el.className = 'w-2 h-2 rounded-full bg-slate-600';
  614. }
  615. }
  616. function updateBadges() {
  617. const bIfaces = document.getElementById('badge-ifaces-count');
  618. if (bIfaces) bIfaces.innerText = (state.interfaces || []).length;
  619. const bVlans = document.getElementById('badge-vlans-count');
  620. if (bVlans) bVlans.innerText = (state.vlans || []).length;
  621. if (state.fwSummary) {
  622. const totalFwRules = (state.fwSummary.filter_rules_count || 0) + (state.fwSummary.nat_rules_count || 0) + (state.fwSummary.mangle_rules_count || 0);
  623. const badgeFw = document.getElementById('badge-firewall-count');
  624. if (badgeFw) badgeFw.innerText = totalFwRules;
  625. }
  626. if (state.vpnStatus) {
  627. const v = state.vpnStatus;
  628. const bEoIP = document.getElementById('badge-eoip-count');
  629. if (bEoIP) bEoIP.innerText = v.total_eoip || 0;
  630. const bAero = document.getElementById('badge-aerotun-count');
  631. if (bAero) bAero.innerText = v.total_aerotun || 0;
  632. const bPPPSess = document.getElementById('badge-ppp-sessions');
  633. if (bPPPSess) bPPPSess.innerText = v.total_ppp_sessions || 0;
  634. setDotBadge('badge-pppoe-status', v.active_pppoe > 0 || v.pppoe_server_running);
  635. setDotBadge('badge-wg-status', v.active_wireguard > 0);
  636. setDotBadge('badge-ipsec-status', v.active_ipsec > 0 || v.ipsec_server_running);
  637. setDotBadge('badge-l2tp-status', v.active_l2tp > 0 || v.l2tp_server_running);
  638. setDotBadge('badge-pptp-status', v.active_pptp > 0 || v.pptp_server_running);
  639. }
  640. if (state.dynSummary) {
  641. const d = state.dynSummary;
  642. setDotBadge('badge-bgp-dot', d.bgp_running);
  643. setDotBadge('badge-ospf-dot', d.ospf_running);
  644. const bBgp = document.getElementById('badge-bgp-count');
  645. if (bBgp) bBgp.innerText = (state.bgpPeers || []).length;
  646. const bOspf = document.getElementById('badge-ospf-count');
  647. if (bOspf) bOspf.innerText = (state.ospfInterfaces || []).length;
  648. const bFilters = document.getElementById('badge-filters-count');
  649. if (bFilters) bFilters.innerText = (state.routingFilters || []).length;
  650. }
  651. const bDhcpServer = document.getElementById('badge-dhcp-server-count');
  652. if (bDhcpServer) {
  653. bDhcpServer.innerText = state.dhcpServerSummary ? (state.dhcpServerSummary.active_leases || state.dhcpServerSummary.total_servers || 0) : (state.dhcpServers || []).length;
  654. }
  655. }
  656. // Render Dashboard View
  657. function renderDashboard() {
  658. const matrix = document.getElementById('port-matrix');
  659. if (!matrix) return;
  660. const ifaces = state.interfaces || [];
  661. const sig = ifaces.map(i => `${i.name}:${i.state}:${(i.ipv4 || []).join(',')}:${i.type}:${i.is_vlan}`).join(';');
  662. if (matrix.dataset.sig === sig) {
  663. return; // Structure & link states haven't changed! Do not rebuild or flicker!
  664. }
  665. matrix.dataset.sig = sig;
  666. matrix.innerHTML = '';
  667. (state.interfaces || []).forEach(iface => {
  668. const isUp = iface.state === 'UP';
  669. const isVlan = iface.is_vlan;
  670. const portCard = document.createElement('div');
  671. portCard.className = `p-3 rounded-xl border transition-all cursor-pointer select-none group ${
  672. isUp
  673. ? (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')
  674. : 'bg-slate-900/40 border-slate-800/60 opacity-60 hover:opacity-100 hover:border-slate-700'
  675. }`;
  676. portCard.onclick = () => openIfaceModal(iface.name);
  677. let statusPillClass = isUp ? 'bg-emerald-500 shadow-sm shadow-emerald-500/50' : 'bg-rose-500';
  678. if (isVlan) statusPillClass = isUp ? 'bg-cyan-400 shadow-sm shadow-cyan-400/50' : 'bg-rose-500';
  679. portCard.innerHTML = `
  680. <div class="flex items-center justify-between mb-2">
  681. <span class="font-bold text-xs font-mono text-white group-hover:text-brand-400 transition truncate">${iface.name}</span>
  682. <span class="w-2 h-2 rounded-full ${statusPillClass}"></span>
  683. </div>
  684. <div class="text-[11px] font-mono text-slate-300 truncate">${iface.ipv4 && iface.ipv4.length > 0 ? iface.ipv4[0] : (iface.mac || 'No IP')}</div>
  685. <div class="mt-2 flex items-center justify-between text-[10px] text-slate-400">
  686. <span class="uppercase tracking-wider font-semibold">${isVlan ? `VLAN ${iface.vlan_id}` : iface.type}</span>
  687. <span id="port-card-rate-${iface.name}">${iface.rate?.rx_human || '0 B/s'}</span>
  688. </div>
  689. `;
  690. matrix.appendChild(portCard);
  691. });
  692. const ifaceTbody = document.getElementById('quick-interfaces-table');
  693. if (ifaceTbody) {
  694. ifaceTbody.innerHTML = '';
  695. (state.interfaces || []).forEach(i => {
  696. const isUp = i.state === 'UP';
  697. const tr = document.createElement('tr');
  698. tr.className = 'hover:bg-slate-800/40 transition cursor-pointer';
  699. tr.onclick = () => openIfaceModal(i.name);
  700. const rxStr = i.rate?.rx_human || '0 B/s';
  701. const txStr = i.rate?.tx_human || '0 B/s';
  702. tr.innerHTML = `
  703. <td class="py-2.5 font-bold text-white flex items-center gap-2">
  704. <span class="w-2 h-2 rounded-full ${isUp ? 'bg-emerald-400 shadow-sm shadow-emerald-400/50' : 'bg-rose-400'}"></span>
  705. <span>${i.name}</span>
  706. </td>
  707. <td class="py-2.5 text-slate-300 font-sans">
  708. ${getRoleBadge(i.role || 'LAN')}
  709. </td>
  710. <td class="py-2.5 text-slate-400 text-[11px] font-mono">${i.mac || '-'}</td>
  711. <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>
  712. <td class="py-2.5 text-slate-300 text-[11px] font-mono">
  713. <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>
  714. </td>
  715. <td class="py-2.5 text-right font-sans font-semibold">
  716. <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>
  717. </td>
  718. `;
  719. ifaceTbody.appendChild(tr);
  720. });
  721. }
  722. const vlanTbody = document.getElementById('quick-vlans-table');
  723. if (vlanTbody) {
  724. vlanTbody.innerHTML = '';
  725. }
  726. }
  727. // Expand / Collapse Handlers
  728. function toggleExpand(parentName) {
  729. if (state.expandedParents.has(parentName)) {
  730. state.expandedParents.delete(parentName);
  731. } else {
  732. state.expandedParents.add(parentName);
  733. }
  734. renderInterfacesList();
  735. }
  736. // VLAN Support Checker: 802.1Q sub-interfaces are only supported on physical ethernet, veth, bridge, bond
  737. function supportsVLAN(iface) {
  738. if (!iface) return false;
  739. if (iface.is_vlan) return false;
  740. const name = (iface.name || '').toLowerCase();
  741. const type = (iface.type || '').toLowerCase();
  742. const role = (iface.role || '').toLowerCase();
  743. // Exclude loopback
  744. if (name === 'lo' || type === 'loopback' || role === 'loopback') return false;
  745. // Exclude WireGuard (Layer 3 tunnel, no 802.1Q support)
  746. if (type === 'wireguard' || name.startsWith('wg')) return false;
  747. // Exclude PPP / PPPoE
  748. if (type === 'ppp' || name.startsWith('ppp')) return false;
  749. // Exclude other Layer 3 tunnels and dummy devices
  750. if (type === 'dummy' || type === 'gre' || type === 'sit' || type === 'tun' || type === 'tap' ||
  751. name.startsWith('gre') || name.startsWith('sit') || name.startsWith('ipsec') || name.startsWith('xfrm') || name.startsWith('dummy')) {
  752. return false;
  753. }
  754. // If name already contains a dot, it's already a sub-interface
  755. if (name.includes('.')) return false;
  756. return true;
  757. }
  758. // DHCP Client Support Checker: Only broadcast-capable layer-2 interfaces (Ethernet, veth, VLAN, bridge, bond)
  759. function supportsDHCPClient(iface) {
  760. if (!iface) return false;
  761. const name = (iface.name || '').toLowerCase();
  762. const type = (iface.type || '').toLowerCase();
  763. const role = (iface.role || '').toLowerCase();
  764. // Exclude loopback
  765. if (name === 'lo' || type === 'loopback' || role === 'loopback') return false;
  766. // Exclude WireGuard (Layer 3 point-to-point tunnel, no broadcast/DHCP)
  767. if (type === 'wireguard' || name.startsWith('wg')) return false;
  768. // Exclude PPP / PPPoE / L2TP / PPTP tunnels
  769. if (type === 'ppp' || name.startsWith('ppp') || name.startsWith('l2tp') || name.startsWith('pptp')) return false;
  770. // Exclude other Layer 3 tunnels and dummy devices
  771. if (type === 'dummy' || type === 'gre' || type === 'sit' || type === 'tun' || type === 'tap' ||
  772. name.startsWith('gre') || name.startsWith('sit') || name.startsWith('ipsec') || name.startsWith('xfrm') || name.startsWith('dummy')) {
  773. return false;
  774. }
  775. // Exclude bridge member/slave ports (bridge itself handles IP / DHCP)
  776. const isBridgePort = (state.bridgePorts || []).some(bp => bp.interface === iface.name);
  777. if (isBridgePort) return false;
  778. return true;
  779. }
  780. // Expand / Collapse Handlers
  781. function toggleExpand(parentName) {
  782. const childVlans = (state.vlans || []).filter(v => v.parent_name === parentName || v.name.startsWith(parentName + '.'));
  783. if (childVlans.length === 0) {
  784. // Cannot expand an interface with no VLANs
  785. state.expandedParents.delete(parentName);
  786. return;
  787. }
  788. if (state.expandedParents.has(parentName)) {
  789. state.expandedParents.delete(parentName);
  790. } else {
  791. state.expandedParents.add(parentName);
  792. }
  793. renderInterfacesList();
  794. }
  795. function expandAllIfaces(expand) {
  796. if (expand) {
  797. (state.interfaces || []).forEach(i => {
  798. const hasVlans = (state.vlans || []).some(v => v.parent_name === i.name || v.name.startsWith(i.name + '.'));
  799. if (!i.is_vlan && hasVlans) state.expandedParents.add(i.name);
  800. });
  801. } else {
  802. state.expandedParents.clear();
  803. }
  804. renderInterfacesList();
  805. }
  806. // =========================================================================
  807. // INTERFACE ROLE TAGS MANAGEMENT
  808. // =========================================================================
  809. const ROLE_COLORS = {
  810. amber: { bg: 'bg-amber-500/20', text: 'text-amber-300', border: 'border-amber-500/30' },
  811. blue: { bg: 'bg-blue-500/20', text: 'text-blue-300', border: 'border-blue-500/30' },
  812. cyan: { bg: 'bg-cyan-500/20', text: 'text-cyan-300', border: 'border-cyan-500/30' },
  813. emerald: { bg: 'bg-emerald-500/20', text: 'text-emerald-300', border: 'border-emerald-500/30' },
  814. purple: { bg: 'bg-purple-500/20', text: 'text-purple-300', border: 'border-purple-500/30' },
  815. rose: { bg: 'bg-rose-500/20', text: 'text-rose-300', border: 'border-rose-500/30' },
  816. indigo: { bg: 'bg-indigo-500/20', text: 'text-indigo-300', border: 'border-indigo-500/30' },
  817. sky: { bg: 'bg-sky-500/20', text: 'text-sky-300', border: 'border-sky-500/30' },
  818. slate: { bg: 'bg-slate-800', text: 'text-slate-300', border: 'border-slate-700' }
  819. };
  820. function getRoleBadge(roleName) {
  821. const name = roleName || 'LAN';
  822. const role = (state.roles || []).find(r => r.name.toLowerCase() === name.toLowerCase() || r.id.toLowerCase() === name.toLowerCase());
  823. const colorKey = (role?.color || 'blue').toLowerCase();
  824. const theme = ROLE_COLORS[colorKey] || ROLE_COLORS.blue;
  825. 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>`;
  826. }
  827. function switchIfaceSubTab(subTab) {
  828. state.activeIfaceSubTab = subTab;
  829. const treeTab = document.getElementById('ifaces-subtab-tree');
  830. const rolesTab = document.getElementById('ifaces-subtab-roles');
  831. const btnTree = document.getElementById('ifaces-subtab-btn-tree');
  832. const btnRoles = document.getElementById('ifaces-subtab-btn-roles');
  833. if (subTab === 'roles') {
  834. treeTab?.classList.add('hidden');
  835. rolesTab?.classList.remove('hidden');
  836. if (btnRoles) {
  837. 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';
  838. }
  839. if (btnTree) {
  840. 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';
  841. }
  842. loadRoles();
  843. } else {
  844. rolesTab?.classList.add('hidden');
  845. treeTab?.classList.remove('hidden');
  846. if (btnTree) {
  847. 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';
  848. }
  849. if (btnRoles) {
  850. 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';
  851. }
  852. renderInterfacesList();
  853. }
  854. }
  855. async function loadRoles() {
  856. try {
  857. const res = await fetch(`${API_BASE}/roles`);
  858. if (res.ok) {
  859. state.roles = await res.json();
  860. const countEl = document.getElementById('badge-roles-count');
  861. if (countEl) countEl.innerText = (state.roles || []).length;
  862. renderRolesTable();
  863. populateRoleSelects();
  864. }
  865. } catch (err) {
  866. console.error('Failed to load role tags:', err);
  867. }
  868. }
  869. function renderRolesTable() {
  870. const tbody = document.getElementById('roles-table-body');
  871. const empty = document.getElementById('roles-empty-state');
  872. if (!tbody) return;
  873. const roles = state.roles || [];
  874. if (roles.length === 0) {
  875. tbody.innerHTML = '';
  876. empty?.classList.remove('hidden');
  877. return;
  878. }
  879. empty?.classList.add('hidden');
  880. const sig = roles.map(r => `${r.id}:${r.name}:${r.color}:${r.description}:${(r.interfaces||[]).join(',')}`).join(';');
  881. if (tbody.dataset.sig === sig) return;
  882. tbody.dataset.sig = sig;
  883. tbody.innerHTML = roles.map(r => {
  884. const colorKey = (r.color || 'blue').toLowerCase();
  885. const theme = ROLE_COLORS[colorKey] || ROLE_COLORS.blue;
  886. const ifaces = Array.isArray(r.interfaces) ? r.interfaces : [];
  887. const ifacesChips = ifaces.length > 0
  888. ? 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('')
  889. : '<span class="text-slate-600 font-sans text-xs italic">Unassigned (0)</span>';
  890. return `
  891. <tr class="hover:bg-slate-800/40 transition">
  892. <td class="py-3 px-4">
  893. <span class="px-2.5 py-1 rounded text-xs font-semibold ${theme.bg} ${theme.text} border ${theme.border}">
  894. ${escapeHtml(r.name)}
  895. </span>
  896. </td>
  897. <td class="py-3 px-4 font-bold text-white font-mono flex items-center gap-2">
  898. <span>${escapeHtml(r.name)}</span>
  899. ${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>' : ''}
  900. </td>
  901. <td class="py-3 px-4 font-sans capitalize text-slate-300">
  902. <span class="inline-flex items-center gap-1.5">
  903. <span class="w-2 h-2 rounded-full ${theme.bg.replace('/20', '')}"></span>
  904. <span>${escapeHtml(r.color || 'blue')}</span>
  905. </span>
  906. </td>
  907. <td class="py-3 px-4 font-sans text-slate-400 text-xs">${escapeHtml(r.description || '-')}</td>
  908. <td class="py-3 px-4 font-sans">
  909. <div class="flex flex-wrap items-center">
  910. ${ifacesChips}
  911. </div>
  912. </td>
  913. <td class="py-3 px-4 text-right space-x-2 font-sans whitespace-nowrap">
  914. <button onclick="openRoleModal('${escapeHtml(r.id)}')"
  915. class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold px-2 py-1 rounded hover:bg-slate-800 transition">
  916. Edit
  917. </button>
  918. <button onclick="deleteRoleTag('${escapeHtml(r.id)}', '${escapeHtml(r.name)}')"
  919. class="text-xs text-rose-400 hover:text-rose-300 font-semibold px-2 py-1 rounded hover:bg-slate-800 transition">
  920. Delete
  921. </button>
  922. </td>
  923. </tr>
  924. `;
  925. }).join('');
  926. }
  927. function openRoleModal(id = null) {
  928. const modal = document.getElementById('role-modal');
  929. if (!modal) return;
  930. const idInput = document.getElementById('role-modal-id');
  931. const nameInput = document.getElementById('role-modal-name');
  932. const colorSelect = document.getElementById('role-modal-color');
  933. const descInput = document.getElementById('role-modal-desc');
  934. const title = document.getElementById('role-modal-title');
  935. if (id) {
  936. const role = (state.roles || []).find(r => r.id === id);
  937. if (role) {
  938. if (title) title.innerText = `Edit Role Tag: ${role.name}`;
  939. if (idInput) idInput.value = role.id;
  940. if (nameInput) nameInput.value = role.name;
  941. if (colorSelect) colorSelect.value = role.color || 'blue';
  942. if (descInput) descInput.value = role.description || '';
  943. }
  944. } else {
  945. if (title) title.innerText = 'Add Role Tag';
  946. if (idInput) idInput.value = '';
  947. if (nameInput) nameInput.value = '';
  948. if (colorSelect) colorSelect.value = 'blue';
  949. if (descInput) descInput.value = '';
  950. }
  951. updateRoleModalPreview();
  952. modal.classList.remove('hidden');
  953. }
  954. function closeRoleModal() {
  955. const modal = document.getElementById('role-modal');
  956. if (modal) modal.classList.add('hidden');
  957. }
  958. function updateRoleModalPreview() {
  959. const name = document.getElementById('role-modal-name')?.value.trim() || 'Preview';
  960. const colorKey = (document.getElementById('role-modal-color')?.value || 'blue').toLowerCase();
  961. const theme = ROLE_COLORS[colorKey] || ROLE_COLORS.blue;
  962. const preview = document.getElementById('role-modal-preview');
  963. if (preview) {
  964. preview.innerText = name;
  965. preview.className = `px-2.5 py-1 rounded text-xs font-semibold ${theme.bg} ${theme.text} border ${theme.border}`;
  966. }
  967. }
  968. async function submitSaveRole(e) {
  969. e.preventDefault();
  970. const id = document.getElementById('role-modal-id')?.value;
  971. const name = document.getElementById('role-modal-name')?.value.trim();
  972. const color = document.getElementById('role-modal-color')?.value;
  973. const desc = document.getElementById('role-modal-desc')?.value.trim();
  974. if (!name) return;
  975. try {
  976. const payload = { id, name, color, description: desc };
  977. const method = id ? 'PUT' : 'POST';
  978. const url = id ? `${API_BASE}/roles/${encodeURIComponent(id)}` : `${API_BASE}/roles`;
  979. const res = await fetch(url, {
  980. method,
  981. headers: { 'Content-Type': 'application/json' },
  982. body: JSON.stringify(payload)
  983. });
  984. if (res.ok) {
  985. showToast('Role Tag Saved', `Role tag "${name}" saved successfully`, 'success');
  986. closeRoleModal();
  987. await loadRoles();
  988. fetchData(false);
  989. } else {
  990. const err = await res.json();
  991. showToast('Error', err.error || err.message || 'Failed to save role tag', 'error');
  992. }
  993. } catch (err) {
  994. showToast('Error', err.message, 'error');
  995. }
  996. }
  997. async function deleteRoleTag(id, name) {
  998. if (!confirm(`Are you sure you want to delete role tag "${name}"?\nInterfaces assigned to this role will default to LAN.`)) return;
  999. try {
  1000. const res = await fetch(`${API_BASE}/roles/${encodeURIComponent(id)}`, {
  1001. method: 'DELETE'
  1002. });
  1003. if (res.ok) {
  1004. showToast('Role Tag Deleted', `Role tag "${name}" removed`, 'success');
  1005. await loadRoles();
  1006. fetchData(false);
  1007. } else {
  1008. const err = await res.json();
  1009. showToast('Error', err.error || err.message || 'Failed to delete role tag', 'error');
  1010. }
  1011. } catch (err) {
  1012. showToast('Error', err.message, 'error');
  1013. }
  1014. }
  1015. function populateRoleSelects(selectedRole = '') {
  1016. const ifaceSelect = document.getElementById('modal-iface-role');
  1017. const vlanSelect = document.getElementById('vlan-role');
  1018. const roles = state.roles || [];
  1019. const optionsHtml = roles.map(r => `<option value="${escapeHtml(r.name)}">${escapeHtml(r.name)}${r.description ? ` (${escapeHtml(r.description)})` : ''}</option>`).join('');
  1020. if (ifaceSelect) {
  1021. const currentVal = selectedRole || ifaceSelect.value || 'LAN';
  1022. if (ifaceSelect.dataset.optionsSig !== optionsHtml) {
  1023. ifaceSelect.innerHTML = optionsHtml;
  1024. ifaceSelect.dataset.optionsSig = optionsHtml;
  1025. }
  1026. if (currentVal) ifaceSelect.value = currentVal;
  1027. }
  1028. if (vlanSelect) {
  1029. const currentVal = selectedRole || vlanSelect.value || 'LAN';
  1030. if (vlanSelect.dataset.optionsSig !== optionsHtml) {
  1031. vlanSelect.innerHTML = optionsHtml;
  1032. vlanSelect.dataset.optionsSig = optionsHtml;
  1033. }
  1034. if (currentVal) vlanSelect.value = currentVal;
  1035. }
  1036. }
  1037. // Filter and Render Hierarchical Interfaces List
  1038. function filterIfaces(filter) {
  1039. state.ifaceFilter = filter || 'all';
  1040. renderInterfacesList();
  1041. }
  1042. function renderInterfacesList() {
  1043. const tbody = document.getElementById('interfaces-tree-tbody');
  1044. const emptyState = document.getElementById('interfaces-empty-state');
  1045. const summary = document.getElementById('ifaces-list-summary');
  1046. const query = (document.getElementById('iface-search')?.value || '').trim().toLowerCase();
  1047. const allIfaces = state.interfaces || [];
  1048. const allVlans = state.vlans || [];
  1049. const parentIfaces = allIfaces.filter(i => !i.is_vlan);
  1050. const filteredParents = parentIfaces.filter(parent => {
  1051. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  1052. if (query) {
  1053. const matchName = parent.name.toLowerCase().includes(query);
  1054. const matchIp = (parent.ipv4 || []).some(ip => ip.toLowerCase().includes(query));
  1055. const matchRole = (parent.role || '').toLowerCase().includes(query);
  1056. const matchType = (parent.type || '').toLowerCase().includes(query);
  1057. const matchVlan = childVlans.some(v =>
  1058. v.name.toLowerCase().includes(query) ||
  1059. String(v.vlan_id).includes(query) ||
  1060. (v.ipv4 || []).some(ip => ip.toLowerCase().includes(query)) ||
  1061. (v.description || '').toLowerCase().includes(query)
  1062. );
  1063. if (!matchName && !matchIp && !matchRole && !matchType && !matchVlan) return false;
  1064. }
  1065. if (state.ifaceFilter === 'has_vlans') return childVlans.length > 0;
  1066. if (state.ifaceFilter === 'physical') return parent.type !== 'loopback';
  1067. if (state.ifaceFilter === 'up') return parent.state === 'UP';
  1068. return true;
  1069. });
  1070. if (summary) {
  1071. summary.innerText = `${parentIfaces.length} Interfaces • ${allVlans.length} Active VLANs`;
  1072. }
  1073. if (filteredParents.length === 0) {
  1074. emptyState?.classList.remove('hidden');
  1075. tbody.innerHTML = '';
  1076. return;
  1077. }
  1078. emptyState?.classList.add('hidden');
  1079. const sig = `${state.ifaceFilter}|${query}|` + filteredParents.map(p => {
  1080. const cVlans = allVlans.filter(v => v.parent_name === p.name || v.name.startsWith(p.name + '.'));
  1081. const dhcp = (state.dhcpClients || []).find(dc => dc.interface === p.name);
  1082. return `${p.name}:${p.state}:${p.role||'LAN'}:${(p.ipv4||[]).join(',')}:${p.mtu}:${cVlans.length}:${state.expandedParents.has(p.name)}:${dhcp?.status || ''}`;
  1083. }).join(';');
  1084. if (tbody.dataset.sig === sig) {
  1085. return; // ZERO changes to structure, links, IPs or VLANs! Do not rebuild DOM!
  1086. }
  1087. tbody.dataset.sig = sig;
  1088. tbody.innerHTML = '';
  1089. filteredParents.forEach(parent => {
  1090. const isUp = parent.state === 'UP';
  1091. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  1092. const hasVlans = childVlans.length > 0;
  1093. const isExpanded = hasVlans && state.expandedParents.has(parent.name);
  1094. const canHaveVlan = supportsVLAN(parent);
  1095. const parentRow = document.createElement('tr');
  1096. parentRow.className = `hover:bg-slate-800/50 transition border-b border-slate-800/80 ${isExpanded ? 'bg-slate-900/80' : ''}`;
  1097. parentRow.innerHTML = `
  1098. <td class="py-3 px-3 text-center">
  1099. ${hasVlans ? `
  1100. <button onclick="toggleExpand('${parent.name}')" title="${isExpanded ? 'Collapse VLANs' : 'Expand VLANs'}"
  1101. class="w-6 h-6 rounded flex items-center justify-center hover:bg-slate-800 text-slate-400 hover:text-white transition">
  1102. <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">
  1103. <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M9 5l7 7-7 7" />
  1104. </svg>
  1105. </button>
  1106. ` : `
  1107. <div class="w-6 h-6 flex items-center justify-center text-slate-700 select-none">
  1108. <span class="w-1.5 h-1.5 rounded-full bg-slate-800"></span>
  1109. </div>
  1110. `}
  1111. </td>
  1112. <td class="py-3 px-4">
  1113. <div class="flex items-center space-x-2.5">
  1114. <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">
  1115. ${parent.type === 'loopback' ? 'LO' : (parent.type === 'wireguard' ? 'WG' : (parent.type === 'bridge' ? 'BR' : 'NIC'))}
  1116. </div>
  1117. <div>
  1118. <div class="flex items-center gap-2">
  1119. <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'}">
  1120. <span>${parent.name}</span>
  1121. <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>
  1122. </span>
  1123. ${hasVlans ? `
  1124. <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>
  1125. ` : `
  1126. <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>
  1127. `}
  1128. </div>
  1129. <div class="text-[10px] text-slate-500 font-sans mt-0.5">${parent.type}</div>
  1130. </div>
  1131. </div>
  1132. </td>
  1133. <td class="py-3 px-4 font-sans">
  1134. <div class="flex items-center gap-1.5">
  1135. ${getRoleBadge(parent.role || 'LAN')}
  1136. <span class="text-xs text-slate-400 truncate max-w-[120px]">${parent.description || '-'}</span>
  1137. </div>
  1138. </td>
  1139. <td class="py-3 px-4">
  1140. ${parent.ipv4 && parent.ipv4.length > 0
  1141. ? `<div class="text-white font-medium">${parent.ipv4[0]}</div>`
  1142. : '<span class="text-slate-600 font-sans">Unassigned</span>'
  1143. }
  1144. ${(() => {
  1145. const c = (state.dhcpClients || []).find(dc => dc.interface === parent.name);
  1146. if (!c) return '';
  1147. 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');
  1148. 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>`;
  1149. })()}
  1150. </td>
  1151. <td class="py-3 px-4 text-slate-400 text-[11px]">
  1152. <div>${parent.mac || 'N/A'}</div>
  1153. <div class="text-[10px] text-slate-500">MTU ${parent.mtu}</div>
  1154. </td>
  1155. <td class="py-3 px-4 text-[11px]">
  1156. <div class="flex items-center space-x-2">
  1157. <span id="iface-rate-rx-${parent.name}" class="text-emerald-400">↓ ${parent.rate?.rx_human || '0 B/s'}</span>
  1158. <span id="iface-rate-tx-${parent.name}" class="text-cyan-400">↑ ${parent.rate?.tx_human || '0 B/s'}</span>
  1159. </div>
  1160. </td>
  1161. <td class="py-3 px-4 font-sans">
  1162. <button onclick="toggleInterfaceState('${parent.name}', '${isUp ? 'down' : 'up'}')"
  1163. class="flex items-center gap-1.5 text-xs font-semibold px-2.5 py-1 rounded-full transition ${
  1164. 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'
  1165. }" title="Click to toggle link status">
  1166. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  1167. <span>${parent.state}</span>
  1168. </button>
  1169. </td>
  1170. <td class="py-3 px-4 text-right space-x-2 font-sans">
  1171. ${(() => {
  1172. const c = (state.dhcpClients || []).find(dc => dc.interface === parent.name);
  1173. if (c) {
  1174. 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>`;
  1175. }
  1176. if (!supportsDHCPClient(parent)) {
  1177. return '';
  1178. }
  1179. 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>`;
  1180. })()}
  1181. ${canHaveVlan ? `
  1182. <button onclick="openVlanModal('${parent.name}')"
  1183. 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">
  1184. + Add VLAN
  1185. </button>
  1186. ` : ''}
  1187. <button onclick="openIfaceModal('${parent.name}')"
  1188. 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">
  1189. Edit
  1190. </button>
  1191. </td>
  1192. `;
  1193. tbody.appendChild(parentRow);
  1194. if (isExpanded) {
  1195. const drawerRow = document.createElement('tr');
  1196. drawerRow.className = 'bg-slate-950/80 border-b border-slate-800/90';
  1197. const drawerCell = document.createElement('td');
  1198. drawerCell.colSpan = 8;
  1199. drawerCell.className = 'p-0';
  1200. drawerCell.innerHTML = `
  1201. <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">
  1202. <div class="flex items-center justify-between mb-3">
  1203. <div class="flex items-center space-x-3">
  1204. <span class="font-bold text-xs text-white uppercase tracking-wider flex items-center gap-1.5 font-sans">
  1205. <span>VLAN Sub-interfaces on <code class="text-cyan-300 lowercase">${parent.name}</code></span>
  1206. </span>
  1207. <span class="text-[11px] bg-cyan-950 text-cyan-400 px-2 py-0.5 rounded-full border border-cyan-800/60 font-mono">
  1208. ${childVlans.length} Attached
  1209. </span>
  1210. </div>
  1211. <button onclick="openVlanModal('${parent.name}')"
  1212. 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">
  1213. <span>+ Create VLAN on ${parent.name}</span>
  1214. </button>
  1215. </div>
  1216. ${childVlans.length === 0 ? `
  1217. <div class="p-6 text-center border border-dashed border-slate-800 rounded-xl bg-slate-900/40 font-sans">
  1218. <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>
  1219. <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">
  1220. <span>+ Create Your First VLAN on ${parent.name}</span>
  1221. </button>
  1222. </div>
  1223. ` : `
  1224. <div class="overflow-x-auto rounded-lg border border-slate-800 bg-slate-900/90 shadow-inner">
  1225. <table class="w-full text-left text-xs font-mono">
  1226. <thead class="text-slate-400 bg-slate-950/70 border-b border-slate-800 uppercase tracking-wider text-[10px] font-sans">
  1227. <tr>
  1228. <th class="py-2.5 px-4">VLAN ID</th>
  1229. <th class="py-2.5 px-4">Interface Device</th>
  1230. <th class="py-2.5 px-4">Subnet Gateway</th>
  1231. <th class="py-2.5 px-4">Role / Alias</th>
  1232. <th class="py-2.5 px-4">MTU</th>
  1233. <th class="py-2.5 px-4">Throughput</th>
  1234. <th class="py-2.5 px-4">Status</th>
  1235. <th class="py-2.5 px-4 text-right">Actions</th>
  1236. </tr>
  1237. </thead>
  1238. <tbody class="divide-y divide-slate-800/70">
  1239. ${childVlans.map(v => {
  1240. const isVlanUp = v.state === 'UP';
  1241. return `
  1242. <tr class="hover:bg-slate-800/40 transition">
  1243. <td class="py-2.5 px-4">
  1244. <span class="px-2 py-0.5 rounded text-xs font-bold bg-cyan-950 text-cyan-300 border border-cyan-800 shadow-sm">
  1245. VLAN ${v.vlan_id}
  1246. </span>
  1247. </td>
  1248. <td class="py-2.5 px-4 font-bold text-white flex items-center gap-1.5">
  1249. <span class="text-cyan-500">└─</span>
  1250. <span class="cursor-pointer hover:text-cyan-400 flex items-center gap-1" onclick="openIfaceModal('${v.name}')" title="Configure / Rename ${v.name}">
  1251. <span>${v.name}</span>
  1252. <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>
  1253. </span>
  1254. </td>
  1255. <td class="py-2.5 px-4 text-emerald-400 font-medium">
  1256. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  1257. ${(() => {
  1258. const c = (state.dhcpClients || []).find(dc => dc.interface === v.name);
  1259. if (!c) return '';
  1260. 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';
  1261. 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>`;
  1262. })()}
  1263. </td>
  1264. <td class="py-2.5 px-4 font-sans text-slate-300">
  1265. <div class="flex items-center gap-1.5">
  1266. ${getRoleBadge(v.role || 'LAN')}
  1267. <span class="text-slate-400 text-xs">${v.description || '-'}</span>
  1268. </div>
  1269. </td>
  1270. <td class="py-2.5 px-4 text-slate-400">${v.mtu}</td>
  1271. <td class="py-2.5 px-4 text-[11px]">
  1272. <span id="vlan-rate-rx-${v.name}" class="text-emerald-400">↓ ${v.rate?.rx_human || '0 B/s'}</span>
  1273. <span id="vlan-rate-tx-${v.name}" class="text-cyan-400 ml-1.5">↑ ${v.rate?.tx_human || '0 B/s'}</span>
  1274. </td>
  1275. <td class="py-2.5 px-4 font-sans">
  1276. <button onclick="toggleInterfaceState('${v.name}', '${isVlanUp ? 'down' : 'up'}')"
  1277. class="flex items-center gap-1 text-[11px] font-semibold px-2 py-0.5 rounded-full ${
  1278. 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'
  1279. }">
  1280. <span class="w-1.5 h-1.5 rounded-full ${isVlanUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  1281. <span>${v.state}</span>
  1282. </button>
  1283. </td>
  1284. <td class="py-2.5 px-4 text-right space-x-1.5 font-sans">
  1285. ${(() => {
  1286. const c = (state.dhcpClients || []).find(dc => dc.interface === v.name);
  1287. if (c) {
  1288. 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>`;
  1289. }
  1290. if (!supportsDHCPClient(v)) {
  1291. return '';
  1292. }
  1293. 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>`;
  1294. })()}
  1295. <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>
  1296. <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>
  1297. </td>
  1298. </tr>
  1299. `;
  1300. }).join('')}
  1301. </tbody>
  1302. </table>
  1303. </div>
  1304. `}
  1305. </div>
  1306. `;
  1307. drawerRow.appendChild(drawerCell);
  1308. tbody.appendChild(drawerRow);
  1309. }
  1310. });
  1311. }
  1312. // Render VLANs Dedicated View
  1313. function renderVlansList() {
  1314. const tbody = document.getElementById('vlans-table-body');
  1315. if (!tbody) return;
  1316. const emptyState = document.getElementById('vlans-empty-state');
  1317. const countBadge = document.getElementById('vlans-table-count');
  1318. const query = (document.getElementById('vlan-search')?.value || '').toLowerCase();
  1319. const allVlans = state.vlans || [];
  1320. if (countBadge) countBadge.innerText = allVlans.length;
  1321. const filtered = allVlans.filter(v => {
  1322. if (!query) return true;
  1323. return v.name.toLowerCase().includes(query) ||
  1324. String(v.vlan_id).includes(query) ||
  1325. (v.description || '').toLowerCase().includes(query) ||
  1326. (v.ipv4 && v.ipv4.some(ip => ip.includes(query)));
  1327. });
  1328. if (allVlans.length === 0) {
  1329. emptyState.classList.remove('hidden');
  1330. tbody.innerHTML = '';
  1331. return;
  1332. }
  1333. emptyState.classList.add('hidden');
  1334. const sig = `${query}|` + filtered.map(v => `${v.name}:${v.state}:${(v.ipv4||[]).join(',')}:${v.vlan_id}:${v.mtu}`).join(';');
  1335. if (tbody.dataset.sig === sig) return;
  1336. tbody.dataset.sig = sig;
  1337. tbody.innerHTML = '';
  1338. filtered.forEach(v => {
  1339. const isUp = v.state === 'UP';
  1340. const tr = document.createElement('tr');
  1341. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  1342. tr.innerHTML = `
  1343. <td class="py-3 px-4">
  1344. <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">
  1345. VLAN ${v.vlan_id}
  1346. </span>
  1347. </td>
  1348. <td class="py-3 px-4 font-bold text-white">
  1349. <span class="cursor-pointer hover:text-cyan-400 flex items-center gap-1.5" onclick="openIfaceModal('${v.name}')" title="Configure / Rename ${v.name}">
  1350. <span>${v.name}</span>
  1351. <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>
  1352. </span>
  1353. </td>
  1354. <td class="py-3 px-4 text-slate-300">
  1355. <span class="bg-slate-800 text-slate-200 px-2 py-0.5 rounded text-[11px]">${v.parent_name || 'eth0'}</span>
  1356. </td>
  1357. <td class="py-3 px-4 text-emerald-400 font-medium">
  1358. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  1359. </td>
  1360. <td class="py-3 px-4 text-slate-300 font-sans">
  1361. <span class="text-slate-400 text-xs">${v.description || v.role || '-'}</span>
  1362. </td>
  1363. <td class="py-3 px-4 text-slate-400">${v.mtu}</td>
  1364. <td class="py-3 px-4 font-sans">
  1365. <button onclick="toggleInterfaceState('${v.name}', '${isUp ? 'down' : 'up'}')"
  1366. class="flex items-center gap-1.5 text-xs font-semibold px-2 py-0.5 rounded-full ${
  1367. 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'
  1368. }">
  1369. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  1370. <span>${v.state}</span>
  1371. </button>
  1372. </td>
  1373. <td class="py-3 px-4 text-right space-x-2 font-sans">
  1374. <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>
  1375. <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>
  1376. </td>
  1377. `;
  1378. tbody.appendChild(tr);
  1379. });
  1380. }
  1381. // Toggle interface UP / DOWN
  1382. async function toggleInterfaceState(name, newState) {
  1383. try {
  1384. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(name)}/state`, {
  1385. method: 'POST',
  1386. headers: { 'Content-Type': 'application/json' },
  1387. body: JSON.stringify({ state: newState })
  1388. });
  1389. const data = await res.json();
  1390. if (res.ok) {
  1391. showToast('Interface Updated', `Interface ${name} is now ${newState.toUpperCase()}`, 'success');
  1392. fetchData(false);
  1393. } else {
  1394. showToast('Error', data.message || 'Failed to toggle interface state', 'error');
  1395. }
  1396. } catch (err) {
  1397. showToast('Error', err.message, 'error');
  1398. }
  1399. }
  1400. // ---------------- MikroTik Flag & Utilities ----------------
  1401. function renderMikroTikFlag(running, disabled) {
  1402. if (running) {
  1403. 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>`;
  1404. }
  1405. if (disabled) {
  1406. 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>`;
  1407. }
  1408. 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>`;
  1409. }
  1410. function copyToClipboard(text, label = 'Text') {
  1411. navigator.clipboard.writeText(text).then(() => {
  1412. showToast('Copied', `${label} copied to clipboard`, 'success');
  1413. }).catch(() => {
  1414. prompt('Copy value:', text);
  1415. });
  1416. }
  1417. // ======================== PPP Profiles Shared Helper ========================
  1418. async function fetchPPPProfilesList() {
  1419. try {
  1420. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`);
  1421. if (res.ok) {
  1422. state.pppProfiles = await res.json();
  1423. }
  1424. } catch (err) {
  1425. console.error('Failed to load PPP profiles:', err);
  1426. }
  1427. }
  1428. function populateProfileSelect(selectId, selectedVal, defaultVal = 'default') {
  1429. const sel = document.getElementById(selectId);
  1430. if (!sel) return;
  1431. const profiles = (state.pppProfiles && state.pppProfiles.length > 0) ? state.pppProfiles : [
  1432. { name: 'default', use_encryption: 'no' },
  1433. { name: 'default-encryption', use_encryption: 'required' }
  1434. ];
  1435. sel.innerHTML = '';
  1436. profiles.forEach(p => {
  1437. const opt = document.createElement('option');
  1438. opt.value = p.name;
  1439. const encBadge = p.use_encryption === 'required' ? ' (MPPE-128)' : (p.use_encryption === 'yes' ? ' (MPPE)' : '');
  1440. opt.innerText = `${p.name}${encBadge}`;
  1441. sel.appendChild(opt);
  1442. });
  1443. if (selectedVal) {
  1444. sel.value = selectedVal;
  1445. } else {
  1446. sel.value = defaultVal;
  1447. }
  1448. if (!sel.value && sel.options.length > 0) {
  1449. sel.selectedIndex = 0;
  1450. }
  1451. }
  1452. // ======================== PPPoE Multi-Instance ========================
  1453. async function loadPPPoE(populateInputs = true) {
  1454. try {
  1455. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  1456. await fetchPPPProfilesList();
  1457. }
  1458. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`);
  1459. const list = await res.json();
  1460. state.pppoeList = Array.isArray(list) ? list : [];
  1461. const badge = document.getElementById('pppoe-count-badge');
  1462. if (badge) badge.innerText = `${state.pppoeList.length} Interface${state.pppoeList.length !== 1 ? 's' : ''}`;
  1463. const tbody = document.getElementById('pppoe-table-body');
  1464. const empty = document.getElementById('pppoe-empty');
  1465. if (!tbody) return;
  1466. tbody.innerHTML = '';
  1467. if (state.pppoeList.length === 0) {
  1468. if (empty) empty.classList.remove('hidden');
  1469. } else {
  1470. if (empty) empty.classList.add('hidden');
  1471. state.pppoeList.forEach(inst => {
  1472. const tr = document.createElement('tr');
  1473. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1474. tr.innerHTML = `
  1475. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  1476. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  1477. <td class="py-2.5 px-3 text-cyan-400 font-mono">${escapeHtml(inst.interface)}</td>
  1478. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  1479. <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>
  1480. <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>
  1481. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  1482. <td class="py-2.5 px-3 text-center">
  1483. <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'}">
  1484. ${inst.default_route ? 'Yes' : 'No'}
  1485. </span>
  1486. </td>
  1487. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  1488. ${inst.running ? `
  1489. <button onclick="disconnectPPPoEInstance('${inst.name}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  1490. ` : `
  1491. <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>
  1492. `}
  1493. <button onclick="togglePPPoEState('${inst.name}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  1494. ${inst.disabled ? 'Enable' : 'Disable'}
  1495. </button>
  1496. <button onclick="openEditPPPoEModal('${inst.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  1497. <button onclick="deletePPPoEInstance('${inst.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  1498. </td>
  1499. `;
  1500. tbody.appendChild(tr);
  1501. });
  1502. }
  1503. } catch (err) {
  1504. console.error('Failed to load PPPoE:', err);
  1505. }
  1506. }
  1507. function openAddPPPoEModal() {
  1508. document.getElementById('pppoe-modal-title').innerText = 'Add PPPoE Client Interface';
  1509. document.getElementById('pppoe-modal-edit-orig').value = '';
  1510. document.getElementById('pppoe-modal-name').value = `pppoe-out${(state.pppoeList || []).length + 1}`;
  1511. document.getElementById('pppoe-modal-name').readOnly = false;
  1512. document.getElementById('pppoe-modal-user').value = '';
  1513. document.getElementById('pppoe-modal-pass').value = '';
  1514. document.getElementById('pppoe-modal-service').value = '';
  1515. document.getElementById('pppoe-modal-mtu').value = '1492';
  1516. document.getElementById('pppoe-modal-defroute').checked = true;
  1517. document.getElementById('pppoe-modal-reconnect').checked = true;
  1518. document.getElementById('pppoe-modal-disabled').checked = false;
  1519. // Populate profiles
  1520. populateProfileSelect('pppoe-modal-profile', 'default', 'default');
  1521. // Populate interfaces
  1522. const sel = document.getElementById('pppoe-modal-iface');
  1523. sel.innerHTML = '';
  1524. (state.interfaces || []).forEach(i => {
  1525. if (i.name === 'lo') return;
  1526. const opt = document.createElement('option');
  1527. opt.value = i.name;
  1528. opt.innerText = `${i.name} (${i.role || i.type})`;
  1529. sel.appendChild(opt);
  1530. });
  1531. document.getElementById('pppoe-modal').classList.remove('hidden');
  1532. }
  1533. function openEditPPPoEModal(name) {
  1534. const inst = (state.pppoeList || []).find(i => i.name === name);
  1535. if (!inst) return;
  1536. document.getElementById('pppoe-modal-title').innerText = `Edit PPPoE Client: ${name}`;
  1537. document.getElementById('pppoe-modal-edit-orig').value = name;
  1538. document.getElementById('pppoe-modal-name').value = inst.name;
  1539. document.getElementById('pppoe-modal-name').readOnly = true;
  1540. document.getElementById('pppoe-modal-user').value = inst.username || '';
  1541. document.getElementById('pppoe-modal-pass').value = inst.password || '';
  1542. document.getElementById('pppoe-modal-service').value = inst.service_name || '';
  1543. document.getElementById('pppoe-modal-mtu').value = inst.mtu || 1492;
  1544. document.getElementById('pppoe-modal-defroute').checked = inst.default_route ?? true;
  1545. document.getElementById('pppoe-modal-reconnect').checked = inst.auto_reconnect ?? true;
  1546. document.getElementById('pppoe-modal-disabled').checked = !!inst.disabled;
  1547. // Populate profiles
  1548. populateProfileSelect('pppoe-modal-profile', inst.profile || 'default', 'default');
  1549. const sel = document.getElementById('pppoe-modal-iface');
  1550. sel.innerHTML = '';
  1551. (state.interfaces || []).forEach(i => {
  1552. if (i.name === 'lo') return;
  1553. const opt = document.createElement('option');
  1554. opt.value = i.name;
  1555. opt.innerText = `${i.name} (${i.role || i.type})`;
  1556. if (i.name === inst.interface) opt.selected = true;
  1557. sel.appendChild(opt);
  1558. });
  1559. document.getElementById('pppoe-modal').classList.remove('hidden');
  1560. }
  1561. function closePPPoEModal() {
  1562. document.getElementById('pppoe-modal').classList.add('hidden');
  1563. }
  1564. async function submitSavePPPoE(e) {
  1565. e.preventDefault();
  1566. const name = document.getElementById('pppoe-modal-name').value.trim();
  1567. const iface = document.getElementById('pppoe-modal-iface').value;
  1568. const user = document.getElementById('pppoe-modal-user').value.trim();
  1569. const pass = document.getElementById('pppoe-modal-pass').value;
  1570. const profile = document.getElementById('pppoe-modal-profile')?.value || 'default';
  1571. const service = document.getElementById('pppoe-modal-service').value.trim();
  1572. const mtu = parseInt(document.getElementById('pppoe-modal-mtu').value, 10) || 1492;
  1573. const defRoute = document.getElementById('pppoe-modal-defroute').checked;
  1574. const reconnect = document.getElementById('pppoe-modal-reconnect').checked;
  1575. const disabled = document.getElementById('pppoe-modal-disabled').checked;
  1576. try {
  1577. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`, {
  1578. method: 'POST',
  1579. headers: { 'Content-Type': 'application/json' },
  1580. body: JSON.stringify({
  1581. name,
  1582. interface: iface,
  1583. username: user,
  1584. password: pass,
  1585. profile: profile,
  1586. service_name: service,
  1587. mtu,
  1588. default_route: defRoute,
  1589. auto_reconnect: reconnect,
  1590. disabled
  1591. })
  1592. });
  1593. if (res.ok) {
  1594. showToast('PPPoE Saved', `Configuration for ${name} saved`, 'success');
  1595. closePPPoEModal();
  1596. loadPPPoE(false);
  1597. fetchData(false);
  1598. } else {
  1599. const err = await res.json();
  1600. showToast('Error', err.message || 'Failed to save PPPoE', 'error');
  1601. }
  1602. } catch (err) {
  1603. showToast('Error', err.message, 'error');
  1604. }
  1605. }
  1606. async function connectPPPoEInstance(name) {
  1607. try {
  1608. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  1609. if (res.ok) {
  1610. showToast('Connecting', `Dialing ${name}...`, 'info');
  1611. setTimeout(() => loadPPPoE(false), 2000);
  1612. }
  1613. } catch (err) {
  1614. showToast('Error', err.message, 'error');
  1615. }
  1616. }
  1617. async function disconnectPPPoEInstance(name) {
  1618. try {
  1619. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  1620. if (res.ok) {
  1621. showToast('Disconnected', `${name} session terminated`, 'info');
  1622. setTimeout(() => loadPPPoE(false), 1000);
  1623. }
  1624. } catch (err) {
  1625. showToast('Error', err.message, 'error');
  1626. }
  1627. }
  1628. async function togglePPPoEState(name, enable) {
  1629. try {
  1630. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/state`, {
  1631. method: 'POST',
  1632. headers: { 'Content-Type': 'application/json' },
  1633. body: JSON.stringify({ enabled: enable })
  1634. });
  1635. if (res.ok) {
  1636. showToast(enable ? 'Enabled' : 'Disabled', `${name} is now ${enable ? 'enabled' : 'disabled'}`, 'info');
  1637. loadPPPoE(false);
  1638. }
  1639. } catch (err) {
  1640. showToast('Error', err.message, 'error');
  1641. }
  1642. }
  1643. async function deletePPPoEInstance(name) {
  1644. if (!confirm(`Are you sure you want to delete PPPoE client ${name}?`)) return;
  1645. try {
  1646. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1647. if (res.ok) {
  1648. showToast('Deleted', `PPPoE client ${name} removed`, 'success');
  1649. loadPPPoE(false);
  1650. fetchData(false);
  1651. }
  1652. } catch (err) {
  1653. showToast('Error', err.message, 'error');
  1654. }
  1655. }
  1656. // ======================== WireGuard Multi-Interface & Multi-Peer ========================
  1657. state.wgSubTab = 'ifaces';
  1658. function switchWGSubTab(tab) {
  1659. state.wgSubTab = tab;
  1660. const ifacesPanel = document.getElementById('wg-subtab-ifaces');
  1661. const peersPanel = document.getElementById('wg-subtab-peers');
  1662. const ifacesBtn = document.getElementById('wg-subtab-btn-ifaces');
  1663. const peersBtn = document.getElementById('wg-subtab-btn-peers');
  1664. if (tab === 'ifaces') {
  1665. ifacesPanel?.classList.remove('hidden');
  1666. peersPanel?.classList.add('hidden');
  1667. 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';
  1668. 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';
  1669. } else {
  1670. ifacesPanel?.classList.add('hidden');
  1671. peersPanel?.classList.remove('hidden');
  1672. 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';
  1673. 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';
  1674. renderWGPeers();
  1675. }
  1676. }
  1677. async function loadWireGuard(populateInputs = true) {
  1678. try {
  1679. const [ifacesRes, peersRes] = await Promise.all([
  1680. fetch(`${API_BASE}/vpn/wireguard/interfaces`),
  1681. fetch(`${API_BASE}/vpn/wireguard/peers`)
  1682. ]);
  1683. const ifaces = ifacesRes.ok ? await ifacesRes.json() : [];
  1684. const peers = peersRes.ok ? await peersRes.json() : [];
  1685. state.wgInterfaces = Array.isArray(ifaces) ? ifaces : [];
  1686. state.wgPeers = Array.isArray(peers) ? peers : [];
  1687. // Badges
  1688. const ifacesCountBadge = document.getElementById('wg-ifaces-count');
  1689. if (ifacesCountBadge) ifacesCountBadge.innerText = `${state.wgInterfaces.length} Interfaces`;
  1690. const peersCountBadge = document.getElementById('wg-peers-count');
  1691. if (peersCountBadge) peersCountBadge.innerText = `${state.wgPeers.length} Peers`;
  1692. const subTabIfaces = document.getElementById('wg-subtab-badge-ifaces');
  1693. if (subTabIfaces) subTabIfaces.innerText = state.wgInterfaces.length;
  1694. const subTabPeers = document.getElementById('wg-subtab-badge-peers');
  1695. if (subTabPeers) subTabPeers.innerText = state.wgPeers.length;
  1696. // Render Interfaces
  1697. const ifacesTbody = document.getElementById('wg-ifaces-table-body');
  1698. const ifacesEmpty = document.getElementById('wg-ifaces-empty');
  1699. if (ifacesTbody) {
  1700. ifacesTbody.innerHTML = '';
  1701. if (state.wgInterfaces.length === 0) {
  1702. if (ifacesEmpty) ifacesEmpty.classList.remove('hidden');
  1703. } else {
  1704. if (ifacesEmpty) ifacesEmpty.classList.add('hidden');
  1705. state.wgInterfaces.forEach(iface => {
  1706. const peersOnIface = state.wgPeers.filter(p => p.interface === iface.name).length;
  1707. const tr = document.createElement('tr');
  1708. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1709. tr.innerHTML = `
  1710. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(iface.running, iface.disabled)}</td>
  1711. <td class="py-2.5 px-3">
  1712. <div class="flex items-center gap-1.5">
  1713. <span class="font-bold text-white">${escapeHtml(iface.name)}</span>
  1714. ${iface.comment ? `<span class="text-[10px] text-slate-400 font-sans italic">(${escapeHtml(iface.comment)})</span>` : ''}
  1715. </div>
  1716. </td>
  1717. <td class="py-2.5 px-3 text-amber-400 font-mono">${iface.listen_port}</td>
  1718. <td class="py-2.5 px-3 text-emerald-400 font-mono">${iface.address || '<span class="text-slate-600 font-sans">--</span>'}</td>
  1719. <td class="py-2.5 px-3 text-slate-300 font-mono">
  1720. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${iface.public_key}', 'Public Key')" title="Click to copy: ${iface.public_key}">
  1721. ${(iface.public_key || '').substring(0, 10)}... 📋
  1722. </span>
  1723. </td>
  1724. <td class="py-2.5 px-3 text-slate-400 font-mono">${iface.mtu || 1420}</td>
  1725. <td class="py-2.5 px-3 text-center">
  1726. <span class="px-2 py-0.5 rounded text-[10px] font-sans bg-slate-800 text-slate-300">${peersOnIface} peer${peersOnIface !== 1 ? 's' : ''}</span>
  1727. </td>
  1728. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  1729. ${iface.running ? `
  1730. <button onclick="stopWGInterface('${iface.name}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Stop</button>
  1731. ` : `
  1732. <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>
  1733. `}
  1734. <button onclick="toggleWGInterfaceState('${iface.name}', ${iface.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white font-medium">
  1735. ${iface.disabled ? 'Enable' : 'Disable'}
  1736. </button>
  1737. <button onclick="openEditWGInterfaceModal('${iface.name}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Edit</button>
  1738. <button onclick="deleteWGInterface('${iface.name}')" class="text-xs text-slate-500 hover:text-rose-400 font-medium">Delete</button>
  1739. </td>
  1740. `;
  1741. ifacesTbody.appendChild(tr);
  1742. });
  1743. }
  1744. }
  1745. // Populate filter dropdown in peers tab
  1746. const filterSel = document.getElementById('wg-peers-filter-iface');
  1747. if (filterSel) {
  1748. const currentVal = filterSel.value;
  1749. filterSel.innerHTML = '<option value="">All Interfaces</option>';
  1750. state.wgInterfaces.forEach(i => {
  1751. const opt = document.createElement('option');
  1752. opt.value = i.name;
  1753. opt.innerText = i.name;
  1754. if (i.name === currentVal) opt.selected = true;
  1755. filterSel.appendChild(opt);
  1756. });
  1757. }
  1758. renderWGPeers();
  1759. } catch (err) {
  1760. console.error('Failed to load WireGuard:', err);
  1761. }
  1762. }
  1763. function formatWGPeerEndpoint(address, port) {
  1764. if (!address || address === '(none)') return '--';
  1765. let addr = address.trim();
  1766. let p = port || 0;
  1767. while (addr.includes(':') && !addr.startsWith('[')) {
  1768. const lastColon = addr.lastIndexOf(':');
  1769. const maybePort = addr.substring(lastColon + 1);
  1770. if (!isNaN(parseInt(maybePort, 10)) && parseInt(maybePort, 10) > 0) {
  1771. if (!p) p = parseInt(maybePort, 10);
  1772. addr = addr.substring(0, lastColon);
  1773. } else {
  1774. break;
  1775. }
  1776. }
  1777. return p ? `${addr}:${p}` : addr;
  1778. }
  1779. function renderWGPeers() {
  1780. const filterSel = document.getElementById('wg-peers-filter-iface');
  1781. const selectedIface = filterSel ? filterSel.value : '';
  1782. const tbody = document.getElementById('wg-peers-table-body');
  1783. const empty = document.getElementById('wg-peers-empty');
  1784. if (!tbody) return;
  1785. tbody.innerHTML = '';
  1786. const filtered = selectedIface ? state.wgPeers.filter(p => p.interface === selectedIface) : state.wgPeers;
  1787. if (filtered.length === 0) {
  1788. if (empty) empty.classList.remove('hidden');
  1789. } else {
  1790. if (empty) empty.classList.add('hidden');
  1791. filtered.forEach(p => {
  1792. const isOnline = p.latest_handshake && !p.latest_handshake.includes('Never');
  1793. const tr = document.createElement('tr');
  1794. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1795. tr.innerHTML = `
  1796. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(isOnline, p.disabled)}</td>
  1797. <td class="py-2.5 px-3 font-mono font-bold text-rose-400">${escapeHtml(p.interface)}</td>
  1798. <td class="py-2.5 px-3 font-bold text-white font-sans">${escapeHtml(p.name || 'Unnamed')}</td>
  1799. <td class="py-2.5 px-3 text-slate-300 font-mono">
  1800. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${p.public_key}', 'Peer Public Key')" title="${p.public_key}">
  1801. ${(p.public_key || '').substring(0, 10)}... 📋
  1802. </span>
  1803. </td>
  1804. <td class="py-2.5 px-3 text-emerald-400 font-mono font-semibold">${(p.allowed_ips || []).join(', ')}</td>
  1805. <td class="py-2.5 px-3 text-slate-400 font-mono">${formatWGPeerEndpoint(p.endpoint_address, p.endpoint_port)}</td>
  1806. <td class="py-2.5 px-3 text-slate-300 font-sans">${p.latest_handshake || 'Never'}</td>
  1807. <td class="py-2.5 px-3 font-mono text-[11px]">
  1808. <span class="text-emerald-400">↓ ${p.transfer_rx_human || '0 B'}</span>
  1809. <span class="text-cyan-400 ml-1">↑ ${p.transfer_tx_human || '0 B'}</span>
  1810. </td>
  1811. <td class="py-2.5 px-3 text-right font-sans space-x-2 whitespace-nowrap">
  1812. <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">
  1813. ${p.disabled ? 'Enable' : 'Disable'}
  1814. </button>
  1815. <button onclick="openEditWGPeerModal('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Edit</button>
  1816. <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>
  1817. <button onclick="deleteWGPeer('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Delete</button>
  1818. </td>
  1819. `;
  1820. tbody.appendChild(tr);
  1821. });
  1822. }
  1823. }
  1824. function openAddWGInterfaceModal() {
  1825. document.getElementById('wg-iface-modal-title').innerText = 'Add WireGuard Interface';
  1826. document.getElementById('wg-iface-modal-edit-orig').value = '';
  1827. const nameEl = document.getElementById('wg-iface-modal-name');
  1828. nameEl.value = `wg${(state.wgInterfaces || []).length}`;
  1829. nameEl.readOnly = false;
  1830. document.getElementById('wg-iface-modal-port').value = 51820 + (state.wgInterfaces || []).length;
  1831. document.getElementById('wg-iface-modal-addr').value = `10.${10 + (state.wgInterfaces || []).length}.0.1/24`;
  1832. document.getElementById('wg-iface-modal-mtu').value = '1420';
  1833. document.getElementById('wg-iface-modal-comment').value = '';
  1834. document.getElementById('wg-iface-modal-pubkey').value = '';
  1835. document.getElementById('wg-iface-modal-privkey').value = '';
  1836. document.getElementById('wg-iface-modal-disabled').checked = false;
  1837. generateWGInterfaceKeys();
  1838. document.getElementById('wg-iface-modal').classList.remove('hidden');
  1839. }
  1840. function openEditWGInterfaceModal(name) {
  1841. const iface = (state.wgInterfaces || []).find(i => i.name === name);
  1842. if (!iface) return;
  1843. document.getElementById('wg-iface-modal-title').innerText = `Edit WireGuard Interface: ${name}`;
  1844. document.getElementById('wg-iface-modal-edit-orig').value = name;
  1845. const nameEl = document.getElementById('wg-iface-modal-name');
  1846. nameEl.value = iface.name;
  1847. nameEl.readOnly = false; // ALLOW RENAMING
  1848. document.getElementById('wg-iface-modal-port').value = iface.listen_port || 51820;
  1849. document.getElementById('wg-iface-modal-addr').value = iface.address || '';
  1850. document.getElementById('wg-iface-modal-mtu').value = iface.mtu || 1420;
  1851. document.getElementById('wg-iface-modal-comment').value = iface.comment || '';
  1852. document.getElementById('wg-iface-modal-pubkey').value = iface.public_key || '';
  1853. document.getElementById('wg-iface-modal-privkey').value = iface.private_key || '';
  1854. document.getElementById('wg-iface-modal-disabled').checked = !!iface.disabled;
  1855. document.getElementById('wg-iface-modal').classList.remove('hidden');
  1856. }
  1857. function closeAddWGInterfaceModal() {
  1858. document.getElementById('wg-iface-modal').classList.add('hidden');
  1859. }
  1860. async function generateWGInterfaceKeys() {
  1861. try {
  1862. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  1863. const keys = await res.json();
  1864. if (res.ok) {
  1865. document.getElementById('wg-iface-modal-privkey').value = keys.private_key;
  1866. document.getElementById('wg-iface-modal-pubkey').value = keys.public_key;
  1867. }
  1868. } catch (err) {
  1869. showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
  1870. }
  1871. }
  1872. async function onWGInterfacePrivKeyInput() {
  1873. const privKey = document.getElementById('wg-iface-modal-privkey').value.trim();
  1874. if (!privKey) return;
  1875. try {
  1876. const res = await fetch(`${API_BASE}/vpn/wireguard/calc-pubkey`, {
  1877. method: 'POST',
  1878. headers: { 'Content-Type': 'application/json' },
  1879. body: JSON.stringify({ private_key: privKey })
  1880. });
  1881. if (res.ok) {
  1882. const data = await res.json();
  1883. if (data.public_key) {
  1884. document.getElementById('wg-iface-modal-pubkey').value = data.public_key;
  1885. }
  1886. }
  1887. } catch (err) {
  1888. // Ignore while typing
  1889. }
  1890. }
  1891. function toggleWGPrivKeyVisibility() {
  1892. const el = document.getElementById('wg-iface-modal-privkey');
  1893. const btn = document.getElementById('btn-toggle-wg-privkey');
  1894. if (el.type === 'password') {
  1895. el.type = 'text';
  1896. btn.innerText = '🙈 Hide';
  1897. } else {
  1898. el.type = 'password';
  1899. btn.innerText = '👁️ Show';
  1900. }
  1901. }
  1902. function copyWGInterfacePubKey() {
  1903. const pub = document.getElementById('wg-iface-modal-pubkey').value;
  1904. if (pub) copyToClipboard(pub, 'Interface Public Key');
  1905. }
  1906. async function submitSaveWGInterface(e) {
  1907. e.preventDefault();
  1908. const origName = document.getElementById('wg-iface-modal-edit-orig').value.trim();
  1909. const name = document.getElementById('wg-iface-modal-name').value.trim();
  1910. const port = parseInt(document.getElementById('wg-iface-modal-port').value, 10) || 51820;
  1911. const addr = document.getElementById('wg-iface-modal-addr').value.trim();
  1912. const mtu = parseInt(document.getElementById('wg-iface-modal-mtu').value, 10) || 1420;
  1913. const comment = document.getElementById('wg-iface-modal-comment').value.trim();
  1914. const pub = document.getElementById('wg-iface-modal-pubkey').value.trim();
  1915. const priv = document.getElementById('wg-iface-modal-privkey').value.trim();
  1916. const disabled = document.getElementById('wg-iface-modal-disabled').checked;
  1917. try {
  1918. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces`, {
  1919. method: 'POST',
  1920. headers: { 'Content-Type': 'application/json' },
  1921. body: JSON.stringify({
  1922. orig_name: origName,
  1923. name,
  1924. listen_port: port,
  1925. address: addr,
  1926. mtu,
  1927. comment,
  1928. public_key: pub,
  1929. private_key: priv,
  1930. disabled
  1931. })
  1932. });
  1933. const data = await res.json();
  1934. if (res.ok) {
  1935. showToast('WireGuard Saved', `Interface ${name} configured successfully`, 'success');
  1936. closeAddWGInterfaceModal();
  1937. loadWireGuard(false);
  1938. fetchData(false);
  1939. } else {
  1940. showToast('Error', data.error || 'Failed to save interface', 'error');
  1941. }
  1942. } catch (err) {
  1943. showToast('Error', err.message, 'error');
  1944. }
  1945. }
  1946. async function startWGInterface(name) {
  1947. try {
  1948. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/start`, { method: 'POST' });
  1949. if (res.ok) {
  1950. showToast('Interface UP', `Started WireGuard interface ${name}`, 'success');
  1951. loadWireGuard(false);
  1952. fetchData(false);
  1953. }
  1954. } catch (err) {
  1955. showToast('Error', err.message, 'error');
  1956. }
  1957. }
  1958. async function stopWGInterface(name) {
  1959. try {
  1960. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  1961. if (res.ok) {
  1962. showToast('Interface DOWN', `Stopped WireGuard interface ${name}`, 'info');
  1963. loadWireGuard(false);
  1964. fetchData(false);
  1965. }
  1966. } catch (err) {
  1967. showToast('Error', err.message, 'error');
  1968. }
  1969. }
  1970. async function toggleWGInterfaceState(name, enable) {
  1971. try {
  1972. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/state`, {
  1973. method: 'POST',
  1974. headers: { 'Content-Type': 'application/json' },
  1975. body: JSON.stringify({ enabled: enable })
  1976. });
  1977. if (res.ok) {
  1978. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  1979. loadWireGuard(false);
  1980. fetchData(false);
  1981. }
  1982. } catch (err) {
  1983. showToast('Error', err.message, 'error');
  1984. }
  1985. }
  1986. async function deleteWGInterface(name) {
  1987. if (!confirm(`Are you sure you want to delete WireGuard interface ${name}? All associated peers will also be removed.`)) return;
  1988. try {
  1989. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1990. if (res.ok) {
  1991. showToast('Deleted', `Interface ${name} removed`, 'success');
  1992. loadWireGuard(false);
  1993. fetchData(false);
  1994. }
  1995. } catch (err) {
  1996. showToast('Error', err.message, 'error');
  1997. }
  1998. }
  1999. function populateWGPeerIfaceSelect(selectedIface = '') {
  2000. const sel = document.getElementById('wg-peer-modal-iface');
  2001. if (!sel) return;
  2002. sel.innerHTML = '';
  2003. (state.wgInterfaces || []).forEach(i => {
  2004. const opt = document.createElement('option');
  2005. opt.value = i.name;
  2006. opt.innerText = `${i.name} (${i.address || 'No IP'})`;
  2007. if (i.name === selectedIface) opt.selected = true;
  2008. sel.appendChild(opt);
  2009. });
  2010. }
  2011. function openAddWGPeerModal() {
  2012. if ((state.wgInterfaces || []).length === 0) {
  2013. showToast('No Interfaces', 'Please add a WireGuard interface first before adding peers', 'warning');
  2014. openAddWGInterfaceModal();
  2015. return;
  2016. }
  2017. document.getElementById('wg-peer-modal-title').innerText = 'Add WireGuard Peer';
  2018. document.getElementById('wg-peer-modal-edit-orig-iface').value = '';
  2019. document.getElementById('wg-peer-modal-edit-orig-pubkey').value = '';
  2020. populateWGPeerIfaceSelect();
  2021. document.getElementById('wg-peer-modal-name').value = '';
  2022. document.getElementById('wg-peer-modal-pubkey').value = '';
  2023. document.getElementById('wg-peer-modal-allowedips').value = '10.10.0.2/32';
  2024. document.getElementById('wg-peer-modal-endpoint').value = '';
  2025. document.getElementById('wg-peer-modal-port').value = '';
  2026. document.getElementById('wg-peer-modal-keepalive').value = '25';
  2027. document.getElementById('wg-peer-modal-preshared').value = '';
  2028. document.getElementById('wg-peer-modal-disabled').checked = false;
  2029. document.getElementById('wg-peer-key-warning').classList.add('hidden');
  2030. document.getElementById('wg-peer-gen-key-box').classList.add('hidden');
  2031. document.getElementById('wg-peer-modal').classList.remove('hidden');
  2032. }
  2033. function openEditWGPeerModal(ifaceName, pubKey) {
  2034. const peer = (state.wgPeers || []).find(p => p.interface === ifaceName && p.public_key === pubKey);
  2035. if (!peer) {
  2036. showToast('Not Found', 'Peer not found', 'warning');
  2037. return;
  2038. }
  2039. document.getElementById('wg-peer-modal-title').innerText = `Edit WireGuard Peer (${peer.name || ifaceName})`;
  2040. document.getElementById('wg-peer-modal-edit-orig-iface').value = peer.interface;
  2041. document.getElementById('wg-peer-modal-edit-orig-pubkey').value = peer.public_key;
  2042. populateWGPeerIfaceSelect(peer.interface);
  2043. document.getElementById('wg-peer-modal-name').value = peer.name || '';
  2044. document.getElementById('wg-peer-modal-pubkey').value = peer.public_key || '';
  2045. document.getElementById('wg-peer-modal-allowedips').value = (peer.allowed_ips || []).join(', ');
  2046. let epHost = (peer.endpoint_address || '').trim();
  2047. let epPort = peer.endpoint_port || '';
  2048. while (epHost.includes(':') && !epHost.startsWith('[')) {
  2049. const lastColon = epHost.lastIndexOf(':');
  2050. const maybePort = epHost.substring(lastColon + 1);
  2051. if (!isNaN(parseInt(maybePort, 10)) && parseInt(maybePort, 10) > 0) {
  2052. if (!epPort) epPort = parseInt(maybePort, 10);
  2053. epHost = epHost.substring(0, lastColon);
  2054. } else {
  2055. break;
  2056. }
  2057. }
  2058. document.getElementById('wg-peer-modal-endpoint').value = epHost;
  2059. document.getElementById('wg-peer-modal-port').value = epPort;
  2060. document.getElementById('wg-peer-modal-keepalive').value = peer.persistent_keepalive ?? 25;
  2061. document.getElementById('wg-peer-modal-preshared').value = peer.preshared_key || '';
  2062. document.getElementById('wg-peer-modal-disabled').checked = !!peer.disabled;
  2063. document.getElementById('wg-peer-key-warning').classList.add('hidden');
  2064. document.getElementById('wg-peer-gen-key-box').classList.add('hidden');
  2065. document.getElementById('wg-peer-modal').classList.remove('hidden');
  2066. }
  2067. function closeAddWGPeerModal() {
  2068. document.getElementById('wg-peer-modal').classList.add('hidden');
  2069. }
  2070. async function generatePeerKeypairHelper() {
  2071. try {
  2072. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  2073. const keys = await res.json();
  2074. if (res.ok) {
  2075. document.getElementById('wg-peer-modal-pubkey').value = keys.public_key;
  2076. document.getElementById('wg-peer-gen-privkey').value = keys.private_key;
  2077. document.getElementById('wg-peer-gen-key-box').classList.remove('hidden');
  2078. checkWGPeerKeyValidity();
  2079. showToast('Keypair Generated', 'Public key inserted and client private key ready to copy', 'info');
  2080. }
  2081. } catch (err) {
  2082. showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
  2083. }
  2084. }
  2085. function copyGeneratedPeerPrivKey() {
  2086. const priv = document.getElementById('wg-peer-gen-privkey').value;
  2087. if (priv) copyToClipboard(priv, 'Client Private Key');
  2088. }
  2089. async function generatePeerPSK() {
  2090. try {
  2091. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  2092. const keys = await res.json();
  2093. if (res.ok && keys.private_key) {
  2094. document.getElementById('wg-peer-modal-preshared').value = keys.private_key;
  2095. showToast('PSK Generated', 'Generated 256-bit preshared key', 'info');
  2096. }
  2097. } catch (err) {
  2098. showToast('Error', err.message, 'error');
  2099. }
  2100. }
  2101. function checkWGPeerKeyValidity() {
  2102. const ifaceName = document.getElementById('wg-peer-modal-iface').value;
  2103. const peerPubKey = document.getElementById('wg-peer-modal-pubkey').value.trim();
  2104. const warningEl = document.getElementById('wg-peer-key-warning');
  2105. if (!warningEl) return;
  2106. const targetIface = (state.wgInterfaces || []).find(i => i.name === ifaceName);
  2107. if (targetIface && targetIface.public_key && peerPubKey && targetIface.public_key === peerPubKey) {
  2108. warningEl.classList.remove('hidden');
  2109. } else {
  2110. warningEl.classList.add('hidden');
  2111. }
  2112. }
  2113. async function submitSaveWGPeer(e) {
  2114. e.preventDefault();
  2115. const origIface = document.getElementById('wg-peer-modal-edit-orig-iface').value.trim();
  2116. const origPubKey = document.getElementById('wg-peer-modal-edit-orig-pubkey').value.trim();
  2117. const iface = document.getElementById('wg-peer-modal-iface').value;
  2118. const name = document.getElementById('wg-peer-modal-name').value.trim();
  2119. const pub = document.getElementById('wg-peer-modal-pubkey').value.trim();
  2120. const allowed = document.getElementById('wg-peer-modal-allowedips').value
  2121. .split(',')
  2122. .map(s => s.trim())
  2123. .filter(s => s.length > 0);
  2124. let epHost = document.getElementById('wg-peer-modal-endpoint').value.trim();
  2125. let epPort = parseInt(document.getElementById('wg-peer-modal-port').value, 10) || 0;
  2126. while (epHost.includes(':') && !epHost.startsWith('[')) {
  2127. const lastColon = epHost.lastIndexOf(':');
  2128. const maybePort = epHost.substring(lastColon + 1);
  2129. if (!isNaN(parseInt(maybePort, 10)) && parseInt(maybePort, 10) > 0) {
  2130. if (!epPort) epPort = parseInt(maybePort, 10);
  2131. epHost = epHost.substring(0, lastColon);
  2132. } else {
  2133. break;
  2134. }
  2135. }
  2136. const keepalive = parseInt(document.getElementById('wg-peer-modal-keepalive').value, 10) || 0;
  2137. const psk = document.getElementById('wg-peer-modal-preshared').value.trim();
  2138. const disabled = document.getElementById('wg-peer-modal-disabled').checked;
  2139. // Validation
  2140. const targetIface = (state.wgInterfaces || []).find(i => i.name === iface);
  2141. if (targetIface && targetIface.public_key === pub) {
  2142. showToast('Invalid Peer Key', 'Peer public key cannot be the same as the interface public key!', 'error');
  2143. return;
  2144. }
  2145. try {
  2146. const res = await fetch(`${API_BASE}/vpn/wireguard/peers`, {
  2147. method: 'POST',
  2148. headers: { 'Content-Type': 'application/json' },
  2149. body: JSON.stringify({
  2150. orig_interface: origIface,
  2151. orig_public_key: origPubKey,
  2152. interface: iface,
  2153. name,
  2154. public_key: pub,
  2155. allowed_ips: allowed,
  2156. endpoint_address: epHost,
  2157. endpoint_port: epPort,
  2158. persistent_keepalive: keepalive,
  2159. preshared_key: psk,
  2160. disabled
  2161. })
  2162. });
  2163. const data = await res.json();
  2164. if (res.ok) {
  2165. showToast('Peer Saved', `Peer ${name} saved on ${iface}`, 'success');
  2166. closeAddWGPeerModal();
  2167. loadWireGuard(false);
  2168. } else {
  2169. showToast('Error', data.error || 'Failed to save peer', 'error');
  2170. }
  2171. } catch (err) {
  2172. showToast('Error', err.message, 'error');
  2173. }
  2174. }
  2175. async function toggleWGPeerState(iface, pubkey, enable) {
  2176. try {
  2177. const res = await fetch(`${API_BASE}/vpn/wireguard/peers/state`, {
  2178. method: 'POST',
  2179. headers: { 'Content-Type': 'application/json' },
  2180. body: JSON.stringify({ interface: iface, public_key: pubkey, enabled: enable })
  2181. });
  2182. const data = await res.json();
  2183. if (res.ok) {
  2184. showToast(enable ? 'Peer Enabled' : 'Peer Disabled', `Peer state updated on ${iface}`, 'info');
  2185. loadWireGuard(false);
  2186. } else {
  2187. showToast('Error', data.error || 'Failed to update peer state', 'error');
  2188. }
  2189. } catch (err) {
  2190. showToast('Error', err.message, 'error');
  2191. }
  2192. }
  2193. async function deleteWGPeer(iface, pubkey) {
  2194. if (!confirm(`Are you sure you want to remove peer from ${iface}?`)) return;
  2195. try {
  2196. const res = await fetch(`${API_BASE}/vpn/wireguard/peers/delete`, {
  2197. method: 'POST',
  2198. headers: { 'Content-Type': 'application/json' },
  2199. body: JSON.stringify({ interface: iface, public_key: pubkey })
  2200. });
  2201. const data = await res.json();
  2202. if (res.ok) {
  2203. showToast('Peer Deleted', 'WireGuard peer removed', 'success');
  2204. loadWireGuard(false);
  2205. } else {
  2206. showToast('Error', data.error || 'Failed to remove peer', 'error');
  2207. }
  2208. } catch (err) {
  2209. showToast('Error', err.message, 'error');
  2210. }
  2211. }
  2212. // ======================== IPSec FortiGate Phase 1 & 2 Multi-Tunnel Engine ========================
  2213. function switchIpsecModalTab(tab) {
  2214. const p1Tab = document.getElementById('tab-btn-ipsec-p1');
  2215. const p2Tab = document.getElementById('tab-btn-ipsec-p2');
  2216. const p1Content = document.getElementById('ipsec-tab-content-p1');
  2217. const p2Content = document.getElementById('ipsec-tab-content-p2');
  2218. const stepBtn = document.getElementById('btn-ipsec-switch-step');
  2219. if (tab === 'p1') {
  2220. if (p1Tab) {
  2221. 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';
  2222. }
  2223. if (p2Tab) {
  2224. 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';
  2225. }
  2226. if (p1Content) p1Content.classList.remove('hidden');
  2227. if (p2Content) p2Content.classList.add('hidden');
  2228. if (stepBtn) stepBtn.innerHTML = 'Next: Phase 2 Selectors &rarr;';
  2229. } else {
  2230. if (p1Tab) {
  2231. 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';
  2232. }
  2233. if (p2Tab) {
  2234. 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';
  2235. }
  2236. if (p1Content) p1Content.classList.add('hidden');
  2237. if (p2Content) p2Content.classList.remove('hidden');
  2238. if (stepBtn) stepBtn.innerHTML = '&larr; Back: Phase 1 (IKE)';
  2239. }
  2240. }
  2241. function toggleIpsecPhaseStep() {
  2242. const p1Content = document.getElementById('ipsec-tab-content-p1');
  2243. if (p1Content && !p1Content.classList.contains('hidden')) {
  2244. switchIpsecModalTab('p2');
  2245. } else {
  2246. switchIpsecModalTab('p1');
  2247. }
  2248. }
  2249. function toggleIpsecPskVisibility() {
  2250. const pskInput = document.getElementById('ipsec-modal-psk');
  2251. if (!pskInput) return;
  2252. pskInput.type = pskInput.type === 'password' ? 'text' : 'password';
  2253. }
  2254. function addIpsecLocalSubnet(val = '') {
  2255. const container = document.getElementById('ipsec-modal-local-subnets-container');
  2256. if (!container) return;
  2257. const row = document.createElement('div');
  2258. row.className = 'flex items-center gap-2 ipsec-subnet-row';
  2259. row.innerHTML = `
  2260. <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">
  2261. <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>
  2262. `;
  2263. container.appendChild(row);
  2264. }
  2265. function addIpsecRemoteSubnet(val = '') {
  2266. const container = document.getElementById('ipsec-modal-remote-subnets-container');
  2267. if (!container) return;
  2268. const row = document.createElement('div');
  2269. row.className = 'flex items-center gap-2 ipsec-subnet-row';
  2270. row.innerHTML = `
  2271. <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">
  2272. <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>
  2273. `;
  2274. container.appendChild(row);
  2275. }
  2276. function updateIpsecEspProposalFromPFS(val) {
  2277. const prop = document.getElementById('ipsec-modal-espprop');
  2278. if (!prop) return;
  2279. if (val === 'none') {
  2280. prop.value = 'aes256-sha256,aes128-sha256,default';
  2281. } else {
  2282. prop.value = `aes256-sha256-${val},aes128-sha256-${val},default`;
  2283. }
  2284. }
  2285. function updateIpsecIkeProposalFromDH(dh) {
  2286. const el = document.getElementById('ipsec-modal-ikeprop');
  2287. if (el) {
  2288. el.value = `aes256-sha256-${dh},aes128-sha256-${dh},default`;
  2289. }
  2290. }
  2291. function safeSetVal(id, val) {
  2292. const el = document.getElementById(id);
  2293. if (el) el.value = val;
  2294. }
  2295. function safeSetChecked(id, val) {
  2296. const el = document.getElementById(id);
  2297. if (el) el.checked = !!val;
  2298. }
  2299. function safeGetVal(id, def = '') {
  2300. const el = document.getElementById(id);
  2301. return el ? el.value : def;
  2302. }
  2303. async function loadIPSec(populateInputs = true) {
  2304. try {
  2305. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`);
  2306. const list = await res.json();
  2307. state.ipsecTunnels = Array.isArray(list) ? list : [];
  2308. const activeCount = state.ipsecTunnels.filter(t => t.running || t.status === 'ESTABLISHED').length;
  2309. const badge = document.getElementById('ipsec-sas-badge');
  2310. if (badge) badge.innerText = `${activeCount} Active SAs`;
  2311. const tbody = document.getElementById('ipsec-table-body');
  2312. const empty = document.getElementById('ipsec-empty');
  2313. if (!tbody) return;
  2314. tbody.innerHTML = '';
  2315. if (state.ipsecTunnels.length === 0) {
  2316. if (empty) empty.classList.remove('hidden');
  2317. } else {
  2318. if (empty) empty.classList.add('hidden');
  2319. state.ipsecTunnels.forEach(c => {
  2320. const isEstablished = c.running || c.status === 'ESTABLISHED';
  2321. const tr = document.createElement('tr');
  2322. tr.className = 'hover:bg-slate-800/40 transition text-xs select-none';
  2323. // Local subnets tags
  2324. const localList = (c.local_subnets && c.local_subnets.length > 0) ? c.local_subnets : (c.local_subnet ? [c.local_subnet] : ['0.0.0.0/0']);
  2325. 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('');
  2326. // Remote subnets tags
  2327. const remoteList = (c.remote_subnets && c.remote_subnets.length > 0) ? c.remote_subnets : (c.remote_subnet ? [c.remote_subnet] : ['0.0.0.0/0']);
  2328. 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('');
  2329. const ikeVersionBadge = (c.ike_version || 'ikev2').toUpperCase();
  2330. const p2Name = c.phase2_name || `${c.name}_p2`;
  2331. tr.innerHTML = `
  2332. <td class="py-2.5 px-3 text-center">
  2333. ${isEstablished ? `
  2334. <span class="inline-flex items-center gap-1.5 text-emerald-400 font-mono font-bold text-[11px]" title="Active SA Established">
  2335. <span class="w-2.5 h-2.5 rounded-full bg-emerald-400 animate-pulse"></span>
  2336. <span>UP</span>
  2337. </span>
  2338. ` : (c.disabled ? `
  2339. <span class="inline-flex items-center gap-1.5 text-slate-500 font-mono text-[11px]" title="Tunnel Disabled">
  2340. <span class="w-2 h-2 rounded-full bg-rose-500"></span>
  2341. <span>DOWN</span>
  2342. </span>
  2343. ` : `
  2344. <span class="inline-flex items-center gap-1.5 text-amber-400 font-mono text-[11px]" title="Disconnected / Idle">
  2345. <span class="w-2 h-2 rounded-full bg-amber-400"></span>
  2346. <span>IDLE</span>
  2347. </span>
  2348. `)}
  2349. </td>
  2350. <td class="py-2.5 px-4 font-bold text-white">
  2351. <div class="flex items-center gap-2">
  2352. <span class="text-amber-400">🛡</span>
  2353. <div>
  2354. <div>${escapeHtml(c.name)}</div>
  2355. <div class="text-[10px] text-slate-500 font-normal">P2: ${escapeHtml(p2Name)}</div>
  2356. </div>
  2357. </div>
  2358. </td>
  2359. <td class="py-2.5 px-4 text-slate-300 font-mono font-medium">${escapeHtml(c.remote_addrs || '%any')}</td>
  2360. <td class="py-2.5 px-4 font-sans">
  2361. <div class="flex items-center gap-1.5">
  2362. <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>
  2363. <span class="text-[10px] text-slate-400">${c.auth_method || 'PSK'}</span>
  2364. </div>
  2365. </td>
  2366. <td class="py-2.5 px-4">
  2367. <div class="space-y-1">
  2368. <div class="flex items-center flex-wrap gap-1">
  2369. <span class="text-[9px] text-cyan-400 uppercase font-bold mr-1">Local:</span>
  2370. ${localBadges}
  2371. </div>
  2372. <div class="flex items-center flex-wrap gap-1">
  2373. <span class="text-[9px] text-purple-400 uppercase font-bold mr-1">Remote:</span>
  2374. ${remoteBadges}
  2375. </div>
  2376. </div>
  2377. </td>
  2378. <td class="py-2.5 px-4 font-mono text-[11px] text-slate-400">
  2379. <div class="truncate max-w-[140px]" title="${escapeHtml(c.esp_proposals || '')}">
  2380. ${escapeHtml(c.esp_proposals || 'aes256-sha256')}
  2381. </div>
  2382. <div class="text-[10px] text-slate-500">PFS: ${escapeHtml(c.pfs_group || 'modp2048')}</div>
  2383. </td>
  2384. <td class="py-2.5 px-4 text-right space-x-2 font-sans">
  2385. ${isEstablished ? `
  2386. <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>
  2387. ` : `
  2388. <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>
  2389. `}
  2390. <button onclick="toggleIPSecState('${c.name}', ${c.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  2391. ${c.disabled ? 'Enable' : 'Disable'}
  2392. </button>
  2393. <button onclick="openEditIPSecModal('${c.name}')" class="text-xs text-amber-400 hover:text-amber-300">Edit</button>
  2394. <button onclick="deleteIPSecConn('${c.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2395. </td>
  2396. `;
  2397. tbody.appendChild(tr);
  2398. });
  2399. }
  2400. } catch (err) {
  2401. console.error('Failed to load IPSec:', err);
  2402. }
  2403. }
  2404. function openAddIPSecModal() {
  2405. const modal = document.getElementById('ipsec-modal');
  2406. if (!modal) return;
  2407. const title = document.getElementById('ipsec-modal-title');
  2408. if (title) title.innerText = 'Configure IPSec Site-to-Site Tunnel';
  2409. // Phase 1 Fields
  2410. safeSetVal('ipsec-modal-name', `tunnel-${(state.ipsecTunnels || []).length + 1}`);
  2411. const nameEl = document.getElementById('ipsec-modal-name');
  2412. if (nameEl) nameEl.readOnly = false;
  2413. safeSetVal('ipsec-modal-ikeversion', 'ikev2');
  2414. safeSetVal('ipsec-modal-ikever', 'ikev2');
  2415. safeSetVal('ipsec-modal-remotegw', '');
  2416. safeSetVal('ipsec-modal-localaddrs', '');
  2417. safeSetVal('ipsec-modal-comments', '');
  2418. safeSetVal('ipsec-modal-psk', '');
  2419. safeSetVal('ipsec-modal-ikeprop', 'aes256-sha256-modp2048,aes128-sha256-modp2048,default');
  2420. safeSetVal('ipsec-modal-dhgroup', 'modp2048');
  2421. safeSetVal('ipsec-modal-ikekeylife', '86400');
  2422. safeSetVal('ipsec-modal-localid', '');
  2423. safeSetVal('ipsec-modal-remoteid', '');
  2424. safeSetVal('ipsec-modal-dpd', 'on-demand');
  2425. // Phase 2 Fields
  2426. safeSetVal('ipsec-modal-p2name', `tunnel-${(state.ipsecTunnels || []).length + 1}_p2`);
  2427. safeSetVal('ipsec-modal-espkeylife', '28800');
  2428. safeSetVal('ipsec-modal-espprop', 'aes256-sha256-modp2048,aes128-sha256-modp2048,default');
  2429. safeSetVal('ipsec-modal-pfsgroup', 'modp2048');
  2430. safeSetChecked('ipsec-modal-autostart', true);
  2431. safeSetChecked('ipsec-modal-disabled', false);
  2432. // Clear & Populate default dynamic subnets
  2433. const localContainer = document.getElementById('ipsec-modal-local-subnets-container');
  2434. const remoteContainer = document.getElementById('ipsec-modal-remote-subnets-container');
  2435. if (localContainer) {
  2436. localContainer.innerHTML = '';
  2437. addIpsecLocalSubnet('192.168.10.0/24');
  2438. }
  2439. if (remoteContainer) {
  2440. remoteContainer.innerHTML = '';
  2441. addIpsecRemoteSubnet('192.168.20.0/24');
  2442. }
  2443. switchIpsecModalTab('p1');
  2444. modal.classList.remove('hidden');
  2445. }
  2446. function openEditIPSecModal(name) {
  2447. const modal = document.getElementById('ipsec-modal');
  2448. if (!modal) return;
  2449. const conn = (state.ipsecTunnels || []).find(c => c.name === name);
  2450. if (!conn) return;
  2451. const title = document.getElementById('ipsec-modal-title');
  2452. if (title) title.innerText = `Edit IPSec Tunnel: ${name}`;
  2453. // Phase 1 Fields
  2454. safeSetVal('ipsec-modal-name', conn.name);
  2455. const nameEl = document.getElementById('ipsec-modal-name');
  2456. if (nameEl) nameEl.readOnly = true;
  2457. safeSetVal('ipsec-modal-ikeversion', conn.ike_version || 'ikev2');
  2458. safeSetVal('ipsec-modal-ikever', conn.ike_version || 'ikev2');
  2459. safeSetVal('ipsec-modal-remotegw', conn.remote_addrs || '');
  2460. safeSetVal('ipsec-modal-localaddrs', conn.local_addrs || '');
  2461. safeSetVal('ipsec-modal-comments', conn.comment || '');
  2462. safeSetVal('ipsec-modal-psk', conn.preshared_key || '');
  2463. safeSetVal('ipsec-modal-ikeprop', conn.ike_proposals || 'aes256-sha256-modp2048,default');
  2464. safeSetVal('ipsec-modal-ikekeylife', conn.ike_keylife || 86400);
  2465. safeSetVal('ipsec-modal-localid', conn.local_id || '');
  2466. safeSetVal('ipsec-modal-remoteid', conn.remote_id || '');
  2467. safeSetVal('ipsec-modal-dpd', conn.dpd || 'on-demand');
  2468. // Phase 2 Fields
  2469. safeSetVal('ipsec-modal-p2name', conn.phase2_name || `${conn.name}_p2`);
  2470. safeSetVal('ipsec-modal-espkeylife', conn.esp_keylife || 28800);
  2471. safeSetVal('ipsec-modal-espprop', conn.esp_proposals || 'aes256-sha256-modp2048,default');
  2472. safeSetVal('ipsec-modal-pfsgroup', conn.pfs_group || 'modp2048');
  2473. safeSetChecked('ipsec-modal-autostart', conn.auto_start ?? true);
  2474. safeSetChecked('ipsec-modal-disabled', !!conn.disabled);
  2475. // Populate dynamic subnets
  2476. const localContainer = document.getElementById('ipsec-modal-local-subnets-container');
  2477. const remoteContainer = document.getElementById('ipsec-modal-remote-subnets-container');
  2478. if (localContainer) {
  2479. localContainer.innerHTML = '';
  2480. const locals = (conn.local_subnets && conn.local_subnets.length > 0) ? conn.local_subnets : (conn.local_subnet ? [conn.local_subnet] : ['192.168.10.0/24']);
  2481. locals.forEach(s => addIpsecLocalSubnet(s));
  2482. }
  2483. if (remoteContainer) {
  2484. remoteContainer.innerHTML = '';
  2485. const remotes = (conn.remote_subnets && conn.remote_subnets.length > 0) ? conn.remote_subnets : (conn.remote_subnet ? [conn.remote_subnet] : ['192.168.20.0/24']);
  2486. remotes.forEach(s => addIpsecRemoteSubnet(s));
  2487. }
  2488. switchIpsecModalTab('p1');
  2489. modal.classList.remove('hidden');
  2490. }
  2491. function closeAddIPSecModal() {
  2492. const modal = document.getElementById('ipsec-modal');
  2493. if (modal) modal.classList.add('hidden');
  2494. }
  2495. async function submitSaveIPSec(e) {
  2496. if (e) e.preventDefault();
  2497. const name = safeGetVal('ipsec-modal-name').trim();
  2498. if (!name) {
  2499. showToast('Error', 'Tunnel name is required', 'error');
  2500. return;
  2501. }
  2502. const ikeVersion = safeGetVal('ipsec-modal-ikeversion') || safeGetVal('ipsec-modal-ikever', 'ikev2');
  2503. const remotegw = safeGetVal('ipsec-modal-remotegw').trim();
  2504. const localAddrs = safeGetVal('ipsec-modal-localaddrs').trim() || '%any';
  2505. const comments = safeGetVal('ipsec-modal-comments').trim();
  2506. const psk = safeGetVal('ipsec-modal-psk');
  2507. const ikeProposals = safeGetVal('ipsec-modal-ikeprop', 'aes256-sha256-modp2048,default').trim();
  2508. const ikeKeylife = parseInt(safeGetVal('ipsec-modal-ikekeylife', '86400'), 10) || 86400;
  2509. const localId = safeGetVal('ipsec-modal-localid').trim();
  2510. const remoteId = safeGetVal('ipsec-modal-remoteid').trim();
  2511. const dpd = safeGetVal('ipsec-modal-dpd', 'on-demand');
  2512. const phase2Name = safeGetVal('ipsec-modal-p2name').trim() || `${name}_p2`;
  2513. const espProposals = safeGetVal('ipsec-modal-espprop', 'aes256-sha256-modp2048,default').trim();
  2514. const espKeylife = parseInt(safeGetVal('ipsec-modal-espkeylife', '28800'), 10) || 28800;
  2515. const pfsGroup = safeGetVal('ipsec-modal-pfsgroup', 'modp2048');
  2516. const autostart = document.getElementById('ipsec-modal-autostart')?.checked ?? true;
  2517. const disabled = document.getElementById('ipsec-modal-disabled')?.checked ?? false;
  2518. // Scrape dynamic local and remote subnets
  2519. const localInputs = document.querySelectorAll('#ipsec-modal-local-subnets-container input');
  2520. const localSubnets = [];
  2521. localInputs.forEach(inp => {
  2522. const v = inp.value.trim();
  2523. if (v) localSubnets.push(v);
  2524. });
  2525. const remoteInputs = document.querySelectorAll('#ipsec-modal-remote-subnets-container input');
  2526. const remoteSubnets = [];
  2527. remoteInputs.forEach(inp => {
  2528. const v = inp.value.trim();
  2529. if (v) remoteSubnets.push(v);
  2530. });
  2531. try {
  2532. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`, {
  2533. method: 'POST',
  2534. headers: { 'Content-Type': 'application/json' },
  2535. body: JSON.stringify({
  2536. name,
  2537. comment: comments,
  2538. ike_version: ikeVersion,
  2539. local_addrs: localAddrs,
  2540. remote_addrs: remotegw,
  2541. preshared_key: psk,
  2542. ike_proposals: ikeProposals,
  2543. ike_keylife: ikeKeylife,
  2544. local_id: localId,
  2545. remote_id: remoteId,
  2546. dpd: dpd,
  2547. phase2_name: phase2Name,
  2548. esp_proposals: espProposals,
  2549. esp_keylife: espKeylife,
  2550. pfs_group: pfsGroup,
  2551. pfs: pfsGroup !== 'none',
  2552. local_subnets: localSubnets,
  2553. remote_subnets: remoteSubnets,
  2554. local_subnet: localSubnets[0] || '0.0.0.0/0',
  2555. remote_subnet: remoteSubnets[0] || '0.0.0.0/0',
  2556. auto_start: autostart,
  2557. disabled
  2558. })
  2559. });
  2560. if (res.ok) {
  2561. showToast('IPSec Saved', `FortiGate Tunnel ${name} configured`, 'success');
  2562. closeAddIPSecModal();
  2563. loadIPSec(false);
  2564. } else {
  2565. const err = await res.json();
  2566. showToast('Error', err.error || 'Failed to save IPSec tunnel', 'error');
  2567. }
  2568. } catch (err) {
  2569. showToast('Error', err.message, 'error');
  2570. }
  2571. }
  2572. async function startIPSecTunnel(name) {
  2573. try {
  2574. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/start`, { method: 'POST' });
  2575. if (res.ok) {
  2576. showToast('Initiating Tunnel', `Attempting SA handshake for ${name}...`, 'info');
  2577. setTimeout(() => loadIPSec(false), 2000);
  2578. }
  2579. } catch (err) {
  2580. showToast('Error', err.message, 'error');
  2581. }
  2582. }
  2583. async function stopIPSecTunnel(name) {
  2584. try {
  2585. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  2586. if (res.ok) {
  2587. showToast('Terminated', `IPSec SA for ${name} closed`, 'info');
  2588. loadIPSec(false);
  2589. }
  2590. } catch (err) {
  2591. showToast('Error', err.message, 'error');
  2592. }
  2593. }
  2594. async function toggleIPSecState(name, enable) {
  2595. try {
  2596. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/state`, {
  2597. method: 'POST',
  2598. headers: { 'Content-Type': 'application/json' },
  2599. body: JSON.stringify({ enabled: enable })
  2600. });
  2601. if (res.ok) {
  2602. showToast(enable ? 'Enabled' : 'Disabled', `IPSec tunnel ${name} updated`, 'info');
  2603. loadIPSec(false);
  2604. }
  2605. } catch (err) {
  2606. showToast('Error', err.message, 'error');
  2607. }
  2608. }
  2609. async function deleteIPSecConn(name) {
  2610. if (!confirm(`Are you sure you want to delete IPSec tunnel ${name}?`)) return;
  2611. try {
  2612. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2613. if (res.ok) {
  2614. showToast('Deleted', `IPSec connection ${name} removed`, 'success');
  2615. loadIPSec(false);
  2616. fetchData(false);
  2617. }
  2618. } catch (err) {
  2619. showToast('Error', err.message, 'error');
  2620. }
  2621. }
  2622. // ======================== L2TP Multi-Instance ========================
  2623. async function loadL2TP(populateInputs = true) {
  2624. try {
  2625. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2626. await fetchPPPProfilesList();
  2627. }
  2628. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`);
  2629. const list = await res.json();
  2630. state.l2tpList = Array.isArray(list) ? list : [];
  2631. const badge = document.getElementById('l2tp-count-badge');
  2632. if (badge) badge.innerText = `${state.l2tpList.length} Client${state.l2tpList.length !== 1 ? 's' : ''}`;
  2633. const tbody = document.getElementById('l2tp-table-body');
  2634. const empty = document.getElementById('l2tp-empty');
  2635. if (!tbody) return;
  2636. tbody.innerHTML = '';
  2637. if (state.l2tpList.length === 0) {
  2638. if (empty) empty.classList.remove('hidden');
  2639. } else {
  2640. if (empty) empty.classList.add('hidden');
  2641. state.l2tpList.forEach(inst => {
  2642. const tr = document.createElement('tr');
  2643. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  2644. tr.innerHTML = `
  2645. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  2646. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  2647. <td class="py-2.5 px-3 text-cyan-400 font-mono">${escapeHtml(inst.connect_to)}</td>
  2648. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  2649. <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>
  2650. <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>
  2651. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  2652. <td class="py-2.5 px-3 text-center">
  2653. <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'}">
  2654. ${inst.default_route ? 'Yes' : 'No'}
  2655. </span>
  2656. </td>
  2657. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  2658. ${inst.running ? `
  2659. <button onclick="disconnectL2TPInstance('${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  2660. ` : `
  2661. <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>
  2662. `}
  2663. <button onclick="toggleL2TPState('${escapeHtml(inst.name)}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  2664. ${inst.disabled ? 'Enable' : 'Disable'}
  2665. </button>
  2666. <button onclick="openEditL2TPModal('${escapeHtml(inst.name)}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2667. <button onclick="deleteL2TPInstance('${escapeHtml(inst.name)}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2668. </td>
  2669. `;
  2670. tbody.appendChild(tr);
  2671. });
  2672. }
  2673. } catch (err) {
  2674. console.error('Failed to load L2TP:', err);
  2675. }
  2676. }
  2677. async function openAddL2TPModal() {
  2678. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2679. await fetchPPPProfilesList();
  2680. }
  2681. document.getElementById('l2tp-modal-title').innerText = 'Add L2TP Client Interface';
  2682. document.getElementById('l2tp-modal-name').value = `l2tp-out${(state.l2tpList || []).length + 1}`;
  2683. document.getElementById('l2tp-modal-name').readOnly = false;
  2684. document.getElementById('l2tp-modal-server').value = '';
  2685. document.getElementById('l2tp-modal-user').value = '';
  2686. document.getElementById('l2tp-modal-pass').value = '';
  2687. document.getElementById('l2tp-modal-ipsec').value = '';
  2688. document.getElementById('l2tp-modal-defroute').checked = true;
  2689. document.getElementById('l2tp-modal-disabled').checked = false;
  2690. populateProfileSelect('l2tp-modal-profile', 'default-encryption', 'default-encryption');
  2691. document.getElementById('l2tp-modal').classList.remove('hidden');
  2692. }
  2693. async function openEditL2TPModal(name) {
  2694. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2695. await fetchPPPProfilesList();
  2696. }
  2697. const inst = (state.l2tpList || []).find(i => i.name === name);
  2698. if (!inst) return;
  2699. document.getElementById('l2tp-modal-title').innerText = `Edit L2TP Client: ${name}`;
  2700. document.getElementById('l2tp-modal-name').value = inst.name;
  2701. document.getElementById('l2tp-modal-name').readOnly = true;
  2702. document.getElementById('l2tp-modal-server').value = inst.connect_to || '';
  2703. document.getElementById('l2tp-modal-user').value = inst.username || '';
  2704. document.getElementById('l2tp-modal-pass').value = inst.password || '';
  2705. document.getElementById('l2tp-modal-ipsec').value = inst.ipsec_secret || '';
  2706. document.getElementById('l2tp-modal-defroute').checked = inst.default_route ?? true;
  2707. document.getElementById('l2tp-modal-disabled').checked = !!inst.disabled;
  2708. populateProfileSelect('l2tp-modal-profile', inst.profile || 'default-encryption', 'default-encryption');
  2709. document.getElementById('l2tp-modal').classList.remove('hidden');
  2710. }
  2711. function closeL2TPModal() {
  2712. document.getElementById('l2tp-modal').classList.add('hidden');
  2713. }
  2714. async function submitSaveL2TP(e) {
  2715. e.preventDefault();
  2716. const name = document.getElementById('l2tp-modal-name').value.trim();
  2717. const server = document.getElementById('l2tp-modal-server').value.trim();
  2718. const user = document.getElementById('l2tp-modal-user').value.trim();
  2719. const pass = document.getElementById('l2tp-modal-pass').value;
  2720. const profile = document.getElementById('l2tp-modal-profile')?.value || 'default-encryption';
  2721. const ipsec = document.getElementById('l2tp-modal-ipsec').value;
  2722. const defRoute = document.getElementById('l2tp-modal-defroute').checked;
  2723. const disabled = document.getElementById('l2tp-modal-disabled').checked;
  2724. try {
  2725. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`, {
  2726. method: 'POST',
  2727. headers: { 'Content-Type': 'application/json' },
  2728. body: JSON.stringify({
  2729. name,
  2730. connect_to: server,
  2731. username: user,
  2732. password: pass,
  2733. profile: profile,
  2734. ipsec_secret: ipsec,
  2735. default_route: defRoute,
  2736. disabled
  2737. })
  2738. });
  2739. if (res.ok) {
  2740. showToast('L2TP Saved', `Client ${name} configuration saved`, 'success');
  2741. closeL2TPModal();
  2742. loadL2TP(false);
  2743. fetchData(false);
  2744. }
  2745. } catch (err) {
  2746. showToast('Error', err.message, 'error');
  2747. }
  2748. }
  2749. async function connectL2TPInstance(name) {
  2750. try {
  2751. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  2752. if (res.ok) {
  2753. showToast('Connecting', `Dialing L2TP ${name}...`, 'info');
  2754. setTimeout(() => loadL2TP(false), 2000);
  2755. }
  2756. } catch (err) {
  2757. showToast('Error', err.message, 'error');
  2758. }
  2759. }
  2760. async function disconnectL2TPInstance(name) {
  2761. try {
  2762. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  2763. if (res.ok) {
  2764. showToast('Disconnected', `L2TP tunnel ${name} terminated`, 'info');
  2765. loadL2TP(false);
  2766. }
  2767. } catch (err) {
  2768. showToast('Error', err.message, 'error');
  2769. }
  2770. }
  2771. async function toggleL2TPState(name, enable) {
  2772. try {
  2773. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/state`, {
  2774. method: 'POST',
  2775. headers: { 'Content-Type': 'application/json' },
  2776. body: JSON.stringify({ enabled: enable })
  2777. });
  2778. if (res.ok) {
  2779. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  2780. loadL2TP(false);
  2781. }
  2782. } catch (err) {
  2783. showToast('Error', err.message, 'error');
  2784. }
  2785. }
  2786. async function deleteL2TPInstance(name) {
  2787. if (!confirm(`Are you sure you want to delete L2TP client ${name}?`)) return;
  2788. try {
  2789. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2790. if (res.ok) {
  2791. showToast('Deleted', `L2TP client ${name} removed`, 'success');
  2792. loadL2TP(false);
  2793. fetchData(false);
  2794. }
  2795. } catch (err) {
  2796. showToast('Error', err.message, 'error');
  2797. }
  2798. }
  2799. // ======================== PPTP Multi-Instance ========================
  2800. async function loadPPTP(populateInputs = true) {
  2801. try {
  2802. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2803. await fetchPPPProfilesList();
  2804. }
  2805. const res = await fetch(`${API_BASE}/vpn/pptp/clients`);
  2806. const list = await res.json();
  2807. state.pptpList = Array.isArray(list) ? list : [];
  2808. const badge = document.getElementById('pptp-count-badge');
  2809. if (badge) badge.innerText = `${state.pptpList.length} Client${state.pptpList.length !== 1 ? 's' : ''}`;
  2810. const tbody = document.getElementById('pptp-table-body');
  2811. const empty = document.getElementById('pptp-empty');
  2812. if (!tbody) return;
  2813. tbody.innerHTML = '';
  2814. if (state.pptpList.length === 0) {
  2815. if (empty) empty.classList.remove('hidden');
  2816. } else {
  2817. if (empty) empty.classList.add('hidden');
  2818. state.pptpList.forEach(inst => {
  2819. const tr = document.createElement('tr');
  2820. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  2821. tr.innerHTML = `
  2822. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  2823. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  2824. <td class="py-2.5 px-3 text-purple-400 font-mono">${escapeHtml(inst.connect_to)}</td>
  2825. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  2826. <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>
  2827. <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>
  2828. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  2829. <td class="py-2.5 px-3 text-center">
  2830. <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'}">
  2831. ${inst.require_mppe ? 'MPPE-128' : 'None'}
  2832. </span>
  2833. </td>
  2834. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  2835. ${inst.running ? `
  2836. <button onclick="disconnectPPTPInstance('${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  2837. ` : `
  2838. <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>
  2839. `}
  2840. <button onclick="togglePPTPState('${escapeHtml(inst.name)}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  2841. ${inst.disabled ? 'Enable' : 'Disable'}
  2842. </button>
  2843. <button onclick="openEditPPTPModal('${escapeHtml(inst.name)}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2844. <button onclick="deletePPTPInstance('${escapeHtml(inst.name)}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2845. </td>
  2846. `;
  2847. tbody.appendChild(tr);
  2848. });
  2849. }
  2850. } catch (err) {
  2851. console.error('Failed to load PPTP:', err);
  2852. }
  2853. }
  2854. async function openAddPPTPModal() {
  2855. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2856. await fetchPPPProfilesList();
  2857. }
  2858. document.getElementById('pptp-modal-title').innerText = 'Add PPTP Client Interface';
  2859. document.getElementById('pptp-modal-name').value = `pptp-out${(state.pptpList || []).length + 1}`;
  2860. document.getElementById('pptp-modal-name').readOnly = false;
  2861. document.getElementById('pptp-modal-server').value = '';
  2862. document.getElementById('pptp-modal-user').value = '';
  2863. document.getElementById('pptp-modal-pass').value = '';
  2864. document.getElementById('pptp-modal-mppe').checked = true;
  2865. document.getElementById('pptp-modal-defroute').checked = true;
  2866. document.getElementById('pptp-modal-disabled').checked = false;
  2867. populateProfileSelect('pptp-modal-profile', 'default-encryption', 'default-encryption');
  2868. document.getElementById('pptp-modal').classList.remove('hidden');
  2869. }
  2870. async function openEditPPTPModal(name) {
  2871. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2872. await fetchPPPProfilesList();
  2873. }
  2874. const inst = (state.pptpList || []).find(i => i.name === name);
  2875. if (!inst) return;
  2876. document.getElementById('pptp-modal-title').innerText = `Edit PPTP Client: ${name}`;
  2877. document.getElementById('pptp-modal-name').value = inst.name;
  2878. document.getElementById('pptp-modal-name').readOnly = true;
  2879. document.getElementById('pptp-modal-server').value = inst.connect_to || '';
  2880. document.getElementById('pptp-modal-user').value = inst.username || '';
  2881. document.getElementById('pptp-modal-pass').value = inst.password || '';
  2882. document.getElementById('pptp-modal-mppe').checked = inst.require_mppe ?? true;
  2883. document.getElementById('pptp-modal-defroute').checked = inst.default_route ?? true;
  2884. document.getElementById('pptp-modal-disabled').checked = !!inst.disabled;
  2885. populateProfileSelect('pptp-modal-profile', inst.profile || 'default-encryption', 'default-encryption');
  2886. document.getElementById('pptp-modal').classList.remove('hidden');
  2887. }
  2888. function closePPTPModal() {
  2889. document.getElementById('pptp-modal').classList.add('hidden');
  2890. }
  2891. async function submitSavePPTP(e) {
  2892. e.preventDefault();
  2893. const name = document.getElementById('pptp-modal-name').value.trim();
  2894. const server = document.getElementById('pptp-modal-server').value.trim();
  2895. const user = document.getElementById('pptp-modal-user').value.trim();
  2896. const pass = document.getElementById('pptp-modal-pass').value;
  2897. const profile = document.getElementById('pptp-modal-profile')?.value || 'default-encryption';
  2898. const mppe = document.getElementById('pptp-modal-mppe').checked;
  2899. const defRoute = document.getElementById('pptp-modal-defroute').checked;
  2900. const disabled = document.getElementById('pptp-modal-disabled').checked;
  2901. try {
  2902. const res = await fetch(`${API_BASE}/vpn/pptp/clients`, {
  2903. method: 'POST',
  2904. headers: { 'Content-Type': 'application/json' },
  2905. body: JSON.stringify({
  2906. name,
  2907. connect_to: server,
  2908. username: user,
  2909. password: pass,
  2910. profile: profile,
  2911. require_mppe: mppe,
  2912. default_route: defRoute,
  2913. auto_reconnect: true,
  2914. disabled
  2915. })
  2916. });
  2917. if (res.ok) {
  2918. showToast('PPTP Saved', `Client ${name} configuration saved`, 'success');
  2919. closePPTPModal();
  2920. loadPPTP(false);
  2921. fetchData(false);
  2922. }
  2923. } catch (err) {
  2924. showToast('Error', err.message, 'error');
  2925. }
  2926. }
  2927. async function connectPPTPInstance(name) {
  2928. try {
  2929. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  2930. if (res.ok) {
  2931. showToast('Connecting', `Dialing PPTP ${name}...`, 'info');
  2932. setTimeout(() => loadPPTP(false), 2000);
  2933. }
  2934. } catch (err) {
  2935. showToast('Error', err.message, 'error');
  2936. }
  2937. }
  2938. async function disconnectPPTPInstance(name) {
  2939. try {
  2940. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  2941. if (res.ok) {
  2942. showToast('Disconnected', `PPTP tunnel ${name} terminated`, 'info');
  2943. loadPPTP(false);
  2944. }
  2945. } catch (err) {
  2946. showToast('Error', err.message, 'error');
  2947. }
  2948. }
  2949. async function togglePPTPState(name, enable) {
  2950. try {
  2951. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/state`, {
  2952. method: 'POST',
  2953. headers: { 'Content-Type': 'application/json' },
  2954. body: JSON.stringify({ enabled: enable })
  2955. });
  2956. if (res.ok) {
  2957. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  2958. loadPPTP(false);
  2959. }
  2960. } catch (err) {
  2961. showToast('Error', err.message, 'error');
  2962. }
  2963. }
  2964. async function deletePPTPInstance(name) {
  2965. if (!confirm(`Are you sure you want to delete PPTP client ${name}?`)) return;
  2966. try {
  2967. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2968. if (res.ok) {
  2969. showToast('Deleted', `PPTP client ${name} removed`, 'success');
  2970. loadPPTP(false);
  2971. fetchData(false);
  2972. }
  2973. } catch (err) {
  2974. showToast('Error', err.message, 'error');
  2975. }
  2976. }
  2977. // ---------------- Modal & Helper Functions ----------------
  2978. function openVlanModal(defaultParent = '') {
  2979. const select = document.getElementById('vlan-parent');
  2980. select.innerHTML = '';
  2981. const allIfaces = state.interfaces || [];
  2982. const eligible = allIfaces.filter(i => supportsVLAN(i));
  2983. if (eligible.length === 0) {
  2984. const opt = document.createElement('option');
  2985. opt.value = '';
  2986. opt.innerText = 'No VLAN-capable interfaces available';
  2987. select.appendChild(opt);
  2988. } else {
  2989. eligible.forEach(i => {
  2990. const opt = document.createElement('option');
  2991. opt.value = i.name;
  2992. opt.innerText = `${i.name} (${i.role || i.type || 'Ethernet'} - ${i.state})`;
  2993. if (i.name === defaultParent) opt.selected = true;
  2994. select.appendChild(opt);
  2995. });
  2996. }
  2997. document.getElementById('vlan-id').value = '';
  2998. document.getElementById('vlan-name').value = '';
  2999. document.getElementById('vlan-ip').value = '';
  3000. document.getElementById('vlan-desc').value = '';
  3001. populateRoleSelects('LAN');
  3002. autoSuggestVlanName();
  3003. document.getElementById('vlan-modal').classList.remove('hidden');
  3004. }
  3005. function closeVlanModal() {
  3006. document.getElementById('vlan-modal').classList.add('hidden');
  3007. }
  3008. function autoSuggestVlanName() {
  3009. const parent = document.getElementById('vlan-parent').value;
  3010. if (!parent) return;
  3011. const id = document.getElementById('vlan-id').value;
  3012. const nameInput = document.getElementById('vlan-name');
  3013. if (parent && id) nameInput.placeholder = `${parent}.${id}`;
  3014. }
  3015. function setSubnetPreset(cidr) {
  3016. const ipInput = document.getElementById('vlan-ip');
  3017. const id = document.getElementById('vlan-id').value || '10';
  3018. ipInput.value = `192.168.${id}.1${cidr}`;
  3019. }
  3020. async function submitCreateVlan(e) {
  3021. e.preventDefault();
  3022. const btn = document.getElementById('vlan-submit-btn');
  3023. btn.disabled = true;
  3024. btn.innerText = 'Creating...';
  3025. const parent = document.getElementById('vlan-parent').value;
  3026. if (!parent) {
  3027. showToast('Error', 'Please select a valid VLAN-capable parent interface', 'error');
  3028. btn.disabled = false;
  3029. btn.innerText = 'Create VLAN';
  3030. return;
  3031. }
  3032. const id = parseInt(document.getElementById('vlan-id').value, 10);
  3033. const name = document.getElementById('vlan-name').value.trim();
  3034. const ip = document.getElementById('vlan-ip').value.trim();
  3035. const role = document.getElementById('vlan-role').value;
  3036. const desc = document.getElementById('vlan-desc').value.trim();
  3037. try {
  3038. const res = await fetch(`${API_BASE}/vlans`, {
  3039. method: 'POST',
  3040. headers: { 'Content-Type': 'application/json' },
  3041. body: JSON.stringify({
  3042. parent_name: parent,
  3043. vlan_id: id,
  3044. name: name,
  3045. ip_address: ip,
  3046. role: role,
  3047. description: desc,
  3048. mtu: 1500,
  3049. auto_up: true
  3050. })
  3051. });
  3052. const data = await res.json();
  3053. if (res.ok) {
  3054. showToast('VLAN Created', `Created ${data.name} (VLAN ${data.vlan_id})`, 'success');
  3055. state.expandedParents.add(parent);
  3056. closeVlanModal();
  3057. await fetchData(true);
  3058. if (state.activeTab !== 'interfaces') navigate('interfaces');
  3059. } else {
  3060. showToast('Creation Failed', data.message || 'Failed to create VLAN', 'error');
  3061. }
  3062. } catch (err) {
  3063. showToast('Error', err.message, 'error');
  3064. } finally {
  3065. btn.disabled = false;
  3066. btn.innerText = 'Create VLAN';
  3067. }
  3068. }
  3069. async function confirmDeleteVlan(name) {
  3070. if (!confirm(`Delete VLAN interface ${name}?`)) return;
  3071. try {
  3072. const res = await fetch(`${API_BASE}/vlans/${encodeURIComponent(name)}`, { method: 'DELETE' });
  3073. if (res.ok) {
  3074. showToast('VLAN Deleted', `Interface ${name} removed`, 'success');
  3075. closeIfaceModal();
  3076. fetchData(true);
  3077. }
  3078. } catch (err) {
  3079. showToast('Error', err.message, 'error');
  3080. }
  3081. }
  3082. function openIfaceModal(name) {
  3083. const iface = (state.interfaces || []).find(i => i.name === name);
  3084. if (!iface) return;
  3085. state.currentModalIface = iface.name;
  3086. document.getElementById('modal-iface-name').innerText = iface.name;
  3087. document.getElementById('modal-iface-badge').innerText = iface.is_vlan ? `VLAN ${iface.vlan_id}` : iface.type;
  3088. document.getElementById('modal-iface-mtu').value = iface.mtu;
  3089. populateRoleSelects(iface.role || 'LAN');
  3090. document.getElementById('modal-iface-desc').value = iface.description || '';
  3091. const nameInput = document.getElementById('modal-iface-new-name');
  3092. const renameBtn = document.getElementById('modal-btn-rename');
  3093. const renameHelp = document.getElementById('modal-iface-rename-help');
  3094. if (nameInput) {
  3095. nameInput.value = iface.name;
  3096. if (iface.name === 'lo' || iface.type === 'loopback') {
  3097. nameInput.disabled = true;
  3098. if (renameBtn) renameBtn.disabled = true;
  3099. if (renameHelp) renameHelp.innerText = 'Loopback interface cannot be renamed.';
  3100. } else {
  3101. nameInput.disabled = false;
  3102. if (renameBtn) renameBtn.disabled = false;
  3103. if (renameHelp) renameHelp.innerText = 'Device name in Linux (max 15 characters). Automatically preserves operational link state and metadata.';
  3104. }
  3105. }
  3106. const delBtn = document.getElementById('modal-delete-vlan-btn');
  3107. if (iface.is_vlan) {
  3108. delBtn.classList.remove('hidden');
  3109. } else {
  3110. delBtn.classList.add('hidden');
  3111. }
  3112. renderModalIPs(iface);
  3113. document.getElementById('iface-modal').classList.remove('hidden');
  3114. }
  3115. function renderModalIPs(iface) {
  3116. const container = document.getElementById('modal-ip-list');
  3117. container.innerHTML = '';
  3118. const addrs = [...(iface.ipv4 || []), ...(iface.ipv6 || [])];
  3119. if (addrs.length === 0) {
  3120. container.innerHTML = `<span class="text-slate-500 text-xs font-sans">No IP addresses currently bound</span>`;
  3121. return;
  3122. }
  3123. addrs.forEach(addr => {
  3124. const row = document.createElement('div');
  3125. row.className = 'flex items-center justify-between p-2 rounded bg-slate-900 border border-slate-800';
  3126. row.innerHTML = `
  3127. <span class="text-white">${addr}</span>
  3128. <button onclick="removeInterfaceIP('${addr}')" class="text-[11px] text-rose-400 hover:text-rose-300 font-sans">Remove</button>
  3129. `;
  3130. container.appendChild(row);
  3131. });
  3132. }
  3133. function closeIfaceModal() {
  3134. document.getElementById('iface-modal').classList.add('hidden');
  3135. state.currentModalIface = null;
  3136. }
  3137. async function setIfaceState(name, newState) {
  3138. const target = name || state.currentModalIface;
  3139. if (!target) return;
  3140. await toggleInterfaceState(target, newState);
  3141. const updated = (state.interfaces || []).find(i => i.name === target);
  3142. if (updated) openIfaceModal(target);
  3143. }
  3144. async function applyMTU() {
  3145. const mtu = parseInt(document.getElementById('modal-iface-mtu').value, 10);
  3146. try {
  3147. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/mtu`, {
  3148. method: 'POST',
  3149. headers: { 'Content-Type': 'application/json' },
  3150. body: JSON.stringify({ mtu })
  3151. });
  3152. if (res.ok) {
  3153. showToast('MTU Applied', `Set MTU to ${mtu} on ${state.currentModalIface}`, 'success');
  3154. fetchData(false);
  3155. }
  3156. } catch (err) {
  3157. showToast('Error', err.message, 'error');
  3158. }
  3159. }
  3160. async function addInterfaceIP() {
  3161. const ip = document.getElementById('modal-new-ip').value.trim();
  3162. if (!ip) return;
  3163. try {
  3164. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  3165. method: 'POST',
  3166. headers: { 'Content-Type': 'application/json' },
  3167. body: JSON.stringify({ ip })
  3168. });
  3169. if (res.ok) {
  3170. showToast('IP Added', `Bound ${ip} to ${state.currentModalIface}`, 'success');
  3171. document.getElementById('modal-new-ip').value = '';
  3172. await fetchData(false);
  3173. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  3174. if (iface) renderModalIPs(iface);
  3175. } else {
  3176. const err = await res.json();
  3177. showToast('Error', err.error || err.message || 'Failed to add IP address', 'error');
  3178. }
  3179. } catch (err) {
  3180. showToast('Error', err.message, 'error');
  3181. }
  3182. }
  3183. async function removeInterfaceIP(ip) {
  3184. if (!confirm(`Remove IP ${ip}?`)) return;
  3185. try {
  3186. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  3187. method: 'DELETE',
  3188. headers: { 'Content-Type': 'application/json' },
  3189. body: JSON.stringify({ ip })
  3190. });
  3191. if (res.ok) {
  3192. showToast('IP Removed', `Removed ${ip}`, 'success');
  3193. await fetchData(false);
  3194. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  3195. if (iface) renderModalIPs(iface);
  3196. }
  3197. } catch (err) {
  3198. showToast('Error', err.message, 'error');
  3199. }
  3200. }
  3201. async function renameInterface() {
  3202. const oldName = state.currentModalIface;
  3203. const newNameInput = document.getElementById('modal-iface-new-name');
  3204. const newName = (newNameInput?.value || '').trim();
  3205. if (!oldName) return;
  3206. if (!newName) {
  3207. showToast('Warning', 'Interface name cannot be empty', 'warning');
  3208. return;
  3209. }
  3210. if (newName === oldName) {
  3211. showToast('Info', `Interface name is already "${oldName}"`, 'info');
  3212. return;
  3213. }
  3214. if (newName.length > 15) {
  3215. showToast('Validation Error', 'Interface name cannot exceed 15 characters (Linux IFNAMSIZ)', 'error');
  3216. return;
  3217. }
  3218. if (!/^[a-zA-Z0-9_][a-zA-Z0-9_.-]*$/.test(newName)) {
  3219. showToast('Validation Error', 'Name must contain only alphanumeric characters, underscores, hyphens or dots', 'error');
  3220. return;
  3221. }
  3222. const renameBtn = document.getElementById('modal-btn-rename');
  3223. if (renameBtn) {
  3224. renameBtn.disabled = true;
  3225. renameBtn.innerHTML = `<span class="animate-spin inline-block mr-1">⟳</span> Renaming...`;
  3226. }
  3227. try {
  3228. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(oldName)}/rename`, {
  3229. method: 'POST',
  3230. headers: { 'Content-Type': 'application/json' },
  3231. body: JSON.stringify({ new_name: newName })
  3232. });
  3233. const data = await res.json();
  3234. if (!res.ok) {
  3235. showToast('Rename Failed', data.error || data.message || 'Failed to rename interface', 'error');
  3236. return;
  3237. }
  3238. showToast('Interface Renamed', `Successfully renamed ${oldName} → ${newName}`, 'success');
  3239. state.currentModalIface = newName;
  3240. document.getElementById('modal-iface-name').innerText = newName;
  3241. // Refresh application state
  3242. await fetchData(false);
  3243. const updated = (state.interfaces || []).find(i => i.name === newName);
  3244. if (updated) {
  3245. openIfaceModal(newName);
  3246. } else {
  3247. closeIfaceModal();
  3248. }
  3249. } catch (err) {
  3250. showToast('Error', err.message, 'error');
  3251. } finally {
  3252. if (renameBtn) {
  3253. renameBtn.disabled = false;
  3254. renameBtn.innerHTML = `
  3255. <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>
  3256. <span>Rename</span>
  3257. `;
  3258. }
  3259. }
  3260. }
  3261. async function saveInterfaceMetadata() {
  3262. const oldName = state.currentModalIface;
  3263. const newName = (document.getElementById('modal-iface-new-name')?.value || '').trim();
  3264. const role = document.getElementById('modal-iface-role').value;
  3265. const desc = document.getElementById('modal-iface-desc').value.trim();
  3266. let targetName = oldName;
  3267. // If user changed the name before clicking Save Changes, execute rename first
  3268. if (newName && newName !== oldName && oldName !== 'lo') {
  3269. try {
  3270. const renameRes = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(oldName)}/rename`, {
  3271. method: 'POST',
  3272. headers: { 'Content-Type': 'application/json' },
  3273. body: JSON.stringify({ new_name: newName })
  3274. });
  3275. const data = await renameRes.json();
  3276. if (!renameRes.ok) {
  3277. showToast('Rename Failed', data.error || data.message || 'Could not rename interface', 'error');
  3278. return;
  3279. }
  3280. targetName = newName;
  3281. state.currentModalIface = newName;
  3282. showToast('Renamed', `Interface renamed from ${oldName} to ${newName}`, 'success');
  3283. } catch (err) {
  3284. showToast('Error', err.message, 'error');
  3285. return;
  3286. }
  3287. }
  3288. try {
  3289. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(targetName)}/metadata`, {
  3290. method: 'POST',
  3291. headers: { 'Content-Type': 'application/json' },
  3292. body: JSON.stringify({ role, description: desc })
  3293. });
  3294. if (res.ok) {
  3295. showToast('Saved', 'Interface configuration updated', 'success');
  3296. closeIfaceModal();
  3297. fetchData(false);
  3298. } else {
  3299. const err = await res.json();
  3300. showToast('Error', err.error || err.message || 'Failed to save metadata', 'error');
  3301. }
  3302. } catch (err) {
  3303. showToast('Error', err.message, 'error');
  3304. }
  3305. }
  3306. // ======================== MIKROTIK FIREWALL (/ip firewall) ========================
  3307. state.fwSubTab = 'filter';
  3308. state.routesSubTab = 'routes';
  3309. function renderRuleFlag(disabled, hasComment) {
  3310. let flags = '';
  3311. if (disabled) flags += '<span class="text-rose-400 font-bold" title="Disabled">X</span>';
  3312. if (hasComment) flags += '<span class="text-amber-400 font-bold ml-1" title="Has Comment">C</span>';
  3313. return flags || '<span class="text-slate-600">-</span>';
  3314. }
  3315. function renderActionBadge(action) {
  3316. const act = (action || '').toLowerCase();
  3317. let color = 'bg-slate-800 text-slate-300';
  3318. if (act === 'accept') color = 'bg-emerald-500/20 text-emerald-300 border border-emerald-500/30';
  3319. else if (act === 'drop' || act === 'reject') color = 'bg-rose-500/20 text-rose-300 border border-rose-500/30';
  3320. else if (act === 'masquerade' || act === 'src-nat' || act === 'dst-nat') color = 'bg-amber-500/20 text-amber-300 border border-amber-500/30';
  3321. else if (act.startsWith('mark-')) color = 'bg-purple-500/20 text-purple-300 border border-purple-500/30';
  3322. else if (act === 'log') color = 'bg-cyan-500/20 text-cyan-300 border border-cyan-500/30';
  3323. return `<span class="px-2 py-0.5 rounded text-[10px] font-mono font-semibold ${color}">${action}</span>`;
  3324. }
  3325. function switchFWSubTab(tab) {
  3326. state.fwSubTab = tab;
  3327. const tabs = ['filter', 'nat', 'mangle', 'addrlist', 'geo', 'connections'];
  3328. tabs.forEach(t => {
  3329. const panel = document.getElementById(`fw-subtab-${t}`);
  3330. const btn = document.getElementById(`fw-subtab-btn-${t}`);
  3331. if (panel) {
  3332. if (t === tab) panel.classList.remove('hidden');
  3333. else panel.classList.add('hidden');
  3334. }
  3335. if (btn) {
  3336. if (t === tab) {
  3337. 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';
  3338. } else {
  3339. 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';
  3340. }
  3341. }
  3342. });
  3343. const addBtn = document.getElementById('fw-primary-add-btn');
  3344. if (addBtn) {
  3345. if (tab === 'filter') addBtn.innerHTML = '<span>+ Add Filter Rule</span>';
  3346. else if (tab === 'nat') addBtn.innerHTML = '<span>+ Add NAT Rule</span>';
  3347. else if (tab === 'mangle') addBtn.innerHTML = '<span>+ Add Mangle Rule</span>';
  3348. else if (tab === 'addrlist') addBtn.innerHTML = '<span>+ Add Address List</span>';
  3349. else if (tab === 'geo') addBtn.innerHTML = '<span>⚙️ Schedule Settings</span>';
  3350. else if (tab === 'connections') addBtn.innerHTML = '<span>Refresh Flows</span>';
  3351. }
  3352. if (tab === 'filter') renderFilterRules();
  3353. else if (tab === 'nat') renderNATRules();
  3354. else if (tab === 'mangle') renderMangleRules();
  3355. else if (tab === 'addrlist') renderAddressLists();
  3356. else if (tab === 'geo') loadGeoIP();
  3357. else if (tab === 'connections') loadConnections();
  3358. setTimeout(initTableSorting, 50);
  3359. }
  3360. function openCurrentFWModal() {
  3361. if (state.fwSubTab === 'filter') openAddFilterModal();
  3362. else if (state.fwSubTab === 'nat') openAddNATModal();
  3363. else if (state.fwSubTab === 'mangle') openAddMangleModal();
  3364. else if (state.fwSubTab === 'addrlist') openAddAddrListModal();
  3365. else if (state.fwSubTab === 'geo') openGeoIntervalModal();
  3366. else if (state.fwSubTab === 'connections') loadConnections();
  3367. }
  3368. async function loadFirewall(populateDropdowns = true) {
  3369. try {
  3370. const [summaryRes, filterRes, natRes, mangleRes, addrlistRes, geoStatusRes, geoCountriesRes] = await Promise.all([
  3371. fetch(`${API_BASE}/firewall/summary`),
  3372. fetch(`${API_BASE}/firewall/filter`),
  3373. fetch(`${API_BASE}/firewall/nat`),
  3374. fetch(`${API_BASE}/firewall/mangle`),
  3375. fetch(`${API_BASE}/firewall/address-lists`),
  3376. fetch(`${API_BASE}/firewall/geoip/status`),
  3377. fetch(`${API_BASE}/firewall/geoip/countries`)
  3378. ]);
  3379. if (summaryRes.ok) state.fwSummary = await summaryRes.json();
  3380. if (filterRes.ok) state.filterRules = await filterRes.json();
  3381. if (natRes.ok) state.natRules = await natRes.json();
  3382. if (mangleRes.ok) state.mangleRules = await mangleRes.json();
  3383. if (addrlistRes.ok) state.addressLists = await addrlistRes.json();
  3384. if (geoStatusRes.ok) state.geoStatus = await geoStatusRes.json();
  3385. if (geoCountriesRes.ok) state.geoCountries = await geoCountriesRes.json();
  3386. // Badges
  3387. const bFilter = document.getElementById('fw-badge-filter');
  3388. if (bFilter) bFilter.innerText = (state.filterRules || []).length;
  3389. const bNat = document.getElementById('fw-badge-nat');
  3390. if (bNat) bNat.innerText = (state.natRules || []).length;
  3391. const bMangle = document.getElementById('fw-badge-mangle');
  3392. if (bMangle) bMangle.innerText = (state.mangleRules || []).length;
  3393. const bAddr = document.getElementById('fw-badge-addrlist');
  3394. if (bAddr) bAddr.innerText = (state.addressLists || []).length;
  3395. const bGeo = document.getElementById('fw-badge-geo');
  3396. if (bGeo) bGeo.innerText = state.geoStatus?.enabled_count || 0;
  3397. const sigFilter = (state.filterRules || []).map(r => `${r.id}:${r.chain}:${r.action}:${r.disabled}`).join(';');
  3398. const sigNat = (state.natRules || []).map(r => `${r.id}:${r.chain}:${r.action}:${r.disabled}`).join(';');
  3399. const sigMangle = (state.mangleRules || []).map(r => `${r.id}:${r.chain}:${r.action}:${r.disabled}`).join(';');
  3400. const sigAddr = (state.addressLists || []).map(a => `${a.id}:${a.name}:${a.address}:${a.disabled}`).join(';');
  3401. const tbodyFilter = document.getElementById('filter-table-body');
  3402. if (tbodyFilter) {
  3403. if (populateDropdowns || tbodyFilter.dataset.sig !== sigFilter) {
  3404. tbodyFilter.dataset.sig = sigFilter;
  3405. renderFilterRules();
  3406. } else {
  3407. // In-place live stats update (ZERO flicker)
  3408. (state.filterRules || []).forEach(r => {
  3409. const p = document.getElementById(`filter-pkts-${r.id}`);
  3410. if (p) p.innerText = `${(r.packets || 0).toLocaleString()}p`;
  3411. const b = document.getElementById(`filter-bytes-${r.id}`);
  3412. if (b) b.innerText = formatTraffic(r.bytes || 0).replace('/s', '');
  3413. });
  3414. }
  3415. }
  3416. const tbodyNat = document.getElementById('nat-table-body');
  3417. if (tbodyNat) {
  3418. if (populateDropdowns || tbodyNat.dataset.sig !== sigNat) {
  3419. tbodyNat.dataset.sig = sigNat;
  3420. renderNATRules();
  3421. } else {
  3422. (state.natRules || []).forEach(r => {
  3423. const p = document.getElementById(`nat-pkts-${r.id}`);
  3424. if (p) p.innerText = `${(r.packets || 0).toLocaleString()}p`;
  3425. const b = document.getElementById(`nat-bytes-${r.id}`);
  3426. if (b) b.innerText = formatTraffic(r.bytes || 0).replace('/s', '');
  3427. });
  3428. }
  3429. }
  3430. const tbodyMangle = document.getElementById('mangle-table-body');
  3431. if (tbodyMangle) {
  3432. if (populateDropdowns || tbodyMangle.dataset.sig !== sigMangle) {
  3433. tbodyMangle.dataset.sig = sigMangle;
  3434. renderMangleRules();
  3435. } else {
  3436. (state.mangleRules || []).forEach(r => {
  3437. const p = document.getElementById(`mangle-pkts-${r.id}`);
  3438. if (p) p.innerText = `${(r.packets || 0).toLocaleString()}p`;
  3439. const b = document.getElementById(`mangle-bytes-${r.id}`);
  3440. if (b) b.innerText = formatTraffic(r.bytes || 0).replace('/s', '');
  3441. });
  3442. }
  3443. }
  3444. const tbodyAddr = document.getElementById('addrlist-table-body');
  3445. if (tbodyAddr && (populateDropdowns || tbodyAddr.dataset.sig !== sigAddr)) {
  3446. tbodyAddr.dataset.sig = sigAddr;
  3447. renderAddressLists();
  3448. }
  3449. renderGeoCountries();
  3450. if (state.fwSubTab === 'connections') {
  3451. loadConnections();
  3452. }
  3453. } catch (err) {
  3454. console.error('Failed to load firewall:', err);
  3455. }
  3456. }
  3457. // ----------------- Filter Rules -----------------
  3458. function renderFilterRules() {
  3459. const chainFilter = document.getElementById('filter-filter-chain')?.value || '';
  3460. const tbody = document.getElementById('filter-table-body');
  3461. const empty = document.getElementById('filter-empty');
  3462. if (!tbody) return;
  3463. tbody.innerHTML = '';
  3464. const rules = (state.filterRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  3465. document.getElementById('filter-count-badge').innerText = `${rules.length} Rules`;
  3466. if (rules.length === 0) {
  3467. empty?.classList.remove('hidden');
  3468. return;
  3469. }
  3470. empty?.classList.add('hidden');
  3471. rules.forEach((r, idx) => {
  3472. const tr = document.createElement('tr');
  3473. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  3474. const ports = [r.src_port ? 's:' + r.src_port : '', r.dst_port ? 'd:' + r.dst_port : ''].filter(Boolean).join(' ');
  3475. const ifaces = [r.in_interface ? 'in:' + r.in_interface : '', r.out_interface ? 'out:' + r.out_interface : ''].filter(Boolean).join(' ');
  3476. let actionExtra = '';
  3477. if (r.action === 'reject') {
  3478. actionExtra = `<span class="block text-[10px] text-rose-300 font-mono mt-0.5">(${r.reject_with || 'icmp-net-unreach'})</span>`;
  3479. } else if (r.action === 'jump') {
  3480. actionExtra = `<span class="block text-[10px] text-yellow-300 font-mono mt-0.5">&rarr; ${r.jump_target || '-'}</span>`;
  3481. } else if (r.action.includes('address-list') || r.action.includes('address list')) {
  3482. actionExtra = `<span class="block text-[10px] text-emerald-300 font-mono mt-0.5">&rarr; ${r.address_list || '-'}</span>`;
  3483. } else if (r.action === 'log' && r.log_prefix) {
  3484. actionExtra = `<span class="block text-[10px] text-slate-400 font-mono mt-0.5">${r.log_prefix}</span>`;
  3485. }
  3486. tr.innerHTML = `
  3487. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  3488. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  3489. <td class="py-2.5 px-3 font-bold text-white">${r.chain}</td>
  3490. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  3491. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  3492. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}</td>
  3493. <td class="py-2.5 px-3 text-amber-400">${ports || '-'}</td>
  3494. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  3495. <td class="py-2.5 px-3">${renderActionBadge(r.action)}${actionExtra}</td>
  3496. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  3497. <span class="text-slate-300" id="filter-pkts-${r.id}">${(r.packets || 0).toLocaleString()}p</span> /
  3498. <span class="text-slate-500" id="filter-bytes-${r.id}">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  3499. </td>
  3500. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  3501. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  3502. <button onclick="moveFilterRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  3503. <button onclick="moveFilterRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  3504. <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>
  3505. <button onclick="openEditFilterModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  3506. <button onclick="deleteFilterRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  3507. </td>
  3508. `;
  3509. tbody.appendChild(tr);
  3510. });
  3511. }
  3512. function formatTarget(addr, list, geo) {
  3513. const parts = [];
  3514. if (addr) parts.push(`<span>${addr}</span>`);
  3515. if (list) {
  3516. const inv = list.startsWith('!') ? '!' : '';
  3517. const clean = list.replace(/^!/, '');
  3518. 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>`);
  3519. }
  3520. if (geo) {
  3521. const inv = geo.startsWith('!') ? '!' : '';
  3522. const clean = geo.replace(/^!/, '').replace(/^geo:/, '');
  3523. 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>`);
  3524. }
  3525. if (parts.length === 0) return '<span class="text-slate-600">0.0.0.0/0</span>';
  3526. return parts.join(' ');
  3527. }
  3528. function populateInterfaceSelect(selectId, currentVal = '') {
  3529. const sel = document.getElementById(selectId);
  3530. if (!sel) return;
  3531. sel.innerHTML = '<option value="">(Any Interface)</option>';
  3532. (state.interfaces || []).forEach(i => {
  3533. const opt = document.createElement('option');
  3534. opt.value = i.name;
  3535. opt.innerText = `${i.name} (${i.role || i.type})`;
  3536. if (i.name === currentVal) opt.selected = true;
  3537. sel.appendChild(opt);
  3538. });
  3539. }
  3540. function populateAddressListSelect(selectId, currentVal = '') {
  3541. const sel = document.getElementById(selectId);
  3542. if (!sel) return;
  3543. sel.innerHTML = '<option value="">(None)</option>';
  3544. const cleanVal = (currentVal || '').replace(/^!/, '');
  3545. const customNames = Array.from(new Set((state.addressLists || []).map(a => a.name))).sort();
  3546. customNames.forEach(name => {
  3547. const count = (state.addressLists || []).filter(a => a.name === name).length;
  3548. const opt = document.createElement('option');
  3549. opt.value = name;
  3550. opt.innerText = `${name} (${count} entries)`;
  3551. if (name === cleanVal) opt.selected = true;
  3552. sel.appendChild(opt);
  3553. });
  3554. if (cleanVal && !sel.querySelector(`option[value="${cleanVal}"]`)) {
  3555. const opt = document.createElement('option');
  3556. opt.value = cleanVal;
  3557. opt.innerText = cleanVal;
  3558. opt.selected = true;
  3559. sel.appendChild(opt);
  3560. }
  3561. populateCommonAddrListDatalist();
  3562. }
  3563. function populateCommonAddrListDatalist() {
  3564. const dl = document.getElementById('fw-addrlist-datalist');
  3565. if (!dl) return;
  3566. dl.innerHTML = '';
  3567. const names = Array.from(new Set((state.addressLists || []).map(a => a.name).filter(Boolean))).sort();
  3568. names.forEach(name => {
  3569. const opt = document.createElement('option');
  3570. opt.value = name;
  3571. dl.appendChild(opt);
  3572. });
  3573. }
  3574. function populateGeoIPSelect(selectId, currentVal = '') {
  3575. const sel = document.getElementById(selectId);
  3576. if (!sel) return;
  3577. sel.innerHTML = '<option value="">(None)</option>';
  3578. const cleanVal = (currentVal || '').replace(/^!/, '').replace(/^geo:/, '').toUpperCase();
  3579. // Presets optgroup
  3580. const grpPresets = document.createElement('optgroup');
  3581. grpPresets.label = '⚡ Regional Presets';
  3582. const presets = [
  3583. { code: 'EU', label: '🇪🇺 European Union (EU - 27 countries)' },
  3584. { code: 'BALKANS', label: '🏛️ Balkans (GR, CY, BG, RO, AL, etc.)' },
  3585. { code: 'BLOCKLIST', label: '🛡️ High-Risk Blocklist (CN, RU, IR, KP, BY)' }
  3586. ];
  3587. presets.forEach(p => {
  3588. const opt = document.createElement('option');
  3589. opt.value = p.code;
  3590. opt.innerText = p.label;
  3591. if (p.code === cleanVal) opt.selected = true;
  3592. grpPresets.appendChild(opt);
  3593. });
  3594. sel.appendChild(grpPresets);
  3595. // All Countries optgroup
  3596. const grpCountries = document.createElement('optgroup');
  3597. grpCountries.label = '🌍 All Countries';
  3598. const countries = (state.geoCountries || []).slice().sort((a, b) => a.name.localeCompare(b.name));
  3599. countries.forEach(c => {
  3600. const opt = document.createElement('option');
  3601. opt.value = c.code;
  3602. const subnetsInfo = c.subnet_count ? ` [${c.subnet_count.toLocaleString()} subnets]` : '';
  3603. opt.innerText = `${c.name} (${c.code})${subnetsInfo}`;
  3604. if (c.code === cleanVal) opt.selected = true;
  3605. grpCountries.appendChild(opt);
  3606. });
  3607. sel.appendChild(grpCountries);
  3608. }
  3609. // ==================== FIREWALL FILTER MODAL (ROUTEROS WEBFIG / WINBOX V4) ====================
  3610. function switchFwRuleTab(tab) {
  3611. state.activeFwRuleTab = tab;
  3612. document.querySelectorAll('.fw-rule-tab-btn').forEach(btn => {
  3613. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  3614. btn.classList.add('text-slate-400', 'border-transparent');
  3615. });
  3616. const activeBtn = document.getElementById(`fw-tab-btn-${tab}`);
  3617. if (activeBtn) {
  3618. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  3619. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  3620. }
  3621. document.querySelectorAll('.fw-rule-pane').forEach(p => p.classList.add('hidden'));
  3622. const activePane = document.getElementById(`fw-pane-${tab}`);
  3623. if (activePane) activePane.classList.remove('hidden');
  3624. if (tab === 'statistics') {
  3625. startFwStatPolling();
  3626. } else {
  3627. stopFwStatPolling();
  3628. }
  3629. }
  3630. function toggleFwField(fieldKey, expand) {
  3631. const plusBtn = document.getElementById(`fw-plus-${fieldKey}`);
  3632. const fieldBox = document.getElementById(`fw-field-${fieldKey}`);
  3633. if (!plusBtn || !fieldBox) return;
  3634. if (expand) {
  3635. plusBtn.classList.add('hidden');
  3636. fieldBox.classList.remove('hidden');
  3637. const valInput = document.getElementById(`fw-val-${fieldKey}`);
  3638. if (valInput) valInput.focus();
  3639. } else {
  3640. fieldBox.classList.add('hidden');
  3641. plusBtn.classList.remove('hidden');
  3642. const valInput = document.getElementById(`fw-val-${fieldKey}`);
  3643. if (valInput) {
  3644. if (valInput.tagName === 'SELECT') {
  3645. valInput.selectedIndex = 0;
  3646. } else {
  3647. valInput.value = '';
  3648. }
  3649. }
  3650. const invInput = document.getElementById(`fw-inv-${fieldKey}`);
  3651. if (invInput) invInput.checked = false;
  3652. if (fieldKey === 'cs') {
  3653. ['filter-modal-cs-established', 'filter-modal-cs-related', 'filter-modal-cs-new', 'filter-modal-cs-invalid', 'filter-modal-cs-untracked'].forEach(id => {
  3654. const el = document.getElementById(id);
  3655. if (el) el.checked = false;
  3656. });
  3657. }
  3658. if (fieldKey === 'natstate') {
  3659. ['filter-modal-nat-srcnat', 'filter-modal-nat-dstnat'].forEach(id => {
  3660. const el = document.getElementById(id);
  3661. if (el) el.checked = false;
  3662. });
  3663. }
  3664. if (fieldKey === 'days') {
  3665. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3666. const el = document.getElementById(`fw-day-${d}`);
  3667. if (el) el.checked = true;
  3668. });
  3669. }
  3670. }
  3671. }
  3672. function setFwFieldVal(fieldKey, value, hasInvert = false) {
  3673. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  3674. toggleFwField(fieldKey, true);
  3675. let strVal = String(value);
  3676. if (hasInvert) {
  3677. const inv = strVal.startsWith('!');
  3678. if (inv) strVal = strVal.slice(1);
  3679. const invEl = document.getElementById(`fw-inv-${fieldKey}`);
  3680. if (invEl) invEl.checked = inv;
  3681. }
  3682. const valEl = document.getElementById(`fw-val-${fieldKey}`);
  3683. if (valEl) valEl.value = strVal;
  3684. } else {
  3685. toggleFwField(fieldKey, false);
  3686. }
  3687. }
  3688. function getFwFieldVal(fieldKey, hasInvert = false) {
  3689. const fieldBox = document.getElementById(`fw-field-${fieldKey}`);
  3690. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  3691. const valEl = document.getElementById(`fw-val-${fieldKey}`);
  3692. let v = valEl ? valEl.value.trim() : '';
  3693. if (!v) return '';
  3694. if (hasInvert) {
  3695. const invEl = document.getElementById(`fw-inv-${fieldKey}`);
  3696. if (invEl && invEl.checked) {
  3697. v = '!' + v.replace(/^!/, '');
  3698. }
  3699. }
  3700. return v;
  3701. }
  3702. function toggleMaximizeFilterModal() {
  3703. const win = document.getElementById('filter-modal-window');
  3704. if (!win) return;
  3705. if (win.classList.contains('max-w-[720px]')) {
  3706. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  3707. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  3708. } else {
  3709. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  3710. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  3711. }
  3712. }
  3713. function openAddFilterModal() {
  3714. switchFwRuleTab('general');
  3715. const badge = document.getElementById('fw-modal-badge');
  3716. if (badge) badge.innerText = 'New...';
  3717. document.getElementById('filter-modal-id').value = '';
  3718. document.getElementById('filter-modal-enabled').checked = true;
  3719. document.getElementById('filter-modal-comment').value = '';
  3720. document.getElementById('filter-modal-chain').value = 'forward';
  3721. document.getElementById('filter-modal-action').value = 'accept';
  3722. document.getElementById('filter-modal-log').checked = false;
  3723. populateInterfaceSelect('fw-val-iniface');
  3724. populateInterfaceSelect('fw-val-outiface');
  3725. populateAddressListSelect('fw-val-srclist');
  3726. populateAddressListSelect('fw-val-dstlist');
  3727. populateGeoIPSelect('fw-val-srcgeo');
  3728. populateGeoIPSelect('fw-val-dstgeo');
  3729. const allFieldKeys = [
  3730. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  3731. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  3732. 'routingmark', 'conntype', 'cs', 'natstate',
  3733. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  3734. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  3735. 'ipsec', 'tlshost', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  3736. 'pktsize', 'random', 'tcpflags', 'icmpoptions', 'ipv4options', 'ttl',
  3737. 'time', 'days', 'limit', 'dstlimit', 'psd', 'logprefix'
  3738. ];
  3739. allFieldKeys.forEach(k => toggleFwField(k, false));
  3740. resetCurrentRuleCounters();
  3741. toggleFilterActionFields();
  3742. document.getElementById('filter-modal').classList.remove('hidden');
  3743. }
  3744. function openEditFilterModal(id) {
  3745. const r = (state.filterRules || []).find(rule => rule.id === id);
  3746. if (!r) return;
  3747. switchFwRuleTab('general');
  3748. const badge = document.getElementById('fw-modal-badge');
  3749. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  3750. document.getElementById('filter-modal-id').value = r.id;
  3751. document.getElementById('filter-modal-enabled').checked = !r.disabled;
  3752. document.getElementById('filter-modal-comment').value = r.comment || '';
  3753. document.getElementById('filter-modal-chain').value = r.chain || 'forward';
  3754. document.getElementById('filter-modal-action').value = r.action || 'accept';
  3755. document.getElementById('filter-modal-log').checked = !!r.log;
  3756. populateInterfaceSelect('fw-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  3757. populateInterfaceSelect('fw-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  3758. populateAddressListSelect('fw-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  3759. populateAddressListSelect('fw-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  3760. populateGeoIPSelect('fw-val-srcgeo', r.src_geoip || '');
  3761. populateGeoIPSelect('fw-val-dstgeo', r.dst_geoip || '');
  3762. setFwFieldVal('src', r.src_address, true);
  3763. setFwFieldVal('dst', r.dst_address, true);
  3764. setFwFieldVal('srclist', r.src_address_list, true);
  3765. setFwFieldVal('dstlist', r.dst_address_list, true);
  3766. setFwFieldVal('srcgeo', r.src_geoip, true);
  3767. setFwFieldVal('dstgeo', r.dst_geoip, true);
  3768. if (r.protocol && r.protocol !== 'all') {
  3769. setFwFieldVal('proto', r.protocol, true);
  3770. } else {
  3771. toggleFwField('proto', false);
  3772. }
  3773. setFwFieldVal('sport', r.src_port, true);
  3774. setFwFieldVal('dport', r.dst_port, true);
  3775. setFwFieldVal('anyport', r.any_port, true);
  3776. setFwFieldVal('iniface', r.in_interface, true);
  3777. setFwFieldVal('outiface', r.out_interface, true);
  3778. setFwFieldVal('inifacelist', r.in_interface_list, true);
  3779. setFwFieldVal('outifacelist', r.out_interface_list, true);
  3780. setFwFieldVal('pktmark', r.packet_mark, true);
  3781. setFwFieldVal('connmark', r.connection_mark, true);
  3782. setFwFieldVal('routingmark', r.routing_mark, true);
  3783. setFwFieldVal('conntype', r.connection_type, false);
  3784. const states = r.connection_state || [];
  3785. if (states.length > 0) {
  3786. toggleFwField('cs', true);
  3787. document.getElementById('filter-modal-cs-established').checked = states.includes('established');
  3788. document.getElementById('filter-modal-cs-related').checked = states.includes('related');
  3789. document.getElementById('filter-modal-cs-new').checked = states.includes('new');
  3790. document.getElementById('filter-modal-cs-invalid').checked = states.includes('invalid');
  3791. document.getElementById('filter-modal-cs-untracked').checked = states.includes('untracked');
  3792. } else {
  3793. toggleFwField('cs', false);
  3794. }
  3795. const natStates = r.connection_nat_state || [];
  3796. if (natStates.length > 0) {
  3797. toggleFwField('natstate', true);
  3798. document.getElementById('filter-modal-nat-srcnat').checked = natStates.includes('srcnat');
  3799. document.getElementById('filter-modal-nat-dstnat').checked = natStates.includes('dstnat');
  3800. } else {
  3801. toggleFwField('natstate', false);
  3802. }
  3803. // Advanced tab fields
  3804. setFwFieldVal('layer7', r.layer7_protocol, false);
  3805. setFwFieldVal('content', r.content, false);
  3806. setFwFieldVal('connbytes', r.connection_bytes, false);
  3807. setFwFieldVal('connrate', r.connection_rate, false);
  3808. setFwFieldVal('pcc', r.pcc, false);
  3809. setFwFieldVal('srcmac', r.src_mac_address, true);
  3810. setFwFieldVal('outbridgeport', r.out_bridge_port, false);
  3811. setFwFieldVal('inbridgeport', r.in_bridge_port, false);
  3812. setFwFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  3813. setFwFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  3814. setFwFieldVal('ipsec', r.ipsec_policy, false);
  3815. setFwFieldVal('tlshost', r.tls_host, false);
  3816. setFwFieldVal('ingresspriority', r.ingress_priority, false);
  3817. setFwFieldVal('priority', r.priority, false);
  3818. setFwFieldVal('dscp', r.dscp, false);
  3819. setFwFieldVal('tcpmss', r.tcp_mss, false);
  3820. if (r.tos) {
  3821. const tosEl = document.getElementById('fw-val-tos');
  3822. if (tosEl) tosEl.value = r.tos;
  3823. }
  3824. setFwFieldVal('pktsize', r.packet_size, false);
  3825. setFwFieldVal('random', r.random, false);
  3826. setFwFieldVal('tcpflags', r.tcp_flags, false);
  3827. setFwFieldVal('icmpoptions', r.icmp_options, false);
  3828. setFwFieldVal('ipv4options', r.ipv4_options, false);
  3829. setFwFieldVal('ttl', r.ttl, false);
  3830. // Extra tab fields
  3831. setFwFieldVal('time', r.time, false);
  3832. if (r.days) {
  3833. toggleFwField('days', true);
  3834. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3835. const chk = document.getElementById(`fw-day-${d}`);
  3836. if (chk) chk.checked = r.days.includes(d);
  3837. });
  3838. } else {
  3839. toggleFwField('days', false);
  3840. }
  3841. setFwFieldVal('limit', r.limit, false);
  3842. setFwFieldVal('dstlimit', r.dst_limit, false);
  3843. setFwFieldVal('psd', r.psd, false);
  3844. // Action fields
  3845. if (r.reject_with) {
  3846. const rwEl = document.getElementById('filter-modal-rejectwith');
  3847. if (rwEl) rwEl.value = r.reject_with;
  3848. }
  3849. if (r.jump_target) {
  3850. const jtEl = document.getElementById('filter-modal-jumptarget');
  3851. if (jtEl) jtEl.value = r.jump_target;
  3852. }
  3853. if (r.address_list) {
  3854. const alEl = document.getElementById('filter-modal-action-addrlist');
  3855. if (alEl) alEl.value = r.address_list;
  3856. }
  3857. if (r.address_list_timeout) {
  3858. const toEl = document.getElementById('filter-modal-action-timeout');
  3859. if (toEl) toEl.value = r.address_list_timeout;
  3860. }
  3861. setFwFieldVal('logprefix', r.log_prefix, false);
  3862. // Statistics
  3863. const bEl = document.getElementById('fw-stat-bytes');
  3864. const pEl = document.getElementById('fw-stat-packets');
  3865. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  3866. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  3867. state.fwLastBytes = r.bytes || 0;
  3868. state.fwLastPackets = r.packets || 0;
  3869. state.fwLastTimestamp = Date.now();
  3870. state.fwStatRateHistory = new Array(30).fill(0);
  3871. state.fwStatPktHistory = new Array(30).fill(0);
  3872. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  3873. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  3874. toggleFilterActionFields();
  3875. document.getElementById('filter-modal').classList.remove('hidden');
  3876. }
  3877. function closeFilterModal() {
  3878. stopFwStatPolling();
  3879. document.getElementById('filter-modal').classList.add('hidden');
  3880. }
  3881. function toggleFilterActionFields() {
  3882. const act = document.getElementById('filter-modal-action')?.value || 'accept';
  3883. const rejectBox = document.getElementById('filter-action-reject-box');
  3884. const jumpBox = document.getElementById('filter-action-jump-box');
  3885. const addrBox = document.getElementById('filter-action-addrlist-box');
  3886. if (rejectBox) {
  3887. if (act === 'reject') rejectBox.classList.remove('hidden');
  3888. else rejectBox.classList.add('hidden');
  3889. }
  3890. if (jumpBox) {
  3891. if (act === 'jump') jumpBox.classList.remove('hidden');
  3892. else jumpBox.classList.add('hidden');
  3893. }
  3894. if (addrBox) {
  3895. if (act === 'add-dst-to-address-list' || act === 'add-src-to-address-list' || act.includes('address-list') || act.includes('address list')) {
  3896. addrBox.classList.remove('hidden');
  3897. } else {
  3898. addrBox.classList.add('hidden');
  3899. }
  3900. }
  3901. if (act === 'log') {
  3902. const logEl = document.getElementById('filter-modal-log');
  3903. if (logEl) logEl.checked = true;
  3904. toggleFwField('logprefix', true);
  3905. }
  3906. }
  3907. function toggleFwLogPrefix() {
  3908. const isLog = document.getElementById('filter-modal-log')?.checked;
  3909. toggleFwField('logprefix', !!isLog);
  3910. }
  3911. function copyFilterRule() {
  3912. document.getElementById('filter-modal-id').value = '';
  3913. const badge = document.getElementById('fw-modal-badge');
  3914. if (badge) badge.innerText = 'New...';
  3915. showToast('Rule Cloned', 'Ready to save as a new rule copy', 'info');
  3916. }
  3917. function resetCurrentRuleCounters() {
  3918. state.fwStatRateHistory = new Array(30).fill(0);
  3919. state.fwStatPktHistory = new Array(30).fill(0);
  3920. state.fwLastBytes = 0;
  3921. state.fwLastPackets = 0;
  3922. state.fwLastTimestamp = Date.now();
  3923. const bEl = document.getElementById('fw-stat-bytes');
  3924. const pEl = document.getElementById('fw-stat-packets');
  3925. const rEl = document.getElementById('fw-stat-rate');
  3926. const prEl = document.getElementById('fw-stat-pktrate');
  3927. if (bEl) bEl.value = '0 B';
  3928. if (pEl) pEl.value = '0';
  3929. if (rEl) rEl.value = '0 bps';
  3930. if (prEl) prEl.value = '0 p/s';
  3931. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  3932. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  3933. showToast('Counters Reset', 'Rule counter display reset to 0', 'info');
  3934. }
  3935. async function resetAllFwCounters() {
  3936. try {
  3937. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  3938. if (res.ok) {
  3939. resetCurrentRuleCounters();
  3940. showToast('All Counters Reset', 'All firewall counters zeroed', 'success');
  3941. loadFirewall(false);
  3942. }
  3943. } catch (err) {
  3944. showToast('Error', err.message, 'error');
  3945. }
  3946. }
  3947. async function applyFilterRule(closeAfter = false) {
  3948. const id = document.getElementById('filter-modal-id').value;
  3949. const chain = document.getElementById('filter-modal-chain').value;
  3950. const action = document.getElementById('filter-modal-action').value;
  3951. const comment = document.getElementById('filter-modal-comment').value.trim();
  3952. const enabled = document.getElementById('filter-modal-enabled').checked;
  3953. const src = getFwFieldVal('src', true);
  3954. const dst = getFwFieldVal('dst', true);
  3955. const srclist = getFwFieldVal('srclist', true);
  3956. const dstlist = getFwFieldVal('dstlist', true);
  3957. const srcgeo = getFwFieldVal('srcgeo', true);
  3958. const dstgeo = getFwFieldVal('dstgeo', true);
  3959. const proto = getFwFieldVal('proto', true);
  3960. const sport = getFwFieldVal('sport', true);
  3961. const dport = getFwFieldVal('dport', true);
  3962. const anyport = getFwFieldVal('anyport', true);
  3963. const iniface = getFwFieldVal('iniface', true);
  3964. const outiface = getFwFieldVal('outiface', true);
  3965. const inifacelist = getFwFieldVal('inifacelist', true);
  3966. const outifacelist = getFwFieldVal('outifacelist', true);
  3967. const pktmark = getFwFieldVal('pktmark', true);
  3968. const connmark = getFwFieldVal('connmark', true);
  3969. const routingmark = getFwFieldVal('routingmark', true);
  3970. const conntype = getFwFieldVal('conntype', false);
  3971. const states = [];
  3972. const csBox = document.getElementById('fw-field-cs');
  3973. if (csBox && !csBox.classList.contains('hidden')) {
  3974. if (document.getElementById('filter-modal-cs-established')?.checked) states.push('established');
  3975. if (document.getElementById('filter-modal-cs-related')?.checked) states.push('related');
  3976. if (document.getElementById('filter-modal-cs-new')?.checked) states.push('new');
  3977. if (document.getElementById('filter-modal-cs-invalid')?.checked) states.push('invalid');
  3978. if (document.getElementById('filter-modal-cs-untracked')?.checked) states.push('untracked');
  3979. }
  3980. const natStates = [];
  3981. const natBox = document.getElementById('fw-field-natstate');
  3982. if (natBox && !natBox.classList.contains('hidden')) {
  3983. if (document.getElementById('filter-modal-nat-srcnat')?.checked) natStates.push('srcnat');
  3984. if (document.getElementById('filter-modal-nat-dstnat')?.checked) natStates.push('dstnat');
  3985. }
  3986. const payload = {
  3987. id,
  3988. chain,
  3989. action,
  3990. protocol: proto || 'all',
  3991. src_address: src,
  3992. dst_address: dst,
  3993. src_port: sport,
  3994. dst_port: dport,
  3995. any_port: anyport,
  3996. in_interface: iniface,
  3997. out_interface: outiface,
  3998. in_interface_list: inifacelist,
  3999. out_interface_list: outifacelist,
  4000. packet_mark: pktmark,
  4001. connection_mark: connmark,
  4002. routing_mark: routingmark,
  4003. connection_type: conntype,
  4004. connection_state: states,
  4005. connection_nat_state: natStates,
  4006. src_address_list: srclist,
  4007. dst_address_list: dstlist,
  4008. src_geoip: srcgeo,
  4009. dst_geoip: dstgeo,
  4010. comment,
  4011. disabled: !enabled,
  4012. // Advanced tab
  4013. layer7_protocol: getFwFieldVal('layer7', false),
  4014. content: getFwFieldVal('content', false),
  4015. connection_bytes: getFwFieldVal('connbytes', false),
  4016. connection_rate: getFwFieldVal('connrate', false),
  4017. pcc: getFwFieldVal('pcc', false),
  4018. src_mac_address: getFwFieldVal('srcmac', true),
  4019. out_bridge_port: getFwFieldVal('outbridgeport', false),
  4020. in_bridge_port: getFwFieldVal('inbridgeport', false),
  4021. in_bridge_port_list: getFwFieldVal('inbridgeportlist', false),
  4022. out_bridge_port_list: getFwFieldVal('outbridgeportlist', false),
  4023. ipsec_policy: getFwFieldVal('ipsec', false),
  4024. tls_host: getFwFieldVal('tlshost', false),
  4025. ingress_priority: getFwFieldVal('ingresspriority', false),
  4026. priority: getFwFieldVal('priority', false),
  4027. dscp: getFwFieldVal('dscp', false),
  4028. tcp_mss: getFwFieldVal('tcpmss', false),
  4029. tos: document.getElementById('fw-val-tos')?.value || '',
  4030. packet_size: getFwFieldVal('pktsize', false),
  4031. random: getFwFieldVal('random', false),
  4032. tcp_flags: getFwFieldVal('tcpflags', false),
  4033. icmp_options: getFwFieldVal('icmpoptions', false),
  4034. ipv4_options: getFwFieldVal('ipv4options', false),
  4035. ttl: getFwFieldVal('ttl', false),
  4036. // Extra tab
  4037. time: getFwFieldVal('time', false),
  4038. limit: getFwFieldVal('limit', false),
  4039. dst_limit: getFwFieldVal('dstlimit', false),
  4040. psd: getFwFieldVal('psd', false),
  4041. // Action tab
  4042. reject_with: action === 'reject' ? (document.getElementById('filter-modal-rejectwith')?.value || '') : '',
  4043. jump_target: action === 'jump' ? (document.getElementById('filter-modal-jumptarget')?.value || '') : '',
  4044. address_list: action.startsWith('add-') ? (document.getElementById('filter-modal-action-addrlist')?.value || '') : '',
  4045. address_list_timeout: action.startsWith('add-') ? (document.getElementById('filter-modal-action-timeout')?.value || '') : '',
  4046. log: document.getElementById('filter-modal-log')?.checked || false,
  4047. log_prefix: getFwFieldVal('logprefix', false)
  4048. };
  4049. try {
  4050. const res = await fetch(`${API_BASE}/firewall/filter`, {
  4051. method: 'POST',
  4052. headers: { 'Content-Type': 'application/json' },
  4053. body: JSON.stringify(payload)
  4054. });
  4055. if (res.ok) {
  4056. const data = await res.json();
  4057. showToast('Filter Rule Saved', 'Rule applied successfully to firewall', 'success');
  4058. loadFirewall(false);
  4059. if (closeAfter) {
  4060. closeFilterModal();
  4061. } else {
  4062. if (data.id) {
  4063. document.getElementById('filter-modal-id').value = data.id;
  4064. const badge = document.getElementById('fw-modal-badge');
  4065. if (badge) badge.innerText = `#${data.id}`;
  4066. }
  4067. }
  4068. } else {
  4069. const err = await res.json();
  4070. showToast('Error', err.message || 'Failed to save rule', 'error');
  4071. }
  4072. } catch (err) {
  4073. showToast('Error', err.message, 'error');
  4074. }
  4075. }
  4076. function submitSaveFilterRule(e) {
  4077. if (e && e.preventDefault) e.preventDefault();
  4078. return applyFilterRule(true);
  4079. }
  4080. function startFwStatPolling() {
  4081. stopFwStatPolling();
  4082. pollRuleStats();
  4083. state.fwStatInterval = setInterval(pollRuleStats, 1000);
  4084. }
  4085. function stopFwStatPolling() {
  4086. if (state.fwStatInterval) {
  4087. clearInterval(state.fwStatInterval);
  4088. state.fwStatInterval = null;
  4089. }
  4090. }
  4091. async function pollRuleStats() {
  4092. const id = document.getElementById('filter-modal-id')?.value;
  4093. if (!id) {
  4094. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory || new Array(30).fill(0), 'bps', 'fw-stat-legend-rate');
  4095. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory || new Array(30).fill(0), 'p/s', 'fw-stat-legend-pktrate');
  4096. return;
  4097. }
  4098. try {
  4099. const res = await fetch(`${API_BASE}/firewall/filter`);
  4100. if (!res.ok) return;
  4101. const rules = await res.json();
  4102. const r = rules.find(x => x.id === id);
  4103. if (!r) return;
  4104. const now = Date.now();
  4105. const dt = Math.max(0.2, (now - (state.fwLastTimestamp || now)) / 1000);
  4106. state.fwLastTimestamp = now;
  4107. const curBytes = r.bytes || 0;
  4108. const curPackets = r.packets || 0;
  4109. const deltaBytes = Math.max(0, curBytes - (state.fwLastBytes || curBytes));
  4110. const deltaPkts = Math.max(0, curPackets - (state.fwLastPackets || curPackets));
  4111. state.fwLastBytes = curBytes;
  4112. state.fwLastPackets = curPackets;
  4113. const rateBps = Math.round((deltaBytes * 8) / dt);
  4114. const ratePkt = Math.round(deltaPkts / dt);
  4115. if (!state.fwStatRateHistory) state.fwStatRateHistory = new Array(30).fill(0);
  4116. if (!state.fwStatPktHistory) state.fwStatPktHistory = new Array(30).fill(0);
  4117. state.fwStatRateHistory.push(rateBps);
  4118. if (state.fwStatRateHistory.length > 30) state.fwStatRateHistory.shift();
  4119. state.fwStatPktHistory.push(ratePkt);
  4120. if (state.fwStatPktHistory.length > 30) state.fwStatPktHistory.shift();
  4121. const bEl = document.getElementById('fw-stat-bytes');
  4122. const pEl = document.getElementById('fw-stat-packets');
  4123. const rEl = document.getElementById('fw-stat-rate');
  4124. const prEl = document.getElementById('fw-stat-pktrate');
  4125. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  4126. if (pEl) pEl.value = curPackets.toLocaleString();
  4127. if (rEl) rEl.value = formatBps(rateBps);
  4128. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  4129. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  4130. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  4131. } catch (e) {
  4132. console.error('Error polling rule stats', e);
  4133. }
  4134. }
  4135. function formatBps(bps) {
  4136. if (bps >= 1000000000) return (bps / 1000000000).toFixed(1) + ' Gbps';
  4137. if (bps >= 1000000) return (bps / 1000000).toFixed(1) + ' Mbps';
  4138. if (bps >= 1000) return (bps / 1000).toFixed(1) + ' kbps';
  4139. return bps + ' bps';
  4140. }
  4141. function renderFwSparkline(svgId, dataArray, unit, legendId) {
  4142. const svg = document.getElementById(svgId);
  4143. if (!svg) return;
  4144. const w = 500;
  4145. const h = 100;
  4146. const paddingRight = 45;
  4147. const graphWidth = w - paddingRight;
  4148. const maxVal = Math.max(5, ...dataArray);
  4149. const currentVal = dataArray[dataArray.length - 1] || 0;
  4150. const leg = document.getElementById(legendId);
  4151. if (leg) {
  4152. leg.innerText = unit === 'bps' ? formatBps(currentVal) : `${currentVal.toLocaleString()} p/s`;
  4153. }
  4154. let gridLines = '';
  4155. for (let i = 0; i <= 5; i++) {
  4156. const y = 8 + (i * (h - 18) / 5);
  4157. const valAtLevel = Math.round(maxVal * (5 - i) / 5);
  4158. const label = unit === 'bps' ? formatBps(valAtLevel) : `${valAtLevel} p/s`;
  4159. gridLines += `
  4160. <line x1="0" y1="${y.toFixed(1)}" x2="${graphWidth}" y2="${y.toFixed(1)}" stroke="#1e2c3e" stroke-width="1" />
  4161. <text x="${w - 2}" y="${(y + 3).toFixed(1)}" fill="#64748b" font-size="9" font-family="monospace" text-anchor="end">${label}</text>
  4162. `;
  4163. }
  4164. const step = graphWidth / (dataArray.length - 1);
  4165. const points = dataArray.map((val, idx) => {
  4166. const x = idx * step;
  4167. const y = (h - 10) - (val / maxVal) * (h - 20);
  4168. return `${x.toFixed(1)},${y.toFixed(1)}`;
  4169. });
  4170. const polylineStr = points.join(' ');
  4171. const areaPath = `M 0,${h - 10} L ${polylineStr} L ${graphWidth},${h - 10} Z`;
  4172. svg.innerHTML = `
  4173. ${gridLines}
  4174. <path d="${areaPath}" fill="rgba(14, 165, 233, 0.12)" />
  4175. <polyline fill="none" stroke="#38bdf8" stroke-width="1.8" stroke-linejoin="round" points="${polylineStr}" />
  4176. <circle cx="${graphWidth}" cy="${points[points.length - 1].split(',')[1]}" r="3" fill="#38bdf8" />
  4177. `;
  4178. }
  4179. async function moveFilterRule(id, dir) {
  4180. try {
  4181. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/move`, {
  4182. method: 'POST',
  4183. headers: { 'Content-Type': 'application/json' },
  4184. body: JSON.stringify({ direction: dir })
  4185. });
  4186. if (res.ok) loadFirewall(false);
  4187. } catch (err) {
  4188. showToast('Error', err.message, 'error');
  4189. }
  4190. }
  4191. async function toggleFilterRuleState(id, disabled) {
  4192. try {
  4193. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/state`, {
  4194. method: 'POST',
  4195. headers: { 'Content-Type': 'application/json' },
  4196. body: JSON.stringify({ disabled })
  4197. });
  4198. if (res.ok) loadFirewall(false);
  4199. } catch (err) {
  4200. showToast('Error', err.message, 'error');
  4201. }
  4202. }
  4203. async function deleteFilterRule(id) {
  4204. if (!confirm('Are you sure you want to delete this filter rule?')) return;
  4205. try {
  4206. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4207. if (res.ok) {
  4208. showToast('Deleted', 'Filter rule removed', 'success');
  4209. loadFirewall(false);
  4210. }
  4211. } catch (err) {
  4212. showToast('Error', err.message, 'error');
  4213. }
  4214. }
  4215. // ----------------- NAT Rules -----------------
  4216. function renderNATRules() {
  4217. const chainFilter = document.getElementById('nat-filter-chain')?.value || '';
  4218. const tbody = document.getElementById('nat-table-body');
  4219. const empty = document.getElementById('nat-empty');
  4220. if (!tbody) return;
  4221. tbody.innerHTML = '';
  4222. const rules = (state.natRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  4223. document.getElementById('nat-count-badge').innerText = `${rules.length} Rules`;
  4224. if (rules.length === 0) {
  4225. empty?.classList.remove('hidden');
  4226. return;
  4227. }
  4228. empty?.classList.add('hidden');
  4229. rules.forEach((r, idx) => {
  4230. const tr = document.createElement('tr');
  4231. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  4232. let toTarget = '-';
  4233. if (r.action === 'jump') {
  4234. toTarget = `<span class="text-yellow-300 font-mono font-bold">&rarr; ${r.jump_target || '-'}</span>`;
  4235. } else if (r.action.includes('address-list') || r.action.includes('address list')) {
  4236. toTarget = `<span class="text-emerald-300 font-mono font-bold">&rarr; ${r.address_list || '-'}</span>`;
  4237. } else if (r.action === 'redirect') {
  4238. toTarget = `<span class="text-amber-300 font-mono font-bold">ports:${r.to_ports || 'all'}</span>`;
  4239. } else if (r.action === 'masquerade') {
  4240. 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>`;
  4241. } else if (r.action === 'log') {
  4242. toTarget = `<span class="text-slate-400 font-mono font-bold">${r.log_prefix || 'log'}</span>`;
  4243. } else {
  4244. const parts = [r.to_addresses, r.to_ports].filter(Boolean);
  4245. toTarget = parts.length ? `<span class="text-amber-300 font-mono font-bold">${parts.join(':')}</span>` : '-';
  4246. }
  4247. const ifaces = [r.out_interface ? 'out:' + r.out_interface : '', r.in_interface ? 'in:' + r.in_interface : ''].filter(Boolean).join(' ');
  4248. tr.innerHTML = `
  4249. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  4250. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  4251. <td class="py-2.5 px-3 font-bold text-amber-400">${r.chain}</td>
  4252. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  4253. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  4254. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}${r.dst_port ? ':' + r.dst_port : ''}</td>
  4255. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  4256. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  4257. <td class="py-2.5 px-3 font-mono text-xs">${toTarget}</td>
  4258. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  4259. <span class="text-slate-300" id="nat-pkts-${r.id}">${(r.packets || 0).toLocaleString()}p</span> /
  4260. <span class="text-slate-500" id="nat-bytes-${r.id}">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  4261. </td>
  4262. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  4263. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  4264. <button onclick="moveNATRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  4265. <button onclick="moveNATRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  4266. <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>
  4267. <button onclick="openEditNATModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  4268. <button onclick="deleteNATRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  4269. </td>
  4270. `;
  4271. tbody.appendChild(tr);
  4272. });
  4273. }
  4274. // ==================== FIREWALL NAT MODAL (ROUTEROS WEBFIG / WINBOX V4) ====================
  4275. function switchNATRuleTab(tab) {
  4276. state.activeNATRuleTab = tab;
  4277. document.querySelectorAll('.nat-rule-tab-btn').forEach(btn => {
  4278. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  4279. btn.classList.add('text-slate-400', 'border-transparent');
  4280. });
  4281. const activeBtn = document.getElementById(`nat-tab-btn-${tab}`);
  4282. if (activeBtn) {
  4283. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  4284. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  4285. }
  4286. document.querySelectorAll('.nat-rule-pane').forEach(p => p.classList.add('hidden'));
  4287. const activePane = document.getElementById(`nat-pane-${tab}`);
  4288. if (activePane) activePane.classList.remove('hidden');
  4289. if (tab === 'statistics') {
  4290. startNATStatPolling();
  4291. } else {
  4292. stopNATStatPolling();
  4293. }
  4294. }
  4295. function toggleNATField(fieldKey, expand) {
  4296. const plusBtn = document.getElementById(`nat-plus-${fieldKey}`);
  4297. const fieldBox = document.getElementById(`nat-field-${fieldKey}`);
  4298. if (!plusBtn || !fieldBox) return;
  4299. if (expand) {
  4300. plusBtn.classList.add('hidden');
  4301. fieldBox.classList.remove('hidden');
  4302. const valInput = document.getElementById(`nat-val-${fieldKey}`);
  4303. if (valInput) valInput.focus();
  4304. } else {
  4305. fieldBox.classList.add('hidden');
  4306. plusBtn.classList.remove('hidden');
  4307. const valInput = document.getElementById(`nat-val-${fieldKey}`);
  4308. if (valInput) {
  4309. if (valInput.tagName === 'SELECT') {
  4310. valInput.selectedIndex = 0;
  4311. } else {
  4312. valInput.value = '';
  4313. }
  4314. }
  4315. const invInput = document.getElementById(`nat-inv-${fieldKey}`);
  4316. if (invInput) invInput.checked = false;
  4317. if (fieldKey === 'days') {
  4318. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  4319. const el = document.getElementById(`nat-day-${d}`);
  4320. if (el) el.checked = true;
  4321. });
  4322. }
  4323. }
  4324. }
  4325. function setNATFieldVal(fieldKey, value, hasInvert = false) {
  4326. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  4327. toggleNATField(fieldKey, true);
  4328. let strVal = String(value);
  4329. if (hasInvert) {
  4330. const inv = strVal.startsWith('!');
  4331. if (inv) strVal = strVal.slice(1);
  4332. const invEl = document.getElementById(`nat-inv-${fieldKey}`);
  4333. if (invEl) invEl.checked = inv;
  4334. }
  4335. const valEl = document.getElementById(`nat-val-${fieldKey}`);
  4336. if (valEl) valEl.value = strVal;
  4337. } else {
  4338. toggleNATField(fieldKey, false);
  4339. }
  4340. }
  4341. function getNATFieldVal(fieldKey, hasInvert = false) {
  4342. const fieldBox = document.getElementById(`nat-field-${fieldKey}`);
  4343. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  4344. const valEl = document.getElementById(`nat-val-${fieldKey}`);
  4345. let v = valEl ? valEl.value.trim() : '';
  4346. if (!v) return '';
  4347. if (hasInvert) {
  4348. const invEl = document.getElementById(`nat-inv-${fieldKey}`);
  4349. if (invEl && invEl.checked) {
  4350. v = '!' + v.replace(/^!/, '');
  4351. }
  4352. }
  4353. return v;
  4354. }
  4355. function toggleMaximizeNATModal() {
  4356. const win = document.getElementById('nat-modal-window');
  4357. if (!win) return;
  4358. if (win.classList.contains('max-w-[720px]')) {
  4359. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  4360. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  4361. } else {
  4362. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  4363. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  4364. }
  4365. }
  4366. function handleNATChainChange() {
  4367. const ch = document.getElementById('nat-modal-chain')?.value || 'srcnat';
  4368. const actSel = document.getElementById('nat-modal-action');
  4369. if (actSel) {
  4370. if (ch === 'srcnat' && (actSel.value === 'dst-nat' || actSel.value === 'redirect')) {
  4371. actSel.value = 'masquerade';
  4372. } else if (ch === 'dstnat' && (actSel.value === 'masquerade' || actSel.value === 'src-nat')) {
  4373. actSel.value = 'dst-nat';
  4374. }
  4375. }
  4376. toggleNATActionFields();
  4377. }
  4378. function toggleNATActionFields() {
  4379. const act = document.getElementById('nat-modal-action')?.value || 'masquerade';
  4380. const rowAddr = document.getElementById('nat-row-toaddr');
  4381. const rowPort = document.getElementById('nat-row-toport');
  4382. const jumpBox = document.getElementById('nat-action-jump-box');
  4383. const addrBox = document.getElementById('nat-action-addrlist-box');
  4384. // Hide all dynamic rows first
  4385. if (rowAddr) rowAddr.classList.add('hidden');
  4386. if (rowPort) rowPort.classList.add('hidden');
  4387. if (jumpBox) jumpBox.classList.add('hidden');
  4388. if (addrBox) addrBox.classList.add('hidden');
  4389. if (['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat'].includes(act)) {
  4390. if (rowAddr) rowAddr.classList.remove('hidden');
  4391. if (rowPort) rowPort.classList.remove('hidden');
  4392. } else if (act === 'redirect' || act === 'masquerade') {
  4393. if (rowPort) rowPort.classList.remove('hidden');
  4394. } else if (act === 'jump') {
  4395. if (jumpBox) jumpBox.classList.remove('hidden');
  4396. } else if (act.includes('address-list') || act.includes('address list')) {
  4397. if (addrBox) addrBox.classList.remove('hidden');
  4398. }
  4399. if (act === 'log') {
  4400. const logEl = document.getElementById('nat-modal-log');
  4401. if (logEl) logEl.checked = true;
  4402. toggleNATField('logprefix', true);
  4403. }
  4404. }
  4405. function toggleNATLogPrefix() {
  4406. const isLog = document.getElementById('nat-modal-log')?.checked;
  4407. toggleNATField('logprefix', !!isLog);
  4408. }
  4409. function openAddNATModal() {
  4410. switchNATRuleTab('general');
  4411. const badge = document.getElementById('nat-modal-badge');
  4412. if (badge) badge.innerText = 'New...';
  4413. document.getElementById('nat-modal-id').value = '';
  4414. document.getElementById('nat-modal-enabled').checked = true;
  4415. document.getElementById('nat-modal-comment').value = '';
  4416. document.getElementById('nat-modal-chain').value = 'srcnat';
  4417. document.getElementById('nat-modal-action').value = 'masquerade';
  4418. document.getElementById('nat-modal-toaddr').value = '';
  4419. document.getElementById('nat-modal-toport').value = '';
  4420. document.getElementById('nat-modal-log').checked = false;
  4421. populateInterfaceSelect('nat-val-iniface');
  4422. populateInterfaceSelect('nat-val-outiface');
  4423. populateAddressListSelect('nat-val-srclist');
  4424. populateAddressListSelect('nat-val-dstlist');
  4425. populateGeoIPSelect('nat-val-srcgeo');
  4426. populateGeoIPSelect('nat-val-dstgeo');
  4427. const allFieldKeys = [
  4428. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  4429. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  4430. 'routingmark', 'conntype',
  4431. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  4432. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  4433. 'ipsec', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  4434. 'pktsize', 'random', 'icmpoptions', 'ipv4options', 'ttl',
  4435. 'time', 'days', 'limit', 'dstlimit', 'psd', 'logprefix'
  4436. ];
  4437. allFieldKeys.forEach(k => toggleNATField(k, false));
  4438. resetCurrentNATRuleCounters();
  4439. toggleNATActionFields();
  4440. document.getElementById('nat-modal').classList.remove('hidden');
  4441. }
  4442. function openEditNATModal(id) {
  4443. const r = (state.natRules || []).find(rule => rule.id === id);
  4444. if (!r) return;
  4445. switchNATRuleTab('general');
  4446. const badge = document.getElementById('nat-modal-badge');
  4447. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  4448. document.getElementById('nat-modal-id').value = r.id;
  4449. document.getElementById('nat-modal-enabled').checked = !r.disabled;
  4450. document.getElementById('nat-modal-comment').value = r.comment || '';
  4451. document.getElementById('nat-modal-chain').value = r.chain || 'srcnat';
  4452. document.getElementById('nat-modal-action').value = r.action || 'masquerade';
  4453. document.getElementById('nat-modal-toaddr').value = r.to_addresses || '';
  4454. document.getElementById('nat-modal-toport').value = r.to_ports || '';
  4455. document.getElementById('nat-modal-log').checked = !!r.log;
  4456. populateInterfaceSelect('nat-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  4457. populateInterfaceSelect('nat-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  4458. populateAddressListSelect('nat-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  4459. populateAddressListSelect('nat-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  4460. populateGeoIPSelect('nat-val-srcgeo', r.src_geoip || '');
  4461. populateGeoIPSelect('nat-val-dstgeo', r.dst_geoip || '');
  4462. setNATFieldVal('src', r.src_address, true);
  4463. setNATFieldVal('dst', r.dst_address, true);
  4464. setNATFieldVal('srclist', r.src_address_list, true);
  4465. setNATFieldVal('dstlist', r.dst_address_list, true);
  4466. setNATFieldVal('srcgeo', r.src_geoip, true);
  4467. setNATFieldVal('dstgeo', r.dst_geoip, true);
  4468. if (r.protocol && r.protocol !== 'all') {
  4469. setNATFieldVal('proto', r.protocol, true);
  4470. } else {
  4471. toggleNATField('proto', false);
  4472. }
  4473. setNATFieldVal('sport', r.src_port, true);
  4474. setNATFieldVal('dport', r.dst_port, true);
  4475. setNATFieldVal('anyport', r.any_port, true);
  4476. setNATFieldVal('iniface', r.in_interface, true);
  4477. setNATFieldVal('outiface', r.out_interface, true);
  4478. setNATFieldVal('inifacelist', r.in_interface_list, true);
  4479. setNATFieldVal('outifacelist', r.out_interface_list, true);
  4480. setNATFieldVal('pktmark', r.packet_mark, true);
  4481. setNATFieldVal('connmark', r.connection_mark, true);
  4482. setNATFieldVal('routingmark', r.routing_mark, true);
  4483. setNATFieldVal('conntype', r.connection_type, false);
  4484. // Advanced tab fields
  4485. setNATFieldVal('layer7', r.layer7_protocol, false);
  4486. setNATFieldVal('content', r.content, false);
  4487. setNATFieldVal('connbytes', r.connection_bytes, false);
  4488. setNATFieldVal('connrate', r.connection_rate, false);
  4489. setNATFieldVal('pcc', r.pcc, false);
  4490. setNATFieldVal('srcmac', r.src_mac_address, true);
  4491. setNATFieldVal('outbridgeport', r.out_bridge_port, false);
  4492. setNATFieldVal('inbridgeport', r.in_bridge_port, false);
  4493. setNATFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  4494. setNATFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  4495. setNATFieldVal('ipsec', r.ipsec_policy, false);
  4496. setNATFieldVal('ingresspriority', r.ingress_priority, false);
  4497. setNATFieldVal('priority', r.priority, false);
  4498. setNATFieldVal('dscp', r.dscp, false);
  4499. setNATFieldVal('tcpmss', r.tcp_mss, false);
  4500. if (r.tos) {
  4501. const tosEl = document.getElementById('nat-val-tos');
  4502. if (tosEl) tosEl.value = r.tos;
  4503. }
  4504. setNATFieldVal('pktsize', r.packet_size, false);
  4505. setNATFieldVal('random', r.random, false);
  4506. setNATFieldVal('icmpoptions', r.icmp_options, false);
  4507. setNATFieldVal('ipv4options', r.ipv4_options, false);
  4508. setNATFieldVal('ttl', r.ttl, false);
  4509. // Extra tab fields
  4510. setNATFieldVal('time', r.time, false);
  4511. if (r.days) {
  4512. toggleNATField('days', true);
  4513. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  4514. const chk = document.getElementById(`nat-day-${d}`);
  4515. if (chk) chk.checked = r.days.includes(d);
  4516. });
  4517. } else {
  4518. toggleNATField('days', false);
  4519. }
  4520. setNATFieldVal('limit', r.limit, false);
  4521. setNATFieldVal('dstlimit', r.dst_limit, false);
  4522. setNATFieldVal('psd', r.psd, false);
  4523. // Action fields
  4524. if (r.jump_target) {
  4525. const jtEl = document.getElementById('nat-modal-jumptarget');
  4526. if (jtEl) jtEl.value = r.jump_target;
  4527. }
  4528. if (r.address_list) {
  4529. const alEl = document.getElementById('nat-modal-action-addrlist');
  4530. if (alEl) alEl.value = r.address_list;
  4531. }
  4532. if (r.address_list_timeout) {
  4533. const toEl = document.getElementById('nat-modal-action-timeout');
  4534. if (toEl) toEl.value = r.address_list_timeout;
  4535. }
  4536. setNATFieldVal('logprefix', r.log_prefix, false);
  4537. // Statistics
  4538. const bEl = document.getElementById('nat-stat-bytes');
  4539. const pEl = document.getElementById('nat-stat-packets');
  4540. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  4541. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  4542. state.natLastBytes = r.bytes || 0;
  4543. state.natLastPackets = r.packets || 0;
  4544. state.natLastTimestamp = Date.now();
  4545. state.natStatRateHistory = new Array(30).fill(0);
  4546. state.natStatPktHistory = new Array(30).fill(0);
  4547. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  4548. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  4549. toggleNATActionFields();
  4550. document.getElementById('nat-modal').classList.remove('hidden');
  4551. }
  4552. function closeNATModal() {
  4553. stopNATStatPolling();
  4554. document.getElementById('nat-modal').classList.add('hidden');
  4555. }
  4556. function copyNATRule() {
  4557. document.getElementById('nat-modal-id').value = '';
  4558. const badge = document.getElementById('nat-modal-badge');
  4559. if (badge) badge.innerText = 'New...';
  4560. showToast('Rule Cloned', 'Ready to save as a new NAT rule copy', 'info');
  4561. }
  4562. function resetCurrentNATRuleCounters() {
  4563. state.natStatRateHistory = new Array(30).fill(0);
  4564. state.natStatPktHistory = new Array(30).fill(0);
  4565. state.natLastBytes = 0;
  4566. state.natLastPackets = 0;
  4567. state.natLastTimestamp = Date.now();
  4568. const bEl = document.getElementById('nat-stat-bytes');
  4569. const pEl = document.getElementById('nat-stat-packets');
  4570. const rEl = document.getElementById('nat-stat-rate');
  4571. const prEl = document.getElementById('nat-stat-pktrate');
  4572. if (bEl) bEl.value = '0 B';
  4573. if (pEl) pEl.value = '0';
  4574. if (rEl) rEl.value = '0 bps';
  4575. if (prEl) prEl.value = '0 p/s';
  4576. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  4577. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  4578. showToast('Counters Reset', 'NAT rule counter display reset to 0', 'info');
  4579. }
  4580. async function applyNATRule(closeAfter = false) {
  4581. const id = document.getElementById('nat-modal-id').value;
  4582. const chain = document.getElementById('nat-modal-chain').value;
  4583. const action = document.getElementById('nat-modal-action').value;
  4584. const comment = document.getElementById('nat-modal-comment').value.trim();
  4585. const enabled = document.getElementById('nat-modal-enabled').checked;
  4586. const src = getNATFieldVal('src', true);
  4587. const dst = getNATFieldVal('dst', true);
  4588. const srclist = getNATFieldVal('srclist', true);
  4589. const dstlist = getNATFieldVal('dstlist', true);
  4590. const srcgeo = getNATFieldVal('srcgeo', true);
  4591. const dstgeo = getNATFieldVal('dstgeo', true);
  4592. const proto = getNATFieldVal('proto', true);
  4593. const sport = getNATFieldVal('sport', true);
  4594. const dport = getNATFieldVal('dport', true);
  4595. const anyport = getNATFieldVal('anyport', true);
  4596. const iniface = getNATFieldVal('iniface', true);
  4597. const outiface = getNATFieldVal('outiface', true);
  4598. const inifacelist = getNATFieldVal('inifacelist', true);
  4599. const outifacelist = getNATFieldVal('outifacelist', true);
  4600. const pktmark = getNATFieldVal('pktmark', true);
  4601. const connmark = getNATFieldVal('connmark', true);
  4602. const routingmark = getNATFieldVal('routingmark', true);
  4603. const conntype = getNATFieldVal('conntype', false);
  4604. const usesAddr = ['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat'].includes(action);
  4605. const usesPort = ['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat', 'redirect', 'masquerade'].includes(action);
  4606. const payload = {
  4607. id,
  4608. chain,
  4609. action,
  4610. to_addresses: usesAddr ? (document.getElementById('nat-modal-toaddr')?.value.trim() || '') : '',
  4611. to_ports: usesPort ? (document.getElementById('nat-modal-toport')?.value.trim() || '') : '',
  4612. protocol: proto || 'all',
  4613. src_address: src,
  4614. dst_address: dst,
  4615. src_port: sport,
  4616. dst_port: dport,
  4617. any_port: anyport,
  4618. in_interface: iniface,
  4619. out_interface: outiface,
  4620. in_interface_list: inifacelist,
  4621. out_interface_list: outifacelist,
  4622. packet_mark: pktmark,
  4623. connection_mark: connmark,
  4624. routing_mark: routingmark,
  4625. connection_type: conntype,
  4626. src_address_list: srclist,
  4627. dst_address_list: dstlist,
  4628. src_geoip: srcgeo,
  4629. dst_geoip: dstgeo,
  4630. comment,
  4631. disabled: !enabled,
  4632. // Advanced tab
  4633. layer7_protocol: getNATFieldVal('layer7', false),
  4634. content: getNATFieldVal('content', false),
  4635. connection_bytes: getNATFieldVal('connbytes', false),
  4636. connection_rate: getNATFieldVal('connrate', false),
  4637. pcc: getNATFieldVal('pcc', false),
  4638. src_mac_address: getNATFieldVal('srcmac', true),
  4639. out_bridge_port: getNATFieldVal('outbridgeport', false),
  4640. in_bridge_port: getNATFieldVal('inbridgeport', false),
  4641. in_bridge_port_list: getNATFieldVal('inbridgeportlist', false),
  4642. out_bridge_port_list: getNATFieldVal('outbridgeportlist', false),
  4643. ipsec_policy: getNATFieldVal('ipsec', false),
  4644. ingress_priority: getNATFieldVal('ingresspriority', false),
  4645. priority: getNATFieldVal('priority', false),
  4646. dscp: getNATFieldVal('dscp', false),
  4647. tcp_mss: getNATFieldVal('tcpmss', false),
  4648. tos: document.getElementById('nat-val-tos')?.value || '',
  4649. packet_size: getNATFieldVal('pktsize', false),
  4650. random: getNATFieldVal('random', false),
  4651. icmp_options: getNATFieldVal('icmpoptions', false),
  4652. ipv4_options: getNATFieldVal('ipv4options', false),
  4653. ttl: getNATFieldVal('ttl', false),
  4654. // Extra tab
  4655. time: getNATFieldVal('time', false),
  4656. limit: getNATFieldVal('limit', false),
  4657. dst_limit: getNATFieldVal('dstlimit', false),
  4658. psd: getNATFieldVal('psd', false),
  4659. // Action tab
  4660. jump_target: action === 'jump' ? (document.getElementById('nat-modal-jumptarget')?.value || '') : '',
  4661. address_list: action.includes('address') ? (document.getElementById('nat-modal-action-addrlist')?.value || '') : '',
  4662. address_list_timeout: action.includes('address') ? (document.getElementById('nat-modal-action-timeout')?.value || '') : '',
  4663. log: document.getElementById('nat-modal-log')?.checked || false,
  4664. log_prefix: getNATFieldVal('logprefix', false)
  4665. };
  4666. try {
  4667. const res = await fetch(`${API_BASE}/firewall/nat`, {
  4668. method: 'POST',
  4669. headers: { 'Content-Type': 'application/json' },
  4670. body: JSON.stringify(payload)
  4671. });
  4672. if (res.ok) {
  4673. const data = await res.json();
  4674. showToast('NAT Rule Saved', 'NAT mapping updated', 'success');
  4675. loadFirewall(false);
  4676. if (closeAfter) {
  4677. closeNATModal();
  4678. } else {
  4679. if (data.id) {
  4680. document.getElementById('nat-modal-id').value = data.id;
  4681. const badge = document.getElementById('nat-modal-badge');
  4682. if (badge) badge.innerText = `#${data.id}`;
  4683. }
  4684. }
  4685. } else {
  4686. const err = await res.json();
  4687. showToast('Error', err.message || 'Failed to save rule', 'error');
  4688. }
  4689. } catch (err) {
  4690. showToast('Error', err.message, 'error');
  4691. }
  4692. }
  4693. function submitSaveNATRule(e) {
  4694. if (e && e.preventDefault) e.preventDefault();
  4695. return applyNATRule(true);
  4696. }
  4697. function startNATStatPolling() {
  4698. stopNATStatPolling();
  4699. pollNATRuleStats();
  4700. state.natStatInterval = setInterval(pollNATRuleStats, 1000);
  4701. }
  4702. function stopNATStatPolling() {
  4703. if (state.natStatInterval) {
  4704. clearInterval(state.natStatInterval);
  4705. state.natStatInterval = null;
  4706. }
  4707. }
  4708. async function pollNATRuleStats() {
  4709. const id = document.getElementById('nat-modal-id')?.value;
  4710. if (!id) {
  4711. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory || new Array(30).fill(0), 'bps', 'nat-stat-legend-rate');
  4712. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory || new Array(30).fill(0), 'p/s', 'nat-stat-legend-pktrate');
  4713. return;
  4714. }
  4715. try {
  4716. const res = await fetch(`${API_BASE}/firewall/nat`);
  4717. if (!res.ok) return;
  4718. const rules = await res.json();
  4719. const r = rules.find(x => x.id === id);
  4720. if (!r) return;
  4721. const now = Date.now();
  4722. const dt = Math.max(0.2, (now - (state.natLastTimestamp || now)) / 1000);
  4723. state.natLastTimestamp = now;
  4724. const curBytes = r.bytes || 0;
  4725. const curPackets = r.packets || 0;
  4726. const deltaBytes = Math.max(0, curBytes - (state.natLastBytes || curBytes));
  4727. const deltaPkts = Math.max(0, curPackets - (state.natLastPackets || curPackets));
  4728. state.natLastBytes = curBytes;
  4729. state.natLastPackets = curPackets;
  4730. const rateBps = Math.round((deltaBytes * 8) / dt);
  4731. const ratePkt = Math.round(deltaPkts / dt);
  4732. if (!state.natStatRateHistory) state.natStatRateHistory = new Array(30).fill(0);
  4733. if (!state.natStatPktHistory) state.natStatPktHistory = new Array(30).fill(0);
  4734. state.natStatRateHistory.push(rateBps);
  4735. if (state.natStatRateHistory.length > 30) state.natStatRateHistory.shift();
  4736. state.natStatPktHistory.push(ratePkt);
  4737. if (state.natStatPktHistory.length > 30) state.natStatPktHistory.shift();
  4738. const bEl = document.getElementById('nat-stat-bytes');
  4739. const pEl = document.getElementById('nat-stat-packets');
  4740. const rEl = document.getElementById('nat-stat-rate');
  4741. const prEl = document.getElementById('nat-stat-pktrate');
  4742. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  4743. if (pEl) pEl.value = curPackets.toLocaleString();
  4744. if (rEl) rEl.value = formatBps(rateBps);
  4745. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  4746. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  4747. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  4748. } catch (e) {
  4749. console.error('Error polling NAT rule stats', e);
  4750. }
  4751. }
  4752. async function moveNATRule(id, dir) {
  4753. try {
  4754. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/move`, {
  4755. method: 'POST',
  4756. headers: { 'Content-Type': 'application/json' },
  4757. body: JSON.stringify({ direction: dir })
  4758. });
  4759. if (res.ok) loadFirewall(false);
  4760. } catch (err) {
  4761. showToast('Error', err.message, 'error');
  4762. }
  4763. }
  4764. async function toggleNATRuleState(id, disabled) {
  4765. try {
  4766. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/state`, {
  4767. method: 'POST',
  4768. headers: { 'Content-Type': 'application/json' },
  4769. body: JSON.stringify({ disabled })
  4770. });
  4771. if (res.ok) loadFirewall(false);
  4772. } catch (err) {
  4773. showToast('Error', err.message, 'error');
  4774. }
  4775. }
  4776. async function deleteNATRule(id) {
  4777. if (!confirm('Are you sure you want to delete this NAT rule?')) return;
  4778. try {
  4779. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4780. if (res.ok) {
  4781. showToast('Deleted', 'NAT rule removed', 'success');
  4782. loadFirewall(false);
  4783. }
  4784. } catch (err) {
  4785. showToast('Error', err.message, 'error');
  4786. }
  4787. }
  4788. // ----------------- Mangle Rules -----------------
  4789. function renderMangleRules() {
  4790. const chainFilter = document.getElementById('mangle-filter-chain')?.value || '';
  4791. const tbody = document.getElementById('mangle-table-body');
  4792. const empty = document.getElementById('mangle-empty');
  4793. if (!tbody) return;
  4794. tbody.innerHTML = '';
  4795. const rules = (state.mangleRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  4796. document.getElementById('mangle-count-badge').innerText = `${rules.length} Rules`;
  4797. if (rules.length === 0) {
  4798. empty?.classList.remove('hidden');
  4799. return;
  4800. }
  4801. empty?.classList.add('hidden');
  4802. rules.forEach((r, idx) => {
  4803. const tr = document.createElement('tr');
  4804. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  4805. let markVal = '<span class="text-slate-500">-</span>';
  4806. if (r.new_connection_mark) markVal = `<span class="text-cyan-300 font-mono font-bold">${r.new_connection_mark}</span>`;
  4807. else if (r.new_routing_mark) markVal = `<span class="text-amber-300 font-mono font-bold">${r.new_routing_mark}</span>`;
  4808. else if (r.new_packet_mark) markVal = `<span class="text-emerald-300 font-mono font-bold">${r.new_packet_mark}</span>`;
  4809. else if (r.new_mss) markVal = `<span class="text-sky-300 font-mono font-bold">mss:${r.new_mss}</span>`;
  4810. else if (r.new_dscp) markVal = `<span class="text-purple-300 font-mono font-bold">dscp:${r.new_dscp}</span>`;
  4811. else if (r.new_ttl) markVal = `<span class="text-blue-300 font-mono font-bold">ttl:${r.new_ttl}</span>`;
  4812. else if (r.new_priority) markVal = `<span class="text-indigo-300 font-mono font-bold">prio:${r.new_priority}</span>`;
  4813. else if (r.route) markVal = `<span class="text-orange-300 font-mono font-bold">route:${r.route}</span>`;
  4814. else if (r.sniff_target) markVal = `<span class="text-pink-300 font-mono font-bold">sniff:${r.sniff_target}</span>`;
  4815. else if (r.action === 'jump') markVal = `<span class="text-yellow-300 font-mono font-bold">&rarr; ${r.jump_target || '-'}</span>`;
  4816. 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>`;
  4817. else if (r.action === 'log') markVal = `<span class="text-slate-400 font-mono font-bold">${r.log_prefix || 'log'}</span>`;
  4818. tr.innerHTML = `
  4819. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  4820. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  4821. <td class="py-2.5 px-3 font-bold text-purple-400">${r.chain}</td>
  4822. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  4823. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  4824. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  4825. <td class="py-2.5 px-3 font-mono text-xs">${markVal}</td>
  4826. <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>
  4827. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  4828. <span class="text-slate-300" id="mangle-pkts-${r.id}">${(r.packets || 0).toLocaleString()}p</span> /
  4829. <span class="text-slate-500" id="mangle-bytes-${r.id}">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  4830. </td>
  4831. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  4832. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  4833. <button onclick="moveMangleRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  4834. <button onclick="moveMangleRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  4835. <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>
  4836. <button onclick="openEditMangleModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  4837. <button onclick="deleteMangleRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  4838. </td>
  4839. `;
  4840. tbody.appendChild(tr);
  4841. });
  4842. }
  4843. // ==================== FIREWALL MANGLE MODAL (ROUTEROS WEBFIG / WINBOX V4) ====================
  4844. function switchMangleRuleTab(tab) {
  4845. state.activeMangleRuleTab = tab;
  4846. document.querySelectorAll('.mangle-rule-tab-btn').forEach(btn => {
  4847. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  4848. btn.classList.add('text-slate-400', 'border-transparent');
  4849. });
  4850. const activeBtn = document.getElementById(`mangle-tab-btn-${tab}`);
  4851. if (activeBtn) {
  4852. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  4853. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  4854. }
  4855. document.querySelectorAll('.mangle-rule-pane').forEach(p => p.classList.add('hidden'));
  4856. const activePane = document.getElementById(`mangle-pane-${tab}`);
  4857. if (activePane) activePane.classList.remove('hidden');
  4858. if (tab === 'statistics') {
  4859. startMangleStatPolling();
  4860. } else {
  4861. stopMangleStatPolling();
  4862. }
  4863. }
  4864. function toggleMangleField(fieldKey, expand) {
  4865. const plusBtn = document.getElementById(`mangle-plus-${fieldKey}`);
  4866. const fieldBox = document.getElementById(`mangle-field-${fieldKey}`);
  4867. if (!plusBtn || !fieldBox) return;
  4868. if (expand) {
  4869. plusBtn.classList.add('hidden');
  4870. fieldBox.classList.remove('hidden');
  4871. const valInput = document.getElementById(`mangle-val-${fieldKey}`);
  4872. if (valInput) valInput.focus();
  4873. } else {
  4874. fieldBox.classList.add('hidden');
  4875. plusBtn.classList.remove('hidden');
  4876. const valInput = document.getElementById(`mangle-val-${fieldKey}`);
  4877. if (valInput) {
  4878. if (valInput.tagName === 'SELECT') {
  4879. valInput.selectedIndex = 0;
  4880. } else {
  4881. valInput.value = '';
  4882. }
  4883. }
  4884. const invInput = document.getElementById(`mangle-inv-${fieldKey}`);
  4885. if (invInput) invInput.checked = false;
  4886. if (fieldKey === 'cs') {
  4887. ['mangle-modal-cs-established', 'mangle-modal-cs-related', 'mangle-modal-cs-new', 'mangle-modal-cs-invalid', 'mangle-modal-cs-untracked'].forEach(id => {
  4888. const el = document.getElementById(id);
  4889. if (el) el.checked = false;
  4890. });
  4891. }
  4892. if (fieldKey === 'natstate') {
  4893. ['mangle-modal-nat-srcnat', 'mangle-modal-nat-dstnat'].forEach(id => {
  4894. const el = document.getElementById(id);
  4895. if (el) el.checked = false;
  4896. });
  4897. }
  4898. }
  4899. }
  4900. function setMangleFieldVal(fieldKey, value, hasInvert = false) {
  4901. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  4902. toggleMangleField(fieldKey, true);
  4903. let strVal = String(value);
  4904. if (hasInvert) {
  4905. const inv = strVal.startsWith('!');
  4906. if (inv) strVal = strVal.slice(1);
  4907. const invEl = document.getElementById(`mangle-inv-${fieldKey}`);
  4908. if (invEl) invEl.checked = inv;
  4909. }
  4910. const valEl = document.getElementById(`mangle-val-${fieldKey}`);
  4911. if (valEl) valEl.value = strVal;
  4912. } else {
  4913. toggleMangleField(fieldKey, false);
  4914. }
  4915. }
  4916. function getMangleFieldVal(fieldKey, hasInvert = false) {
  4917. const fieldBox = document.getElementById(`mangle-field-${fieldKey}`);
  4918. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  4919. const valEl = document.getElementById(`mangle-val-${fieldKey}`);
  4920. let v = valEl ? valEl.value.trim() : '';
  4921. if (!v) return '';
  4922. if (hasInvert) {
  4923. const invEl = document.getElementById(`mangle-inv-${fieldKey}`);
  4924. if (invEl && invEl.checked) {
  4925. v = '!' + v.replace(/^!/, '');
  4926. }
  4927. }
  4928. return v;
  4929. }
  4930. function toggleMaximizeMangleModal() {
  4931. const win = document.getElementById('mangle-modal-window');
  4932. if (!win) return;
  4933. if (win.classList.contains('max-w-[720px]')) {
  4934. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  4935. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  4936. } else {
  4937. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  4938. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  4939. }
  4940. }
  4941. function toggleMangleActionFields() {
  4942. const act = document.getElementById('mangle-modal-action')?.value || 'mark-connection';
  4943. // Hide all dynamic rows first
  4944. ['newconnmark', 'newroutingmark', 'newpktmark', 'newmss', 'newdscp', 'newttl', 'newpriority', 'route', 'sniff', 'passthrough'].forEach(id => {
  4945. const el = document.getElementById(`mangle-row-${id}`);
  4946. if (el) el.classList.add('hidden');
  4947. });
  4948. const jumpBox = document.getElementById('mangle-action-jump-box');
  4949. const addrBox = document.getElementById('mangle-action-addrlist-box');
  4950. if (jumpBox) jumpBox.classList.add('hidden');
  4951. if (addrBox) addrBox.classList.add('hidden');
  4952. // Activate matching rows
  4953. if (act === 'mark-connection') {
  4954. document.getElementById('mangle-row-newconnmark')?.classList.remove('hidden');
  4955. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4956. } else if (act === 'mark-routing') {
  4957. document.getElementById('mangle-row-newroutingmark')?.classList.remove('hidden');
  4958. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4959. } else if (act === 'mark-packet') {
  4960. document.getElementById('mangle-row-newpktmark')?.classList.remove('hidden');
  4961. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4962. } else if (act === 'change-mss') {
  4963. document.getElementById('mangle-row-newmss')?.classList.remove('hidden');
  4964. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4965. } else if (act === 'change-dscp') {
  4966. document.getElementById('mangle-row-newdscp')?.classList.remove('hidden');
  4967. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4968. } else if (act === 'change-ttl') {
  4969. document.getElementById('mangle-row-newttl')?.classList.remove('hidden');
  4970. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4971. } else if (act === 'set-priority') {
  4972. document.getElementById('mangle-row-newpriority')?.classList.remove('hidden');
  4973. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4974. } else if (act === 'route') {
  4975. document.getElementById('mangle-row-route')?.classList.remove('hidden');
  4976. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4977. } else if (act === 'sniff-pc' || act === 'sniff-tzsp') {
  4978. document.getElementById('mangle-row-sniff')?.classList.remove('hidden');
  4979. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4980. } else if (act === 'clear-df' || act === 'strip-ipv4-options') {
  4981. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4982. } else if (act === 'jump') {
  4983. if (jumpBox) jumpBox.classList.remove('hidden');
  4984. } else if (act.includes('address-list') || act.includes('address list')) {
  4985. if (addrBox) addrBox.classList.remove('hidden');
  4986. }
  4987. if (act === 'log') {
  4988. const logEl = document.getElementById('mangle-modal-log');
  4989. if (logEl) logEl.checked = true;
  4990. toggleMangleField('logprefix', true);
  4991. }
  4992. }
  4993. function toggleMangleLogPrefix() {
  4994. const isLog = document.getElementById('mangle-modal-log')?.checked;
  4995. toggleMangleField('logprefix', !!isLog);
  4996. }
  4997. const allMangleFieldKeys = [
  4998. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  4999. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  5000. 'routingmark', 'conntype', 'cs', 'natstate',
  5001. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  5002. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  5003. 'ipsec', 'tlshost', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  5004. 'pktsize', 'random', 'tcpflags', 'icmpoptions', 'ipv4options', 'ttl',
  5005. 'nth', 'connlimit', 'srcaddrtype', 'dstaddrtype', 'hotspot', 'ipfragment',
  5006. 'limit', 'dstlimit', 'time', 'psd', 'logprefix'
  5007. ];
  5008. function openAddMangleModal() {
  5009. switchMangleRuleTab('general');
  5010. const badge = document.getElementById('mangle-modal-badge');
  5011. if (badge) badge.innerText = 'New...';
  5012. document.getElementById('mangle-modal-id').value = '';
  5013. document.getElementById('mangle-modal-enabled').checked = true;
  5014. document.getElementById('mangle-modal-comment').value = '';
  5015. document.getElementById('mangle-modal-chain').value = 'prerouting';
  5016. document.getElementById('mangle-modal-action').value = 'mark-connection';
  5017. if (document.getElementById('mangle-modal-newconnmark')) document.getElementById('mangle-modal-newconnmark').value = '';
  5018. if (document.getElementById('mangle-modal-newroutingmark')) document.getElementById('mangle-modal-newroutingmark').value = '';
  5019. if (document.getElementById('mangle-modal-newpktmark')) document.getElementById('mangle-modal-newpktmark').value = '';
  5020. if (document.getElementById('mangle-modal-newmss')) document.getElementById('mangle-modal-newmss').value = '';
  5021. if (document.getElementById('mangle-modal-newdscp')) document.getElementById('mangle-modal-newdscp').value = '';
  5022. if (document.getElementById('mangle-modal-newttl')) document.getElementById('mangle-modal-newttl').value = '';
  5023. if (document.getElementById('mangle-modal-newpriority')) document.getElementById('mangle-modal-newpriority').value = '';
  5024. if (document.getElementById('mangle-modal-route')) document.getElementById('mangle-modal-route').value = '';
  5025. if (document.getElementById('mangle-modal-sniff')) document.getElementById('mangle-modal-sniff').value = '';
  5026. if (document.getElementById('mangle-modal-jumptarget')) document.getElementById('mangle-modal-jumptarget').value = '';
  5027. if (document.getElementById('mangle-modal-action-addrlist')) document.getElementById('mangle-modal-action-addrlist').value = '';
  5028. if (document.getElementById('mangle-modal-action-timeout')) document.getElementById('mangle-modal-action-timeout').value = '';
  5029. if (document.getElementById('mangle-modal-passthrough')) document.getElementById('mangle-modal-passthrough').checked = true;
  5030. if (document.getElementById('mangle-modal-log')) document.getElementById('mangle-modal-log').checked = false;
  5031. populateInterfaceSelect('mangle-val-iniface');
  5032. populateInterfaceSelect('mangle-val-outiface');
  5033. populateAddressListSelect('mangle-val-srclist');
  5034. populateAddressListSelect('mangle-val-dstlist');
  5035. populateGeoIPSelect('mangle-val-srcgeo');
  5036. populateGeoIPSelect('mangle-val-dstgeo');
  5037. allMangleFieldKeys.forEach(k => toggleMangleField(k, false));
  5038. resetCurrentMangleRuleCounters();
  5039. toggleMangleActionFields();
  5040. document.getElementById('mangle-modal').classList.remove('hidden');
  5041. }
  5042. function openEditMangleModal(id) {
  5043. const r = (state.mangleRules || []).find(rule => rule.id === id);
  5044. if (!r) return;
  5045. switchMangleRuleTab('general');
  5046. const badge = document.getElementById('mangle-modal-badge');
  5047. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  5048. document.getElementById('mangle-modal-id').value = r.id;
  5049. document.getElementById('mangle-modal-enabled').checked = !r.disabled;
  5050. document.getElementById('mangle-modal-comment').value = r.comment || '';
  5051. document.getElementById('mangle-modal-chain').value = r.chain || 'prerouting';
  5052. document.getElementById('mangle-modal-action').value = r.action || 'mark-connection';
  5053. if (document.getElementById('mangle-modal-newconnmark')) document.getElementById('mangle-modal-newconnmark').value = r.new_connection_mark || '';
  5054. if (document.getElementById('mangle-modal-newroutingmark')) document.getElementById('mangle-modal-newroutingmark').value = r.new_routing_mark || '';
  5055. if (document.getElementById('mangle-modal-newpktmark')) document.getElementById('mangle-modal-newpktmark').value = r.new_packet_mark || '';
  5056. if (document.getElementById('mangle-modal-newmss')) document.getElementById('mangle-modal-newmss').value = r.new_mss || '';
  5057. if (document.getElementById('mangle-modal-newdscp')) document.getElementById('mangle-modal-newdscp').value = r.new_dscp != null ? r.new_dscp : '';
  5058. if (document.getElementById('mangle-modal-newttl')) document.getElementById('mangle-modal-newttl').value = r.new_ttl || '';
  5059. if (document.getElementById('mangle-modal-newpriority')) document.getElementById('mangle-modal-newpriority').value = r.new_priority || '';
  5060. if (document.getElementById('mangle-modal-route')) document.getElementById('mangle-modal-route').value = r.route || '';
  5061. if (document.getElementById('mangle-modal-sniff')) document.getElementById('mangle-modal-sniff').value = r.sniff_target || '';
  5062. if (document.getElementById('mangle-modal-jumptarget')) document.getElementById('mangle-modal-jumptarget').value = r.jump_target || '';
  5063. if (document.getElementById('mangle-modal-action-addrlist')) document.getElementById('mangle-modal-action-addrlist').value = r.address_list || '';
  5064. if (document.getElementById('mangle-modal-action-timeout')) document.getElementById('mangle-modal-action-timeout').value = r.address_list_timeout || '';
  5065. if (document.getElementById('mangle-modal-passthrough')) document.getElementById('mangle-modal-passthrough').checked = r.passthrough ?? true;
  5066. if (document.getElementById('mangle-modal-log')) document.getElementById('mangle-modal-log').checked = !!r.log;
  5067. populateInterfaceSelect('mangle-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  5068. populateInterfaceSelect('mangle-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  5069. populateAddressListSelect('mangle-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  5070. populateAddressListSelect('mangle-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  5071. populateGeoIPSelect('mangle-val-srcgeo', r.src_geoip || '');
  5072. populateGeoIPSelect('mangle-val-dstgeo', r.dst_geoip || '');
  5073. setMangleFieldVal('src', r.src_address, true);
  5074. setMangleFieldVal('dst', r.dst_address, true);
  5075. setMangleFieldVal('srclist', r.src_address_list, true);
  5076. setMangleFieldVal('dstlist', r.dst_address_list, true);
  5077. setMangleFieldVal('srcgeo', r.src_geoip, true);
  5078. setMangleFieldVal('dstgeo', r.dst_geoip, true);
  5079. if (r.protocol && r.protocol !== 'all') {
  5080. setMangleFieldVal('proto', r.protocol, true);
  5081. } else {
  5082. toggleMangleField('proto', false);
  5083. }
  5084. setMangleFieldVal('sport', r.src_port, true);
  5085. setMangleFieldVal('dport', r.dst_port, true);
  5086. setMangleFieldVal('anyport', r.any_port, true);
  5087. setMangleFieldVal('iniface', r.in_interface, true);
  5088. setMangleFieldVal('outiface', r.out_interface, true);
  5089. setMangleFieldVal('inifacelist', r.in_interface_list, true);
  5090. setMangleFieldVal('outifacelist', r.out_interface_list, true);
  5091. setMangleFieldVal('pktmark', r.packet_mark, true);
  5092. setMangleFieldVal('connmark', r.connection_mark, true);
  5093. setMangleFieldVal('routingmark', r.routing_mark, true);
  5094. setMangleFieldVal('conntype', r.connection_type, false);
  5095. // Connection State
  5096. const states = r.connection_state || [];
  5097. if (states.length > 0) {
  5098. toggleMangleField('cs', true);
  5099. ['established', 'related', 'new', 'invalid', 'untracked'].forEach(s => {
  5100. const el = document.getElementById(`mangle-modal-cs-${s}`);
  5101. if (el) el.checked = states.includes(s);
  5102. });
  5103. } else {
  5104. toggleMangleField('cs', false);
  5105. }
  5106. // Connection NAT State
  5107. const natStates = r.connection_nat_state || [];
  5108. if (natStates.length > 0) {
  5109. toggleMangleField('natstate', true);
  5110. ['srcnat', 'dstnat'].forEach(s => {
  5111. const el = document.getElementById(`mangle-modal-nat-${s}`);
  5112. if (el) el.checked = natStates.includes(s);
  5113. });
  5114. } else {
  5115. toggleMangleField('natstate', false);
  5116. }
  5117. // Advanced tab fields
  5118. setMangleFieldVal('layer7', r.layer7_protocol, false);
  5119. setMangleFieldVal('content', r.content, false);
  5120. setMangleFieldVal('connbytes', r.connection_bytes, false);
  5121. setMangleFieldVal('connrate', r.connection_rate, false);
  5122. setMangleFieldVal('pcc', r.pcc, false);
  5123. setMangleFieldVal('srcmac', r.src_mac_address, true);
  5124. setMangleFieldVal('outbridgeport', r.out_bridge_port, false);
  5125. setMangleFieldVal('inbridgeport', r.in_bridge_port, false);
  5126. setMangleFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  5127. setMangleFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  5128. setMangleFieldVal('ipsec', r.ipsec_policy, false);
  5129. setMangleFieldVal('tlshost', r.tls_host, false);
  5130. setMangleFieldVal('ingresspriority', r.ingress_priority, false);
  5131. setMangleFieldVal('priority', r.priority, false);
  5132. setMangleFieldVal('dscp', r.dscp, false);
  5133. setMangleFieldVal('tcpmss', r.tcp_mss, false);
  5134. if (r.tos) {
  5135. const tosEl = document.getElementById('mangle-val-tos');
  5136. if (tosEl) tosEl.value = r.tos;
  5137. }
  5138. setMangleFieldVal('pktsize', r.packet_size, false);
  5139. setMangleFieldVal('random', r.random, false);
  5140. setMangleFieldVal('tcpflags', r.tcp_flags, false);
  5141. setMangleFieldVal('icmpoptions', r.icmp_options, false);
  5142. setMangleFieldVal('ipv4options', r.ipv4_options, false);
  5143. setMangleFieldVal('ttl', r.ttl, false);
  5144. // Extra tab fields
  5145. setMangleFieldVal('nth', r.nth, false);
  5146. setMangleFieldVal('connlimit', r.connection_limit, false);
  5147. setMangleFieldVal('srcaddrtype', r.src_address_type, false);
  5148. setMangleFieldVal('dstaddrtype', r.dst_address_type, false);
  5149. setMangleFieldVal('hotspot', r.hotspot, false);
  5150. setMangleFieldVal('ipfragment', r.ip_fragment, false);
  5151. setMangleFieldVal('limit', r.limit, false);
  5152. setMangleFieldVal('dstlimit', r.dst_limit, false);
  5153. setMangleFieldVal('time', r.time, false);
  5154. setMangleFieldVal('psd', r.psd, false);
  5155. // Action fields
  5156. if (r.jump_target) {
  5157. const jtEl = document.getElementById('mangle-modal-jumptarget');
  5158. if (jtEl) jtEl.value = r.jump_target;
  5159. }
  5160. if (r.address_list) {
  5161. const alEl = document.getElementById('mangle-modal-action-addrlist');
  5162. if (alEl) alEl.value = r.address_list;
  5163. }
  5164. if (r.address_list_timeout) {
  5165. const toEl = document.getElementById('mangle-modal-action-timeout');
  5166. if (toEl) toEl.value = r.address_list_timeout;
  5167. }
  5168. setMangleFieldVal('logprefix', r.log_prefix, false);
  5169. // Statistics
  5170. const bEl = document.getElementById('mangle-stat-bytes');
  5171. const pEl = document.getElementById('mangle-stat-packets');
  5172. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  5173. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  5174. state.mangleLastBytes = r.bytes || 0;
  5175. state.mangleLastPackets = r.packets || 0;
  5176. state.mangleLastTimestamp = Date.now();
  5177. state.mangleStatRateHistory = new Array(30).fill(0);
  5178. state.mangleStatPktHistory = new Array(30).fill(0);
  5179. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  5180. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  5181. toggleMangleActionFields();
  5182. document.getElementById('mangle-modal').classList.remove('hidden');
  5183. }
  5184. function closeMangleModal() {
  5185. stopMangleStatPolling();
  5186. document.getElementById('mangle-modal').classList.add('hidden');
  5187. }
  5188. function copyMangleRule() {
  5189. document.getElementById('mangle-modal-id').value = '';
  5190. const badge = document.getElementById('mangle-modal-badge');
  5191. if (badge) badge.innerText = 'New...';
  5192. showToast('Rule Cloned', 'Ready to save as a new Mangle rule copy', 'info');
  5193. }
  5194. function resetCurrentMangleRuleCounters() {
  5195. state.mangleStatRateHistory = new Array(30).fill(0);
  5196. state.mangleStatPktHistory = new Array(30).fill(0);
  5197. state.mangleLastBytes = 0;
  5198. state.mangleLastPackets = 0;
  5199. state.mangleLastTimestamp = Date.now();
  5200. const bEl = document.getElementById('mangle-stat-bytes');
  5201. const pEl = document.getElementById('mangle-stat-packets');
  5202. const rEl = document.getElementById('mangle-stat-rate');
  5203. const prEl = document.getElementById('mangle-stat-pktrate');
  5204. if (bEl) bEl.value = '0 B';
  5205. if (pEl) pEl.value = '0';
  5206. if (rEl) rEl.value = '0 bps';
  5207. if (prEl) prEl.value = '0 p/s';
  5208. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  5209. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  5210. showToast('Counters Reset', 'Mangle rule counter display reset to 0', 'info');
  5211. }
  5212. async function applyMangleRule(closeAfter = false) {
  5213. const id = document.getElementById('mangle-modal-id').value;
  5214. const chain = document.getElementById('mangle-modal-chain').value;
  5215. const action = document.getElementById('mangle-modal-action').value;
  5216. const comment = document.getElementById('mangle-modal-comment').value.trim();
  5217. const enabled = document.getElementById('mangle-modal-enabled').checked;
  5218. const src = getMangleFieldVal('src', true);
  5219. const dst = getMangleFieldVal('dst', true);
  5220. const srclist = getMangleFieldVal('srclist', true);
  5221. const dstlist = getMangleFieldVal('dstlist', true);
  5222. const srcgeo = getMangleFieldVal('srcgeo', true);
  5223. const dstgeo = getMangleFieldVal('dstgeo', true);
  5224. const proto = getMangleFieldVal('proto', true);
  5225. const sport = getMangleFieldVal('sport', true);
  5226. const dport = getMangleFieldVal('dport', true);
  5227. const anyport = getMangleFieldVal('anyport', true);
  5228. const iniface = getMangleFieldVal('iniface', true);
  5229. const outiface = getMangleFieldVal('outiface', true);
  5230. const inifacelist = getMangleFieldVal('inifacelist', true);
  5231. const outifacelist = getMangleFieldVal('outifacelist', true);
  5232. const pktmark = getMangleFieldVal('pktmark', true);
  5233. const connmark = getMangleFieldVal('connmark', true);
  5234. const routingmark = getMangleFieldVal('routingmark', true);
  5235. const conntype = getMangleFieldVal('conntype', false);
  5236. const states = [];
  5237. const csBox = document.getElementById('mangle-field-cs');
  5238. if (csBox && !csBox.classList.contains('hidden')) {
  5239. ['established', 'related', 'new', 'invalid', 'untracked'].forEach(s => {
  5240. if (document.getElementById(`mangle-modal-cs-${s}`)?.checked) states.push(s);
  5241. });
  5242. }
  5243. const natStates = [];
  5244. const natBox = document.getElementById('mangle-field-natstate');
  5245. if (natBox && !natBox.classList.contains('hidden')) {
  5246. ['srcnat', 'dstnat'].forEach(s => {
  5247. if (document.getElementById(`mangle-modal-nat-${s}`)?.checked) natStates.push(s);
  5248. });
  5249. }
  5250. const payload = {
  5251. id,
  5252. chain,
  5253. action,
  5254. protocol: proto || 'all',
  5255. src_address: src,
  5256. dst_address: dst,
  5257. src_port: sport,
  5258. dst_port: dport,
  5259. any_port: anyport,
  5260. in_interface: iniface,
  5261. out_interface: outiface,
  5262. in_interface_list: inifacelist,
  5263. out_interface_list: outifacelist,
  5264. packet_mark: pktmark,
  5265. connection_mark: connmark,
  5266. routing_mark: routingmark,
  5267. connection_type: conntype,
  5268. connection_state: states,
  5269. connection_nat_state: natStates,
  5270. src_address_list: srclist,
  5271. dst_address_list: dstlist,
  5272. src_geoip: srcgeo,
  5273. dst_geoip: dstgeo,
  5274. comment,
  5275. disabled: !enabled,
  5276. // Advanced tab
  5277. layer7_protocol: getMangleFieldVal('layer7', false),
  5278. content: getMangleFieldVal('content', false),
  5279. connection_bytes: getMangleFieldVal('connbytes', false),
  5280. connection_rate: getMangleFieldVal('connrate', false),
  5281. pcc: getMangleFieldVal('pcc', false),
  5282. src_mac_address: getMangleFieldVal('srcmac', true),
  5283. out_bridge_port: getMangleFieldVal('outbridgeport', false),
  5284. in_bridge_port: getMangleFieldVal('inbridgeport', false),
  5285. in_bridge_port_list: getMangleFieldVal('inbridgeportlist', false),
  5286. out_bridge_port_list: getMangleFieldVal('outbridgeportlist', false),
  5287. ipsec_policy: getMangleFieldVal('ipsec', false),
  5288. tls_host: getMangleFieldVal('tlshost', false),
  5289. ingress_priority: getMangleFieldVal('ingresspriority', false),
  5290. priority: getMangleFieldVal('priority', false),
  5291. dscp: getMangleFieldVal('dscp', false),
  5292. tcp_mss: getMangleFieldVal('tcpmss', false),
  5293. tos: document.getElementById('mangle-val-tos')?.value || '',
  5294. packet_size: getMangleFieldVal('pktsize', false),
  5295. random: getMangleFieldVal('random', false),
  5296. tcp_flags: getMangleFieldVal('tcpflags', false),
  5297. icmp_options: getMangleFieldVal('icmpoptions', false),
  5298. ipv4_options: getMangleFieldVal('ipv4options', false),
  5299. ttl: getMangleFieldVal('ttl', false),
  5300. // Extra tab
  5301. nth: getMangleFieldVal('nth', false),
  5302. connection_limit: getMangleFieldVal('connlimit', false),
  5303. src_address_type: getMangleFieldVal('srcaddrtype', false),
  5304. dst_address_type: getMangleFieldVal('dstaddrtype', false),
  5305. hotspot: getMangleFieldVal('hotspot', false),
  5306. ip_fragment: getMangleFieldVal('ipfragment', false),
  5307. limit: getMangleFieldVal('limit', false),
  5308. dst_limit: getMangleFieldVal('dstlimit', false),
  5309. time: getMangleFieldVal('time', false),
  5310. psd: getMangleFieldVal('psd', false),
  5311. // Action tab
  5312. new_connection_mark: action === 'mark-connection' ? (document.getElementById('mangle-modal-newconnmark')?.value.trim() || '') : '',
  5313. new_routing_mark: action === 'mark-routing' ? (document.getElementById('mangle-modal-newroutingmark')?.value.trim() || '') : '',
  5314. new_packet_mark: action === 'mark-packet' ? (document.getElementById('mangle-modal-newpktmark')?.value.trim() || '') : '',
  5315. new_mss: action === 'change-mss' ? (document.getElementById('mangle-modal-newmss')?.value.trim() || '') : '',
  5316. new_dscp: action === 'change-dscp' ? parseInt(document.getElementById('mangle-modal-newdscp')?.value || '0', 10) : 0,
  5317. new_ttl: action === 'change-ttl' ? (document.getElementById('mangle-modal-newttl')?.value.trim() || '') : '',
  5318. new_priority: action === 'set-priority' ? (document.getElementById('mangle-modal-newpriority')?.value.trim() || '') : '',
  5319. route: action === 'route' ? (document.getElementById('mangle-modal-route')?.value.trim() || '') : '',
  5320. sniff_target: (action === 'sniff-pc' || action === 'sniff-tzsp') ? (document.getElementById('mangle-modal-sniff')?.value.trim() || '') : '',
  5321. passthrough: document.getElementById('mangle-modal-passthrough')?.checked ?? true,
  5322. jump_target: action === 'jump' ? (document.getElementById('mangle-modal-jumptarget')?.value || '') : '',
  5323. address_list: action.includes('address') ? (document.getElementById('mangle-modal-action-addrlist')?.value || '') : '',
  5324. address_list_timeout: action.includes('address') ? (document.getElementById('mangle-modal-action-timeout')?.value || '') : '',
  5325. log: document.getElementById('mangle-modal-log')?.checked || false,
  5326. log_prefix: getMangleFieldVal('logprefix', false)
  5327. };
  5328. try {
  5329. const res = await fetch(`${API_BASE}/firewall/mangle`, {
  5330. method: 'POST',
  5331. headers: { 'Content-Type': 'application/json' },
  5332. body: JSON.stringify(payload)
  5333. });
  5334. if (res.ok) {
  5335. const data = await res.json();
  5336. showToast('Mangle Rule Saved', 'Marking rule updated', 'success');
  5337. loadFirewall(false);
  5338. if (closeAfter) {
  5339. closeMangleModal();
  5340. } else {
  5341. if (data.id) {
  5342. document.getElementById('mangle-modal-id').value = data.id;
  5343. const badge = document.getElementById('mangle-modal-badge');
  5344. if (badge) badge.innerText = `#${data.id}`;
  5345. }
  5346. }
  5347. } else {
  5348. const err = await res.json();
  5349. showToast('Error', err.message || 'Failed to save mangle rule', 'error');
  5350. }
  5351. } catch (err) {
  5352. showToast('Error', err.message, 'error');
  5353. }
  5354. }
  5355. function submitSaveMangleRule(e) {
  5356. if (e && e.preventDefault) e.preventDefault();
  5357. return applyMangleRule(true);
  5358. }
  5359. function startMangleStatPolling() {
  5360. stopMangleStatPolling();
  5361. pollMangleRuleStats();
  5362. state.mangleStatInterval = setInterval(pollMangleRuleStats, 1000);
  5363. }
  5364. function stopMangleStatPolling() {
  5365. if (state.mangleStatInterval) {
  5366. clearInterval(state.mangleStatInterval);
  5367. state.mangleStatInterval = null;
  5368. }
  5369. }
  5370. async function pollMangleRuleStats() {
  5371. const id = document.getElementById('mangle-modal-id')?.value;
  5372. if (!id) {
  5373. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory || new Array(30).fill(0), 'bps', 'mangle-stat-legend-rate');
  5374. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory || new Array(30).fill(0), 'p/s', 'mangle-stat-legend-pktrate');
  5375. return;
  5376. }
  5377. try {
  5378. const res = await fetch(`${API_BASE}/firewall/mangle`);
  5379. if (!res.ok) return;
  5380. const rules = await res.json();
  5381. const r = rules.find(x => x.id === id);
  5382. if (!r) return;
  5383. const now = Date.now();
  5384. const dt = Math.max(0.2, (now - (state.mangleLastTimestamp || now)) / 1000);
  5385. state.mangleLastTimestamp = now;
  5386. const curBytes = r.bytes || 0;
  5387. const curPackets = r.packets || 0;
  5388. const deltaBytes = Math.max(0, curBytes - (state.mangleLastBytes || curBytes));
  5389. const deltaPkts = Math.max(0, curPackets - (state.mangleLastPackets || curPackets));
  5390. state.mangleLastBytes = curBytes;
  5391. state.mangleLastPackets = curPackets;
  5392. const rateBps = Math.round((deltaBytes * 8) / dt);
  5393. const ratePkt = Math.round(deltaPkts / dt);
  5394. if (!state.mangleStatRateHistory) state.mangleStatRateHistory = new Array(30).fill(0);
  5395. if (!state.mangleStatPktHistory) state.mangleStatPktHistory = new Array(30).fill(0);
  5396. state.mangleStatRateHistory.push(rateBps);
  5397. if (state.mangleStatRateHistory.length > 30) state.mangleStatRateHistory.shift();
  5398. state.mangleStatPktHistory.push(ratePkt);
  5399. if (state.mangleStatPktHistory.length > 30) state.mangleStatPktHistory.shift();
  5400. const bEl = document.getElementById('mangle-stat-bytes');
  5401. const pEl = document.getElementById('mangle-stat-packets');
  5402. const rEl = document.getElementById('mangle-stat-rate');
  5403. const prEl = document.getElementById('mangle-stat-pktrate');
  5404. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  5405. if (pEl) pEl.value = curPackets.toLocaleString();
  5406. if (rEl) rEl.value = formatBps(rateBps);
  5407. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  5408. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  5409. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  5410. } catch (e) {
  5411. console.error('Error polling Mangle rule stats', e);
  5412. }
  5413. }
  5414. async function moveMangleRule(id, dir) {
  5415. try {
  5416. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/move`, {
  5417. method: 'POST',
  5418. headers: { 'Content-Type': 'application/json' },
  5419. body: JSON.stringify({ direction: dir })
  5420. });
  5421. if (res.ok) loadFirewall(false);
  5422. } catch (err) {
  5423. showToast('Error', err.message, 'error');
  5424. }
  5425. }
  5426. async function toggleMangleRuleState(id, disabled) {
  5427. try {
  5428. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/state`, {
  5429. method: 'POST',
  5430. headers: { 'Content-Type': 'application/json' },
  5431. body: JSON.stringify({ disabled })
  5432. });
  5433. if (res.ok) loadFirewall(false);
  5434. } catch (err) {
  5435. showToast('Error', err.message, 'error');
  5436. }
  5437. }
  5438. async function deleteMangleRule(id) {
  5439. if (!confirm('Are you sure you want to delete this mangle rule?')) return;
  5440. try {
  5441. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5442. if (res.ok) {
  5443. showToast('Deleted', 'Mangle rule removed', 'success');
  5444. loadFirewall(false);
  5445. }
  5446. } catch (err) {
  5447. showToast('Error', err.message, 'error');
  5448. }
  5449. }
  5450. // ----------------- Address Lists -----------------
  5451. function renderAddressLists() {
  5452. const filterList = document.getElementById('addrlist-filter-name')?.value || '';
  5453. const tbody = document.getElementById('addrlist-table-body');
  5454. const empty = document.getElementById('addrlist-empty');
  5455. if (!tbody) return;
  5456. tbody.innerHTML = '';
  5457. const entries = (state.addressLists || []).filter(e => !filterList || e.name === filterList);
  5458. document.getElementById('addrlist-count-badge').innerText = `${entries.length} Entries`;
  5459. // Update filter select
  5460. const sel = document.getElementById('addrlist-filter-name');
  5461. if (sel) {
  5462. const cur = sel.value;
  5463. sel.innerHTML = '<option value="">All Lists</option>';
  5464. const set = new Set((state.addressLists || []).map(a => a.name));
  5465. set.forEach(n => {
  5466. const opt = document.createElement('option');
  5467. opt.value = n;
  5468. opt.innerText = n;
  5469. if (n === cur) opt.selected = true;
  5470. sel.appendChild(opt);
  5471. });
  5472. }
  5473. if (entries.length === 0) {
  5474. empty?.classList.remove('hidden');
  5475. return;
  5476. }
  5477. empty?.classList.add('hidden');
  5478. entries.forEach((e, idx) => {
  5479. const tr = document.createElement('tr');
  5480. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${e.disabled ? 'opacity-50' : ''}`;
  5481. tr.setAttribute('ondblclick', `openEditAddrListModal('${e.id}')`);
  5482. tr.innerHTML = `
  5483. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  5484. <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>
  5485. <td class="py-2.5 px-3 font-bold text-white font-mono">${e.name}</td>
  5486. <td class="py-2.5 px-3 font-mono font-bold text-emerald-400">${e.address}</td>
  5487. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[150px]">${e.comment || '-'}</td>
  5488. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  5489. <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>
  5490. <button onclick="openEditAddrListModal('${e.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-medium">Edit</button>
  5491. <button onclick="deleteAddrList('${e.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  5492. </td>
  5493. `;
  5494. tbody.appendChild(tr);
  5495. });
  5496. populateCommonAddrListDatalist();
  5497. }
  5498. function openAddAddrListModal() {
  5499. document.getElementById('addrlist-modal-title').innerText = 'Add Address List Entry';
  5500. document.getElementById('addrlist-modal-id').value = '';
  5501. document.getElementById('addrlist-modal-name').value = '';
  5502. document.getElementById('addrlist-modal-addr').value = '';
  5503. document.getElementById('addrlist-modal-comment').value = '';
  5504. document.getElementById('addrlist-modal-disabled').checked = false;
  5505. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  5506. if (submitBtn) submitBtn.innerText = 'Add to List';
  5507. document.getElementById('addrlist-modal').classList.remove('hidden');
  5508. }
  5509. function openEditAddrListModal(id) {
  5510. const e = (state.addressLists || []).find(item => item.id === id);
  5511. if (!e) return;
  5512. document.getElementById('addrlist-modal-title').innerText = `Edit Address List Entry: ${e.name}`;
  5513. document.getElementById('addrlist-modal-id').value = e.id;
  5514. document.getElementById('addrlist-modal-name').value = e.name;
  5515. document.getElementById('addrlist-modal-addr').value = e.address;
  5516. document.getElementById('addrlist-modal-comment').value = e.comment || '';
  5517. document.getElementById('addrlist-modal-disabled').checked = !!e.disabled;
  5518. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  5519. if (submitBtn) submitBtn.innerText = 'Save Changes';
  5520. document.getElementById('addrlist-modal').classList.remove('hidden');
  5521. }
  5522. function closeAddrListModal() {
  5523. document.getElementById('addrlist-modal').classList.add('hidden');
  5524. }
  5525. async function submitSaveAddrList(e) {
  5526. e.preventDefault();
  5527. const id = document.getElementById('addrlist-modal-id').value;
  5528. const name = document.getElementById('addrlist-modal-name').value.trim();
  5529. const addr = document.getElementById('addrlist-modal-addr').value.trim();
  5530. const comment = document.getElementById('addrlist-modal-comment').value.trim();
  5531. const disabled = document.getElementById('addrlist-modal-disabled').checked;
  5532. try {
  5533. const res = await fetch(`${API_BASE}/firewall/address-lists`, {
  5534. method: 'POST',
  5535. headers: { 'Content-Type': 'application/json' },
  5536. body: JSON.stringify({ id, name, address: addr, comment, disabled })
  5537. });
  5538. if (res.ok) {
  5539. showToast('Address List Item Saved', `Saved ${addr} in ${name}`, 'success');
  5540. closeAddrListModal();
  5541. loadFirewall(false);
  5542. } else {
  5543. const err = await res.json();
  5544. showToast('Error', err.message || 'Failed to save address list', 'error');
  5545. }
  5546. } catch (err) {
  5547. showToast('Error', err.message, 'error');
  5548. }
  5549. }
  5550. async function toggleAddrListState(id, disabled) {
  5551. try {
  5552. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}/state`, {
  5553. method: 'POST',
  5554. headers: { 'Content-Type': 'application/json' },
  5555. body: JSON.stringify({ disabled })
  5556. });
  5557. if (res.ok) {
  5558. loadFirewall(false);
  5559. }
  5560. } catch (err) {
  5561. showToast('Error', err.message, 'error');
  5562. }
  5563. }
  5564. async function deleteAddrList(id) {
  5565. if (!confirm('Are you sure you want to delete this address list item?')) return;
  5566. try {
  5567. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5568. if (res.ok) {
  5569. showToast('Deleted', 'Address list item removed', 'info');
  5570. loadFirewall(false);
  5571. }
  5572. } catch (err) {
  5573. showToast('Error', err.message, 'error');
  5574. }
  5575. }
  5576. // ----------------- Geo-Location IP Management -----------------
  5577. async function loadGeoIP() {
  5578. try {
  5579. const [statusRes, countriesRes] = await Promise.all([
  5580. fetch(`${API_BASE}/firewall/geoip/status`),
  5581. fetch(`${API_BASE}/firewall/geoip/countries`)
  5582. ]);
  5583. if (statusRes.ok) state.geoStatus = await statusRes.json();
  5584. if (countriesRes.ok) state.geoCountries = await countriesRes.json();
  5585. updateGeoHeader();
  5586. renderGeoCountries();
  5587. } catch (err) {
  5588. console.error('Failed to load GeoIP:', err);
  5589. }
  5590. }
  5591. function getGeoUsageMap() {
  5592. const usage = {};
  5593. const checkRule = (r, type) => {
  5594. ['src_geoip', 'dst_geoip'].forEach(field => {
  5595. let val = (r && r[field]) || '';
  5596. let code = val.replace(/^!/, '').replace(/^geo:/, '').replace(/^geo_/, '').toUpperCase().trim();
  5597. if (code) {
  5598. if (!usage[code]) usage[code] = [];
  5599. const label = `${type} #${r.priority !== undefined ? r.priority : (r.id || '')}`;
  5600. if (!usage[code].includes(label)) usage[code].push(label);
  5601. }
  5602. });
  5603. };
  5604. (state.filterRules || []).forEach(r => checkRule(r, 'Filter'));
  5605. (state.natRules || []).forEach(r => checkRule(r, 'NAT'));
  5606. (state.mangleRules || []).forEach(r => checkRule(r, 'Mangle'));
  5607. return usage;
  5608. }
  5609. function updateGeoHeader() {
  5610. const s = state.geoStatus || {};
  5611. const statusBadge = document.getElementById('geo-status-badge');
  5612. if (statusBadge) {
  5613. statusBadge.innerText = s.auto_update ? 'Auto-Update ON' : 'Auto-Update OFF';
  5614. statusBadge.className = s.auto_update
  5615. ? 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-emerald-500/20 text-emerald-300 border border-emerald-500/30'
  5616. : 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 text-slate-400';
  5617. }
  5618. const intervalLabel = document.getElementById('geo-interval-label');
  5619. if (intervalLabel) {
  5620. intervalLabel.innerText = `Every ${s.interval_hours || 24}h`;
  5621. }
  5622. const usageMap = getGeoUsageMap();
  5623. const inUseCount = Object.keys(usageMap).length;
  5624. const activeCountEl = document.getElementById('geo-stat-active-countries');
  5625. if (activeCountEl) activeCountEl.innerText = inUseCount.toLocaleString();
  5626. const totalSubnetsEl = document.getElementById('geo-stat-total-subnets');
  5627. if (totalSubnetsEl) totalSubnetsEl.innerText = (s.total_subnets || 0).toLocaleString();
  5628. const lastSyncEl = document.getElementById('geo-stat-last-sync');
  5629. if (lastSyncEl) {
  5630. if (s.last_updated && !s.last_updated.startsWith('0001')) {
  5631. const d = new Date(s.last_updated);
  5632. lastSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  5633. } else {
  5634. lastSyncEl.innerText = 'Never (Sync Pending)';
  5635. }
  5636. }
  5637. const nextSyncEl = document.getElementById('geo-stat-next-sync');
  5638. if (nextSyncEl) {
  5639. if (s.next_update && !s.next_update.startsWith('0001')) {
  5640. const d = new Date(s.next_update);
  5641. nextSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  5642. } else {
  5643. nextSyncEl.innerText = '-';
  5644. }
  5645. }
  5646. const badge = document.getElementById('fw-badge-geo');
  5647. if (badge) badge.innerText = inUseCount || (state.geoCountries || []).filter(c => c.subnet_count > 0).length || 0;
  5648. }
  5649. function renderGeoCountries() {
  5650. const tbody = document.getElementById('geo-table-body');
  5651. const empty = document.getElementById('geo-empty');
  5652. if (!tbody) return;
  5653. tbody.innerHTML = '';
  5654. const q = (document.getElementById('geo-search-input')?.value || '').trim().toLowerCase();
  5655. const continent = document.getElementById('geo-continent-filter')?.value || '';
  5656. const inUseOnly = document.getElementById('geo-filter-inuse-only')?.checked;
  5657. const cachedOnly = document.getElementById('geo-filter-cached-only')?.checked;
  5658. const usageMap = getGeoUsageMap();
  5659. const countries = (state.geoCountries || []).filter(c => {
  5660. const isUsed = !!usageMap[c.code];
  5661. if (inUseOnly && !isUsed) return false;
  5662. if (cachedOnly && (!c.subnet_count || c.subnet_count === 0)) return false;
  5663. if (continent && c.continent !== continent) return false;
  5664. if (q) {
  5665. const matchCode = c.code.toLowerCase().includes(q);
  5666. const matchName = c.name.toLowerCase().includes(q);
  5667. if (!matchCode && !matchName) return false;
  5668. }
  5669. return true;
  5670. });
  5671. if (countries.length === 0) {
  5672. empty?.classList.remove('hidden');
  5673. return;
  5674. }
  5675. empty?.classList.add('hidden');
  5676. countries.forEach(c => {
  5677. const tr = document.createElement('tr');
  5678. const isUsed = !!usageMap[c.code];
  5679. const rulesUsing = usageMap[c.code] || [];
  5680. tr.className = `hover:bg-slate-800/40 transition text-xs ${isUsed ? 'bg-emerald-950/20' : ''}`;
  5681. let statusHtml = '';
  5682. if (isUsed) {
  5683. 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>`;
  5684. } else if (c.subnet_count > 0) {
  5685. 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>';
  5686. } else {
  5687. statusHtml = '<span class="px-2 py-0.5 rounded text-[10px] font-mono text-slate-500 bg-slate-800/60">READY</span>';
  5688. }
  5689. tr.innerHTML = `
  5690. <td class="py-2.5 px-3 text-center">
  5691. <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'}">
  5692. ${c.code}
  5693. </span>
  5694. </td>
  5695. <td class="py-2.5 px-3 font-bold text-white">${c.name}</td>
  5696. <td class="py-2.5 px-3 text-slate-400">${c.continent}</td>
  5697. <td class="py-2.5 px-3 font-mono ${c.subnet_count > 0 ? 'text-emerald-400 font-bold' : 'text-slate-500'}">
  5698. ${c.subnet_count > 0 ? c.subnet_count.toLocaleString() + ' CIDRs' : 'Not Cached'}
  5699. </td>
  5700. <td class="py-2.5 px-3 font-mono text-purple-300">${c.ipset_name}</td>
  5701. <td class="py-2.5 px-3">
  5702. ${statusHtml}
  5703. </td>
  5704. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  5705. <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>
  5706. <button onclick="viewGeoSubnets('${c.code}')" class="text-xs text-slate-400 hover:text-white" title="Preview Subnet Ranges">View</button>
  5707. </td>
  5708. `;
  5709. tbody.appendChild(tr);
  5710. });
  5711. }
  5712. function quickFilterGeo(preset) {
  5713. const searchInput = document.getElementById('geo-search-input');
  5714. const continentSel = document.getElementById('geo-continent-filter');
  5715. const inUseCheck = document.getElementById('geo-filter-inuse-only');
  5716. const cachedCheck = document.getElementById('geo-filter-cached-only');
  5717. if (searchInput) searchInput.value = '';
  5718. if (continentSel) continentSel.value = '';
  5719. if (inUseCheck) inUseCheck.checked = false;
  5720. if (cachedCheck) cachedCheck.checked = false;
  5721. if (preset === 'GR') {
  5722. if (searchInput) searchInput.value = 'Greece';
  5723. } else if (preset === 'Europe') {
  5724. if (continentSel) continentSel.value = 'Europe';
  5725. } else if (preset === 'HIGHRISK') {
  5726. if (searchInput) searchInput.value = 'China';
  5727. }
  5728. renderGeoCountries();
  5729. }
  5730. async function toggleGeoCountry(code, enabled) {
  5731. try {
  5732. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/toggle`, {
  5733. method: 'POST',
  5734. headers: { 'Content-Type': 'application/json' },
  5735. body: JSON.stringify({ enabled })
  5736. });
  5737. if (res.ok) {
  5738. showToast(enabled ? 'Country Enabled' : 'Country Disabled', `${code} ${enabled ? 'active in firewall' : 'removed from firewall'}`, 'success');
  5739. loadGeoIP();
  5740. } else {
  5741. const err = await res.json();
  5742. showToast('Error', err.message || 'Failed to toggle country', 'error');
  5743. }
  5744. } catch (err) {
  5745. showToast('Error', err.message, 'error');
  5746. }
  5747. }
  5748. async function updateGeoCountry(code) {
  5749. try {
  5750. showToast('Syncing Country', `Downloading latest IP blocks for ${code}...`, 'info');
  5751. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/update`, { method: 'POST' });
  5752. if (res.ok) {
  5753. const data = await res.json();
  5754. showToast('Synced', `Loaded ${data.subnets} CIDR blocks for ${code}`, 'success');
  5755. loadGeoIP();
  5756. } else {
  5757. const err = await res.json();
  5758. showToast('Sync Error', err.message || 'Failed to sync country', 'error');
  5759. }
  5760. } catch (err) {
  5761. showToast('Error', err.message, 'error');
  5762. }
  5763. }
  5764. async function triggerGeoUpdateNow() {
  5765. const spinner = document.getElementById('geo-update-spinner');
  5766. if (spinner) spinner.classList.remove('hidden');
  5767. try {
  5768. const res = await fetch(`${API_BASE}/firewall/geoip/update-now`, { method: 'POST' });
  5769. if (res.ok) {
  5770. showToast('Update Started', 'Updating all active GeoIP country zones in background...', 'info');
  5771. setTimeout(() => {
  5772. loadGeoIP();
  5773. if (spinner) spinner.classList.add('hidden');
  5774. }, 2500);
  5775. } else {
  5776. const err = await res.json();
  5777. showToast('Notice', err.message || 'Update in progress', 'info');
  5778. if (spinner) spinner.classList.add('hidden');
  5779. }
  5780. } catch (err) {
  5781. showToast('Error', err.message, 'error');
  5782. if (spinner) spinner.classList.add('hidden');
  5783. }
  5784. }
  5785. async function applyGeoPreset(preset) {
  5786. try {
  5787. const res = await fetch(`${API_BASE}/firewall/geoip/batch-toggle`, {
  5788. method: 'POST',
  5789. headers: { 'Content-Type': 'application/json' },
  5790. body: JSON.stringify({ preset, enabled: preset !== 'NONE' })
  5791. });
  5792. if (res.ok) {
  5793. showToast('Preset Applied', `Preset ${preset} updated in firewall`, 'success');
  5794. loadGeoIP();
  5795. }
  5796. } catch (err) {
  5797. showToast('Error', err.message, 'error');
  5798. }
  5799. }
  5800. function openGeoIntervalModal() {
  5801. const s = state.geoStatus || {};
  5802. document.getElementById('geo-cfg-autoupdate').checked = s.auto_update !== false;
  5803. const sel = document.getElementById('geo-cfg-interval');
  5804. const customBox = document.getElementById('geo-cfg-custom-box');
  5805. const customHoursInput = document.getElementById('geo-cfg-custom-hours');
  5806. const curHours = s.interval_hours || 24;
  5807. const matchOption = Array.from(sel.options).find(o => parseInt(o.value, 10) === curHours);
  5808. if (matchOption) {
  5809. sel.value = String(curHours);
  5810. customBox.classList.add('hidden');
  5811. } else {
  5812. sel.value = 'custom';
  5813. customHoursInput.value = curHours;
  5814. customBox.classList.remove('hidden');
  5815. }
  5816. document.getElementById('geo-interval-modal').classList.remove('hidden');
  5817. }
  5818. function closeGeoIntervalModal() {
  5819. document.getElementById('geo-interval-modal').classList.add('hidden');
  5820. }
  5821. function toggleCustomGeoInterval() {
  5822. const val = document.getElementById('geo-cfg-interval').value;
  5823. const customBox = document.getElementById('geo-cfg-custom-box');
  5824. if (val === 'custom') {
  5825. customBox.classList.remove('hidden');
  5826. } else {
  5827. customBox.classList.add('hidden');
  5828. }
  5829. }
  5830. async function submitGeoIntervalSettings(e) {
  5831. e.preventDefault();
  5832. const autoUpdate = document.getElementById('geo-cfg-autoupdate').checked;
  5833. const intervalVal = document.getElementById('geo-cfg-interval').value;
  5834. let hours = 24;
  5835. if (intervalVal === 'custom') {
  5836. hours = parseInt(document.getElementById('geo-cfg-custom-hours').value, 10) || 24;
  5837. } else {
  5838. hours = parseInt(intervalVal, 10) || 24;
  5839. }
  5840. try {
  5841. const res = await fetch(`${API_BASE}/firewall/geoip/config`, {
  5842. method: 'POST',
  5843. headers: { 'Content-Type': 'application/json' },
  5844. body: JSON.stringify({ auto_update: autoUpdate, interval_hours: hours })
  5845. });
  5846. if (res.ok) {
  5847. showToast('Schedule Saved', `Auto-update set to every ${hours} hours`, 'success');
  5848. closeGeoIntervalModal();
  5849. loadGeoIP();
  5850. } else {
  5851. const err = await res.json();
  5852. showToast('Error', err.message || 'Failed to save schedule', 'error');
  5853. }
  5854. } catch (err) {
  5855. showToast('Error', err.message, 'error');
  5856. }
  5857. }
  5858. async function viewGeoSubnets(code, name) {
  5859. if (!name) {
  5860. const found = (state.geoCountries || []).find(x => x.code === code);
  5861. name = found ? found.name : code;
  5862. }
  5863. document.getElementById('geo-subnets-title').innerText = `${name} (${code}) Subnets`;
  5864. document.getElementById('geo-subnets-subtitle').innerText = `Kernel IPSet: mk_geo_${code}`;
  5865. const listEl = document.getElementById('geo-subnets-list');
  5866. listEl.innerHTML = '<span class="text-slate-500">Loading subnets...</span>';
  5867. document.getElementById('geo-subnets-modal').classList.remove('hidden');
  5868. try {
  5869. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/subnets`);
  5870. if (res.ok) {
  5871. const data = await res.json();
  5872. const subnets = data.subnets || [];
  5873. if (subnets.length === 0) {
  5874. listEl.innerHTML = '<span class="text-slate-500">No cached subnets found. Click Sync to download this zone.</span>';
  5875. } else {
  5876. listEl.innerHTML = subnets.map(s => `<div>${s}</div>`).join('');
  5877. }
  5878. } else {
  5879. listEl.innerHTML = '<span class="text-rose-400">Failed to load subnets.</span>';
  5880. }
  5881. } catch (err) {
  5882. listEl.innerHTML = `<span class="text-rose-400">Error: ${err.message}</span>`;
  5883. }
  5884. }
  5885. function closeGeoSubnetsModal() {
  5886. document.getElementById('geo-subnets-modal').classList.add('hidden');
  5887. }
  5888. // ----------------- Active Connections Tracking -----------------
  5889. async function loadConnections() {
  5890. try {
  5891. const res = await fetch(`${API_BASE}/firewall/connections`);
  5892. const data = await res.json();
  5893. state.connections = Array.isArray(data) ? data : [];
  5894. document.getElementById('fw-badge-connections').innerText = state.connections.length;
  5895. document.getElementById('conns-count-badge').innerText = `${state.connections.length} Flows`;
  5896. renderConnections();
  5897. } catch (err) {
  5898. console.error('Failed to load connections:', err);
  5899. }
  5900. }
  5901. function renderConnections() {
  5902. const search = (document.getElementById('conns-search-input')?.value || '').toLowerCase();
  5903. const protoFilter = document.getElementById('conns-filter-proto')?.value || '';
  5904. const tbody = document.getElementById('conns-table-body');
  5905. const empty = document.getElementById('conns-empty');
  5906. if (!tbody) return;
  5907. tbody.innerHTML = '';
  5908. const conns = (state.connections || []).filter(c => {
  5909. if (protoFilter && c.protocol !== protoFilter) return false;
  5910. if (search) {
  5911. const line = `${c.protocol} ${c.src_address} ${c.dst_address} ${c.src_port} ${c.dst_port} ${c.tcp_state} ${c.connection_mark}`.toLowerCase();
  5912. if (!line.includes(search)) return false;
  5913. }
  5914. return true;
  5915. });
  5916. if (conns.length === 0) {
  5917. empty?.classList.remove('hidden');
  5918. return;
  5919. }
  5920. empty?.classList.add('hidden');
  5921. conns.slice(0, 150).forEach(c => {
  5922. const tr = document.createElement('tr');
  5923. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  5924. let stateColor = 'text-slate-400';
  5925. if (c.tcp_state === 'ESTABLISHED') stateColor = 'text-emerald-400 font-bold';
  5926. else if (c.tcp_state === 'TIME_WAIT' || c.tcp_state === 'SYN_SENT') stateColor = 'text-amber-400';
  5927. tr.innerHTML = `
  5928. <td class="py-2.5 px-3 font-bold text-cyan-400">${c.protocol}</td>
  5929. <td class="py-2.5 px-3 font-mono text-white">${c.src_address}:${c.src_port}</td>
  5930. <td class="py-2.5 px-3 font-mono text-white">${c.dst_address}:${c.dst_port}</td>
  5931. <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>
  5932. <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>
  5933. <td class="py-2.5 px-3 font-mono ${stateColor}">${c.tcp_state}</td>
  5934. <td class="py-2.5 px-3 font-mono text-purple-300">${c.connection_mark || '-'}</td>
  5935. <td class="py-2.5 px-3 text-slate-500">${c.timeout ? c.timeout + 's' : '-'}</td>
  5936. <td class="py-2.5 px-3 text-right font-sans">
  5937. <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>
  5938. </td>
  5939. `;
  5940. tbody.appendChild(tr);
  5941. });
  5942. }
  5943. async function killConnection(protocol, src, sport, dst, dport) {
  5944. try {
  5945. const res = await fetch(`${API_BASE}/firewall/connections/kill`, {
  5946. method: 'POST',
  5947. headers: { 'Content-Type': 'application/json' },
  5948. body: JSON.stringify({ protocol, src, sport, dst, dport })
  5949. });
  5950. if (res.ok) {
  5951. showToast('Terminated', `Killed flow ${src}:${sport} -> ${dst}:${dport}`, 'info');
  5952. loadConnections();
  5953. }
  5954. } catch (err) {
  5955. showToast('Error', err.message, 'error');
  5956. }
  5957. }
  5958. async function resetFirewallCounters() {
  5959. if (!confirm('Reset all firewall packet and byte counters to zero?')) return;
  5960. try {
  5961. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  5962. if (res.ok) {
  5963. showToast('Counters Reset', 'All rules counters reset to 0', 'success');
  5964. loadFirewall(false);
  5965. }
  5966. } catch (err) {
  5967. showToast('Error', err.message, 'error');
  5968. }
  5969. }
  5970. // ======================== MIKROTIK ROUTING & POLICY (/ip route) ========================
  5971. function switchRoutesSubTab(tab) {
  5972. state.routesSubTab = tab;
  5973. const tabs = ['routes', 'rules', 'tables'];
  5974. tabs.forEach(t => {
  5975. const panel = document.getElementById(`routes-subtab-${t}`);
  5976. const btn = document.getElementById(`routes-subtab-btn-${t}`);
  5977. if (panel) {
  5978. if (t === tab) panel.classList.remove('hidden');
  5979. else panel.classList.add('hidden');
  5980. }
  5981. if (btn) {
  5982. if (t === tab) {
  5983. 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';
  5984. } else {
  5985. 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';
  5986. }
  5987. }
  5988. });
  5989. setTimeout(initTableSorting, 50);
  5990. }
  5991. async function loadRoutes() {
  5992. try {
  5993. const [routesRes, rulesRes, tablesRes] = await Promise.all([
  5994. fetch(`${API_BASE}/routes`),
  5995. fetch(`${API_BASE}/routing/rules`),
  5996. fetch(`${API_BASE}/routing/tables`)
  5997. ]);
  5998. if (routesRes.ok) state.routes = await routesRes.json();
  5999. if (rulesRes.ok) state.policyRules = await rulesRes.json();
  6000. if (tablesRes.ok) state.routingTables = await tablesRes.json();
  6001. const bRoutes = document.getElementById('routes-badge-routes');
  6002. if (bRoutes) bRoutes.innerText = (state.routes || []).length;
  6003. const showSystem = document.getElementById('prule-show-system')?.checked;
  6004. const userRules = (state.policyRules || []).filter(pr => showSystem || (!pr.is_default && !pr.is_system));
  6005. const bRules = document.getElementById('routes-badge-rules');
  6006. if (bRules) bRules.innerText = userRules.length;
  6007. const bTables = document.getElementById('routes-badge-tables');
  6008. if (bTables) bTables.innerText = (state.routingTables || []).length;
  6009. const bRoutesCount = document.getElementById('badge-routes-count');
  6010. if (bRoutesCount) bRoutesCount.innerText = (state.routes || []).length;
  6011. renderRoutesList();
  6012. renderPolicyRules();
  6013. renderRoutingTables();
  6014. } catch (err) {
  6015. console.error('Failed to load routing:', err);
  6016. }
  6017. }
  6018. function getRouteProtocolBadge(proto) {
  6019. const p = (proto || 'static').toLowerCase();
  6020. switch (p) {
  6021. case 'bgp':
  6022. 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>`;
  6023. case 'ibgp':
  6024. 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>`;
  6025. case 'ospf':
  6026. 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>`;
  6027. case 'rip':
  6028. 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>`;
  6029. case 'static':
  6030. 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>`;
  6031. case 'connected':
  6032. 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>`;
  6033. case 'dhcp':
  6034. 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>`;
  6035. case 'multicast':
  6036. 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>`;
  6037. default:
  6038. 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>`;
  6039. }
  6040. }
  6041. function renderRoutesList() {
  6042. const tableFilter = document.getElementById('routes-filter-table')?.value || '';
  6043. const typeFilter = document.getElementById('routes-filter-type')?.value || '';
  6044. const tbody = document.getElementById('routes-table-body');
  6045. const empty = document.getElementById('routes-empty');
  6046. if (!tbody) return;
  6047. // Update table filter select
  6048. const sel = document.getElementById('routes-filter-table');
  6049. if (sel) {
  6050. const cur = sel.value;
  6051. sel.innerHTML = '<option value="">All Tables</option>';
  6052. (state.routingTables || []).forEach(t => {
  6053. const opt = document.createElement('option');
  6054. opt.value = t.name;
  6055. opt.innerText = t.name;
  6056. if (t.name === cur) opt.selected = true;
  6057. sel.appendChild(opt);
  6058. });
  6059. }
  6060. const routes = (state.routes || []).filter(r => {
  6061. if (tableFilter && r.routing_table !== tableFilter) return false;
  6062. if (typeFilter === 'ecmp' && !r.ecmp) return false;
  6063. if (typeFilter === 'multicast' && !r.multicast) return false;
  6064. if (typeFilter === 'static' && !r.static) return false;
  6065. if (typeFilter === 'dynamic' && !r.dynamic) return false;
  6066. if (typeFilter === 'connected' && !r.connect) return false;
  6067. if (typeFilter === 'bgp' && (r.protocol || '').toLowerCase() !== 'bgp' && (r.protocol || '').toLowerCase() !== 'ibgp') return false;
  6068. if (typeFilter === 'ospf' && (r.protocol || '').toLowerCase() !== 'ospf') return false;
  6069. if (typeFilter === 'dhcp' && (r.protocol || '').toLowerCase() !== 'dhcp') return false;
  6070. return true;
  6071. });
  6072. const ecmpCount = (state.routes || []).filter(r => r.ecmp).length;
  6073. const mcCount = (state.routes || []).filter(r => r.multicast).length;
  6074. let summaryText = `${routes.length} Routes`;
  6075. if (ecmpCount > 0) summaryText += ` • ${ecmpCount} ECMP`;
  6076. if (mcCount > 0) summaryText += ` • ${mcCount} Multicast/IGMP`;
  6077. const badgeEl = document.getElementById('routes-count-badge');
  6078. if (badgeEl) badgeEl.innerText = summaryText;
  6079. if (routes.length === 0) {
  6080. empty?.classList.remove('hidden');
  6081. tbody.innerHTML = '';
  6082. return;
  6083. }
  6084. empty?.classList.add('hidden');
  6085. 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(';');
  6086. if (tbody.dataset.sig === sig) {
  6087. return; // Routes table unchanged! Do not wipe DOM or flicker!
  6088. }
  6089. tbody.dataset.sig = sig;
  6090. tbody.innerHTML = '';
  6091. routes.forEach(r => {
  6092. const tr = document.createElement('tr');
  6093. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${r.disabled ? 'opacity-50' : ''}`;
  6094. tr.setAttribute('ondblclick', `openEditRouteModal('${r.id}')`);
  6095. // Routing Flags string: D=Dynamic, A=Active, C=Connect, S=Static, E=ECMP, M=Multicast, X=Disabled
  6096. let flags = '';
  6097. if (r.dynamic) flags += 'D';
  6098. if (r.active) flags += 'A';
  6099. if (r.connect) flags += 'C';
  6100. if (r.static) flags += 'S';
  6101. if (r.ecmp) flags += 'E';
  6102. if (r.multicast) flags += 'M';
  6103. if (r.disabled) flags += 'X';
  6104. const isDefault = r.dst_address === 'default' || r.dst_address === '0.0.0.0/0';
  6105. let healthCell = `<span class="text-slate-600 font-mono text-[11px]">-</span>`;
  6106. if (r.check_gateway === 'internet') {
  6107. if (r.health_status === 'online') {
  6108. const ms = (r.health_rtt_ms || 0).toFixed(0);
  6109. healthCell = `
  6110. <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)">
  6111. <span class="w-1.5 h-1.5 rounded-full bg-emerald-400 animate-pulse"></span>
  6112. <span>Internet OK (${ms}ms)</span>
  6113. </span>
  6114. `;
  6115. } else if (r.health_status === 'offline') {
  6116. healthCell = `
  6117. <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.">
  6118. <span class="w-1.5 h-1.5 rounded-full bg-rose-400"></span>
  6119. <span>Internet Down</span>
  6120. </span>
  6121. `;
  6122. } else {
  6123. healthCell = `
  6124. <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">
  6125. <span class="w-1.5 h-1.5 rounded-full bg-amber-400 animate-ping"></span>
  6126. <span>Checking...</span>
  6127. </span>
  6128. `;
  6129. }
  6130. } else if (r.check_gateway === 'ping') {
  6131. if (r.health_status === 'online') {
  6132. healthCell = `
  6133. <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">
  6134. <span class="w-1.5 h-1.5 rounded-full bg-cyan-400"></span>
  6135. <span>Gateway OK (${(r.health_rtt_ms || 0).toFixed(0)}ms)</span>
  6136. </span>
  6137. `;
  6138. } else if (r.health_status === 'offline') {
  6139. healthCell = `
  6140. <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">
  6141. <span class="w-1.5 h-1.5 rounded-full bg-rose-400"></span>
  6142. <span>Gateway Dead</span>
  6143. </span>
  6144. `;
  6145. }
  6146. }
  6147. const flagDescriptions = [];
  6148. if (r.dynamic) flagDescriptions.push('Dynamic (D)');
  6149. if (r.active) flagDescriptions.push('Active (A)');
  6150. if (r.connect) flagDescriptions.push('Connected (C)');
  6151. if (r.static) flagDescriptions.push('Static (S)');
  6152. if (r.ecmp) flagDescriptions.push('ECMP - Equal-Cost Multi-Path (E)');
  6153. if (r.multicast) flagDescriptions.push('Multicast / IGMP Group (M)');
  6154. if (r.disabled) flagDescriptions.push('Disabled (X)');
  6155. tr.innerHTML = `
  6156. <td class="py-2.5 px-3 text-center">
  6157. <span class="px-1.5 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 ${
  6158. 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')
  6159. }" title="Flags: ${flagDescriptions.join(', ')}">
  6160. ${flags || '-'}
  6161. </span>
  6162. </td>
  6163. <td class="py-2.5 px-3">
  6164. <div class="flex items-center gap-1.5 flex-wrap">
  6165. <span class="font-bold ${isDefault ? 'text-cyan-300' : 'text-white'}">${escapeHtml(r.dst_address)}</span>
  6166. ${r.ecmp ? `
  6167. <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)">
  6168. <span>⚡ ECMP</span>
  6169. </span>
  6170. ` : ''}
  6171. ${r.multicast ? `
  6172. <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">
  6173. <span>IGMP</span>
  6174. </span>
  6175. ` : ''}
  6176. </div>
  6177. </td>
  6178. <td class="py-2.5 px-3">${getRouteProtocolBadge(r.protocol)}</td>
  6179. <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>
  6180. <td class="py-2.5 px-3 text-slate-400 font-mono">${(r.distance !== undefined && r.distance !== null) ? r.distance : 0}</td>
  6181. <td class="py-2.5 px-3 font-mono font-semibold text-purple-300">${r.routing_table || 'main'}</td>
  6182. <td class="py-2.5 px-3 text-emerald-400 font-mono">${r.interface || '-'}</td>
  6183. <td class="py-2.5 px-3">${healthCell}</td>
  6184. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]">${r.comment || '-'}</td>
  6185. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  6186. ${r.static ? `
  6187. <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>
  6188. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold">Edit</button>
  6189. <button onclick="deleteRoute('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  6190. ` : `
  6191. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">View</button>
  6192. `}
  6193. </td>
  6194. `;
  6195. tbody.appendChild(tr);
  6196. });
  6197. }
  6198. function openAddRouteModal() {
  6199. document.getElementById('route-modal-title').innerText = 'Add Static Route';
  6200. document.getElementById('route-modal-id').value = '';
  6201. document.getElementById('route-modal-old-dst').value = '';
  6202. document.getElementById('route-modal-old-gw').value = '';
  6203. document.getElementById('route-modal-old-distance').value = '';
  6204. document.getElementById('route-modal-old-table').value = '';
  6205. document.getElementById('route-modal-old-iface').value = '';
  6206. const dstInput = document.getElementById('route-modal-dst');
  6207. const gwInput = document.getElementById('route-modal-gw');
  6208. const distInput = document.getElementById('route-modal-distance');
  6209. const ifaceSelect = document.getElementById('route-modal-iface');
  6210. const tableSelect = document.getElementById('route-modal-table');
  6211. const commentInput = document.getElementById('route-modal-comment');
  6212. const disCheck = document.getElementById('route-modal-disabled');
  6213. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  6214. dstInput.disabled = false;
  6215. dstInput.value = '0.0.0.0/0';
  6216. gwInput.disabled = false;
  6217. gwInput.value = '';
  6218. distInput.disabled = false;
  6219. distInput.value = '1';
  6220. ifaceSelect.disabled = false;
  6221. tableSelect.disabled = false;
  6222. commentInput.disabled = false;
  6223. commentInput.value = '';
  6224. disCheck.disabled = false;
  6225. disCheck.checked = false;
  6226. if (saveBtn) saveBtn.classList.remove('hidden');
  6227. const checkGw = document.getElementById('route-modal-check-gw');
  6228. if (checkGw) checkGw.value = 'internet';
  6229. const checkTarget = document.getElementById('route-modal-check-target');
  6230. if (checkTarget) checkTarget.value = '1.1.1.1';
  6231. const checkInterval = document.getElementById('route-modal-check-interval');
  6232. if (checkInterval) checkInterval.value = '5';
  6233. const checkThresh = document.getElementById('route-modal-check-threshold');
  6234. if (checkThresh) checkThresh.value = '3';
  6235. toggleRouteCheckModeUI();
  6236. populateInterfaceSelect('route-modal-iface');
  6237. // Populate tables
  6238. tableSelect.innerHTML = '';
  6239. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  6240. const opt = document.createElement('option');
  6241. opt.value = t.name;
  6242. opt.innerText = t.name;
  6243. if (t.name === 'main') opt.selected = true;
  6244. tableSelect.appendChild(opt);
  6245. });
  6246. document.getElementById('route-modal').classList.remove('hidden');
  6247. }
  6248. function openEditRouteModal(id) {
  6249. const r = (state.routes || []).find(route => route.id === id);
  6250. if (!r) return;
  6251. const isStatic = !!r.static;
  6252. document.getElementById('route-modal-title').innerText = isStatic
  6253. ? `Edit Route: ${r.dst_address}`
  6254. : `Route Properties (Read Only): ${r.dst_address}`;
  6255. document.getElementById('route-modal-id').value = r.id;
  6256. document.getElementById('route-modal-old-dst').value = r.dst_address || '';
  6257. document.getElementById('route-modal-old-gw').value = r.gateway || '';
  6258. document.getElementById('route-modal-old-distance').value = (r.distance !== undefined && r.distance !== null) ? r.distance : '';
  6259. document.getElementById('route-modal-old-table').value = r.routing_table || 'main';
  6260. document.getElementById('route-modal-old-iface').value = r.interface || '';
  6261. const dstInput = document.getElementById('route-modal-dst');
  6262. const gwInput = document.getElementById('route-modal-gw');
  6263. const distInput = document.getElementById('route-modal-distance');
  6264. const ifaceSelect = document.getElementById('route-modal-iface');
  6265. const tableSelect = document.getElementById('route-modal-table');
  6266. const commentInput = document.getElementById('route-modal-comment');
  6267. const disCheck = document.getElementById('route-modal-disabled');
  6268. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  6269. dstInput.value = r.dst_address;
  6270. gwInput.value = r.gateway || '';
  6271. distInput.value = (r.distance !== undefined && r.distance !== null) ? r.distance : 1;
  6272. commentInput.value = r.comment || '';
  6273. disCheck.checked = !!r.disabled;
  6274. const checkGw = document.getElementById('route-modal-check-gw');
  6275. if (checkGw) checkGw.value = r.check_gateway || 'none';
  6276. const checkTarget = document.getElementById('route-modal-check-target');
  6277. if (checkTarget) checkTarget.value = r.check_target || '1.1.1.1';
  6278. const checkInterval = document.getElementById('route-modal-check-interval');
  6279. if (checkInterval) checkInterval.value = r.check_interval || 5;
  6280. const checkThresh = document.getElementById('route-modal-check-threshold');
  6281. if (checkThresh) checkThresh.value = r.check_threshold || 3;
  6282. toggleRouteCheckModeUI();
  6283. dstInput.disabled = !isStatic;
  6284. gwInput.disabled = !isStatic;
  6285. distInput.disabled = !isStatic;
  6286. ifaceSelect.disabled = !isStatic;
  6287. tableSelect.disabled = !isStatic;
  6288. commentInput.disabled = !isStatic;
  6289. disCheck.disabled = !isStatic;
  6290. if (checkGw) checkGw.disabled = !isStatic;
  6291. if (checkTarget) checkTarget.disabled = !isStatic;
  6292. if (checkInterval) checkInterval.disabled = !isStatic;
  6293. if (checkThresh) checkThresh.disabled = !isStatic;
  6294. if (saveBtn) {
  6295. if (isStatic) {
  6296. saveBtn.classList.remove('hidden');
  6297. } else {
  6298. saveBtn.classList.add('hidden');
  6299. }
  6300. }
  6301. populateInterfaceSelect('route-modal-iface', r.interface);
  6302. tableSelect.innerHTML = '';
  6303. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  6304. const opt = document.createElement('option');
  6305. opt.value = t.name;
  6306. opt.innerText = t.name;
  6307. if (t.name === (r.routing_table || 'main')) opt.selected = true;
  6308. tableSelect.appendChild(opt);
  6309. });
  6310. document.getElementById('route-modal').classList.remove('hidden');
  6311. }
  6312. function closeRouteModal() {
  6313. document.getElementById('route-modal').classList.add('hidden');
  6314. }
  6315. function setRouteCheckTarget(ip) {
  6316. const inp = document.getElementById('route-modal-check-target');
  6317. if (inp) inp.value = ip;
  6318. }
  6319. function toggleRouteCheckModeUI() {
  6320. const mode = document.getElementById('route-modal-check-gw')?.value || 'none';
  6321. const targetRow = document.getElementById('route-row-check-target');
  6322. const paramsRow = document.getElementById('route-row-check-params');
  6323. if (mode === 'none') {
  6324. if (targetRow) targetRow.classList.add('opacity-40', 'pointer-events-none');
  6325. if (paramsRow) paramsRow.classList.add('opacity-40', 'pointer-events-none');
  6326. } else if (mode === 'ping') {
  6327. if (targetRow) targetRow.classList.add('opacity-40', 'pointer-events-none');
  6328. if (paramsRow) paramsRow.classList.remove('opacity-40', 'pointer-events-none');
  6329. } else { // internet
  6330. if (targetRow) targetRow.classList.remove('opacity-40', 'pointer-events-none');
  6331. if (paramsRow) paramsRow.classList.remove('opacity-40', 'pointer-events-none');
  6332. }
  6333. }
  6334. async function submitSaveRoute(e) {
  6335. e.preventDefault();
  6336. const id = document.getElementById('route-modal-id').value;
  6337. const oldDst = document.getElementById('route-modal-old-dst')?.value || '';
  6338. const oldGw = document.getElementById('route-modal-old-gw')?.value || '';
  6339. const oldDistStr = document.getElementById('route-modal-old-distance')?.value;
  6340. const oldTable = document.getElementById('route-modal-old-table')?.value || '';
  6341. const oldIface = document.getElementById('route-modal-old-iface')?.value || '';
  6342. const dst = document.getElementById('route-modal-dst').value.trim();
  6343. const gw = document.getElementById('route-modal-gw').value.trim();
  6344. const table = document.getElementById('route-modal-table').value;
  6345. const distance = parseInt(document.getElementById('route-modal-distance').value, 10) || 0;
  6346. const iface = document.getElementById('route-modal-iface').value;
  6347. const comment = document.getElementById('route-modal-comment').value.trim();
  6348. const disabled = document.getElementById('route-modal-disabled').checked;
  6349. const check_gateway = document.getElementById('route-modal-check-gw')?.value || 'none';
  6350. const check_target = document.getElementById('route-modal-check-target')?.value.trim() || '1.1.1.1';
  6351. const check_interval = parseInt(document.getElementById('route-modal-check-interval')?.value, 10) || 5;
  6352. const check_threshold = parseInt(document.getElementById('route-modal-check-threshold')?.value, 10) || 3;
  6353. if (!dst) {
  6354. showToast('Error', 'Destination address is required', 'error');
  6355. return;
  6356. }
  6357. if (!gw && !iface) {
  6358. showToast('Error', 'Either Gateway IP or Interface must be specified', 'error');
  6359. return;
  6360. }
  6361. const payload = {
  6362. id,
  6363. old_dst_address: oldDst,
  6364. old_gateway: oldGw,
  6365. old_routing_table: oldTable,
  6366. old_interface: oldIface,
  6367. dst_address: dst,
  6368. gateway: gw || iface,
  6369. routing_table: table,
  6370. distance,
  6371. interface: iface,
  6372. comment,
  6373. disabled,
  6374. check_gateway,
  6375. check_target,
  6376. check_interval,
  6377. check_threshold
  6378. };
  6379. if (oldDistStr !== undefined && oldDistStr !== '') {
  6380. payload.old_distance = parseInt(oldDistStr, 10);
  6381. }
  6382. try {
  6383. const res = await fetch(`${API_BASE}/routes`, {
  6384. method: 'POST',
  6385. headers: { 'Content-Type': 'application/json' },
  6386. body: JSON.stringify(payload)
  6387. });
  6388. if (res.ok) {
  6389. showToast('Route Saved', `Route to ${dst} installed`, 'success');
  6390. closeRouteModal();
  6391. loadRoutes();
  6392. } else {
  6393. const err = await res.json();
  6394. showToast('Error', err.message || 'Failed to save route', 'error');
  6395. }
  6396. } catch (err) {
  6397. showToast('Error', err.message, 'error');
  6398. }
  6399. }
  6400. async function toggleRouteState(id, disabled) {
  6401. try {
  6402. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}/state`, {
  6403. method: 'POST',
  6404. headers: { 'Content-Type': 'application/json' },
  6405. body: JSON.stringify({ disabled })
  6406. });
  6407. if (res.ok) loadRoutes();
  6408. } catch (err) {
  6409. showToast('Error', err.message, 'error');
  6410. }
  6411. }
  6412. async function deleteRoute(id) {
  6413. if (!confirm('Are you sure you want to delete this route?')) return;
  6414. try {
  6415. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6416. if (res.ok) {
  6417. showToast('Deleted', 'Route removed', 'success');
  6418. loadRoutes();
  6419. }
  6420. } catch (err) {
  6421. showToast('Error', err.message, 'error');
  6422. }
  6423. }
  6424. // ----------------- Policy Rules (/ip route rule) -----------------
  6425. function renderPolicyRules() {
  6426. const tbody = document.getElementById('rules-table-body');
  6427. const empty = document.getElementById('rules-empty');
  6428. if (!tbody) return;
  6429. const showSystem = document.getElementById('prule-show-system')?.checked;
  6430. const filtered = (state.policyRules || []).filter(pr => showSystem || (!pr.is_default && !pr.is_system));
  6431. const countBadge = document.getElementById('rules-count-badge');
  6432. if (countBadge) countBadge.innerText = `${filtered.length} Rules`;
  6433. const bRules = document.getElementById('routes-badge-rules');
  6434. if (bRules) bRules.innerText = filtered.length;
  6435. if (filtered.length === 0) {
  6436. empty?.classList.remove('hidden');
  6437. tbody.innerHTML = '';
  6438. return;
  6439. }
  6440. empty?.classList.add('hidden');
  6441. const sig = `${showSystem}|` + filtered.map(pr => `${pr.id}:${pr.priority}:${pr.src_address}:${pr.dst_address}:${pr.table}:${pr.routing_mark}`).join(';');
  6442. if (tbody.dataset.sig === sig) return;
  6443. tbody.dataset.sig = sig;
  6444. tbody.innerHTML = '';
  6445. filtered.forEach(pr => {
  6446. const isSys = pr.is_default || pr.is_system;
  6447. const tr = document.createElement('tr');
  6448. tr.className = `hover:bg-slate-800/40 transition text-xs ${isSys ? 'opacity-70 bg-slate-950/20' : ''}`;
  6449. tr.innerHTML = `
  6450. <td class="py-2.5 px-3 font-mono text-cyan-400 font-bold">${pr.priority}</td>
  6451. <td class="py-2.5 px-3 font-mono text-white">${pr.src_address || '<span class="text-slate-600">all</span>'}</td>
  6452. <td class="py-2.5 px-3 font-mono text-white">${pr.dst_address || '<span class="text-slate-600">all</span>'}</td>
  6453. <td class="py-2.5 px-3 font-mono font-bold text-purple-300">${pr.routing_mark || '<span class="text-slate-600">-</span>'}</td>
  6454. <td class="py-2.5 px-3 font-mono font-bold text-amber-300">${pr.table}</td>
  6455. <td class="py-2.5 px-3 font-mono text-slate-300">${pr.action}</td>
  6456. <td class="py-2.5 px-3 text-right font-sans">
  6457. ${!pr.is_default ? `
  6458. <button onclick="deletePolicyRule('${pr.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  6459. ` : `<span class="text-slate-600 text-[10px]">Default</span>`}
  6460. </td>
  6461. `;
  6462. tbody.appendChild(tr);
  6463. });
  6464. }
  6465. function openAddPolicyRuleModal() {
  6466. const userRules = (state.policyRules || []).filter(pr => !pr.is_default && !pr.is_system);
  6467. document.getElementById('prule-modal-pref').value = userRules.length * 10 + 1000;
  6468. document.getElementById('prule-modal-mark').value = '';
  6469. document.getElementById('prule-modal-src').value = '';
  6470. document.getElementById('prule-modal-dst').value = '';
  6471. const sel = document.getElementById('prule-modal-table');
  6472. sel.innerHTML = '';
  6473. (state.routingTables || []).forEach(t => {
  6474. const opt = document.createElement('option');
  6475. opt.value = t.name;
  6476. opt.innerText = t.name;
  6477. sel.appendChild(opt);
  6478. });
  6479. document.getElementById('prule-modal').classList.remove('hidden');
  6480. }
  6481. function closePolicyRuleModal() {
  6482. document.getElementById('prule-modal').classList.add('hidden');
  6483. }
  6484. async function submitSavePolicyRule(e) {
  6485. e.preventDefault();
  6486. const pref = parseInt(document.getElementById('prule-modal-pref').value, 10) || 1000;
  6487. const mark = document.getElementById('prule-modal-mark').value.trim();
  6488. const src = document.getElementById('prule-modal-src').value.trim();
  6489. const dst = document.getElementById('prule-modal-dst').value.trim();
  6490. const table = document.getElementById('prule-modal-table').value;
  6491. const action = document.getElementById('prule-modal-action').value;
  6492. try {
  6493. const res = await fetch(`${API_BASE}/routing/rules`, {
  6494. method: 'POST',
  6495. headers: { 'Content-Type': 'application/json' },
  6496. body: JSON.stringify({ priority: pref, routing_mark: mark, src_address: src, dst_address: dst, table, action })
  6497. });
  6498. if (res.ok) {
  6499. showToast('Rule Added', `Policy rule installed for table ${table}`, 'success');
  6500. closePolicyRuleModal();
  6501. loadRoutes();
  6502. } else {
  6503. const err = await res.json();
  6504. showToast('Error', err.message, 'error');
  6505. }
  6506. } catch (err) {
  6507. showToast('Error', err.message, 'error');
  6508. }
  6509. }
  6510. async function deletePolicyRule(id) {
  6511. if (!confirm('Are you sure you want to remove this policy rule?')) return;
  6512. try {
  6513. const res = await fetch(`${API_BASE}/routing/rules/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6514. if (res.ok) {
  6515. showToast('Rule Removed', 'Policy rule deleted', 'success');
  6516. loadRoutes();
  6517. }
  6518. } catch (err) {
  6519. showToast('Error', err.message, 'error');
  6520. }
  6521. }
  6522. // ----------------- Routing Tables -----------------
  6523. function renderRoutingTables() {
  6524. const tbody = document.getElementById('tables-table-body');
  6525. if (!tbody) return;
  6526. const tables = state.routingTables || [];
  6527. const sig = tables.map(t => `${t.table_id}:${t.name}:${t.comment}`).join(';');
  6528. if (tbody.dataset.sig === sig) return;
  6529. tbody.dataset.sig = sig;
  6530. tbody.innerHTML = '';
  6531. (state.routingTables || []).forEach(t => {
  6532. const tr = document.createElement('tr');
  6533. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  6534. tr.innerHTML = `
  6535. <td class="py-2.5 px-3 text-cyan-400 font-bold">${t.table_id}</td>
  6536. <td class="py-2.5 px-3 font-bold text-white">${t.name}</td>
  6537. <td class="py-2.5 px-3 text-slate-400 italic">${t.comment || '-'}</td>
  6538. `;
  6539. tbody.appendChild(tr);
  6540. });
  6541. }
  6542. function openAddTableModal() {
  6543. document.getElementById('table-modal-name').value = '';
  6544. document.getElementById('table-modal-id').value = '';
  6545. document.getElementById('table-modal-comment').value = '';
  6546. document.getElementById('table-modal').classList.remove('hidden');
  6547. }
  6548. function closeTableModal() {
  6549. document.getElementById('table-modal').classList.add('hidden');
  6550. }
  6551. async function submitSaveTable(e) {
  6552. e.preventDefault();
  6553. const name = document.getElementById('table-modal-name').value.trim();
  6554. const id = parseInt(document.getElementById('table-modal-id').value, 10) || 0;
  6555. const comment = document.getElementById('table-modal-comment').value.trim();
  6556. try {
  6557. const res = await fetch(`${API_BASE}/routing/tables`, {
  6558. method: 'POST',
  6559. headers: { 'Content-Type': 'application/json' },
  6560. body: JSON.stringify({ name, table_id: id, comment })
  6561. });
  6562. if (res.ok) {
  6563. showToast('Table Created', `Routing table ${name} registered`, 'success');
  6564. closeTableModal();
  6565. loadRoutes();
  6566. } else {
  6567. const err = await res.json();
  6568. showToast('Error', err.message, 'error');
  6569. }
  6570. } catch (err) {
  6571. showToast('Error', err.message, 'error');
  6572. }
  6573. }
  6574. async function loadDebianConfig() {
  6575. const view = document.getElementById('debian-config-view');
  6576. view.innerText = 'Generating live configuration...';
  6577. try {
  6578. const res = await fetch(`${API_BASE}/debian/config`);
  6579. const data = await res.json();
  6580. view.innerText = data.content || '# Empty config';
  6581. } catch (err) {
  6582. view.innerText = 'Failed to generate Debian network config.';
  6583. }
  6584. }
  6585. async function saveDebianConfig() {
  6586. try {
  6587. const res = await fetch(`${API_BASE}/debian/apply`, { method: 'POST' });
  6588. const data = await res.json();
  6589. if (res.ok) {
  6590. showToast('Configuration Saved', data.message || 'Saved to /etc/network/interfaces.d/vlans.cfg', 'success');
  6591. loadDebianConfig();
  6592. }
  6593. } catch (err) {
  6594. showToast('Error', err.message, 'error');
  6595. }
  6596. }
  6597. function showToast(title, message, type = 'info') {
  6598. const container = document.getElementById('toast-container');
  6599. const toast = document.createElement('div');
  6600. const borderColors = {
  6601. success: 'border-emerald-500/40 bg-slate-900/95 text-emerald-400',
  6602. error: 'border-rose-500/40 bg-slate-900/95 text-rose-400',
  6603. info: 'border-cyan-500/40 bg-slate-900/95 text-cyan-400'
  6604. };
  6605. 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}`;
  6606. toast.innerHTML = `
  6607. <div class="flex-1">
  6608. <div class="font-bold text-xs text-white">${title}</div>
  6609. <div class="text-[11px] text-slate-300 mt-0.5 leading-relaxed font-sans">${message}</div>
  6610. </div>
  6611. `;
  6612. container.appendChild(toast);
  6613. requestAnimationFrame(() => toast.classList.remove('translate-y-2', 'opacity-0'));
  6614. setTimeout(() => {
  6615. toast.classList.add('opacity-0', 'translate-y-2');
  6616. setTimeout(() => toast.remove(), 300);
  6617. }, 4000);
  6618. }
  6619. function formatTraffic(bytesPerSec) {
  6620. if (bytesPerSec < 1024) return `${Math.round(bytesPerSec)} B/s`;
  6621. const kb = bytesPerSec / 1024;
  6622. if (kb < 1024) return `${kb.toFixed(1)} KB/s`;
  6623. const mb = kb / 1024;
  6624. return `${mb.toFixed(2)} MB/s`;
  6625. }
  6626. function toggleSidebar() {
  6627. const sb = document.getElementById('sidebar');
  6628. sb.classList.toggle('-translate-x-full');
  6629. }
  6630. // ======================== EoIP (Ethernet over IP) ========================
  6631. async function loadEoIP(populate = true) {
  6632. try {
  6633. const res = await fetch(`${API_BASE}/vpn/eoip`);
  6634. const data = await res.json();
  6635. state.eoipTunnels = Array.isArray(data) ? data : [];
  6636. const badge = document.getElementById('eoip-count-badge');
  6637. if (badge) badge.innerText = `${state.eoipTunnels.length} Tunnels`;
  6638. const sideBadge = document.getElementById('badge-eoip-count');
  6639. if (sideBadge) sideBadge.innerText = state.eoipTunnels.length;
  6640. renderEoIPTunnels();
  6641. } catch (err) {
  6642. console.error('Failed to load EoIP:', err);
  6643. }
  6644. }
  6645. function renderEoIPTunnels() {
  6646. const tbody = document.getElementById('eoip-table-body');
  6647. const empty = document.getElementById('eoip-empty');
  6648. if (!tbody) return;
  6649. tbody.innerHTML = '';
  6650. const tunnels = state.eoipTunnels || [];
  6651. if (tunnels.length === 0) {
  6652. empty?.classList.remove('hidden');
  6653. return;
  6654. }
  6655. empty?.classList.add('hidden');
  6656. tunnels.forEach(t => {
  6657. const tr = document.createElement('tr');
  6658. tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
  6659. tr.innerHTML = `
  6660. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.running, t.disabled)}</td>
  6661. <td class="py-2.5 px-3 font-bold text-white font-mono">${t.name}</td>
  6662. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${t.tunnel_id}</td>
  6663. <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>
  6664. <td class="py-2.5 px-3 text-cyan-300 font-mono">${t.remote_address}</td>
  6665. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.local_address || '(any)'}</td>
  6666. <td class="py-2.5 px-3 text-slate-300 font-mono text-[11px]">${t.mac_address || '-'}</td>
  6667. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.mtu || 1500}</td>
  6668. <td class="py-2.5 px-3 font-mono text-[11px]">
  6669. <span class="text-emerald-400">↓ ${t.rx_human || '0 B'}</span>
  6670. <span class="text-cyan-400 ml-1">↑ ${t.tx_human || '0 B'}</span>
  6671. </td>
  6672. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${t.comment || ''}">${t.comment || '-'}</td>
  6673. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  6674. <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>
  6675. <button onclick="openEditEoIPModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  6676. <button onclick="deleteEoIP('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  6677. </td>
  6678. `;
  6679. tbody.appendChild(tr);
  6680. });
  6681. }
  6682. function openAddEoIPModal() {
  6683. document.getElementById('eoip-modal-title').innerText = 'Add EoIP Tunnel';
  6684. document.getElementById('eoip-modal-id').value = '';
  6685. document.getElementById('eoip-modal-name').value = `eoip-tunnel${(state.eoipTunnels || []).length + 1}`;
  6686. document.getElementById('eoip-modal-tunnelid').value = (state.eoipTunnels || []).length + 10;
  6687. document.getElementById('eoip-modal-remote').value = '';
  6688. document.getElementById('eoip-modal-ip').value = '';
  6689. document.getElementById('eoip-modal-local').value = '';
  6690. document.getElementById('eoip-modal-mac').value = '';
  6691. document.getElementById('eoip-modal-mtu').value = '1500';
  6692. document.getElementById('eoip-modal-comment').value = '';
  6693. document.getElementById('eoip-modal-clampmss').checked = true;
  6694. document.getElementById('eoip-modal-disabled').checked = false;
  6695. document.getElementById('eoip-modal').classList.remove('hidden');
  6696. }
  6697. function openEditEoIPModal(id) {
  6698. const t = (state.eoipTunnels || []).find(tun => tun.id === id);
  6699. if (!t) return;
  6700. document.getElementById('eoip-modal-title').innerText = `Edit EoIP Tunnel (${t.name})`;
  6701. document.getElementById('eoip-modal-id').value = t.id;
  6702. document.getElementById('eoip-modal-name').value = t.name;
  6703. document.getElementById('eoip-modal-tunnelid').value = t.tunnel_id;
  6704. document.getElementById('eoip-modal-remote').value = t.remote_address;
  6705. document.getElementById('eoip-modal-ip').value = t.ip_address || '';
  6706. document.getElementById('eoip-modal-local').value = t.local_address || '';
  6707. document.getElementById('eoip-modal-mac').value = t.mac_address || '';
  6708. document.getElementById('eoip-modal-mtu').value = t.mtu || 1500;
  6709. document.getElementById('eoip-modal-comment').value = t.comment || '';
  6710. document.getElementById('eoip-modal-clampmss').checked = !!t.clamp_mss;
  6711. document.getElementById('eoip-modal-disabled').checked = !!t.disabled;
  6712. document.getElementById('eoip-modal').classList.remove('hidden');
  6713. }
  6714. function closeEoIPModal() {
  6715. document.getElementById('eoip-modal').classList.add('hidden');
  6716. }
  6717. async function submitSaveEoIP(e) {
  6718. e.preventDefault();
  6719. const id = document.getElementById('eoip-modal-id').value;
  6720. const name = document.getElementById('eoip-modal-name').value.trim();
  6721. const tunnelId = parseInt(document.getElementById('eoip-modal-tunnelid').value);
  6722. const remote = document.getElementById('eoip-modal-remote').value.trim();
  6723. const ipAddress = document.getElementById('eoip-modal-ip').value.trim();
  6724. const local = document.getElementById('eoip-modal-local').value.trim();
  6725. const mac = document.getElementById('eoip-modal-mac').value.trim();
  6726. const mtu = parseInt(document.getElementById('eoip-modal-mtu').value) || 1500;
  6727. const comment = document.getElementById('eoip-modal-comment').value.trim();
  6728. const clampMss = document.getElementById('eoip-modal-clampmss').checked;
  6729. const disabled = document.getElementById('eoip-modal-disabled').checked;
  6730. try {
  6731. const res = await fetch(`${API_BASE}/vpn/eoip`, {
  6732. method: 'POST',
  6733. headers: { 'Content-Type': 'application/json' },
  6734. body: JSON.stringify({
  6735. id,
  6736. name,
  6737. tunnel_id: tunnelId,
  6738. remote_address: remote,
  6739. ip_address: ipAddress,
  6740. local_address: local,
  6741. mac_address: mac,
  6742. mtu,
  6743. clamp_mss: clampMss,
  6744. comment,
  6745. disabled
  6746. })
  6747. });
  6748. if (res.ok) {
  6749. showToast('EoIP Saved', `Tunnel ${name} configured successfully`, 'success');
  6750. closeEoIPModal();
  6751. loadEoIP(false);
  6752. fetchData(false);
  6753. } else {
  6754. const err = await res.json();
  6755. showToast('Error', err.message, 'error');
  6756. }
  6757. } catch (err) {
  6758. showToast('Error', err.message, 'error');
  6759. }
  6760. }
  6761. async function toggleEoIPState(id, disabled) {
  6762. try {
  6763. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}/state`, {
  6764. method: 'POST',
  6765. headers: { 'Content-Type': 'application/json' },
  6766. body: JSON.stringify({ disabled })
  6767. });
  6768. if (res.ok) {
  6769. showToast(disabled ? 'Disabled' : 'Enabled', 'EoIP tunnel state updated', 'info');
  6770. loadEoIP(false);
  6771. fetchData(false);
  6772. }
  6773. } catch (err) {
  6774. showToast('Error', err.message, 'error');
  6775. }
  6776. }
  6777. async function deleteEoIP(id) {
  6778. if (!confirm('Are you sure you want to delete this EoIP tunnel?')) return;
  6779. try {
  6780. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6781. if (res.ok) {
  6782. showToast('Deleted', 'EoIP tunnel removed', 'success');
  6783. loadEoIP(false);
  6784. fetchData(false);
  6785. }
  6786. } catch (err) {
  6787. showToast('Error', err.message, 'error');
  6788. }
  6789. }
  6790. // ======================== AeroTUN (Custom Encrypted VPN with Adaptive LZ4) ========================
  6791. async function loadAeroTUN(populate = true) {
  6792. try {
  6793. const [tunnelsRes, statsRes] = await Promise.all([
  6794. fetch(`${API_BASE}/vpn/aerotun/tunnels`),
  6795. fetch(`${API_BASE}/vpn/aerotun/stats`)
  6796. ]);
  6797. if (tunnelsRes.ok) {
  6798. const data = await tunnelsRes.json();
  6799. state.aerotunTunnels = Array.isArray(data) ? data : [];
  6800. }
  6801. if (statsRes.ok) {
  6802. state.aerotunStats = await statsRes.json();
  6803. }
  6804. const countBadge = document.getElementById('aerotun-count-badge');
  6805. if (countBadge) countBadge.innerText = `${(state.aerotunTunnels || []).length} Tunnels`;
  6806. const sideBadge = document.getElementById('badge-aerotun-count');
  6807. if (sideBadge) sideBadge.innerText = (state.aerotunTunnels || []).length;
  6808. renderAeroTUN();
  6809. } catch (err) {
  6810. console.error('Failed to load AeroTUN:', err);
  6811. }
  6812. }
  6813. function renderAeroTUN() {
  6814. const tbody = document.getElementById('aerotun-table-body');
  6815. const empty = document.getElementById('aerotun-empty');
  6816. // Update summary cards
  6817. const stats = state.aerotunStats || {};
  6818. const tunnels = state.aerotunTunnels || [];
  6819. const statActive = document.getElementById('aerotun-stat-active');
  6820. if (statActive) {
  6821. const activeCount = tunnels.filter(t => t.running).length;
  6822. statActive.innerText = `${activeCount} / ${tunnels.length}`;
  6823. }
  6824. const statSaved = document.getElementById('aerotun-stat-saved');
  6825. if (statSaved) {
  6826. statSaved.innerText = formatBytes(stats.total_saved_bytes || 0);
  6827. }
  6828. const statRatio = document.getElementById('aerotun-stat-ratio');
  6829. if (statRatio) {
  6830. statRatio.innerText = stats.average_ratio || '1.00x (0% saved)';
  6831. }
  6832. const statTraffic = document.getElementById('aerotun-stat-traffic');
  6833. if (statTraffic) {
  6834. statTraffic.innerText = `↓ ${formatBytes(stats.total_rx_bytes || 0)} / ↑ ${formatBytes(stats.total_tx_bytes || 0)}`;
  6835. }
  6836. if (!tbody) return;
  6837. tbody.innerHTML = '';
  6838. if (tunnels.length === 0) {
  6839. empty?.classList.remove('hidden');
  6840. return;
  6841. }
  6842. empty?.classList.add('hidden');
  6843. tunnels.forEach(t => {
  6844. const tr = document.createElement('tr');
  6845. tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
  6846. const modeBadge = t.mode === 'server'
  6847. ? `<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>`
  6848. : `<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>`;
  6849. const endpointInfo = t.mode === 'server'
  6850. ? `<span class="text-sky-300 font-mono">Port :${t.listen_port || 51830}</span>`
  6851. : `<span class="text-indigo-300 font-mono">${escapeHtml(t.remote_endpoint || '(not set)')}</span>`;
  6852. const compBadge = t.compression
  6853. ? `<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>`
  6854. : `<span class="text-slate-500 text-[10px]">Off</span>`;
  6855. const activePeer = t.active_peer_endpoint
  6856. ? `<span class="text-emerald-400 font-mono text-[11px]" title="Last seen: ${t.last_handshake || 'just now'}">● ${escapeHtml(t.active_peer_endpoint)}</span>`
  6857. : `<span class="text-slate-500 text-[11px]">${t.mode === 'server' ? 'Waiting for peer...' : 'Connecting...'}</span>`;
  6858. const rawRx = formatBytes(t.rx_bytes || 0);
  6859. const rawTx = formatBytes(t.tx_bytes || 0);
  6860. const wireRx = formatBytes(t.wire_bytes_in || 0);
  6861. const wireTx = formatBytes(t.wire_bytes_out || 0);
  6862. tr.innerHTML = `
  6863. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.running, t.disabled)}</td>
  6864. <td class="py-2.5 px-3 font-bold text-white font-mono flex items-center gap-1.5">
  6865. <span>${escapeHtml(t.name)}</span>
  6866. ${t.default_route ? '<span class="text-[9px] px-1 rounded bg-amber-500/20 text-amber-300 border border-amber-500/30">DEF</span>' : ''}
  6867. </td>
  6868. <td class="py-2.5 px-3">${modeBadge}</td>
  6869. <td class="py-2.5 px-3 text-xs font-mono">${endpointInfo}</td>
  6870. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${escapeHtml(t.local_address || '-')}</td>
  6871. <td class="py-2.5 px-3">${compBadge}</td>
  6872. <td class="py-2.5 px-3">${activePeer}</td>
  6873. <td class="py-2.5 px-3 font-mono text-[11px]">
  6874. <span class="text-emerald-400">↓ ${rawRx}</span>
  6875. <span class="text-cyan-400 ml-1">↑ ${rawTx}</span>
  6876. </td>
  6877. <td class="py-2.5 px-3 font-mono text-[11px]">
  6878. <span class="text-slate-400">↓ ${wireRx}</span>
  6879. <span class="text-slate-400 ml-1">↑ ${wireTx}</span>
  6880. </td>
  6881. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(t.comment || '')}">${escapeHtml(t.comment || '-')}</td>
  6882. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  6883. ${t.running
  6884. ? `<button onclick="stopAeroTUNTunnel('${t.id}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Stop</button>`
  6885. : `<button onclick="startAeroTUNTunnel('${t.id}')" class="text-xs text-emerald-400 hover:text-emerald-300 font-medium">Start</button>`
  6886. }
  6887. <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>
  6888. <button onclick="openEditAeroTUNModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  6889. <button onclick="deleteAeroTUN('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  6890. </td>
  6891. `;
  6892. tbody.appendChild(tr);
  6893. });
  6894. }
  6895. function onAeroTUNModeChange() {
  6896. const mode = document.getElementById('aerotun-modal-mode').value;
  6897. const endpointInput = document.getElementById('aerotun-modal-endpoint');
  6898. const portInput = document.getElementById('aerotun-modal-port');
  6899. if (mode === 'server') {
  6900. if (!portInput.value) portInput.value = '51830';
  6901. endpointInput.placeholder = 'Optional / learned roaming peer';
  6902. } else {
  6903. endpointInput.placeholder = 'vpn.example.com:51830 (required)';
  6904. if (!portInput.value) portInput.value = '';
  6905. }
  6906. }
  6907. async function generateAeroTUNKey() {
  6908. try {
  6909. const res = await fetch(`${API_BASE}/vpn/aerotun/genkey`);
  6910. if (res.ok) {
  6911. const data = await res.json();
  6912. document.getElementById('aerotun-modal-psk').value = data.key;
  6913. showToast('Key Generated', 'Cryptographic 256-bit PSK generated', 'success');
  6914. }
  6915. } catch (err) {
  6916. const arr = new Uint8Array(32);
  6917. crypto.getRandomValues(arr);
  6918. const hex = Array.from(arr).map(b => b.toString(16).padStart(2, '0')).join('');
  6919. document.getElementById('aerotun-modal-psk').value = hex;
  6920. }
  6921. }
  6922. function openAddAeroTUNModal() {
  6923. const tunnels = state.aerotunTunnels || [];
  6924. document.getElementById('aerotun-modal-title').innerText = 'Add AeroTUN Interface';
  6925. document.getElementById('aerotun-modal-id').value = '';
  6926. document.getElementById('aerotun-modal-name').value = `aerotun${tunnels.length}`;
  6927. document.getElementById('aerotun-modal-mode').value = 'server';
  6928. document.getElementById('aerotun-modal-port').value = 51830 + tunnels.length;
  6929. document.getElementById('aerotun-modal-endpoint').value = '';
  6930. document.getElementById('aerotun-modal-local').value = `10.99.${tunnels.length}.1/24`;
  6931. document.getElementById('aerotun-modal-peer').value = `10.99.${tunnels.length}.2/24`;
  6932. document.getElementById('aerotun-modal-psk').value = '';
  6933. document.getElementById('aerotun-modal-mtu').value = '1420';
  6934. document.getElementById('aerotun-modal-comment').value = '';
  6935. document.getElementById('aerotun-modal-compression').checked = true;
  6936. document.getElementById('aerotun-modal-defroute').checked = false;
  6937. document.getElementById('aerotun-modal-disabled').checked = false;
  6938. generateAeroTUNKey();
  6939. onAeroTUNModeChange();
  6940. document.getElementById('aerotun-modal').classList.remove('hidden');
  6941. }
  6942. function openEditAeroTUNModal(id) {
  6943. const t = (state.aerotunTunnels || []).find(tun => tun.id === id);
  6944. if (!t) return;
  6945. document.getElementById('aerotun-modal-title').innerText = `Edit AeroTUN Interface (${t.name})`;
  6946. document.getElementById('aerotun-modal-id').value = t.id;
  6947. document.getElementById('aerotun-modal-name').value = t.name;
  6948. document.getElementById('aerotun-modal-mode').value = t.mode || 'server';
  6949. document.getElementById('aerotun-modal-port').value = t.listen_port || '';
  6950. document.getElementById('aerotun-modal-endpoint').value = t.remote_endpoint || '';
  6951. document.getElementById('aerotun-modal-local').value = t.local_address || '';
  6952. document.getElementById('aerotun-modal-peer').value = t.peer_address || '';
  6953. document.getElementById('aerotun-modal-psk').value = t.psk || '';
  6954. document.getElementById('aerotun-modal-mtu').value = t.mtu || 1420;
  6955. document.getElementById('aerotun-modal-comment').value = t.comment || '';
  6956. document.getElementById('aerotun-modal-compression').checked = !!t.compression;
  6957. document.getElementById('aerotun-modal-defroute').checked = !!t.default_route;
  6958. document.getElementById('aerotun-modal-disabled').checked = !!t.disabled;
  6959. onAeroTUNModeChange();
  6960. document.getElementById('aerotun-modal').classList.remove('hidden');
  6961. }
  6962. function closeAeroTUNModal() {
  6963. document.getElementById('aerotun-modal').classList.add('hidden');
  6964. }
  6965. async function submitSaveAeroTUN(e) {
  6966. e.preventDefault();
  6967. const id = document.getElementById('aerotun-modal-id').value;
  6968. const name = document.getElementById('aerotun-modal-name').value.trim();
  6969. const mode = document.getElementById('aerotun-modal-mode').value;
  6970. const port = parseInt(document.getElementById('aerotun-modal-port').value) || 0;
  6971. const endpoint = document.getElementById('aerotun-modal-endpoint').value.trim();
  6972. const local = document.getElementById('aerotun-modal-local').value.trim();
  6973. const peer = document.getElementById('aerotun-modal-peer').value.trim();
  6974. const psk = document.getElementById('aerotun-modal-psk').value.trim();
  6975. const mtu = parseInt(document.getElementById('aerotun-modal-mtu').value) || 1420;
  6976. const comment = document.getElementById('aerotun-modal-comment').value.trim();
  6977. const compression = document.getElementById('aerotun-modal-compression').checked;
  6978. const defaultRoute = document.getElementById('aerotun-modal-defroute').checked;
  6979. const disabled = document.getElementById('aerotun-modal-disabled').checked;
  6980. if (mode === 'client' && !endpoint) {
  6981. showToast('Validation Error', 'Remote endpoint (host:port) is required in client mode', 'error');
  6982. return;
  6983. }
  6984. if (!psk) {
  6985. showToast('Validation Error', 'Pre-shared key (PSK) is required', 'error');
  6986. return;
  6987. }
  6988. try {
  6989. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels`, {
  6990. method: 'POST',
  6991. headers: { 'Content-Type': 'application/json' },
  6992. body: JSON.stringify({
  6993. id,
  6994. name,
  6995. mode,
  6996. listen_port: port,
  6997. remote_endpoint: endpoint,
  6998. local_address: local,
  6999. peer_address: peer,
  7000. psk,
  7001. mtu,
  7002. compression,
  7003. default_route: defaultRoute,
  7004. comment,
  7005. disabled
  7006. })
  7007. });
  7008. if (res.ok) {
  7009. showToast('AeroTUN Saved', `Tunnel ${name} configured successfully`, 'success');
  7010. closeAeroTUNModal();
  7011. loadAeroTUN(false);
  7012. fetchData(false);
  7013. } else {
  7014. const err = await res.text();
  7015. showToast('Error Saving Tunnel', err, 'error');
  7016. }
  7017. } catch (err) {
  7018. showToast('Network Error', err.message, 'error');
  7019. }
  7020. }
  7021. async function startAeroTUNTunnel(id) {
  7022. try {
  7023. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/start`, { method: 'POST' });
  7024. if (res.ok) {
  7025. showToast('AeroTUN Started', 'Tunnel interface is active', 'success');
  7026. loadAeroTUN(false);
  7027. fetchData(false);
  7028. } else {
  7029. const err = await res.text();
  7030. showToast('Failed to Start', err, 'error');
  7031. }
  7032. } catch (err) {
  7033. showToast('Error', err.message, 'error');
  7034. }
  7035. }
  7036. async function stopAeroTUNTunnel(id) {
  7037. try {
  7038. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/stop`, { method: 'POST' });
  7039. if (res.ok) {
  7040. showToast('AeroTUN Stopped', 'Tunnel stopped', 'info');
  7041. loadAeroTUN(false);
  7042. fetchData(false);
  7043. } else {
  7044. const err = await res.text();
  7045. showToast('Failed to Stop', err, 'error');
  7046. }
  7047. } catch (err) {
  7048. showToast('Error', err.message, 'error');
  7049. }
  7050. }
  7051. async function toggleAeroTUNState(id, disabled) {
  7052. try {
  7053. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/state`, {
  7054. method: 'POST',
  7055. headers: { 'Content-Type': 'application/json' },
  7056. body: JSON.stringify({ disabled })
  7057. });
  7058. if (res.ok) {
  7059. showToast('State Updated', disabled ? 'Tunnel disabled' : 'Tunnel enabled', 'info');
  7060. loadAeroTUN(false);
  7061. fetchData(false);
  7062. }
  7063. } catch (err) {
  7064. showToast('Error', err.message, 'error');
  7065. }
  7066. }
  7067. async function deleteAeroTUN(id) {
  7068. if (!confirm('Are you sure you want to delete this AeroTUN tunnel?')) return;
  7069. try {
  7070. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7071. if (res.ok) {
  7072. showToast('Deleted', 'AeroTUN tunnel removed', 'success');
  7073. loadAeroTUN(false);
  7074. fetchData(false);
  7075. }
  7076. } catch (err) {
  7077. showToast('Error', err.message, 'error');
  7078. }
  7079. }
  7080. // ======================== PPP Central Hub & Servers ========================
  7081. function switchPPPSubTab(tab) {
  7082. state.pppSubTab = tab;
  7083. const tabs = ['secrets', 'profiles', 'pppoe', 'pptp', 'l2tp', 'active'];
  7084. tabs.forEach(t => {
  7085. const panel = document.getElementById(`ppp-subtab-${t}`);
  7086. const btn = document.getElementById(`ppp-subtab-btn-${t}`);
  7087. if (panel) {
  7088. if (t === tab) panel.classList.remove('hidden');
  7089. else panel.classList.add('hidden');
  7090. }
  7091. if (btn) {
  7092. if (t === tab) {
  7093. 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';
  7094. } else {
  7095. 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';
  7096. }
  7097. }
  7098. });
  7099. const addBtn = document.getElementById('ppp-primary-add-btn');
  7100. if (addBtn) {
  7101. if (tab === 'secrets') addBtn.innerHTML = '<span>+ Add User (Secret)</span>';
  7102. else if (tab === 'profiles') addBtn.innerHTML = '<span>+ Add Profile</span>';
  7103. else if (tab === 'active') addBtn.innerHTML = '<span>Refresh Sessions</span>';
  7104. else addBtn.innerHTML = '<span>Save Config</span>';
  7105. }
  7106. if (tab === 'active') loadPPPSessions();
  7107. }
  7108. function openCurrentPPPModal() {
  7109. if (state.pppSubTab === 'secrets') openAddPPPSecretModal();
  7110. else if (state.pppSubTab === 'profiles') openAddPPPProfileModal();
  7111. else if (state.pppSubTab === 'active') loadPPPSessions();
  7112. else if (state.pppSubTab === 'pppoe') document.querySelector('#ppp-subtab-pppoe form')?.requestSubmit();
  7113. else if (state.pppSubTab === 'pptp') document.querySelector('#ppp-subtab-pptp form')?.requestSubmit();
  7114. else if (state.pppSubTab === 'l2tp') document.querySelector('#ppp-subtab-l2tp form')?.requestSubmit();
  7115. }
  7116. async function loadPPP(populateDropdowns = true) {
  7117. await Promise.all([
  7118. loadPPPSecrets(),
  7119. loadPPPProfiles(),
  7120. loadPPPServers(),
  7121. loadPPPSessions()
  7122. ]);
  7123. }
  7124. async function loadPPPSecrets() {
  7125. try {
  7126. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`);
  7127. const data = await res.json();
  7128. state.pppSecrets = Array.isArray(data) ? data : [];
  7129. const b = document.getElementById('ppp-badge-secrets');
  7130. if (b) b.innerText = state.pppSecrets.length;
  7131. const b2 = document.getElementById('secrets-count-badge');
  7132. if (b2) b2.innerText = `${state.pppSecrets.length} Users`;
  7133. renderPPPSecrets();
  7134. } catch (err) {
  7135. console.error('Failed to load PPP secrets:', err);
  7136. }
  7137. }
  7138. function renderPPPSecrets() {
  7139. const tbody = document.getElementById('secrets-table-body');
  7140. const empty = document.getElementById('secrets-empty');
  7141. if (!tbody) return;
  7142. tbody.innerHTML = '';
  7143. const secrets = state.pppSecrets || [];
  7144. if (secrets.length === 0) {
  7145. empty?.classList.remove('hidden');
  7146. return;
  7147. }
  7148. empty?.classList.add('hidden');
  7149. secrets.forEach(s => {
  7150. const tr = document.createElement('tr');
  7151. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  7152. tr.innerHTML = `
  7153. <td class="py-2.5 px-3 text-center">${renderRuleFlag(s.disabled, !!s.comment)}</td>
  7154. <td class="py-2.5 px-3 font-bold text-white font-mono">${s.name}</td>
  7155. <td class="py-2.5 px-3 text-purple-300 font-mono font-semibold">${s.service}</td>
  7156. <td class="py-2.5 px-3 text-amber-300 font-mono">${s.profile}</td>
  7157. <td class="py-2.5 px-3 text-slate-400 font-mono">${s.local_address || '(profile)'}</td>
  7158. <td class="py-2.5 px-3 text-cyan-400 font-mono font-bold">${s.remote_address || '(profile)'}</td>
  7159. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]">${s.comment || '-'}</td>
  7160. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  7161. <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>
  7162. <button onclick="openEditPPPSecretModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  7163. <button onclick="deletePPPSecret('${s.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  7164. </td>
  7165. `;
  7166. tbody.appendChild(tr);
  7167. });
  7168. }
  7169. async function loadPPPProfiles() {
  7170. try {
  7171. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`);
  7172. const data = await res.json();
  7173. state.pppProfiles = Array.isArray(data) ? data : [];
  7174. const b = document.getElementById('ppp-badge-profiles');
  7175. if (b) b.innerText = state.pppProfiles.length;
  7176. const b2 = document.getElementById('profiles-count-badge');
  7177. if (b2) b2.innerText = `${state.pppProfiles.length} Profiles`;
  7178. // Populate profile selects across modals
  7179. const selects = ['secret-modal-profile', 'pppoe-server-profile', 'pptp-server-profile', 'l2tp-server-profile'];
  7180. selects.forEach(sid => {
  7181. const el = document.getElementById(sid);
  7182. if (!el) return;
  7183. const cur = el.value;
  7184. el.innerHTML = '';
  7185. state.pppProfiles.forEach(p => {
  7186. const opt = document.createElement('option');
  7187. opt.value = p.name;
  7188. opt.innerText = `${p.name} (${p.remote_address})`;
  7189. if (p.name === cur) opt.selected = true;
  7190. el.appendChild(opt);
  7191. });
  7192. });
  7193. renderPPPProfiles();
  7194. } catch (err) {
  7195. console.error('Failed to load PPP profiles:', err);
  7196. }
  7197. }
  7198. function renderPPPProfiles() {
  7199. const tbody = document.getElementById('profiles-table-body');
  7200. if (!tbody) return;
  7201. tbody.innerHTML = '';
  7202. (state.pppProfiles || []).forEach(p => {
  7203. const isDefault = p.name.startsWith('default');
  7204. const tr = document.createElement('tr');
  7205. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  7206. tr.innerHTML = `
  7207. <td class="py-2.5 px-3 font-bold text-white">${p.name}</td>
  7208. <td class="py-2.5 px-3 text-slate-300">${p.local_address}</td>
  7209. <td class="py-2.5 px-3 text-cyan-400 font-bold">${p.remote_address}</td>
  7210. <td class="py-2.5 px-3 text-slate-400">${p.dns_servers || '-'}</td>
  7211. <td class="py-2.5 px-3 text-purple-300 font-semibold">${p.use_encryption}</td>
  7212. <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>
  7213. <td class="py-2.5 px-3 text-slate-400 italic">${p.comment || '-'}</td>
  7214. <td class="py-2.5 px-3 text-right font-sans whitespace-nowrap">
  7215. ${!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>`}
  7216. </td>
  7217. `;
  7218. tbody.appendChild(tr);
  7219. });
  7220. }
  7221. async function loadPPPServers() {
  7222. try {
  7223. const [pppoeRes, pptpRes, l2tpRes, ipsecRes] = await Promise.all([
  7224. fetch(`${API_BASE}/vpn/servers/pppoe`),
  7225. fetch(`${API_BASE}/vpn/servers/pptp`),
  7226. fetch(`${API_BASE}/vpn/servers/l2tp`),
  7227. fetch(`${API_BASE}/vpn/servers/ipsec`)
  7228. ]);
  7229. if (pppoeRes.ok) {
  7230. state.pppoeServer = await pppoeRes.json();
  7231. const s = state.pppoeServer;
  7232. document.getElementById('pppoe-server-enabled').checked = !!s.enabled;
  7233. document.getElementById('pppoe-server-name').value = s.service_name || 'proxmox-pppoe';
  7234. populateInterfaceSelect('pppoe-server-iface', s.interface || 'eth0');
  7235. document.getElementById('pppoe-server-profile').value = s.default_profile || 'default';
  7236. document.getElementById('pppoe-server-mtu').value = s.max_mtu || 1480;
  7237. document.getElementById('pppoe-server-onesession').checked = !!s.one_session_per_host;
  7238. const pill = document.getElementById('pppoe-server-status-pill');
  7239. if (pill) {
  7240. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  7241. 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';
  7242. }
  7243. setDotBadge('ppp-badge-pppoe-state', s.running);
  7244. }
  7245. if (pptpRes.ok) {
  7246. state.pptpServer = await pptpRes.json();
  7247. const s = state.pptpServer;
  7248. document.getElementById('pptp-server-enabled').checked = !!s.enabled;
  7249. document.getElementById('pptp-server-port').value = s.port || 1723;
  7250. document.getElementById('pptp-server-profile').value = s.default_profile || 'default-encryption';
  7251. document.getElementById('pptp-server-mppe').checked = s.require_mppe !== false;
  7252. const pill = document.getElementById('pptp-server-status-pill');
  7253. if (pill) {
  7254. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  7255. 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';
  7256. }
  7257. setDotBadge('ppp-badge-pptp-state', s.running);
  7258. }
  7259. if (l2tpRes.ok) {
  7260. state.l2tpServer = await l2tpRes.json();
  7261. const s = state.l2tpServer;
  7262. document.getElementById('l2tp-server-enabled').checked = !!s.enabled;
  7263. document.getElementById('l2tp-server-port').value = s.port || 1701;
  7264. document.getElementById('l2tp-server-profile').value = s.default_profile || 'default';
  7265. document.getElementById('l2tp-server-useipsec').value = s.use_ipsec || 'no';
  7266. document.getElementById('l2tp-server-ipsecsecret').value = s.ipsec_secret || '';
  7267. const pill = document.getElementById('l2tp-server-status-pill');
  7268. if (pill) {
  7269. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  7270. 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';
  7271. }
  7272. setDotBadge('ppp-badge-l2tp-state', s.running);
  7273. }
  7274. if (ipsecRes.ok) {
  7275. state.ipsecServer = await ipsecRes.json();
  7276. const s = state.ipsecServer;
  7277. const modalEn = document.getElementById('modal-ipsec-server-enabled');
  7278. if (modalEn) modalEn.checked = !!s.enabled;
  7279. const modalPsk = document.getElementById('modal-ipsec-server-psk');
  7280. if (modalPsk) modalPsk.value = s.preshared_key || '';
  7281. const modalPool = document.getElementById('modal-ipsec-server-pool');
  7282. if (modalPool) modalPool.value = s.pool_address || '10.10.30.0/24';
  7283. const modalDns = document.getElementById('modal-ipsec-server-dns');
  7284. if (modalDns) modalDns.value = s.dns_servers || '1.1.1.1,8.8.8.8';
  7285. const modalSubnet = document.getElementById('modal-ipsec-server-subnet');
  7286. if (modalSubnet) modalSubnet.value = s.local_subnet || '0.0.0.0/0';
  7287. const pill = document.getElementById('modal-ipsec-server-status');
  7288. if (pill) {
  7289. pill.innerText = s.running ? 'ACTIVE RESPONDER' : 'STOPPED';
  7290. 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';
  7291. }
  7292. }
  7293. } catch (err) {
  7294. console.error('Failed to load VPN servers:', err);
  7295. }
  7296. }
  7297. async function loadPPPSessions() {
  7298. try {
  7299. const res = await fetch(`${API_BASE}/vpn/ppp/active`);
  7300. const data = await res.json();
  7301. state.pppActiveSessions = Array.isArray(data) ? data : [];
  7302. const b = document.getElementById('ppp-badge-active');
  7303. if (b) b.innerText = state.pppActiveSessions.length;
  7304. const sideB = document.getElementById('badge-ppp-sessions');
  7305. if (sideB) sideB.innerText = state.pppActiveSessions.length;
  7306. renderPPPSessions();
  7307. } catch (err) {
  7308. console.error('Failed to load active PPP sessions:', err);
  7309. }
  7310. }
  7311. function renderPPPSessions() {
  7312. const tbody = document.getElementById('active-ppp-table-body');
  7313. const empty = document.getElementById('active-ppp-empty');
  7314. if (!tbody) return;
  7315. tbody.innerHTML = '';
  7316. const list = state.pppActiveSessions || [];
  7317. if (list.length === 0) {
  7318. empty?.classList.remove('hidden');
  7319. return;
  7320. }
  7321. empty?.classList.add('hidden');
  7322. list.forEach(s => {
  7323. const tr = document.createElement('tr');
  7324. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  7325. tr.innerHTML = `
  7326. <td class="py-2.5 px-3 font-bold text-white">${s.interface}</td>
  7327. <td class="py-2.5 px-3 font-semibold text-violet-300">${s.username}</td>
  7328. <td class="py-2.5 px-3 text-cyan-400 uppercase">${s.service}</td>
  7329. <td class="py-2.5 px-3 text-emerald-400 font-bold">${s.address || '-'}</td>
  7330. <td class="py-2.5 px-3 text-slate-400">${s.uptime}</td>
  7331. <td class="py-2.5 px-3 text-[11px]">
  7332. <span class="text-emerald-400">↓ ${s.rx_human || '0 B'}</span>
  7333. <span class="text-cyan-400 ml-1">↑ ${s.tx_human || '0 B'}</span>
  7334. </td>
  7335. <td class="py-2.5 px-3 text-right font-sans">
  7336. <button onclick="disconnectPPPSession('${s.interface}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  7337. </td>
  7338. `;
  7339. tbody.appendChild(tr);
  7340. });
  7341. }
  7342. async function disconnectPPPSession(iface) {
  7343. if (!confirm(`Disconnect session ${iface}?`)) return;
  7344. try {
  7345. const res = await fetch(`${API_BASE}/vpn/ppp/active/${encodeURIComponent(iface)}`, { method: 'DELETE' });
  7346. if (res.ok) {
  7347. showToast('Disconnected', `Session ${iface} terminated`, 'info');
  7348. loadPPPSessions();
  7349. }
  7350. } catch (err) {
  7351. showToast('Error', err.message, 'error');
  7352. }
  7353. }
  7354. // PPP Secret Modal handlers
  7355. function openAddPPPSecretModal() {
  7356. document.getElementById('secret-modal-title').innerText = 'Add PPP Secret';
  7357. document.getElementById('secret-modal-id').value = '';
  7358. document.getElementById('secret-modal-name').value = '';
  7359. document.getElementById('secret-modal-password').value = '';
  7360. document.getElementById('secret-modal-service').value = 'any';
  7361. document.getElementById('secret-modal-profile').value = 'default';
  7362. document.getElementById('secret-modal-local').value = '';
  7363. document.getElementById('secret-modal-remote').value = '';
  7364. document.getElementById('secret-modal-comment').value = '';
  7365. document.getElementById('secret-modal-disabled').checked = false;
  7366. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  7367. }
  7368. function openEditPPPSecretModal(id) {
  7369. const s = (state.pppSecrets || []).find(sec => sec.id === id);
  7370. if (!s) return;
  7371. document.getElementById('secret-modal-title').innerText = `Edit PPP Secret (${s.name})`;
  7372. document.getElementById('secret-modal-id').value = s.id;
  7373. document.getElementById('secret-modal-name').value = s.name;
  7374. document.getElementById('secret-modal-password').value = s.password;
  7375. document.getElementById('secret-modal-service').value = s.service || 'any';
  7376. document.getElementById('secret-modal-profile').value = s.profile || 'default';
  7377. document.getElementById('secret-modal-local').value = s.local_address || '';
  7378. document.getElementById('secret-modal-remote').value = s.remote_address || '';
  7379. document.getElementById('secret-modal-comment').value = s.comment || '';
  7380. document.getElementById('secret-modal-disabled').checked = !!s.disabled;
  7381. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  7382. }
  7383. function closePPPSecretModal() {
  7384. document.getElementById('ppp-secret-modal').classList.add('hidden');
  7385. }
  7386. async function submitSavePPPSecret(e) {
  7387. e.preventDefault();
  7388. const id = document.getElementById('secret-modal-id').value;
  7389. const name = document.getElementById('secret-modal-name').value.trim();
  7390. const password = document.getElementById('secret-modal-password').value.trim();
  7391. const service = document.getElementById('secret-modal-service').value;
  7392. const profile = document.getElementById('secret-modal-profile').value;
  7393. const local = document.getElementById('secret-modal-local').value.trim();
  7394. const remote = document.getElementById('secret-modal-remote').value.trim();
  7395. const comment = document.getElementById('secret-modal-comment').value.trim();
  7396. const disabled = document.getElementById('secret-modal-disabled').checked;
  7397. try {
  7398. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`, {
  7399. method: 'POST',
  7400. headers: { 'Content-Type': 'application/json' },
  7401. body: JSON.stringify({
  7402. id,
  7403. name,
  7404. password,
  7405. service,
  7406. profile,
  7407. local_address: local,
  7408. remote_address: remote,
  7409. comment,
  7410. disabled
  7411. })
  7412. });
  7413. if (res.ok) {
  7414. showToast('Secret Saved', `User ${name} saved to PPP database`, 'success');
  7415. closePPPSecretModal();
  7416. loadPPPSecrets();
  7417. } else {
  7418. const err = await res.json();
  7419. showToast('Error', err.message, 'error');
  7420. }
  7421. } catch (err) {
  7422. showToast('Error', err.message, 'error');
  7423. }
  7424. }
  7425. async function togglePPPSecretState(id, disabled) {
  7426. try {
  7427. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}/state`, {
  7428. method: 'POST',
  7429. headers: { 'Content-Type': 'application/json' },
  7430. body: JSON.stringify({ disabled })
  7431. });
  7432. if (res.ok) {
  7433. showToast(disabled ? 'Disabled' : 'Enabled', 'Secret user state updated', 'info');
  7434. loadPPPSecrets();
  7435. }
  7436. } catch (err) {
  7437. showToast('Error', err.message, 'error');
  7438. }
  7439. }
  7440. async function deletePPPSecret(id) {
  7441. if (!confirm('Are you sure you want to delete this secret account?')) return;
  7442. try {
  7443. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7444. if (res.ok) {
  7445. showToast('Deleted', 'Secret account removed', 'success');
  7446. loadPPPSecrets();
  7447. }
  7448. } catch (err) {
  7449. showToast('Error', err.message, 'error');
  7450. }
  7451. }
  7452. // PPP Profile Modal handlers
  7453. function openAddPPPProfileModal() {
  7454. document.getElementById('profile-modal-name').value = '';
  7455. document.getElementById('profile-modal-local').value = '10.10.10.1';
  7456. document.getElementById('profile-modal-remote').value = '10.10.10.10-10.10.10.50';
  7457. document.getElementById('profile-modal-dns').value = '1.1.1.1,8.8.8.8';
  7458. document.getElementById('profile-modal-encryption').value = 'required';
  7459. document.getElementById('profile-modal-onlyone').checked = true;
  7460. document.getElementById('profile-modal-comment').value = '';
  7461. document.getElementById('ppp-profile-modal').classList.remove('hidden');
  7462. }
  7463. function closePPPProfileModal() {
  7464. document.getElementById('ppp-profile-modal').classList.add('hidden');
  7465. }
  7466. async function submitSavePPPProfile(e) {
  7467. e.preventDefault();
  7468. const name = document.getElementById('profile-modal-name').value.trim();
  7469. const local = document.getElementById('profile-modal-local').value.trim();
  7470. const remote = document.getElementById('profile-modal-remote').value.trim();
  7471. const dns = document.getElementById('profile-modal-dns').value.trim();
  7472. const enc = document.getElementById('profile-modal-encryption').value;
  7473. const onlyone = document.getElementById('profile-modal-onlyone').checked;
  7474. const comment = document.getElementById('profile-modal-comment').value.trim();
  7475. try {
  7476. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`, {
  7477. method: 'POST',
  7478. headers: { 'Content-Type': 'application/json' },
  7479. body: JSON.stringify({
  7480. id: name,
  7481. name,
  7482. local_address: local,
  7483. remote_address: remote,
  7484. dns_servers: dns,
  7485. use_encryption: enc,
  7486. only_one: onlyone,
  7487. comment
  7488. })
  7489. });
  7490. if (res.ok) {
  7491. showToast('Profile Saved', `PPP profile ${name} created`, 'success');
  7492. closePPPProfileModal();
  7493. loadPPPProfiles();
  7494. } else {
  7495. const err = await res.json();
  7496. showToast('Error', err.message, 'error');
  7497. }
  7498. } catch (err) {
  7499. showToast('Error', err.message, 'error');
  7500. }
  7501. }
  7502. async function deletePPPProfile(name) {
  7503. if (!confirm(`Delete PPP profile ${name}?`)) return;
  7504. try {
  7505. const res = await fetch(`${API_BASE}/vpn/ppp/profiles/${encodeURIComponent(name)}`, { method: 'DELETE' });
  7506. if (res.ok) {
  7507. showToast('Deleted', 'Profile removed', 'success');
  7508. loadPPPProfiles();
  7509. } else {
  7510. const err = await res.json();
  7511. showToast('Error', err.message, 'error');
  7512. }
  7513. } catch (err) {
  7514. showToast('Error', err.message, 'error');
  7515. }
  7516. }
  7517. // Server Config submissions
  7518. async function savePPPoEServerConfig(e) {
  7519. e.preventDefault();
  7520. const enabled = document.getElementById('pppoe-server-enabled').checked;
  7521. const name = document.getElementById('pppoe-server-name').value.trim();
  7522. const iface = document.getElementById('pppoe-server-iface').value;
  7523. const profile = document.getElementById('pppoe-server-profile').value;
  7524. const mtu = parseInt(document.getElementById('pppoe-server-mtu').value) || 1480;
  7525. const onesession = document.getElementById('pppoe-server-onesession').checked;
  7526. try {
  7527. const res = await fetch(`${API_BASE}/vpn/servers/pppoe`, {
  7528. method: 'POST',
  7529. headers: { 'Content-Type': 'application/json' },
  7530. body: JSON.stringify({
  7531. enabled,
  7532. service_name: name,
  7533. interface: iface,
  7534. default_profile: profile,
  7535. max_mtu: mtu,
  7536. max_mru: mtu,
  7537. one_session_per_host: onesession
  7538. })
  7539. });
  7540. if (res.ok) {
  7541. showToast('PPPoE Server', enabled ? 'PPPoE Server started' : 'PPPoE Server stopped', 'success');
  7542. loadPPPServers();
  7543. fetchData(false);
  7544. } else {
  7545. const err = await res.json();
  7546. showToast('Error', err.message, 'error');
  7547. }
  7548. } catch (err) {
  7549. showToast('Error', err.message, 'error');
  7550. }
  7551. }
  7552. async function savePPTPServerConfig(e) {
  7553. e.preventDefault();
  7554. const enabled = document.getElementById('pptp-server-enabled').checked;
  7555. const port = parseInt(document.getElementById('pptp-server-port').value) || 1723;
  7556. const profile = document.getElementById('pptp-server-profile').value;
  7557. const mppe = document.getElementById('pptp-server-mppe').checked;
  7558. try {
  7559. const res = await fetch(`${API_BASE}/vpn/servers/pptp`, {
  7560. method: 'POST',
  7561. headers: { 'Content-Type': 'application/json' },
  7562. body: JSON.stringify({
  7563. enabled,
  7564. port,
  7565. default_profile: profile,
  7566. require_mppe: mppe
  7567. })
  7568. });
  7569. if (res.ok) {
  7570. showToast('PPTP Server', enabled ? 'PPTP Server started' : 'PPTP Server stopped', 'success');
  7571. loadPPPServers();
  7572. fetchData(false);
  7573. } else {
  7574. const err = await res.json();
  7575. showToast('Error', err.message, 'error');
  7576. }
  7577. } catch (err) {
  7578. showToast('Error', err.message, 'error');
  7579. }
  7580. }
  7581. async function saveL2TPServerConfig(e) {
  7582. e.preventDefault();
  7583. const enabled = document.getElementById('l2tp-server-enabled').checked;
  7584. const port = parseInt(document.getElementById('l2tp-server-port').value) || 1701;
  7585. const profile = document.getElementById('l2tp-server-profile').value;
  7586. const useipsec = document.getElementById('l2tp-server-useipsec').value;
  7587. const psk = document.getElementById('l2tp-server-ipsecsecret').value.trim();
  7588. try {
  7589. const res = await fetch(`${API_BASE}/vpn/servers/l2tp`, {
  7590. method: 'POST',
  7591. headers: { 'Content-Type': 'application/json' },
  7592. body: JSON.stringify({
  7593. enabled,
  7594. port,
  7595. default_profile: profile,
  7596. use_ipsec: useipsec,
  7597. ipsec_secret: psk
  7598. })
  7599. });
  7600. if (res.ok) {
  7601. showToast('L2TP Server', enabled ? 'L2TP Server started' : 'L2TP Server stopped', 'success');
  7602. loadPPPServers();
  7603. fetchData(false);
  7604. } else {
  7605. const err = await res.json();
  7606. showToast('Error', err.message, 'error');
  7607. }
  7608. } catch (err) {
  7609. showToast('Error', err.message, 'error');
  7610. }
  7611. }
  7612. // IPSec Server Modal
  7613. function openIPSecServerModal() {
  7614. loadPPPServers();
  7615. document.getElementById('ipsec-server-modal').classList.remove('hidden');
  7616. }
  7617. function closeIPSecServerModal() {
  7618. document.getElementById('ipsec-server-modal').classList.add('hidden');
  7619. }
  7620. async function submitSaveIPSecServer(e) {
  7621. e.preventDefault();
  7622. const enabled = document.getElementById('modal-ipsec-server-enabled').checked;
  7623. const psk = document.getElementById('modal-ipsec-server-psk').value.trim();
  7624. const pool = document.getElementById('modal-ipsec-server-pool').value.trim();
  7625. const dns = document.getElementById('modal-ipsec-server-dns').value.trim();
  7626. const subnet = document.getElementById('modal-ipsec-server-subnet').value.trim();
  7627. try {
  7628. const res = await fetch(`${API_BASE}/vpn/servers/ipsec`, {
  7629. method: 'POST',
  7630. headers: { 'Content-Type': 'application/json' },
  7631. body: JSON.stringify({
  7632. enabled,
  7633. preshared_key: psk,
  7634. pool_address: pool,
  7635. dns_servers: dns,
  7636. local_subnet: subnet
  7637. })
  7638. });
  7639. if (res.ok) {
  7640. showToast('IPSec Server', enabled ? 'IKEv2 Roadwarrior responder active' : 'IPSec Server stopped', 'success');
  7641. closeIPSecServerModal();
  7642. loadPPPServers();
  7643. fetchData(false);
  7644. } else {
  7645. const err = await res.json();
  7646. showToast('Error', err.message, 'error');
  7647. }
  7648. } catch (err) {
  7649. showToast('Error', err.message, 'error');
  7650. }
  7651. }
  7652. // WireGuard Client Config Viewer
  7653. let currentWGClientConf = '';
  7654. async function openWGClientConfModal(iface, clientIP) {
  7655. try {
  7656. const res = await fetch(`${API_BASE}/vpn/wireguard/client-config`, {
  7657. method: 'POST',
  7658. headers: { 'Content-Type': 'application/json' },
  7659. body: JSON.stringify({
  7660. interface: iface,
  7661. address: clientIP || '10.10.0.2/32',
  7662. dns: '1.1.1.1, 8.8.8.8'
  7663. })
  7664. });
  7665. if (res.ok) {
  7666. const data = await res.json();
  7667. currentWGClientConf = data.config;
  7668. document.getElementById('wg-client-conf-text').value = currentWGClientConf;
  7669. document.getElementById('wg-client-conf-modal').classList.remove('hidden');
  7670. } else {
  7671. const err = await res.json();
  7672. showToast('Error', err.message, 'error');
  7673. }
  7674. } catch (err) {
  7675. showToast('Error', err.message, 'error');
  7676. }
  7677. }
  7678. function closeWGClientConfModal() {
  7679. document.getElementById('wg-client-conf-modal').classList.add('hidden');
  7680. }
  7681. function copyWGClientConf() {
  7682. if (!currentWGClientConf) return;
  7683. copyToClipboard(currentWGClientConf, 'WireGuard Client Profile');
  7684. }
  7685. function downloadWGClientConf() {
  7686. if (!currentWGClientConf) return;
  7687. const blob = new Blob([currentWGClientConf], { type: 'text/plain;charset=utf-8' });
  7688. const a = document.createElement('a');
  7689. a.href = URL.createObjectURL(blob);
  7690. a.download = 'wireguard-client.conf';
  7691. document.body.appendChild(a);
  7692. a.click();
  7693. document.body.removeChild(a);
  7694. showToast('Downloaded', 'wireguard-client.conf saved', 'success');
  7695. }
  7696. // =========================================================================
  7697. // DYNAMIC ROUTING (FRRouting BGP & OSPFv2)
  7698. // =========================================================================
  7699. state.activeDynSubTab = 'bgp-peers';
  7700. state.activeBgpSubTab = 'bgp-peers';
  7701. state.activeOspfTab = 'instances';
  7702. state.bgpInstance = null;
  7703. state.bgpPeers = [];
  7704. state.bgpNets = [];
  7705. state.bgpRoutes = [];
  7706. state.ospfInstance = null;
  7707. state.ospfInstances = [];
  7708. state.ospfAreas = [];
  7709. state.ospfAreaRanges = [];
  7710. state.ospfTemplates = [];
  7711. state.ospfLiveInterfaces = [];
  7712. state.ospfStaticNbrs = [];
  7713. state.ospfNeighbors = [];
  7714. state.ospfLSA = [];
  7715. state.ospfRoutes = [];
  7716. state.selectedOspfRow = {
  7717. instances: null,
  7718. areas: null,
  7719. 'area-ranges': null,
  7720. templates: null,
  7721. interfaces: null,
  7722. 'static-nbrs': null,
  7723. neighbors: null,
  7724. lsa: null,
  7725. };
  7726. state.ospfSort = {
  7727. instances: { col: 'name', asc: true },
  7728. areas: { col: 'name', asc: true },
  7729. ranges: { col: 'area', asc: true },
  7730. templates: { col: 'interfaces', asc: true },
  7731. live_ifaces: { col: 'interface', asc: true },
  7732. snbrs: { col: 'address', asc: true },
  7733. neighbors: { col: 'address', asc: true },
  7734. lsa: { col: 'instance', asc: true },
  7735. };
  7736. function switchBgpSubTab(subTab) {
  7737. state.activeBgpSubTab = subTab;
  7738. const tabs = ['bgp-peers', 'bgp-nets', 'bgp-routes'];
  7739. tabs.forEach(t => {
  7740. const el = document.getElementById(`dyn-subtab-${t}`);
  7741. const btn = document.getElementById(`bgp-subtab-btn-${t}`);
  7742. if (el) el.classList.toggle('hidden', t !== subTab);
  7743. if (btn) {
  7744. if (t === subTab) {
  7745. 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';
  7746. } else {
  7747. 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';
  7748. }
  7749. }
  7750. });
  7751. }
  7752. function switchOspfTab(tabName) {
  7753. state.activeOspfTab = tabName;
  7754. const tabs = ['instances', 'areas', 'area-ranges', 'templates', 'interfaces', 'static-nbrs', 'neighbors', 'lsa'];
  7755. tabs.forEach(t => {
  7756. const pane = document.getElementById(`ospf-pane-${t}`);
  7757. const btn = document.getElementById(`ospf-tab-btn-${t}`);
  7758. if (pane) pane.classList.toggle('hidden', t !== tabName);
  7759. if (btn) {
  7760. if (t === tabName) {
  7761. 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';
  7762. } else {
  7763. 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';
  7764. }
  7765. }
  7766. });
  7767. }
  7768. function switchOspfSubTab(tab) {
  7769. // Legacy alias
  7770. if (tab === 'ospf-ifaces') switchOspfTab('templates');
  7771. else if (tab === 'ospf-areas') switchOspfTab('areas');
  7772. else if (tab === 'ospf-nbrs') switchOspfTab('neighbors');
  7773. else switchOspfTab('instances');
  7774. }
  7775. function switchDynSubTab(subTab) {
  7776. if (subTab.startsWith('bgp')) {
  7777. if (state.activeTab !== 'bgp') navigate('bgp');
  7778. switchBgpSubTab(subTab);
  7779. } else if (subTab.startsWith('ospf')) {
  7780. if (state.activeTab !== 'ospf') navigate('ospf');
  7781. switchOspfTab('instances');
  7782. }
  7783. }
  7784. async function loadDynamicRouting(showToastMsg = false) {
  7785. try {
  7786. const fetchSafeJson = async (url) => {
  7787. try {
  7788. const r = await fetch(url);
  7789. return r.ok ? await r.json() : null;
  7790. } catch (e) {
  7791. return null;
  7792. }
  7793. };
  7794. const [
  7795. sum, bgpInst, bgpPeers, bgpNets, bgpRoutes,
  7796. ospfInsts, ospfAreas, ospfRanges, ospfTemplates, ospfLiveIfaces, ospfStaticNbrs, ospfNbrs, ospfLsa, filters,
  7797. selectRules, commLists, asLists
  7798. ] = await Promise.all([
  7799. fetchSafeJson(`${API_BASE}/routing/dynamic/summary`),
  7800. fetchSafeJson(`${API_BASE}/routing/bgp/instance`),
  7801. fetchSafeJson(`${API_BASE}/routing/bgp/peers`),
  7802. fetchSafeJson(`${API_BASE}/routing/bgp/networks`),
  7803. fetchSafeJson(`${API_BASE}/routing/bgp/routes`),
  7804. fetchSafeJson(`${API_BASE}/routing/ospf/instances`),
  7805. fetchSafeJson(`${API_BASE}/routing/ospf/areas`),
  7806. fetchSafeJson(`${API_BASE}/routing/ospf/area-ranges`),
  7807. fetchSafeJson(`${API_BASE}/routing/ospf/templates`),
  7808. fetchSafeJson(`${API_BASE}/routing/ospf/interfaces-live`),
  7809. fetchSafeJson(`${API_BASE}/routing/ospf/static-neighbors`),
  7810. fetchSafeJson(`${API_BASE}/routing/ospf/neighbors`),
  7811. fetchSafeJson(`${API_BASE}/routing/ospf/lsa`),
  7812. fetchSafeJson(`${API_BASE}/routing/filters`),
  7813. fetchSafeJson(`${API_BASE}/routing/filters/select-rules`),
  7814. fetchSafeJson(`${API_BASE}/routing/filters/community-lists`),
  7815. fetchSafeJson(`${API_BASE}/routing/filters/as-lists`)
  7816. ]);
  7817. if (sum) state.dynSummary = sum;
  7818. if (bgpInst) state.bgpInstance = bgpInst;
  7819. if (bgpPeers) state.bgpPeers = bgpPeers;
  7820. if (bgpNets) state.bgpNets = bgpNets;
  7821. if (bgpRoutes) state.bgpRoutes = bgpRoutes;
  7822. if (ospfInsts) state.ospfInstances = ospfInsts;
  7823. if (ospfAreas) state.ospfAreas = ospfAreas;
  7824. if (ospfRanges) state.ospfAreaRanges = ospfRanges;
  7825. if (ospfTemplates) state.ospfTemplates = ospfTemplates;
  7826. if (ospfLiveIfaces) state.ospfLiveInterfaces = ospfLiveIfaces;
  7827. if (ospfStaticNbrs) state.ospfStaticNbrs = ospfStaticNbrs;
  7828. if (ospfNbrs) state.ospfNeighbors = ospfNbrs;
  7829. if (ospfLsa) state.ospfLSA = ospfLsa;
  7830. if (filters) state.routingFilters = filters;
  7831. if (selectRules) state.routingSelectRules = selectRules;
  7832. if (commLists) state.routingCommunityLists = commLists;
  7833. if (asLists) state.routingASLists = asLists;
  7834. try { renderBgpStatusPill(); } catch(e) { console.error('renderBgpStatusPill error:', e); }
  7835. try { renderBgpPeers(); } catch(e) { console.error('renderBgpPeers error:', e); }
  7836. try { renderBgpNetworks(); } catch(e) { console.error('renderBgpNetworks error:', e); }
  7837. try { renderBgpRoutes(); } catch(e) { console.error('renderBgpRoutes error:', e); }
  7838. try { renderOspfInstances(); } catch(e) { console.error('renderOspfInstances error:', e); }
  7839. try { renderOspfAreas(); } catch(e) { console.error('renderOspfAreas error:', e); }
  7840. try { renderOspfAreaRanges(); } catch(e) { console.error('renderOspfAreaRanges error:', e); }
  7841. try { renderOspfTemplates(); } catch(e) { console.error('renderOspfTemplates error:', e); }
  7842. try { renderOspfLiveInterfaces(); } catch(e) { console.error('renderOspfLiveInterfaces error:', e); }
  7843. try { renderOspfStaticNbrs(); } catch(e) { console.error('renderOspfStaticNbrs error:', e); }
  7844. try { renderOspfNeighbors(); } catch(e) { console.error('renderOspfNeighbors error:', e); }
  7845. try { renderOspfLSA(); } catch(e) { console.error('renderOspfLSA error:', e); }
  7846. try { renderRoutingFilters(); } catch(e) { console.error('renderRoutingFilters error:', e); }
  7847. try { updateBadges(); } catch(e) { console.error('updateBadges error:', e); }
  7848. if (showToastMsg) showToast('Refreshed', 'Dynamic routing telemetry updated', 'info');
  7849. } catch (err) {
  7850. console.error('Failed to load dynamic routing:', err);
  7851. if (showToastMsg) showToast('Notice', 'Unable to refresh dynamic routing telemetry', 'warning');
  7852. }
  7853. }
  7854. async function loadOspfAll() {
  7855. await loadDynamicRouting(true);
  7856. }
  7857. function renderBgpStatusPill() {
  7858. const pill = document.getElementById('bgp-live-status-pill');
  7859. if (!pill) return;
  7860. const inst = state.bgpInstance;
  7861. if (!inst || !inst.enabled) {
  7862. pill.className = 'text-[10px] px-2 py-0.5 rounded font-mono bg-slate-800 text-slate-400 border border-slate-700';
  7863. pill.innerText = 'BGP DISABLED';
  7864. } else if (inst.running) {
  7865. 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';
  7866. pill.innerText = `BGP ACTIVE (AS ${inst.as})`;
  7867. } else {
  7868. 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';
  7869. pill.innerText = 'BGP STARTING...';
  7870. }
  7871. }
  7872. function renderBgpPeers() {
  7873. const tbody = document.getElementById('bgp-peers-table-body');
  7874. if (!tbody) return;
  7875. const empty = document.getElementById('bgp-peers-empty');
  7876. const countBadge = document.getElementById('bgp-peers-count-badge');
  7877. const navBadge = document.getElementById('dyn-badge-bgp-peers');
  7878. const peers = state.bgpPeers || [];
  7879. if (countBadge) countBadge.innerText = `${peers.length} Peers`;
  7880. if (navBadge) navBadge.innerText = peers.length;
  7881. if (peers.length === 0) {
  7882. tbody.innerHTML = '';
  7883. if (empty) empty.classList.remove('hidden');
  7884. return;
  7885. }
  7886. if (empty) empty.classList.add('hidden');
  7887. const sig = peers.map(p => `${p.name}:${p.state}:${p.uptime}:${p.prefix_received}:${p.prefix_sent}:${p.disabled}`).join(';');
  7888. if (tbody.dataset.sig === sig) return;
  7889. tbody.dataset.sig = sig;
  7890. tbody.innerHTML = peers.map(p => {
  7891. let flagA = !p.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  7892. let flagE = p.state === 'Established' ? '<span class="text-emerald-400 font-bold ml-1" title="Established">E</span>' : '';
  7893. let flagX = p.disabled ? '<span class="text-rose-400 font-bold ml-1" title="Disabled">X</span>' : '';
  7894. let stateBadge = '';
  7895. if (p.disabled) {
  7896. 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>';
  7897. } else if (p.state === 'Established') {
  7898. 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>';
  7899. } else if (p.state === 'Connect' || p.state === 'Active') {
  7900. 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>`;
  7901. } else {
  7902. 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>`;
  7903. }
  7904. return `
  7905. <tr class="hover:bg-slate-800/40 transition">
  7906. <td class="py-2.5 px-3 text-center tracking-wider">${flagA}${flagE}${flagX}</td>
  7907. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(p.name)}</td>
  7908. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(p.remote_address)}</td>
  7909. <td class="py-2.5 px-3">
  7910. <div class="font-bold text-slate-200">AS ${p.remote_as}</div>
  7911. ${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>`}
  7912. </td>
  7913. <td class="py-2.5 px-3">${stateBadge}</td>
  7914. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(p.uptime || '-')}</td>
  7915. <td class="py-2.5 px-3 text-slate-300">
  7916. <span class="text-emerald-400 font-bold">↓ ${p.prefix_received || 0}</span> /
  7917. <span class="text-blue-400 font-bold">↑ ${p.prefix_sent || 0}</span>
  7918. </td>
  7919. <td class="py-2.5 px-3 font-mono text-[11px] whitespace-nowrap">
  7920. ${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> ` : ''}
  7921. ${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>` : ''}
  7922. ${!p.in_filter && !p.out_filter ? '<span class="text-slate-600">-</span>' : ''}
  7923. </td>
  7924. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(p.comment || '')}</td>
  7925. <td class="py-2.5 px-3 text-right space-x-1.5 whitespace-nowrap font-sans">
  7926. <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'}">
  7927. ${p.disabled ? 'Enable' : 'Disable'}
  7928. </button>
  7929. <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">
  7930. Edit
  7931. </button>
  7932. <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">
  7933. Delete
  7934. </button>
  7935. </td>
  7936. </tr>
  7937. `;
  7938. }).join('');
  7939. }
  7940. function renderBgpNetworks() {
  7941. const tbody = document.getElementById('bgp-nets-table-body');
  7942. if (!tbody) return;
  7943. const empty = document.getElementById('bgp-nets-empty');
  7944. const countBadge = document.getElementById('bgp-nets-count-badge');
  7945. const navBadge = document.getElementById('dyn-badge-bgp-nets');
  7946. const nets = state.bgpNets || [];
  7947. if (countBadge) countBadge.innerText = `${nets.length} Networks`;
  7948. if (navBadge) navBadge.innerText = nets.length;
  7949. if (nets.length === 0) {
  7950. tbody.innerHTML = '';
  7951. if (empty) empty.classList.remove('hidden');
  7952. return;
  7953. }
  7954. if (empty) empty.classList.add('hidden');
  7955. const sig = nets.map(n => `${n.network}:${n.disabled}:${n.comment}`).join(';');
  7956. if (tbody.dataset.sig === sig) return;
  7957. tbody.dataset.sig = sig;
  7958. tbody.innerHTML = nets.map(n => `
  7959. <tr class="hover:bg-slate-800/40 transition">
  7960. <td class="py-2.5 px-3 font-semibold text-purple-300 font-mono">${escapeHtml(n.network)}</td>
  7961. <td class="py-2.5 px-3">
  7962. ${n.disabled
  7963. ? '<span class="px-2 py-0.5 rounded-full text-[10px] bg-slate-800 text-slate-400 border border-slate-700">Disabled</span>'
  7964. : '<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>'}
  7965. </td>
  7966. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(n.comment || '')}</td>
  7967. <td class="py-2.5 px-3 text-right space-x-1 font-sans">
  7968. <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">
  7969. Delete
  7970. </button>
  7971. </td>
  7972. </tr>
  7973. `).join('');
  7974. }
  7975. function renderBgpRoutes() {
  7976. const tbody = document.getElementById('bgp-routes-table-body');
  7977. if (!tbody) return;
  7978. const empty = document.getElementById('bgp-routes-empty');
  7979. const countBadge = document.getElementById('bgp-routes-count-badge');
  7980. const navBadge = document.getElementById('dyn-badge-bgp-routes');
  7981. const routes = state.bgpRoutes || [];
  7982. if (countBadge) countBadge.innerText = `${routes.length} Routes`;
  7983. if (navBadge) navBadge.innerText = routes.length;
  7984. if (routes.length === 0) {
  7985. tbody.innerHTML = '';
  7986. if (empty) empty.classList.remove('hidden');
  7987. return;
  7988. }
  7989. if (empty) empty.classList.add('hidden');
  7990. const sig = routes.map(r => `${r.prefix}:${r.next_hop}:${r.metric}:${r.path}`).join(';');
  7991. if (tbody.dataset.sig === sig) return;
  7992. tbody.dataset.sig = sig;
  7993. tbody.innerHTML = routes.map(r => `
  7994. <tr class="hover:bg-slate-800/40 transition">
  7995. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.prefix)}</td>
  7996. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(r.next_hop || '-')}</td>
  7997. <td class="py-2.5 px-3 text-slate-300">${r.metric}</td>
  7998. <td class="py-2.5 px-3 text-slate-300">${r.weight}</td>
  7999. <td class="py-2.5 px-3 text-amber-300">${escapeHtml(r.path || 'i')}</td>
  8000. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.origin || 'IGP')}</td>
  8001. </tr>
  8002. `).join('');
  8003. }
  8004. // =========================================================================
  8005. // ROUTEROS v7 OSPF TABLE RENDERING & SORTING
  8006. // =========================================================================
  8007. function sortOspfTable(tab, col) {
  8008. if (!state.ospfSort) state.ospfSort = {};
  8009. if (!state.ospfSort[tab]) state.ospfSort[tab] = { col: col, asc: true };
  8010. if (state.ospfSort[tab].col === col) {
  8011. state.ospfSort[tab].asc = !state.ospfSort[tab].asc;
  8012. } else {
  8013. state.ospfSort[tab].col = col;
  8014. state.ospfSort[tab].asc = true;
  8015. }
  8016. const asc = state.ospfSort[tab].asc;
  8017. let list = [];
  8018. if (tab === 'instances') list = state.ospfInstances || [];
  8019. else if (tab === 'areas') list = state.ospfAreas || [];
  8020. else if (tab === 'ranges') list = state.ospfAreaRanges || [];
  8021. else if (tab === 'templates') list = state.ospfTemplates || [];
  8022. else if (tab === 'live_ifaces') list = state.ospfLiveInterfaces || [];
  8023. else if (tab === 'snbrs') list = state.ospfStaticNbrs || [];
  8024. else if (tab === 'neighbors') list = state.ospfNeighbors || [];
  8025. else if (tab === 'lsa') list = state.ospfLSA || [];
  8026. list.sort((a, b) => {
  8027. let valA = a[col] ?? '';
  8028. let valB = b[col] ?? '';
  8029. if (typeof valA === 'number' && typeof valB === 'number') {
  8030. return asc ? valA - valB : valB - valA;
  8031. }
  8032. return asc ? String(valA).localeCompare(String(valB)) : String(valB).localeCompare(String(valA));
  8033. });
  8034. if (tab === 'instances') renderOspfInstances();
  8035. else if (tab === 'areas') renderOspfAreas();
  8036. else if (tab === 'ranges') renderOspfAreaRanges();
  8037. else if (tab === 'templates') renderOspfTemplates();
  8038. else if (tab === 'live_ifaces') renderOspfLiveInterfaces();
  8039. else if (tab === 'snbrs') renderOspfStaticNbrs();
  8040. else if (tab === 'neighbors') renderOspfNeighbors();
  8041. else if (tab === 'lsa') renderOspfLSA();
  8042. }
  8043. function selectOspfRow(tab, id) {
  8044. if (!state.selectedOspfRow) state.selectedOspfRow = {};
  8045. state.selectedOspfRow[tab] = id;
  8046. if (tab === 'instances') {
  8047. renderOspfInstances();
  8048. const btnEn = document.getElementById('btn-ospf-inst-enable');
  8049. const btnDis = document.getElementById('btn-ospf-inst-disable');
  8050. const btnRem = document.getElementById('btn-ospf-inst-remove');
  8051. const btnCom = document.getElementById('btn-ospf-inst-comment');
  8052. if (btnEn) btnEn.disabled = false;
  8053. if (btnDis) btnDis.disabled = false;
  8054. if (btnRem) btnRem.disabled = false;
  8055. if (btnCom) btnCom.disabled = false;
  8056. } else if (tab === 'areas') {
  8057. renderOspfAreas();
  8058. const btnEn = document.getElementById('btn-ospf-area-enable');
  8059. const btnDis = document.getElementById('btn-ospf-area-disable');
  8060. const btnRem = document.getElementById('btn-ospf-area-remove');
  8061. const btnCom = document.getElementById('btn-ospf-area-comment');
  8062. if (btnEn) btnEn.disabled = false;
  8063. if (btnDis) btnDis.disabled = false;
  8064. if (btnRem) btnRem.disabled = false;
  8065. if (btnCom) btnCom.disabled = false;
  8066. } else if (tab === 'ranges') {
  8067. renderOspfAreaRanges();
  8068. const btnEn = document.getElementById('btn-ospf-range-enable');
  8069. const btnDis = document.getElementById('btn-ospf-range-disable');
  8070. const btnRem = document.getElementById('btn-ospf-range-remove');
  8071. const btnCom = document.getElementById('btn-ospf-range-comment');
  8072. if (btnEn) btnEn.disabled = false;
  8073. if (btnDis) btnDis.disabled = false;
  8074. if (btnRem) btnRem.disabled = false;
  8075. if (btnCom) btnCom.disabled = false;
  8076. } else if (tab === 'templates') {
  8077. renderOspfTemplates();
  8078. const btnEn = document.getElementById('btn-ospf-tmpl-enable');
  8079. const btnDis = document.getElementById('btn-ospf-tmpl-disable');
  8080. const btnRem = document.getElementById('btn-ospf-tmpl-remove');
  8081. const btnCom = document.getElementById('btn-ospf-tmpl-comment');
  8082. if (btnEn) btnEn.disabled = false;
  8083. if (btnDis) btnDis.disabled = false;
  8084. if (btnRem) btnRem.disabled = false;
  8085. if (btnCom) btnCom.disabled = false;
  8086. } else if (tab === 'snbrs') {
  8087. renderOspfStaticNbrs();
  8088. const btnEn = document.getElementById('btn-ospf-snbr-enable');
  8089. const btnDis = document.getElementById('btn-ospf-snbr-disable');
  8090. const btnRem = document.getElementById('btn-ospf-snbr-remove');
  8091. const btnCom = document.getElementById('btn-ospf-snbr-comment');
  8092. if (btnEn) btnEn.disabled = false;
  8093. if (btnDis) btnDis.disabled = false;
  8094. if (btnRem) btnRem.disabled = false;
  8095. if (btnCom) btnCom.disabled = false;
  8096. }
  8097. }
  8098. // TAB 1: INSTANCES
  8099. function renderOspfInstances() {
  8100. const tbody = document.getElementById('ospf-instances-table-body');
  8101. if (!tbody) return;
  8102. const countEl = document.getElementById('ospf-instances-footer-count');
  8103. const filter = (document.getElementById('filter-ospf-instances')?.value || '').toLowerCase();
  8104. let list = state.ospfInstances || [];
  8105. if (filter) {
  8106. list = list.filter(i => (i.name || '').toLowerCase().includes(filter) || (i.router_id || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  8107. }
  8108. if (countEl) countEl.innerText = list.length;
  8109. const selId = state.selectedOspfRow?.instances;
  8110. tbody.innerHTML = list.map((inst, idx) => {
  8111. const isSel = inst.id === selId;
  8112. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  8113. const flagD = inst.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  8114. return `
  8115. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('instances', '${inst.id}')" ondblclick="openEditOspfInstanceModal('${inst.id}')">
  8116. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  8117. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🔀'}</td>
  8118. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(inst.comment || '')}</td>
  8119. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  8120. <span class="text-sky-400">↳</span> <span>${escapeHtml(inst.name || 'Default')}</span>
  8121. </td>
  8122. <td class="py-1.5 px-3">${inst.version || 2}</td>
  8123. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(inst.vrf || 'main')}</td>
  8124. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(inst.router_id || '192.168.131.56')}</td>
  8125. </tr>
  8126. `;
  8127. }).join('');
  8128. }
  8129. // TAB 2: AREAS
  8130. function renderOspfAreas() {
  8131. const tbody = document.getElementById('ospf-areas-table-body');
  8132. if (!tbody) return;
  8133. const countEl = document.getElementById('ospf-areas-footer-count');
  8134. const filter = (document.getElementById('filter-ospf-areas')?.value || '').toLowerCase();
  8135. let list = state.ospfAreas || [];
  8136. if (filter) {
  8137. list = list.filter(a => (a.name || '').toLowerCase().includes(filter) || (a.area_id || '').toLowerCase().includes(filter) || (a.comment || '').toLowerCase().includes(filter));
  8138. }
  8139. if (countEl) countEl.innerText = list.length;
  8140. const selId = state.selectedOspfRow?.areas;
  8141. tbody.innerHTML = list.map((a, idx) => {
  8142. const isSel = a.id === selId;
  8143. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  8144. const flagD = a.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  8145. return `
  8146. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('areas', '${a.id}')" ondblclick="openEditOspfAreaModal('${a.id}')">
  8147. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  8148. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🌐'}</td>
  8149. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(a.comment || '')}</td>
  8150. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  8151. <span class="text-sky-400">↳</span> <span>${escapeHtml(a.name || 'Default')}</span>
  8152. </td>
  8153. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(a.instance || 'Default')}</td>
  8154. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(a.area_id || '0.0.0.0')}</td>
  8155. <td class="py-1.5 px-3 font-mono text-slate-400">${escapeHtml(a.area_type || 'default')}</td>
  8156. </tr>
  8157. `;
  8158. }).join('');
  8159. }
  8160. // TAB 3: AREA RANGES
  8161. function renderOspfAreaRanges() {
  8162. const tbody = document.getElementById('ospf-ranges-table-body');
  8163. if (!tbody) return;
  8164. const countEl = document.getElementById('ospf-ranges-footer-count');
  8165. const filter = (document.getElementById('filter-ospf-area-ranges')?.value || '').toLowerCase();
  8166. let list = state.ospfAreaRanges || [];
  8167. if (filter) {
  8168. list = list.filter(r => (r.prefix || '').toLowerCase().includes(filter) || (r.area || '').toLowerCase().includes(filter) || (r.comment || '').toLowerCase().includes(filter));
  8169. }
  8170. if (countEl) countEl.innerText = list.length;
  8171. const selId = state.selectedOspfRow?.['area-ranges'];
  8172. tbody.innerHTML = list.map((r, idx) => {
  8173. const isSel = r.id === selId;
  8174. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  8175. const flagD = r.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  8176. return `
  8177. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('ranges', '${r.id}')" ondblclick="openEditOspfAreaRangeModal('${r.id}')">
  8178. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  8179. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🏷'}</td>
  8180. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(r.comment || '')}</td>
  8181. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(r.area || 'Default')}</td>
  8182. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(r.prefix || '')}</td>
  8183. <td class="py-1.5 px-3">${r.cost || 1}</td>
  8184. <td class="py-1.5 px-3">${r.advertise !== false ? 'yes' : 'no'}</td>
  8185. </tr>
  8186. `;
  8187. }).join('');
  8188. }
  8189. // TAB 4: INTERFACE TEMPLATES
  8190. function renderOspfTemplates() {
  8191. const tbody = document.getElementById('ospf-templates-table-body');
  8192. if (!tbody) return;
  8193. const countEl = document.getElementById('ospf-templates-footer-count');
  8194. const filter = (document.getElementById('filter-ospf-templates')?.value || '').toLowerCase();
  8195. let list = state.ospfTemplates || [];
  8196. if (filter) {
  8197. list = list.filter(t => (t.interfaces || t.interface || '').toLowerCase().includes(filter) || (t.networks || t.network || '').toLowerCase().includes(filter) || (t.comment || '').toLowerCase().includes(filter));
  8198. }
  8199. if (countEl) countEl.innerText = list.length;
  8200. const selId = state.selectedOspfRow?.templates;
  8201. tbody.innerHTML = list.map((t, idx) => {
  8202. const isSel = t.id === selId;
  8203. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  8204. const ifaces = t.interfaces || t.interface || 'all';
  8205. const nets = t.networks || t.network || '';
  8206. const flagD = t.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  8207. return `
  8208. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('templates', '${t.id}')" ondblclick="openEditOspfTemplateModal('${t.id}')">
  8209. <td class="py-1.5 px-3 w-8 text-center text-slate-500 font-bold">${idx}</td>
  8210. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🔀'}</td>
  8211. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(t.comment || '')}</td>
  8212. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  8213. <span class="text-sky-400">↳</span> <span>${escapeHtml(ifaces)}</span>
  8214. </td>
  8215. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(t.area || 'Default')}</td>
  8216. <td class="py-1.5 px-3 font-mono text-sky-300">${escapeHtml(nets)}</td>
  8217. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(t.network_type || 'broadcast')}</td>
  8218. <td class="py-1.5 px-3">${t.cost || 1}</td>
  8219. <td class="py-1.5 px-3">${t.priority || 128}</td>
  8220. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(t.auth || t.auth_type || '')}</td>
  8221. </tr>
  8222. `;
  8223. }).join('');
  8224. }
  8225. // TAB 5: LIVE INTERFACES
  8226. function renderOspfLiveInterfaces() {
  8227. const tbody = document.getElementById('ospf-live-interfaces-table-body');
  8228. if (!tbody) return;
  8229. const countEl = document.getElementById('ospf-live-interfaces-footer-count');
  8230. const filter = (document.getElementById('filter-ospf-interfaces')?.value || '').toLowerCase();
  8231. let list = state.ospfLiveInterfaces || [];
  8232. if (filter) {
  8233. list = list.filter(i => (i.interface || '').toLowerCase().includes(filter) || (i.address || '').toLowerCase().includes(filter) || (i.state || '').toLowerCase().includes(filter));
  8234. }
  8235. if (countEl) countEl.innerText = list.length;
  8236. tbody.innerHTML = list.map(i => `
  8237. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  8238. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(i.flags || 'D')}</td>
  8239. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(i.interface || '')}</td>
  8240. <td class="py-1.5 px-3 font-mono text-sky-300 font-medium">${escapeHtml(i.address || '')}</td>
  8241. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(i.area || 'Default')}</td>
  8242. <td class="py-1.5 px-3 text-center text-slate-400">${i.instance_id || 0}</td>
  8243. <td class="py-1.5 px-3 font-mono text-amber-300 lowercase">${escapeHtml(i.state || 'waiting')}</td>
  8244. <td class="py-1.5 px-3">${i.cost || 1}</td>
  8245. <td class="py-1.5 px-3">${i.priority || 128}</td>
  8246. </tr>
  8247. `).join('');
  8248. }
  8249. // TAB 6: STATIC NEIGHBORS
  8250. function renderOspfStaticNbrs() {
  8251. const tbody = document.getElementById('ospf-snbrs-table-body');
  8252. if (!tbody) return;
  8253. const countEl = document.getElementById('ospf-snbrs-footer-count');
  8254. const filter = (document.getElementById('filter-ospf-static-nbrs')?.value || '').toLowerCase();
  8255. let list = state.ospfStaticNbrs || [];
  8256. if (filter) {
  8257. list = list.filter(n => (n.address || '').toLowerCase().includes(filter) || (n.area || '').toLowerCase().includes(filter) || (n.comment || '').toLowerCase().includes(filter));
  8258. }
  8259. if (countEl) countEl.innerText = list.length;
  8260. const selId = state.selectedOspfRow?.['static-nbrs'];
  8261. tbody.innerHTML = list.map((n, idx) => {
  8262. const isSel = n.id === selId;
  8263. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  8264. const flagD = n.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  8265. return `
  8266. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('snbrs', '${n.id}')" ondblclick="openEditOspfStaticNbrModal('${n.id}')">
  8267. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  8268. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '📡'}</td>
  8269. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(n.comment || '')}</td>
  8270. <td class="py-1.5 px-3 font-semibold font-mono text-sky-300">${escapeHtml(n.address || '')}</td>
  8271. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(n.area || 'Default')}</td>
  8272. <td class="py-1.5 px-3">${n.poll_interval || 120}s</td>
  8273. <td class="py-1.5 px-3">${n.cost || 1}</td>
  8274. </tr>
  8275. `;
  8276. }).join('');
  8277. }
  8278. // TAB 7: LIVE NEIGHBORS
  8279. function renderOspfNeighbors() {
  8280. const tbody = document.getElementById('ospf-neighbors-table-body');
  8281. if (!tbody) return;
  8282. const countEl = document.getElementById('ospf-neighbors-footer-count');
  8283. const filter = (document.getElementById('filter-ospf-neighbors')?.value || '').toLowerCase();
  8284. let list = state.ospfNeighbors || [];
  8285. if (filter) {
  8286. list = list.filter(n => (n.address || '').toLowerCase().includes(filter) || (n.state || '').toLowerCase().includes(filter) || (n.instance || '').toLowerCase().includes(filter));
  8287. }
  8288. if (countEl) countEl.innerText = list.length;
  8289. tbody.innerHTML = list.map(n => `
  8290. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  8291. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(n.flags || 'D')}</td>
  8292. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(n.comment || '')}</td>
  8293. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  8294. <span class="text-sky-400">↳</span> <span>${escapeHtml(n.instance || 'Default')}</span>
  8295. </td>
  8296. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(n.area || 'Default')}</td>
  8297. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(n.address || '')}</td>
  8298. <td class="py-1.5 px-3 font-mono font-bold text-emerald-400">${escapeHtml(n.state || 'Full')}</td>
  8299. <td class="py-1.5 px-3 text-slate-400">${n.state_changes ?? 6}</td>
  8300. </tr>
  8301. `).join('');
  8302. }
  8303. // TAB 8: LINK-STATE DATABASE (LSA)
  8304. function renderOspfLSA() {
  8305. const tbody = document.getElementById('ospf-lsa-table-body');
  8306. if (!tbody) return;
  8307. const countEl = document.getElementById('ospf-lsa-footer-count');
  8308. const filter = (document.getElementById('filter-ospf-lsa')?.value || '').toLowerCase();
  8309. let list = state.ospfLSA || [];
  8310. if (filter) {
  8311. list = list.filter(l => (l.type || '').toLowerCase().includes(filter) || (l.originator || '').toLowerCase().includes(filter) || (l.id || '').toLowerCase().includes(filter));
  8312. }
  8313. if (countEl) countEl.innerText = list.length;
  8314. tbody.innerHTML = list.map(l => `
  8315. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  8316. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(l.flags || 'D')}</td>
  8317. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  8318. <span class="text-sky-400">↳</span> <span>${escapeHtml(l.instance || 'Default')}</span>
  8319. </td>
  8320. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(l.area || 'Default')}</td>
  8321. <td class="py-1.5 px-3 font-mono text-amber-300">${escapeHtml(l.type || 'router')}</td>
  8322. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(l.originator || '')}</td>
  8323. <td class="py-1.5 px-3 font-mono text-sky-300 font-medium">${escapeHtml(l.id || '')}</td>
  8324. <td class="py-1.5 px-3 text-slate-500">${escapeHtml(l.link || '')}</td>
  8325. <td class="py-1.5 px-3 text-slate-500">${l.link_index ?? 0}</td>
  8326. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(l.sequence || '')}</td>
  8327. <td class="py-1.5 px-3 text-slate-400">${l.age ?? 0}</td>
  8328. </tr>
  8329. `).join('');
  8330. }
  8331. function renderOspfStatusPill() {
  8332. // Maintained for backward compatibility
  8333. const pill = document.getElementById('ospf-live-status-pill');
  8334. if (!pill) return;
  8335. 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';
  8336. pill.innerText = 'OSPF ACTIVE';
  8337. }
  8338. function renderOspfInterfaces() {
  8339. renderOspfTemplates();
  8340. }
  8341. function renderOspfRoutes() {
  8342. // Routes retained in background
  8343. }
  8344. // BGP Modals & Actions
  8345. function openBgpInstanceModal() {
  8346. const inst = state.bgpInstance || { enabled: false, as: 65001, router_id: '192.168.131.56', hold_time: 180, keepalive_time: 60 };
  8347. document.getElementById('modal-bgp-enabled').checked = !!inst.enabled;
  8348. document.getElementById('modal-bgp-as').value = inst.as || 65001;
  8349. document.getElementById('modal-bgp-router-id').value = inst.router_id || '';
  8350. document.getElementById('modal-bgp-keepalive').value = inst.keepalive_time || 60;
  8351. document.getElementById('modal-bgp-holdtime').value = inst.hold_time || 180;
  8352. document.getElementById('modal-bgp-redist-conn').checked = !!inst.redistribute_connected;
  8353. document.getElementById('modal-bgp-redist-static').checked = !!inst.redistribute_static;
  8354. document.getElementById('modal-bgp-redist-ospf').checked = !!inst.redistribute_ospf;
  8355. document.getElementById('bgp-instance-modal').classList.remove('hidden');
  8356. }
  8357. function closeBgpInstanceModal() {
  8358. document.getElementById('bgp-instance-modal').classList.add('hidden');
  8359. }
  8360. async function submitBgpInstance(e) {
  8361. e.preventDefault();
  8362. const payload = {
  8363. enabled: document.getElementById('modal-bgp-enabled').checked,
  8364. as: parseInt(document.getElementById('modal-bgp-as').value, 10),
  8365. router_id: document.getElementById('modal-bgp-router-id').value.trim(),
  8366. keepalive_time: parseInt(document.getElementById('modal-bgp-keepalive').value, 10),
  8367. hold_time: parseInt(document.getElementById('modal-bgp-holdtime').value, 10),
  8368. redistribute_connected: document.getElementById('modal-bgp-redist-conn').checked,
  8369. redistribute_static: document.getElementById('modal-bgp-redist-static').checked,
  8370. redistribute_ospf: document.getElementById('modal-bgp-redist-ospf').checked
  8371. };
  8372. try {
  8373. const res = await fetch(`${API_BASE}/routing/bgp/instance`, {
  8374. method: 'POST',
  8375. headers: { 'Content-Type': 'application/json' },
  8376. body: JSON.stringify(payload)
  8377. });
  8378. if (res.ok) {
  8379. closeBgpInstanceModal();
  8380. showToast('Success', 'BGP instance configuration updated', 'success');
  8381. loadDynamicRouting();
  8382. } else {
  8383. const err = await res.json();
  8384. showToast('Error', err.error || 'Failed to update BGP instance', 'error');
  8385. }
  8386. } catch (err) {
  8387. showToast('Error', err.message, 'error');
  8388. }
  8389. }
  8390. // ----------------- BGP Peer Connection Modal (RouterOS v7) -----------------
  8391. function switchBgpPeerModalTab(tab) {
  8392. const tabs = ['general', 'extra', 'attributes', 'filter'];
  8393. tabs.forEach(t => {
  8394. const pane = document.getElementById(`bgp-peer-tab-${t}`);
  8395. const btn = document.getElementById(`bgp-peer-tab-btn-${t}`);
  8396. if (t === tab) {
  8397. if (pane) pane.classList.remove('hidden');
  8398. if (btn) btn.className = 'px-4 py-2 text-xs font-bold border-b-2 border-cyan-500 text-white transition';
  8399. } else {
  8400. if (pane) pane.classList.add('hidden');
  8401. 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';
  8402. }
  8403. });
  8404. }
  8405. function addOutputNetworkRow(val = '') {
  8406. const container = document.getElementById('modal-bgp-output-networks-container');
  8407. if (!container) return;
  8408. const row = document.createElement('div');
  8409. row.className = 'flex items-center gap-2 output-net-row';
  8410. row.innerHTML = `
  8411. <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">
  8412. <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>
  8413. `;
  8414. container.appendChild(row);
  8415. }
  8416. function parseBgpTime(val) {
  8417. if (!val) return 0;
  8418. val = String(val).trim();
  8419. if (val.includes(':')) {
  8420. const parts = val.split(':').map(x => parseInt(x, 10) || 0);
  8421. if (parts.length === 3) return parts[0] * 3600 + parts[1] * 60 + parts[2];
  8422. if (parts.length === 2) return parts[0] * 60 + parts[1];
  8423. }
  8424. return parseInt(val, 10) || 0;
  8425. }
  8426. function formatBgpTime(secs) {
  8427. if (!secs || secs <= 0) return '00:00:00';
  8428. const h = Math.floor(secs / 3600);
  8429. const m = Math.floor((secs % 3600) / 60);
  8430. const s = secs % 60;
  8431. return `${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`;
  8432. }
  8433. function populateBgpRoutingTables() {
  8434. const sel = document.getElementById('modal-bgp-peer-routing-table');
  8435. if (!sel) return;
  8436. const cur = sel.value || 'main';
  8437. sel.innerHTML = '<option value="main">main</option>';
  8438. (state.routingTables || []).forEach(t => {
  8439. if (t.name !== 'main') {
  8440. const opt = document.createElement('option');
  8441. opt.value = t.name;
  8442. opt.innerText = t.name;
  8443. sel.appendChild(opt);
  8444. }
  8445. });
  8446. sel.value = cur;
  8447. }
  8448. function openAddBgpPeerModal() {
  8449. document.getElementById('bgp-peer-form').reset();
  8450. document.getElementById('modal-bgp-peer-id').value = '';
  8451. document.getElementById('bgp-peer-modal-title').innerText = 'New...';
  8452. // General Tab
  8453. document.getElementById('modal-bgp-peer-enabled').checked = true;
  8454. document.getElementById('modal-bgp-peer-comment').value = '';
  8455. document.getElementById('modal-bgp-peer-name').value = '';
  8456. if (document.getElementById('modal-bgp-peer-instance')) document.getElementById('modal-bgp-peer-instance').value = 'bgp-instance-1';
  8457. if (document.getElementById('modal-bgp-peer-template')) document.getElementById('modal-bgp-peer-template').value = '';
  8458. document.getElementById('modal-bgp-peer-local-as').value = '';
  8459. document.getElementById('modal-bgp-peer-afi-ip').checked = true;
  8460. document.getElementById('modal-bgp-peer-afi-ipv6').checked = false;
  8461. if (document.getElementById('modal-bgp-peer-afi-l2vpn')) document.getElementById('modal-bgp-peer-afi-l2vpn').checked = false;
  8462. if (document.getElementById('modal-bgp-peer-afi-vpnv4')) document.getElementById('modal-bgp-peer-afi-vpnv4').checked = false;
  8463. if (document.getElementById('modal-bgp-peer-afi-l2vpn-cisco')) document.getElementById('modal-bgp-peer-afi-l2vpn-cisco').checked = false;
  8464. document.getElementById('modal-bgp-peer-router-id').value = '';
  8465. document.getElementById('modal-bgp-peer-remote-addr').value = '';
  8466. document.getElementById('modal-bgp-peer-remote-port').value = '';
  8467. document.getElementById('modal-bgp-peer-remote-as').value = '';
  8468. if (document.getElementById('modal-bgp-peer-remote-allow-as')) document.getElementById('modal-bgp-peer-remote-allow-as').value = '';
  8469. document.getElementById('modal-bgp-peer-local-addr').value = '';
  8470. document.getElementById('modal-bgp-peer-local-port').value = '';
  8471. document.getElementById('modal-bgp-peer-local-role').value = 'ebgp';
  8472. document.getElementById('modal-bgp-peer-password').value = '';
  8473. document.getElementById('modal-bgp-peer-multihop').checked = false;
  8474. if (document.getElementById('modal-bgp-peer-tx-ttl')) document.getElementById('modal-bgp-peer-tx-ttl').value = '';
  8475. if (document.getElementById('modal-bgp-peer-rx-min-ttl')) document.getElementById('modal-bgp-peer-rx-min-ttl').value = '';
  8476. document.getElementById('modal-bgp-peer-connect').checked = true;
  8477. document.getElementById('modal-bgp-peer-listen').checked = true;
  8478. // Extra Tab
  8479. document.getElementById('modal-bgp-peer-holdtime').value = '00:00:30';
  8480. document.getElementById('modal-bgp-peer-keepalive').value = '00:00:10';
  8481. if (document.getElementById('modal-bgp-peer-use-bfd')) document.getElementById('modal-bgp-peer-use-bfd').checked = false;
  8482. if (document.getElementById('modal-bgp-peer-vrf')) document.getElementById('modal-bgp-peer-vrf').value = 'main';
  8483. if (document.getElementById('modal-bgp-peer-no-client-reflect')) document.getElementById('modal-bgp-peer-no-client-reflect').checked = true;
  8484. document.getElementById('modal-bgp-peer-redist-conn').checked = false;
  8485. document.getElementById('modal-bgp-peer-redist-static').checked = true;
  8486. if (document.getElementById('modal-bgp-peer-redist-rip')) document.getElementById('modal-bgp-peer-redist-rip').checked = false;
  8487. document.getElementById('modal-bgp-peer-redist-ospf').checked = false;
  8488. document.getElementById('modal-bgp-peer-redist-bgp').checked = false;
  8489. if (document.getElementById('modal-bgp-peer-redist-vpn')) document.getElementById('modal-bgp-peer-redist-vpn').checked = false;
  8490. if (document.getElementById('modal-bgp-peer-redist-dhcp')) document.getElementById('modal-bgp-peer-redist-dhcp').checked = false;
  8491. if (document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn')) document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn').checked = false;
  8492. if (document.getElementById('modal-bgp-peer-redist-slaac')) document.getElementById('modal-bgp-peer-redist-slaac').checked = false;
  8493. document.getElementById('modal-bgp-peer-default-orig').checked = false;
  8494. if (document.getElementById('modal-bgp-peer-network-blackhole')) document.getElementById('modal-bgp-peer-network-blackhole').checked = false;
  8495. if (document.getElementById('modal-bgp-peer-no-early-cut')) document.getElementById('modal-bgp-peer-no-early-cut').checked = false;
  8496. if (document.getElementById('modal-bgp-peer-keep-sent-attrs')) document.getElementById('modal-bgp-peer-keep-sent-attrs').checked = false;
  8497. if (document.getElementById('modal-bgp-peer-input-affinity')) document.getElementById('modal-bgp-peer-input-affinity').value = '';
  8498. if (document.getElementById('modal-bgp-peer-output-affinity')) document.getElementById('modal-bgp-peer-output-affinity').value = '';
  8499. // Attributes Tab
  8500. document.getElementById('modal-bgp-peer-nexthop-choice').value = 'force-self';
  8501. document.getElementById('modal-bgp-peer-default-prepend').value = 0;
  8502. document.getElementById('modal-bgp-peer-allow-as-in').value = 0;
  8503. if (document.getElementById('modal-bgp-peer-ignore-as-path-len')) document.getElementById('modal-bgp-peer-ignore-as-path-len').checked = false;
  8504. document.getElementById('modal-bgp-peer-remove-priv-as').checked = false;
  8505. document.getElementById('modal-bgp-peer-as-override').checked = false;
  8506. // Filter Tab
  8507. populateFilterChainsDatalist();
  8508. document.getElementById('modal-bgp-peer-in-filter').value = '';
  8509. if (document.getElementById('modal-bgp-peer-in-accept-nlri')) document.getElementById('modal-bgp-peer-in-accept-nlri').value = '';
  8510. if (document.getElementById('modal-bgp-peer-in-accept-comm')) document.getElementById('modal-bgp-peer-in-accept-comm').value = '';
  8511. if (document.getElementById('modal-bgp-peer-in-accept-ext-comm')) document.getElementById('modal-bgp-peer-in-accept-ext-comm').value = '';
  8512. if (document.getElementById('modal-bgp-peer-in-accept-large-comm')) document.getElementById('modal-bgp-peer-in-accept-large-comm').value = '';
  8513. if (document.getElementById('modal-bgp-peer-in-filter-comm')) document.getElementById('modal-bgp-peer-in-filter-comm').value = '';
  8514. if (document.getElementById('modal-bgp-peer-in-filter-ext-comm')) document.getElementById('modal-bgp-peer-in-filter-ext-comm').value = '';
  8515. if (document.getElementById('modal-bgp-peer-in-filter-large-comm')) document.getElementById('modal-bgp-peer-in-filter-large-comm').value = '';
  8516. if (document.getElementById('modal-bgp-peer-in-filter-unknown')) document.getElementById('modal-bgp-peer-in-filter-unknown').checked = false;
  8517. document.getElementById('modal-bgp-peer-out-filter').value = '';
  8518. if (document.getElementById('modal-bgp-peer-out-selection-policy')) document.getElementById('modal-bgp-peer-out-selection-policy').value = 'disabled';
  8519. if (document.getElementById('modal-bgp-peer-out-network-name')) document.getElementById('modal-bgp-peer-out-network-name').value = '';
  8520. populateBgpRoutingTables();
  8521. const container = document.getElementById('modal-bgp-output-networks-container');
  8522. if (container) {
  8523. container.innerHTML = '';
  8524. addOutputNetworkRow('');
  8525. }
  8526. const removeBtn = document.getElementById('modal-btn-remove-peer');
  8527. if (removeBtn) removeBtn.classList.add('hidden');
  8528. switchBgpPeerModalTab('general');
  8529. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  8530. }
  8531. function populateFilterChainsDatalist() {
  8532. const dl = document.getElementById('filter-chains-list');
  8533. if (!dl) return;
  8534. const chains = new Set();
  8535. (state.routingFilters || []).forEach(f => {
  8536. if (f.chain) chains.add(f.chain);
  8537. });
  8538. if (chains.size === 0) {
  8539. chains.add('awmn');
  8540. chains.add('bgp-in');
  8541. chains.add('bgp-out');
  8542. }
  8543. dl.innerHTML = '';
  8544. chains.forEach(c => {
  8545. const opt = document.createElement('option');
  8546. opt.value = c;
  8547. dl.appendChild(opt);
  8548. });
  8549. }
  8550. function openEditBgpPeerModal(id) {
  8551. const p = (state.bgpPeers || []).find(item => item.id === id);
  8552. if (!p) return;
  8553. populateBgpRoutingTables();
  8554. populateFilterChainsDatalist();
  8555. document.getElementById('modal-bgp-peer-id').value = p.id;
  8556. document.getElementById('bgp-peer-modal-title').innerText = p.name || p.id;
  8557. // General Tab
  8558. document.getElementById('modal-bgp-peer-enabled').checked = p.enabled !== false && !p.disabled;
  8559. document.getElementById('modal-bgp-peer-comment').value = p.comment || '';
  8560. document.getElementById('modal-bgp-peer-name').value = p.name || '';
  8561. if (document.getElementById('modal-bgp-peer-instance')) document.getElementById('modal-bgp-peer-instance').value = p.instance || 'bgp-instance-1';
  8562. if (document.getElementById('modal-bgp-peer-template')) document.getElementById('modal-bgp-peer-template').value = p.template || '';
  8563. document.getElementById('modal-bgp-peer-local-as').value = p.local_as || '';
  8564. document.getElementById('modal-bgp-peer-router-id').value = p.router_id || '';
  8565. document.getElementById('modal-bgp-peer-afi-ip').checked = true;
  8566. document.getElementById('modal-bgp-peer-afi-ipv6').checked = p.afi === 'ipv6';
  8567. document.getElementById('modal-bgp-peer-remote-addr').value = p.remote_address || '';
  8568. document.getElementById('modal-bgp-peer-remote-port').value = p.remote_port || '';
  8569. document.getElementById('modal-bgp-peer-remote-as').value = p.remote_as || '';
  8570. if (document.getElementById('modal-bgp-peer-remote-allow-as')) document.getElementById('modal-bgp-peer-remote-allow-as').value = p.remote_allow_as || '';
  8571. document.getElementById('modal-bgp-peer-local-addr').value = p.local_address || '';
  8572. document.getElementById('modal-bgp-peer-local-port').value = p.local_port || '';
  8573. document.getElementById('modal-bgp-peer-local-role').value = p.local_role || 'ebgp';
  8574. document.getElementById('modal-bgp-peer-password').value = p.password || '';
  8575. document.getElementById('modal-bgp-peer-multihop').checked = !!p.multihop;
  8576. if (document.getElementById('modal-bgp-peer-tx-ttl')) document.getElementById('modal-bgp-peer-tx-ttl').value = p.tx_ttl || '';
  8577. if (document.getElementById('modal-bgp-peer-rx-min-ttl')) document.getElementById('modal-bgp-peer-rx-min-ttl').value = p.rx_min_ttl || '';
  8578. document.getElementById('modal-bgp-peer-connect').checked = p.connect !== false;
  8579. document.getElementById('modal-bgp-peer-listen').checked = p.listen !== false;
  8580. // Extra Tab
  8581. document.getElementById('modal-bgp-peer-holdtime').value = p.hold_time ? formatBgpTime(p.hold_time) : '00:00:30';
  8582. document.getElementById('modal-bgp-peer-keepalive').value = p.keepalive_time ? formatBgpTime(p.keepalive_time) : '00:00:10';
  8583. if (document.getElementById('modal-bgp-peer-use-bfd')) document.getElementById('modal-bgp-peer-use-bfd').checked = !!p.use_bfd;
  8584. document.getElementById('modal-bgp-peer-routing-table').value = p.routing_table || 'main';
  8585. if (document.getElementById('modal-bgp-peer-vrf')) document.getElementById('modal-bgp-peer-vrf').value = p.vrf || 'main';
  8586. if (document.getElementById('modal-bgp-peer-no-client-reflect')) document.getElementById('modal-bgp-peer-no-client-reflect').checked = p.no_client_reflect !== false;
  8587. document.getElementById('modal-bgp-peer-redist-conn').checked = !!p.redist_connected;
  8588. document.getElementById('modal-bgp-peer-redist-static').checked = p.redist_static !== false;
  8589. if (document.getElementById('modal-bgp-peer-redist-rip')) document.getElementById('modal-bgp-peer-redist-rip').checked = !!p.redist_rip;
  8590. document.getElementById('modal-bgp-peer-redist-ospf').checked = !!p.redist_ospf;
  8591. document.getElementById('modal-bgp-peer-redist-bgp').checked = !!p.redist_bgp;
  8592. if (document.getElementById('modal-bgp-peer-redist-vpn')) document.getElementById('modal-bgp-peer-redist-vpn').checked = !!p.redist_vpn;
  8593. if (document.getElementById('modal-bgp-peer-redist-dhcp')) document.getElementById('modal-bgp-peer-redist-dhcp').checked = !!p.redist_dhcp;
  8594. 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;
  8595. if (document.getElementById('modal-bgp-peer-redist-slaac')) document.getElementById('modal-bgp-peer-redist-slaac').checked = !!p.redist_slaac;
  8596. document.getElementById('modal-bgp-peer-default-orig').checked = !!p.default_originate;
  8597. if (document.getElementById('modal-bgp-peer-network-blackhole')) document.getElementById('modal-bgp-peer-network-blackhole').checked = !!p.network_blackhole;
  8598. if (document.getElementById('modal-bgp-peer-no-early-cut')) document.getElementById('modal-bgp-peer-no-early-cut').checked = !!p.no_early_cut;
  8599. if (document.getElementById('modal-bgp-peer-keep-sent-attrs')) document.getElementById('modal-bgp-peer-keep-sent-attrs').checked = !!p.keep_sent_attrs;
  8600. if (document.getElementById('modal-bgp-peer-input-affinity')) document.getElementById('modal-bgp-peer-input-affinity').value = p.input_affinity || '';
  8601. if (document.getElementById('modal-bgp-peer-output-affinity')) document.getElementById('modal-bgp-peer-output-affinity').value = p.output_affinity || '';
  8602. // Attributes Tab
  8603. document.getElementById('modal-bgp-peer-nexthop-choice').value = p.nexthop_choice || (p.nexthop_self ? 'force-self' : 'default');
  8604. document.getElementById('modal-bgp-peer-default-prepend').value = p.default_prepend || 0;
  8605. document.getElementById('modal-bgp-peer-allow-as-in').value = p.allow_as_in || 0;
  8606. 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;
  8607. document.getElementById('modal-bgp-peer-remove-priv-as').checked = !!p.remove_private_as;
  8608. document.getElementById('modal-bgp-peer-as-override').checked = !!p.as_override;
  8609. // Filter Tab
  8610. document.getElementById('modal-bgp-peer-in-filter').value = p.in_filter || '';
  8611. if (document.getElementById('modal-bgp-peer-in-accept-nlri')) document.getElementById('modal-bgp-peer-in-accept-nlri').value = p.in_accept_nlri || '';
  8612. if (document.getElementById('modal-bgp-peer-in-accept-comm')) document.getElementById('modal-bgp-peer-in-accept-comm').value = p.in_accept_communities || '';
  8613. 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 || '';
  8614. 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 || '';
  8615. if (document.getElementById('modal-bgp-peer-in-filter-comm')) document.getElementById('modal-bgp-peer-in-filter-comm').value = p.in_filter_communities || '';
  8616. 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 || '';
  8617. 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 || '';
  8618. if (document.getElementById('modal-bgp-peer-in-filter-unknown')) document.getElementById('modal-bgp-peer-in-filter-unknown').checked = !!p.in_filter_unknown;
  8619. document.getElementById('modal-bgp-peer-out-filter').value = p.out_filter || '';
  8620. if (document.getElementById('modal-bgp-peer-out-selection-policy')) document.getElementById('modal-bgp-peer-out-selection-policy').value = p.out_selection_policy || 'disabled';
  8621. if (document.getElementById('modal-bgp-peer-out-network-name')) document.getElementById('modal-bgp-peer-out-network-name').value = p.output_network || '';
  8622. // Output Networks
  8623. const container = document.getElementById('modal-bgp-output-networks-container');
  8624. if (container) {
  8625. container.innerHTML = '';
  8626. if (p.output_networks && p.output_networks.length > 0) {
  8627. p.output_networks.forEach(net => addOutputNetworkRow(net));
  8628. } else {
  8629. addOutputNetworkRow('');
  8630. }
  8631. }
  8632. const removeBtn = document.getElementById('modal-btn-remove-peer');
  8633. if (removeBtn) removeBtn.classList.remove('hidden');
  8634. switchBgpPeerModalTab('general');
  8635. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  8636. }
  8637. function copyCurrentBgpPeer() {
  8638. document.getElementById('modal-bgp-peer-id').value = '';
  8639. const nameEl = document.getElementById('modal-bgp-peer-name');
  8640. if (nameEl) nameEl.value = (nameEl.value || 'peer') + '-copy';
  8641. document.getElementById('bgp-peer-modal-title').innerText = 'New...';
  8642. const removeBtn = document.getElementById('modal-btn-remove-peer');
  8643. if (removeBtn) removeBtn.classList.add('hidden');
  8644. showToast('Cloned', 'BGP connection copied to new draft', 'info');
  8645. }
  8646. function removeCurrentBgpPeer() {
  8647. const id = document.getElementById('modal-bgp-peer-id')?.value;
  8648. if (!id) return;
  8649. deleteBgpPeer(id);
  8650. closeBgpPeerModal();
  8651. }
  8652. function closeBgpPeerModal() {
  8653. document.getElementById('bgp-peer-modal').classList.add('hidden');
  8654. }
  8655. function getBgpPeerFormData() {
  8656. const netInputs = document.querySelectorAll('#modal-bgp-output-networks-container .output-net-row input');
  8657. const outputNetworks = [];
  8658. netInputs.forEach(inp => {
  8659. const v = inp.value.trim();
  8660. if (v) outputNetworks.push(v);
  8661. });
  8662. const enabled = document.getElementById('modal-bgp-peer-enabled').checked;
  8663. return {
  8664. id: document.getElementById('modal-bgp-peer-id').value,
  8665. name: document.getElementById('modal-bgp-peer-name').value.trim(),
  8666. enabled: enabled,
  8667. disabled: !enabled,
  8668. comment: document.getElementById('modal-bgp-peer-comment').value.trim(),
  8669. instance: document.getElementById('modal-bgp-peer-instance')?.value.trim() || 'bgp-instance-1',
  8670. template: document.getElementById('modal-bgp-peer-template')?.value.trim() || '',
  8671. local_as: parseInt(document.getElementById('modal-bgp-peer-local-as')?.value, 10) || 0,
  8672. router_id: document.getElementById('modal-bgp-peer-router-id').value.trim(),
  8673. afi: document.getElementById('modal-bgp-peer-afi-ipv6').checked ? 'ipv6' : 'ip',
  8674. remote_address: document.getElementById('modal-bgp-peer-remote-addr').value.trim(),
  8675. remote_port: parseInt(document.getElementById('modal-bgp-peer-remote-port').value, 10) || 0,
  8676. remote_as: parseInt(document.getElementById('modal-bgp-peer-remote-as').value, 10) || 0,
  8677. remote_allow_as: document.getElementById('modal-bgp-peer-remote-allow-as')?.value.trim() || '',
  8678. local_address: document.getElementById('modal-bgp-peer-local-addr').value.trim(),
  8679. local_port: parseInt(document.getElementById('modal-bgp-peer-local-port').value, 10) || 0,
  8680. local_role: document.getElementById('modal-bgp-peer-local-role').value,
  8681. password: document.getElementById('modal-bgp-peer-password').value,
  8682. multihop: document.getElementById('modal-bgp-peer-multihop').checked,
  8683. tx_ttl: parseInt(document.getElementById('modal-bgp-peer-tx-ttl')?.value, 10) || 0,
  8684. rx_min_ttl: parseInt(document.getElementById('modal-bgp-peer-rx-min-ttl')?.value, 10) || 0,
  8685. connect: document.getElementById('modal-bgp-peer-connect').checked,
  8686. listen: document.getElementById('modal-bgp-peer-listen').checked,
  8687. hold_time: parseBgpTime(document.getElementById('modal-bgp-peer-holdtime').value),
  8688. keepalive_time: parseBgpTime(document.getElementById('modal-bgp-peer-keepalive').value),
  8689. use_bfd: document.getElementById('modal-bgp-peer-use-bfd')?.checked || false,
  8690. routing_table: document.getElementById('modal-bgp-peer-routing-table').value,
  8691. vrf: document.getElementById('modal-bgp-peer-vrf')?.value.trim() || 'main',
  8692. no_client_reflect: document.getElementById('modal-bgp-peer-no-client-reflect')?.checked || false,
  8693. redist_connected: document.getElementById('modal-bgp-peer-redist-conn').checked,
  8694. redist_static: document.getElementById('modal-bgp-peer-redist-static').checked,
  8695. redist_rip: document.getElementById('modal-bgp-peer-redist-rip')?.checked || false,
  8696. redist_ospf: document.getElementById('modal-bgp-peer-redist-ospf').checked,
  8697. redist_bgp: document.getElementById('modal-bgp-peer-redist-bgp').checked,
  8698. redist_vpn: document.getElementById('modal-bgp-peer-redist-vpn')?.checked || false,
  8699. redist_dhcp: document.getElementById('modal-bgp-peer-redist-dhcp')?.checked || false,
  8700. redist_bgp_mpls_vpn: document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn')?.checked || false,
  8701. redist_slaac: document.getElementById('modal-bgp-peer-redist-slaac')?.checked || false,
  8702. default_originate: document.getElementById('modal-bgp-peer-default-orig').checked,
  8703. network_blackhole: document.getElementById('modal-bgp-peer-network-blackhole')?.checked || false,
  8704. no_early_cut: document.getElementById('modal-bgp-peer-no-early-cut')?.checked || false,
  8705. keep_sent_attrs: document.getElementById('modal-bgp-peer-keep-sent-attrs')?.checked || false,
  8706. input_affinity: (document.getElementById('modal-bgp-peer-input-affinity')?.value || '').trim(),
  8707. output_affinity: (document.getElementById('modal-bgp-peer-output-affinity')?.value || '').trim(),
  8708. nexthop_choice: document.getElementById('modal-bgp-peer-nexthop-choice').value,
  8709. nexthop_self: document.getElementById('modal-bgp-peer-nexthop-choice').value === 'force-self',
  8710. default_prepend: parseInt(document.getElementById('modal-bgp-peer-default-prepend').value, 10) || 0,
  8711. allow_as_in: parseInt(document.getElementById('modal-bgp-peer-allow-as-in').value, 10) || 0,
  8712. ignore_as_path_len: document.getElementById('modal-bgp-peer-ignore-as-path-len')?.checked || false,
  8713. remove_private_as: document.getElementById('modal-bgp-peer-remove-priv-as').checked,
  8714. as_override: document.getElementById('modal-bgp-peer-as-override').checked,
  8715. in_filter: (document.getElementById('modal-bgp-peer-in-filter')?.value || '').trim(),
  8716. in_accept_nlri: (document.getElementById('modal-bgp-peer-in-accept-nlri')?.value || '').trim(),
  8717. in_accept_communities: (document.getElementById('modal-bgp-peer-in-accept-comm')?.value || '').trim(),
  8718. in_accept_ext_communities: (document.getElementById('modal-bgp-peer-in-accept-ext-comm')?.value || '').trim(),
  8719. in_accept_large_communities: (document.getElementById('modal-bgp-peer-in-accept-large-comm')?.value || '').trim(),
  8720. in_filter_communities: (document.getElementById('modal-bgp-peer-in-filter-comm')?.value || '').trim(),
  8721. in_filter_ext_communities: (document.getElementById('modal-bgp-peer-in-filter-ext-comm')?.value || '').trim(),
  8722. in_filter_large_communities: (document.getElementById('modal-bgp-peer-in-filter-large-comm')?.value || '').trim(),
  8723. in_filter_unknown: document.getElementById('modal-bgp-peer-in-filter-unknown')?.checked || false,
  8724. out_filter: (document.getElementById('modal-bgp-peer-out-filter')?.value || '').trim(),
  8725. out_selection_policy: document.getElementById('modal-bgp-peer-out-selection-policy')?.value || 'disabled',
  8726. output_network: (document.getElementById('modal-bgp-peer-out-network-name')?.value || '').trim(),
  8727. output_networks: outputNetworks
  8728. };
  8729. }
  8730. async function submitBgpPeer(e) {
  8731. if (e) e.preventDefault();
  8732. const payload = getBgpPeerFormData();
  8733. try {
  8734. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  8735. method: 'POST',
  8736. headers: { 'Content-Type': 'application/json' },
  8737. body: JSON.stringify(payload)
  8738. });
  8739. if (res.ok) {
  8740. closeBgpPeerModal();
  8741. showToast('Success', 'BGP Connection saved', 'success');
  8742. loadDynamicRouting();
  8743. } else {
  8744. const err = await res.json();
  8745. showToast('Error', err.error || 'Failed to save peer', 'error');
  8746. }
  8747. } catch (err) {
  8748. showToast('Error', err.message, 'error');
  8749. }
  8750. }
  8751. async function applyBgpPeerModal(e) {
  8752. if (e) e.preventDefault();
  8753. const payload = getBgpPeerFormData();
  8754. try {
  8755. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  8756. method: 'POST',
  8757. headers: { 'Content-Type': 'application/json' },
  8758. body: JSON.stringify(payload)
  8759. });
  8760. if (res.ok) {
  8761. const data = await res.json();
  8762. if (data.peer && data.peer.id) {
  8763. document.getElementById('modal-bgp-peer-id').value = data.peer.id;
  8764. document.getElementById('bgp-peer-modal-title').innerText = data.peer.name || data.peer.id;
  8765. document.getElementById('modal-btn-remove-peer')?.classList.remove('hidden');
  8766. }
  8767. showToast('Applied', 'BGP Connection applied', 'success');
  8768. loadDynamicRouting();
  8769. } else {
  8770. const err = await res.json();
  8771. showToast('Error', err.error || 'Failed to apply peer', 'error');
  8772. }
  8773. } catch (err) {
  8774. showToast('Error', err.message, 'error');
  8775. }
  8776. }
  8777. async function deleteBgpPeer(id) {
  8778. if (!confirm('Are you sure you want to delete this BGP peer connection?')) return;
  8779. try {
  8780. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8781. if (res.ok) {
  8782. showToast('Deleted', 'BGP peer removed', 'success');
  8783. loadDynamicRouting();
  8784. }
  8785. } catch (err) {
  8786. showToast('Error', err.message, 'error');
  8787. }
  8788. }
  8789. async function toggleBgpPeerState(id, disabled) {
  8790. try {
  8791. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}/state`, {
  8792. method: 'POST',
  8793. headers: { 'Content-Type': 'application/json' },
  8794. body: JSON.stringify({ disabled })
  8795. });
  8796. if (res.ok) {
  8797. showToast('Updated', `Peer ${disabled ? 'disabled' : 'enabled'}`, 'success');
  8798. loadDynamicRouting();
  8799. }
  8800. } catch (err) {
  8801. showToast('Error', err.message, 'error');
  8802. }
  8803. }
  8804. function openAddBgpNetworkModal() {
  8805. document.getElementById('bgp-network-form').reset();
  8806. document.getElementById('modal-bgp-net-id').value = '';
  8807. document.getElementById('bgp-network-modal').classList.remove('hidden');
  8808. }
  8809. function closeBgpNetworkModal() {
  8810. document.getElementById('bgp-network-modal').classList.add('hidden');
  8811. }
  8812. async function submitBgpNetwork(e) {
  8813. e.preventDefault();
  8814. const payload = {
  8815. id: document.getElementById('modal-bgp-net-id').value,
  8816. network: document.getElementById('modal-bgp-net-cidr').value.trim(),
  8817. comment: document.getElementById('modal-bgp-net-comment').value.trim(),
  8818. disabled: document.getElementById('modal-bgp-net-disabled').checked
  8819. };
  8820. try {
  8821. const res = await fetch(`${API_BASE}/routing/bgp/networks`, {
  8822. method: 'POST',
  8823. headers: { 'Content-Type': 'application/json' },
  8824. body: JSON.stringify(payload)
  8825. });
  8826. if (res.ok) {
  8827. closeBgpNetworkModal();
  8828. showToast('Success', 'BGP network advertisement saved', 'success');
  8829. loadDynamicRouting();
  8830. } else {
  8831. const err = await res.json();
  8832. showToast('Error', err.error || 'Failed to save network', 'error');
  8833. }
  8834. } catch (err) {
  8835. showToast('Error', err.message, 'error');
  8836. }
  8837. }
  8838. async function deleteBgpNetwork(id) {
  8839. if (!confirm('Are you sure you want to stop announcing this network?')) return;
  8840. try {
  8841. const res = await fetch(`${API_BASE}/routing/bgp/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8842. if (res.ok) {
  8843. showToast('Deleted', 'Network advertisement removed', 'success');
  8844. loadDynamicRouting();
  8845. }
  8846. } catch (err) {
  8847. showToast('Error', err.message, 'error');
  8848. }
  8849. }
  8850. // =========================================================================
  8851. // ROUTEROS v7 OSPF MODALS & ACTIONS
  8852. // =========================================================================
  8853. // --- 1. OSPF INSTANCE ---
  8854. function openOspfInstanceModal(id = null) {
  8855. const isEdit = !!id;
  8856. const inst = (state.ospfInstances || []).find(i => i.id === id) || {
  8857. id: '',
  8858. name: 'Default',
  8859. version: 2,
  8860. vrf: 'main',
  8861. router_id: '192.168.131.56',
  8862. routing_table: 'main',
  8863. enabled: true,
  8864. redistribute_connected: false,
  8865. redistribute_static: true,
  8866. redistribute_bgp: false,
  8867. comment: ''
  8868. };
  8869. document.getElementById('ospf-instance-modal-title').innerText = isEdit ? inst.name : 'New...';
  8870. document.getElementById('modal-ospf-inst-id').value = isEdit ? inst.id : '';
  8871. document.getElementById('modal-ospf-inst-enabled').checked = !inst.disabled;
  8872. document.getElementById('modal-ospf-inst-comment').value = inst.comment || '';
  8873. document.getElementById('modal-ospf-inst-name').value = inst.name || 'Default';
  8874. document.getElementById('modal-ospf-inst-version').value = inst.version || 2;
  8875. document.getElementById('modal-ospf-inst-vrf').value = inst.vrf || 'main';
  8876. document.getElementById('modal-ospf-inst-router-id').value = inst.router_id || '';
  8877. document.getElementById('modal-ospf-inst-routing-table').value = inst.routing_table || 'main';
  8878. document.getElementById('modal-ospf-inst-redist-conn').checked = !!inst.redistribute_connected;
  8879. document.getElementById('modal-ospf-inst-redist-static').checked = inst.redistribute_static !== false;
  8880. document.getElementById('modal-ospf-inst-redist-bgp').checked = !!inst.redistribute_bgp;
  8881. const btnRem = document.getElementById('btn-ospf-inst-modal-remove');
  8882. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  8883. document.getElementById('ospf-instance-modal').classList.remove('hidden');
  8884. }
  8885. function openEditOspfInstanceModal(id) {
  8886. openOspfInstanceModal(id);
  8887. }
  8888. function closeOspfInstanceModal() {
  8889. document.getElementById('ospf-instance-modal').classList.add('hidden');
  8890. }
  8891. async function submitOspfInstance(e) {
  8892. if (e) e.preventDefault();
  8893. const payload = {
  8894. id: document.getElementById('modal-ospf-inst-id').value,
  8895. name: document.getElementById('modal-ospf-inst-name').value.trim() || 'Default',
  8896. version: parseInt(document.getElementById('modal-ospf-inst-version').value, 10) || 2,
  8897. vrf: document.getElementById('modal-ospf-inst-vrf').value.trim() || 'main',
  8898. router_id: document.getElementById('modal-ospf-inst-router-id').value.trim(),
  8899. routing_table: document.getElementById('modal-ospf-inst-routing-table').value.trim() || 'main',
  8900. enabled: document.getElementById('modal-ospf-inst-enabled').checked,
  8901. disabled: !document.getElementById('modal-ospf-inst-enabled').checked,
  8902. comment: document.getElementById('modal-ospf-inst-comment').value.trim(),
  8903. redistribute_connected: document.getElementById('modal-ospf-inst-redist-conn').checked,
  8904. redistribute_static: document.getElementById('modal-ospf-inst-redist-static').checked,
  8905. redistribute_bgp: document.getElementById('modal-ospf-inst-redist-bgp').checked
  8906. };
  8907. try {
  8908. const res = await fetch(`${API_BASE}/routing/ospf/instances`, {
  8909. method: 'POST',
  8910. headers: { 'Content-Type': 'application/json' },
  8911. body: JSON.stringify(payload)
  8912. });
  8913. if (res.ok) {
  8914. closeOspfInstanceModal();
  8915. showToast('Saved', 'OSPF instance updated', 'success');
  8916. loadDynamicRouting();
  8917. } else {
  8918. const err = await res.json();
  8919. showToast('Error', err.error || 'Failed to save OSPF instance', 'error');
  8920. }
  8921. } catch (err) {
  8922. showToast('Error', err.message, 'error');
  8923. }
  8924. }
  8925. function applyOspfInstanceForm() {
  8926. submitOspfInstance(null);
  8927. }
  8928. function copyOspfInstance() {
  8929. document.getElementById('modal-ospf-inst-id').value = '';
  8930. document.getElementById('modal-ospf-inst-name').value += '-copy';
  8931. document.getElementById('ospf-instance-modal-title').innerText = 'New...';
  8932. showToast('Copied', 'Duplicated as new OSPF instance', 'info');
  8933. }
  8934. async function deleteCurrentOspfInstance() {
  8935. const id = document.getElementById('modal-ospf-inst-id').value;
  8936. if (!id) return;
  8937. if (!confirm('Are you sure you want to remove this OSPF instance?')) return;
  8938. try {
  8939. const res = await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8940. if (res.ok) {
  8941. closeOspfInstanceModal();
  8942. showToast('Removed', 'OSPF instance deleted', 'success');
  8943. loadDynamicRouting();
  8944. }
  8945. } catch (err) {
  8946. showToast('Error', err.message, 'error');
  8947. }
  8948. }
  8949. async function enableSelectedOspfInstance() {
  8950. const id = state.selectedOspfRow?.instances;
  8951. if (!id) return;
  8952. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}/state`, {
  8953. method: 'POST',
  8954. headers: { 'Content-Type': 'application/json' },
  8955. body: JSON.stringify({ disabled: false })
  8956. });
  8957. loadDynamicRouting();
  8958. }
  8959. async function disableSelectedOspfInstance() {
  8960. const id = state.selectedOspfRow?.instances;
  8961. if (!id) return;
  8962. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}/state`, {
  8963. method: 'POST',
  8964. headers: { 'Content-Type': 'application/json' },
  8965. body: JSON.stringify({ disabled: true })
  8966. });
  8967. loadDynamicRouting();
  8968. }
  8969. async function removeSelectedOspfInstance() {
  8970. const id = state.selectedOspfRow?.instances;
  8971. if (!id) return;
  8972. if (!confirm('Delete selected OSPF instance?')) return;
  8973. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8974. loadDynamicRouting();
  8975. }
  8976. async function promptCommentOspfInstance() {
  8977. const id = state.selectedOspfRow?.instances;
  8978. if (!id) return;
  8979. const inst = (state.ospfInstances || []).find(i => i.id === id);
  8980. if (!inst) return;
  8981. const comment = prompt('Enter comment for OSPF instance:', inst.comment || '');
  8982. if (comment === null) return;
  8983. inst.comment = comment;
  8984. await fetch(`${API_BASE}/routing/ospf/instances`, {
  8985. method: 'POST',
  8986. headers: { 'Content-Type': 'application/json' },
  8987. body: JSON.stringify(inst)
  8988. });
  8989. loadDynamicRouting();
  8990. }
  8991. // --- 2. OSPF AREA ---
  8992. function populateOspfAreaDropdowns() {
  8993. const instSelect = document.getElementById('modal-ospf-area-instance');
  8994. if (instSelect) {
  8995. const cur = instSelect.value;
  8996. instSelect.innerHTML = (state.ospfInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)}</option>`).join('');
  8997. if (instSelect.innerHTML === '') instSelect.innerHTML = '<option value="Default">Default</option>';
  8998. if (cur) instSelect.value = cur;
  8999. }
  9000. }
  9001. function openOspfAreaModal(id = null) {
  9002. const isEdit = !!id;
  9003. populateOspfAreaDropdowns();
  9004. const area = (state.ospfAreas || []).find(a => a.id === id) || {
  9005. id: '',
  9006. name: 'Default',
  9007. instance: 'Default',
  9008. area_id: '0.0.0.0',
  9009. area_type: 'default',
  9010. default_cost: 1,
  9011. no_summaries: false,
  9012. disabled: false,
  9013. comment: ''
  9014. };
  9015. document.getElementById('ospf-area-modal-title').innerText = isEdit ? area.name : 'New...';
  9016. document.getElementById('modal-ospf-area-id').value = isEdit ? area.id : '';
  9017. document.getElementById('modal-ospf-area-enabled').checked = !area.disabled;
  9018. document.getElementById('modal-ospf-area-comment').value = area.comment || '';
  9019. document.getElementById('modal-ospf-area-name').value = area.name || 'Default';
  9020. document.getElementById('modal-ospf-area-instance').value = area.instance || 'Default';
  9021. document.getElementById('modal-ospf-area-areaid').value = area.area_id || '0.0.0.0';
  9022. document.getElementById('modal-ospf-area-type').value = area.area_type || 'default';
  9023. document.getElementById('modal-ospf-area-default-cost').value = area.default_cost || 1;
  9024. document.getElementById('modal-ospf-area-no-summaries').checked = !!area.no_summaries;
  9025. const btnRem = document.getElementById('btn-ospf-area-modal-remove');
  9026. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  9027. document.getElementById('ospf-area-modal').classList.remove('hidden');
  9028. }
  9029. function openEditOspfAreaModal(id) {
  9030. openOspfAreaModal(id);
  9031. }
  9032. function closeOspfAreaModal() {
  9033. document.getElementById('ospf-area-modal').classList.add('hidden');
  9034. }
  9035. async function submitOspfArea(e) {
  9036. if (e) e.preventDefault();
  9037. const payload = {
  9038. id: document.getElementById('modal-ospf-area-id').value,
  9039. name: document.getElementById('modal-ospf-area-name').value.trim() || 'Default',
  9040. instance: document.getElementById('modal-ospf-area-instance').value.trim() || 'Default',
  9041. area_id: document.getElementById('modal-ospf-area-areaid').value.trim() || '0.0.0.0',
  9042. area_type: document.getElementById('modal-ospf-area-type').value,
  9043. default_cost: parseInt(document.getElementById('modal-ospf-area-default-cost').value, 10) || 1,
  9044. no_summaries: document.getElementById('modal-ospf-area-no-summaries').checked,
  9045. disabled: !document.getElementById('modal-ospf-area-enabled').checked,
  9046. comment: document.getElementById('modal-ospf-area-comment').value.trim()
  9047. };
  9048. try {
  9049. const res = await fetch(`${API_BASE}/routing/ospf/areas`, {
  9050. method: 'POST',
  9051. headers: { 'Content-Type': 'application/json' },
  9052. body: JSON.stringify(payload)
  9053. });
  9054. if (res.ok) {
  9055. closeOspfAreaModal();
  9056. showToast('Saved', 'OSPF area saved', 'success');
  9057. loadDynamicRouting();
  9058. } else {
  9059. const err = await res.json();
  9060. showToast('Error', err.error || 'Failed to save area', 'error');
  9061. }
  9062. } catch (err) {
  9063. showToast('Error', err.message, 'error');
  9064. }
  9065. }
  9066. function applyOspfAreaForm() {
  9067. submitOspfArea(null);
  9068. }
  9069. function copyOspfArea() {
  9070. document.getElementById('modal-ospf-area-id').value = '';
  9071. document.getElementById('modal-ospf-area-name').value += '-copy';
  9072. document.getElementById('ospf-area-modal-title').innerText = 'New...';
  9073. showToast('Copied', 'Duplicated as new OSPF area', 'info');
  9074. }
  9075. async function deleteCurrentOspfArea() {
  9076. const id = document.getElementById('modal-ospf-area-id').value;
  9077. if (!id) return;
  9078. if (!confirm('Are you sure you want to remove this OSPF area?')) return;
  9079. try {
  9080. const res = await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9081. if (res.ok) {
  9082. closeOspfAreaModal();
  9083. showToast('Removed', 'OSPF area deleted', 'success');
  9084. loadDynamicRouting();
  9085. }
  9086. } catch (err) {
  9087. showToast('Error', err.message, 'error');
  9088. }
  9089. }
  9090. async function enableSelectedOspfArea() {
  9091. const id = state.selectedOspfRow?.areas;
  9092. if (!id) return;
  9093. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}/state`, {
  9094. method: 'POST',
  9095. headers: { 'Content-Type': 'application/json' },
  9096. body: JSON.stringify({ disabled: false })
  9097. });
  9098. loadDynamicRouting();
  9099. }
  9100. async function disableSelectedOspfArea() {
  9101. const id = state.selectedOspfRow?.areas;
  9102. if (!id) return;
  9103. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}/state`, {
  9104. method: 'POST',
  9105. headers: { 'Content-Type': 'application/json' },
  9106. body: JSON.stringify({ disabled: true })
  9107. });
  9108. loadDynamicRouting();
  9109. }
  9110. async function removeSelectedOspfArea() {
  9111. const id = state.selectedOspfRow?.areas;
  9112. if (!id) return;
  9113. if (!confirm('Delete selected OSPF area?')) return;
  9114. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9115. loadDynamicRouting();
  9116. }
  9117. async function promptCommentOspfArea() {
  9118. const id = state.selectedOspfRow?.areas;
  9119. if (!id) return;
  9120. const area = (state.ospfAreas || []).find(a => a.id === id);
  9121. if (!area) return;
  9122. const comment = prompt('Enter comment for OSPF area:', area.comment || '');
  9123. if (comment === null) return;
  9124. area.comment = comment;
  9125. await fetch(`${API_BASE}/routing/ospf/areas`, {
  9126. method: 'POST',
  9127. headers: { 'Content-Type': 'application/json' },
  9128. body: JSON.stringify(area)
  9129. });
  9130. loadDynamicRouting();
  9131. }
  9132. // --- 3. OSPF AREA RANGE ---
  9133. function populateAreaRangeDropdowns() {
  9134. const select = document.getElementById('modal-ospf-range-area');
  9135. if (select) {
  9136. const cur = select.value;
  9137. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  9138. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  9139. if (cur) select.value = cur;
  9140. }
  9141. }
  9142. function openOspfAreaRangeModal(id = null) {
  9143. const isEdit = !!id;
  9144. populateAreaRangeDropdowns();
  9145. const r = (state.ospfAreaRanges || []).find(it => it.id === id) || {
  9146. id: '',
  9147. area: 'Default',
  9148. prefix: '',
  9149. cost: 1,
  9150. advertise: true,
  9151. disabled: false,
  9152. comment: ''
  9153. };
  9154. document.getElementById('ospf-area-range-modal-title').innerText = isEdit ? r.prefix : 'New...';
  9155. document.getElementById('modal-ospf-range-id').value = isEdit ? r.id : '';
  9156. document.getElementById('modal-ospf-range-enabled').checked = !r.disabled;
  9157. document.getElementById('modal-ospf-range-comment').value = r.comment || '';
  9158. document.getElementById('modal-ospf-range-area').value = r.area || 'Default';
  9159. document.getElementById('modal-ospf-range-prefix').value = r.prefix || '';
  9160. document.getElementById('modal-ospf-range-cost').value = r.cost || 1;
  9161. document.getElementById('modal-ospf-range-advertise').checked = r.advertise !== false;
  9162. const btnRem = document.getElementById('btn-ospf-range-modal-remove');
  9163. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  9164. document.getElementById('ospf-area-range-modal').classList.remove('hidden');
  9165. }
  9166. function openEditOspfAreaRangeModal(id) {
  9167. openOspfAreaRangeModal(id);
  9168. }
  9169. function closeOspfAreaRangeModal() {
  9170. document.getElementById('ospf-area-range-modal').classList.add('hidden');
  9171. }
  9172. async function submitOspfAreaRange(e) {
  9173. if (e) e.preventDefault();
  9174. const payload = {
  9175. id: document.getElementById('modal-ospf-range-id').value,
  9176. area: document.getElementById('modal-ospf-range-area').value,
  9177. prefix: document.getElementById('modal-ospf-range-prefix').value.trim(),
  9178. cost: parseInt(document.getElementById('modal-ospf-range-cost').value, 10) || 1,
  9179. advertise: document.getElementById('modal-ospf-range-advertise').checked,
  9180. disabled: !document.getElementById('modal-ospf-range-enabled').checked,
  9181. comment: document.getElementById('modal-ospf-range-comment').value.trim()
  9182. };
  9183. try {
  9184. const res = await fetch(`${API_BASE}/routing/ospf/area-ranges`, {
  9185. method: 'POST',
  9186. headers: { 'Content-Type': 'application/json' },
  9187. body: JSON.stringify(payload)
  9188. });
  9189. if (res.ok) {
  9190. closeOspfAreaRangeModal();
  9191. showToast('Saved', 'Area range saved', 'success');
  9192. loadDynamicRouting();
  9193. } else {
  9194. const err = await res.json();
  9195. showToast('Error', err.error || 'Failed to save area range', 'error');
  9196. }
  9197. } catch (err) {
  9198. showToast('Error', err.message, 'error');
  9199. }
  9200. }
  9201. function applyOspfAreaRangeForm() {
  9202. submitOspfAreaRange(null);
  9203. }
  9204. async function deleteCurrentOspfAreaRange() {
  9205. const id = document.getElementById('modal-ospf-range-id').value;
  9206. if (!id) return;
  9207. if (!confirm('Delete this area range?')) return;
  9208. try {
  9209. await fetch(`${API_BASE}/routing/ospf/area-ranges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9210. closeOspfAreaRangeModal();
  9211. showToast('Removed', 'Area range removed', 'success');
  9212. loadDynamicRouting();
  9213. } catch (err) {
  9214. showToast('Error', err.message, 'error');
  9215. }
  9216. }
  9217. async function enableSelectedOspfAreaRange() {
  9218. const id = state.selectedOspfRow?.['area-ranges'];
  9219. if (!id) return;
  9220. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  9221. if (!r) return;
  9222. r.disabled = false;
  9223. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  9224. loadDynamicRouting();
  9225. }
  9226. async function disableSelectedOspfAreaRange() {
  9227. const id = state.selectedOspfRow?.['area-ranges'];
  9228. if (!id) return;
  9229. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  9230. if (!r) return;
  9231. r.disabled = true;
  9232. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  9233. loadDynamicRouting();
  9234. }
  9235. async function removeSelectedOspfAreaRange() {
  9236. const id = state.selectedOspfRow?.['area-ranges'];
  9237. if (!id) return;
  9238. if (!confirm('Delete selected area range?')) return;
  9239. await fetch(`${API_BASE}/routing/ospf/area-ranges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9240. loadDynamicRouting();
  9241. }
  9242. async function promptCommentOspfAreaRange() {
  9243. const id = state.selectedOspfRow?.['area-ranges'];
  9244. if (!id) return;
  9245. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  9246. if (!r) return;
  9247. const comment = prompt('Enter comment for area range:', r.comment || '');
  9248. if (comment === null) return;
  9249. r.comment = comment;
  9250. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  9251. loadDynamicRouting();
  9252. }
  9253. // --- 4. OSPF INTERFACE TEMPLATE ---
  9254. function switchOspfTemplateTab(tab) {
  9255. const tabGen = document.getElementById('ospf-tmpl-tab-general');
  9256. const tabAuth = document.getElementById('ospf-tmpl-tab-auth');
  9257. const btnGen = document.getElementById('ospf-tmpl-tab-btn-general');
  9258. const btnAuth = document.getElementById('ospf-tmpl-tab-btn-auth');
  9259. if (tab === 'general') {
  9260. if (tabGen) tabGen.classList.remove('hidden');
  9261. if (tabAuth) tabAuth.classList.add('hidden');
  9262. if (btnGen) btnGen.className = 'px-4 py-2 text-xs font-bold border-b-2 border-sky-500 text-white transition';
  9263. 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';
  9264. } else {
  9265. if (tabGen) tabGen.classList.add('hidden');
  9266. if (tabAuth) tabAuth.classList.remove('hidden');
  9267. 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';
  9268. if (btnAuth) btnAuth.className = 'px-4 py-2 text-xs font-bold border-b-2 border-sky-500 text-white transition';
  9269. }
  9270. }
  9271. function populateTemplateAreaDropdowns() {
  9272. const select = document.getElementById('modal-ospf-tmpl-area');
  9273. if (select) {
  9274. const cur = select.value;
  9275. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  9276. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  9277. if (cur) select.value = cur;
  9278. }
  9279. }
  9280. function openOspfTemplateModal(id = null) {
  9281. const isEdit = !!id;
  9282. populateTemplateAreaDropdowns();
  9283. switchOspfTemplateTab('general');
  9284. const tmpl = (state.ospfTemplates || []).find(t => t.id === id) || {
  9285. id: '',
  9286. interfaces: '',
  9287. area: 'Default',
  9288. networks: '',
  9289. network_type: 'broadcast',
  9290. cost: 1,
  9291. priority: 128,
  9292. passive: false,
  9293. hello_interval: 10,
  9294. dead_interval: 40,
  9295. auth: 'none',
  9296. auth_key: '',
  9297. disabled: false,
  9298. comment: ''
  9299. };
  9300. document.getElementById('ospf-template-modal-title').innerText = isEdit ? (tmpl.interfaces || tmpl.networks || 'Template') : 'New...';
  9301. document.getElementById('modal-ospf-tmpl-id').value = isEdit ? tmpl.id : '';
  9302. document.getElementById('modal-ospf-tmpl-enabled').checked = !tmpl.disabled;
  9303. document.getElementById('modal-ospf-tmpl-comment').value = tmpl.comment || '';
  9304. document.getElementById('modal-ospf-tmpl-interfaces').value = tmpl.interfaces || tmpl.interface || '';
  9305. document.getElementById('modal-ospf-tmpl-area').value = tmpl.area || 'Default';
  9306. document.getElementById('modal-ospf-tmpl-networks').value = tmpl.networks || tmpl.network || '';
  9307. document.getElementById('modal-ospf-tmpl-net-type').value = tmpl.network_type || 'broadcast';
  9308. document.getElementById('modal-ospf-tmpl-cost').value = tmpl.cost || 1;
  9309. document.getElementById('modal-ospf-tmpl-priority').value = tmpl.priority || 128;
  9310. document.getElementById('modal-ospf-tmpl-passive').checked = !!tmpl.passive;
  9311. document.getElementById('modal-ospf-tmpl-hello').value = tmpl.hello_interval || 10;
  9312. document.getElementById('modal-ospf-tmpl-dead').value = tmpl.dead_interval || 40;
  9313. document.getElementById('modal-ospf-tmpl-auth').value = tmpl.auth || tmpl.auth_type || 'none';
  9314. document.getElementById('modal-ospf-tmpl-auth-key').value = tmpl.auth_key || '';
  9315. const btnRem = document.getElementById('btn-ospf-tmpl-modal-remove');
  9316. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  9317. document.getElementById('ospf-template-modal').classList.remove('hidden');
  9318. }
  9319. function openEditOspfTemplateModal(id) {
  9320. openOspfTemplateModal(id);
  9321. }
  9322. function closeOspfTemplateModal() {
  9323. document.getElementById('ospf-template-modal').classList.add('hidden');
  9324. }
  9325. async function submitOspfTemplate(e) {
  9326. if (e) e.preventDefault();
  9327. const payload = {
  9328. id: document.getElementById('modal-ospf-tmpl-id').value,
  9329. interfaces: document.getElementById('modal-ospf-tmpl-interfaces').value.trim(),
  9330. interface: document.getElementById('modal-ospf-tmpl-interfaces').value.trim(),
  9331. area: document.getElementById('modal-ospf-tmpl-area').value,
  9332. networks: document.getElementById('modal-ospf-tmpl-networks').value.trim(),
  9333. network: document.getElementById('modal-ospf-tmpl-networks').value.trim(),
  9334. network_type: document.getElementById('modal-ospf-tmpl-net-type').value,
  9335. cost: parseInt(document.getElementById('modal-ospf-tmpl-cost').value, 10) || 1,
  9336. priority: parseInt(document.getElementById('modal-ospf-tmpl-priority').value, 10) || 128,
  9337. passive: document.getElementById('modal-ospf-tmpl-passive').checked,
  9338. hello_interval: parseInt(document.getElementById('modal-ospf-tmpl-hello').value, 10) || 10,
  9339. dead_interval: parseInt(document.getElementById('modal-ospf-tmpl-dead').value, 10) || 40,
  9340. auth: document.getElementById('modal-ospf-tmpl-auth').value,
  9341. auth_type: document.getElementById('modal-ospf-tmpl-auth').value,
  9342. auth_key: document.getElementById('modal-ospf-tmpl-auth-key').value,
  9343. disabled: !document.getElementById('modal-ospf-tmpl-enabled').checked,
  9344. comment: document.getElementById('modal-ospf-tmpl-comment').value.trim()
  9345. };
  9346. try {
  9347. const res = await fetch(`${API_BASE}/routing/ospf/templates`, {
  9348. method: 'POST',
  9349. headers: { 'Content-Type': 'application/json' },
  9350. body: JSON.stringify(payload)
  9351. });
  9352. if (res.ok) {
  9353. closeOspfTemplateModal();
  9354. showToast('Saved', 'Interface template saved', 'success');
  9355. loadDynamicRouting();
  9356. } else {
  9357. const err = await res.json();
  9358. showToast('Error', err.error || 'Failed to save interface template', 'error');
  9359. }
  9360. } catch (err) {
  9361. showToast('Error', err.message, 'error');
  9362. }
  9363. }
  9364. function applyOspfTemplateForm() {
  9365. submitOspfTemplate(null);
  9366. }
  9367. function copyOspfTemplate() {
  9368. document.getElementById('modal-ospf-tmpl-id').value = '';
  9369. document.getElementById('ospf-template-modal-title').innerText = 'New...';
  9370. showToast('Copied', 'Duplicated as new template', 'info');
  9371. }
  9372. async function deleteCurrentOspfTemplate() {
  9373. const id = document.getElementById('modal-ospf-tmpl-id').value;
  9374. if (!id) return;
  9375. if (!confirm('Delete this interface template?')) return;
  9376. try {
  9377. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9378. closeOspfTemplateModal();
  9379. showToast('Removed', 'Interface template deleted', 'success');
  9380. loadDynamicRouting();
  9381. } catch (err) {
  9382. showToast('Error', err.message, 'error');
  9383. }
  9384. }
  9385. async function enableSelectedOspfTemplate() {
  9386. const id = state.selectedOspfRow?.templates;
  9387. if (!id) return;
  9388. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  9389. method: 'POST',
  9390. headers: { 'Content-Type': 'application/json' },
  9391. body: JSON.stringify({ disabled: false })
  9392. });
  9393. loadDynamicRouting();
  9394. }
  9395. async function disableSelectedOspfTemplate() {
  9396. const id = state.selectedOspfRow?.templates;
  9397. if (!id) return;
  9398. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  9399. method: 'POST',
  9400. headers: { 'Content-Type': 'application/json' },
  9401. body: JSON.stringify({ disabled: true })
  9402. });
  9403. loadDynamicRouting();
  9404. }
  9405. async function removeSelectedOspfTemplate() {
  9406. const id = state.selectedOspfRow?.templates;
  9407. if (!id) return;
  9408. if (!confirm('Delete selected interface template?')) return;
  9409. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9410. loadDynamicRouting();
  9411. }
  9412. async function promptCommentOspfTemplate() {
  9413. const id = state.selectedOspfRow?.templates;
  9414. if (!id) return;
  9415. const tmpl = (state.ospfTemplates || []).find(t => t.id === id);
  9416. if (!tmpl) return;
  9417. const comment = prompt('Enter comment for template:', tmpl.comment || '');
  9418. if (comment === null) return;
  9419. tmpl.comment = comment;
  9420. await fetch(`${API_BASE}/routing/ospf/templates`, {
  9421. method: 'POST',
  9422. headers: { 'Content-Type': 'application/json' },
  9423. body: JSON.stringify(tmpl)
  9424. });
  9425. loadDynamicRouting();
  9426. }
  9427. // --- 5. OSPF STATIC NEIGHBOR ---
  9428. function populateStaticNbrAreaDropdowns() {
  9429. const select = document.getElementById('modal-ospf-snbr-area');
  9430. if (select) {
  9431. const cur = select.value;
  9432. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  9433. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  9434. if (cur) select.value = cur;
  9435. }
  9436. }
  9437. function openOspfStaticNbrModal(id = null) {
  9438. const isEdit = !!id;
  9439. populateStaticNbrAreaDropdowns();
  9440. const nbr = (state.ospfStaticNbrs || []).find(n => n.id === id) || {
  9441. id: '',
  9442. address: '',
  9443. area: 'Default',
  9444. poll_interval: 120,
  9445. cost: 1,
  9446. disabled: false,
  9447. comment: ''
  9448. };
  9449. document.getElementById('ospf-static-nbr-modal-title').innerText = isEdit ? nbr.address : 'New...';
  9450. document.getElementById('modal-ospf-snbr-id').value = isEdit ? nbr.id : '';
  9451. document.getElementById('modal-ospf-snbr-enabled').checked = !nbr.disabled;
  9452. document.getElementById('modal-ospf-snbr-comment').value = nbr.comment || '';
  9453. document.getElementById('modal-ospf-snbr-address').value = nbr.address || '';
  9454. document.getElementById('modal-ospf-snbr-area').value = nbr.area || 'Default';
  9455. document.getElementById('modal-ospf-snbr-poll').value = nbr.poll_interval || 120;
  9456. document.getElementById('modal-ospf-snbr-cost').value = nbr.cost || 1;
  9457. const btnRem = document.getElementById('btn-ospf-snbr-modal-remove');
  9458. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  9459. document.getElementById('ospf-static-nbr-modal').classList.remove('hidden');
  9460. }
  9461. function openEditOspfStaticNbrModal(id) {
  9462. openOspfStaticNbrModal(id);
  9463. }
  9464. function closeOspfStaticNbrModal() {
  9465. document.getElementById('ospf-static-nbr-modal').classList.add('hidden');
  9466. }
  9467. async function submitOspfStaticNbr(e) {
  9468. if (e) e.preventDefault();
  9469. const payload = {
  9470. id: document.getElementById('modal-ospf-snbr-id').value,
  9471. address: document.getElementById('modal-ospf-snbr-address').value.trim(),
  9472. area: document.getElementById('modal-ospf-snbr-area').value,
  9473. poll_interval: parseInt(document.getElementById('modal-ospf-snbr-poll').value, 10) || 120,
  9474. cost: parseInt(document.getElementById('modal-ospf-snbr-cost').value, 10) || 1,
  9475. disabled: !document.getElementById('modal-ospf-snbr-enabled').checked,
  9476. comment: document.getElementById('modal-ospf-snbr-comment').value.trim()
  9477. };
  9478. try {
  9479. const res = await fetch(`${API_BASE}/routing/ospf/static-neighbors`, {
  9480. method: 'POST',
  9481. headers: { 'Content-Type': 'application/json' },
  9482. body: JSON.stringify(payload)
  9483. });
  9484. if (res.ok) {
  9485. closeOspfStaticNbrModal();
  9486. showToast('Saved', 'Static neighbor saved', 'success');
  9487. loadDynamicRouting();
  9488. } else {
  9489. const err = await res.json();
  9490. showToast('Error', err.error || 'Failed to save static neighbor', 'error');
  9491. }
  9492. } catch (err) {
  9493. showToast('Error', err.message, 'error');
  9494. }
  9495. }
  9496. function applyOspfStaticNbrForm() {
  9497. submitOspfStaticNbr(null);
  9498. }
  9499. async function deleteCurrentOspfStaticNbr() {
  9500. const id = document.getElementById('modal-ospf-snbr-id').value;
  9501. if (!id) return;
  9502. if (!confirm('Delete this static neighbor?')) return;
  9503. try {
  9504. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9505. closeOspfStaticNbrModal();
  9506. showToast('Removed', 'Static neighbor removed', 'success');
  9507. loadDynamicRouting();
  9508. } catch (err) {
  9509. showToast('Error', err.message, 'error');
  9510. }
  9511. }
  9512. async function enableSelectedOspfStaticNbr() {
  9513. const id = state.selectedOspfRow?.['static-nbrs'];
  9514. if (!id) return;
  9515. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  9516. if (!n) return;
  9517. n.disabled = false;
  9518. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  9519. loadDynamicRouting();
  9520. }
  9521. async function disableSelectedOspfStaticNbr() {
  9522. const id = state.selectedOspfRow?.['static-nbrs'];
  9523. if (!id) return;
  9524. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  9525. if (!n) return;
  9526. n.disabled = true;
  9527. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  9528. loadDynamicRouting();
  9529. }
  9530. async function removeSelectedOspfStaticNbr() {
  9531. const id = state.selectedOspfRow?.['static-nbrs'];
  9532. if (!id) return;
  9533. if (!confirm('Delete selected static neighbor?')) return;
  9534. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9535. loadDynamicRouting();
  9536. }
  9537. async function promptCommentOspfStaticNbr() {
  9538. const id = state.selectedOspfRow?.['static-nbrs'];
  9539. if (!id) return;
  9540. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  9541. if (!n) return;
  9542. const comment = prompt('Enter comment for static neighbor:', n.comment || '');
  9543. if (comment === null) return;
  9544. n.comment = comment;
  9545. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  9546. loadDynamicRouting();
  9547. }
  9548. // Backward-compat aliases
  9549. function openAddOspfInterfaceModal() { openOspfTemplateModal(); }
  9550. function openEditOspfInterfaceModal(id) { openEditOspfTemplateModal(id); }
  9551. function closeOspfInterfaceModal() { closeOspfTemplateModal(); }
  9552. function submitOspfInterface(e) { submitOspfTemplate(e); }
  9553. function deleteOspfInterface(id) {
  9554. fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' }).then(() => loadDynamicRouting());
  9555. }
  9556. function toggleOspfInterfaceState(id, disabled) {
  9557. fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  9558. method: 'POST',
  9559. headers: { 'Content-Type': 'application/json' },
  9560. body: JSON.stringify({ disabled })
  9561. }).then(() => loadDynamicRouting());
  9562. }
  9563. function openAddOspfAreaModal() { openOspfAreaModal(); }
  9564. function deleteOspfArea(id) {
  9565. fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' }).then(() => loadDynamicRouting());
  9566. }
  9567. // ============================================================================
  9568. // ==================== MIKROTIK BRIDGE SUBSYSTEM ==============================
  9569. // ============================================================================
  9570. function switchBridgeSubTab(tab) {
  9571. state.bridgeSubTab = tab;
  9572. const tabs = ['bridges', 'ports', 'vlans', 'hosts'];
  9573. tabs.forEach(t => {
  9574. const panel = document.getElementById(`bridge-subtab-${t}`);
  9575. const btn = document.getElementById(`bridge-subtab-btn-${t}`);
  9576. if (panel) {
  9577. if (t === tab) panel.classList.remove('hidden');
  9578. else panel.classList.add('hidden');
  9579. }
  9580. if (btn) {
  9581. if (t === tab) {
  9582. 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';
  9583. } else {
  9584. 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';
  9585. }
  9586. }
  9587. });
  9588. const addBtn = document.getElementById('bridge-top-action-btn');
  9589. if (addBtn) {
  9590. if (tab === 'bridges') addBtn.innerHTML = '<span>+ Add Bridge</span>';
  9591. else if (tab === 'ports') addBtn.innerHTML = '<span>+ Add Port</span>';
  9592. else if (tab === 'vlans') addBtn.innerHTML = '<span>+ Add VLAN Entry</span>';
  9593. else if (tab === 'hosts') addBtn.innerHTML = '<span>🔄 Refresh MACs</span>';
  9594. }
  9595. if (tab === 'hosts') loadBridgeHosts();
  9596. setTimeout(initTableSorting, 50);
  9597. }
  9598. function openCurrentBridgeModal() {
  9599. if (state.bridgeSubTab === 'bridges') openAddBridgeModal();
  9600. else if (state.bridgeSubTab === 'ports') openAddBridgePortModal();
  9601. else if (state.bridgeSubTab === 'vlans') openAddBridgeVLANModal();
  9602. else if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  9603. }
  9604. async function loadBridge() {
  9605. try {
  9606. const [bridgesRes, portsRes, vlansRes, summaryRes, eoipRes, vlanIfacesRes] = await Promise.all([
  9607. fetch(`${API_BASE}/bridge/bridges`),
  9608. fetch(`${API_BASE}/bridge/ports`),
  9609. fetch(`${API_BASE}/bridge/vlans`),
  9610. fetch(`${API_BASE}/bridge/summary`),
  9611. fetch(`${API_BASE}/vpn/eoip`),
  9612. fetch(`${API_BASE}/vlans`)
  9613. ]);
  9614. if (bridgesRes.ok) state.bridges = await bridgesRes.json();
  9615. if (portsRes.ok) state.bridgePorts = await portsRes.json();
  9616. if (vlansRes.ok) state.bridgeVLANs = await vlansRes.json();
  9617. if (summaryRes.ok) state.bridgeSummary = await summaryRes.json();
  9618. if (eoipRes && eoipRes.ok) state.eoipTunnels = await eoipRes.json();
  9619. if (vlanIfacesRes && vlanIfacesRes.ok) state.vlans = await vlanIfacesRes.json();
  9620. // Badges & Stats
  9621. const bBridges = document.getElementById('bridge-badge-bridges');
  9622. if (bBridges) bBridges.innerText = (state.bridges || []).length;
  9623. const bPorts = document.getElementById('bridge-badge-ports');
  9624. if (bPorts) bPorts.innerText = (state.bridgePorts || []).length;
  9625. const bVlans = document.getElementById('bridge-badge-vlans');
  9626. if (bVlans) bVlans.innerText = (state.bridgeVLANs || []).length;
  9627. const bHosts = document.getElementById('bridge-badge-hosts');
  9628. if (bHosts) bHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  9629. const sBr = document.getElementById('bridge-stat-bridges');
  9630. if (sBr) sBr.innerText = (state.bridges || []).length;
  9631. const sPorts = document.getElementById('bridge-stat-ports');
  9632. if (sPorts) sPorts.innerText = (state.bridgePorts || []).length;
  9633. const sHosts = document.getElementById('bridge-stat-hosts');
  9634. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  9635. renderBridges();
  9636. renderBridgePorts();
  9637. renderBridgeVLANs();
  9638. if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  9639. } catch (err) {
  9640. console.error('Failed to load bridge subsystem:', err);
  9641. }
  9642. }
  9643. // ----------------- Bridges -----------------
  9644. function renderBridges() {
  9645. const tbody = document.getElementById('bridge-table-body');
  9646. const empty = document.getElementById('bridge-empty-bridges');
  9647. const countBadge = document.getElementById('bridge-count-badge');
  9648. if (!tbody) return;
  9649. tbody.innerHTML = '';
  9650. const bridges = state.bridges || [];
  9651. if (countBadge) countBadge.innerText = `${bridges.length} Bridges`;
  9652. if (bridges.length === 0) {
  9653. empty?.classList.remove('hidden');
  9654. return;
  9655. }
  9656. empty?.classList.add('hidden');
  9657. bridges.forEach((b, idx) => {
  9658. const tr = document.createElement('tr');
  9659. tr.className = `hover:bg-slate-800/40 transition text-xs ${b.disabled ? 'opacity-50' : ''}`;
  9660. // Format IP addresses pill list
  9661. let ipsHtml = '<span class="text-slate-600 font-sans">None</span>';
  9662. if (b.ip_addresses && b.ip_addresses.length > 0) {
  9663. ipsHtml = b.ip_addresses.map(ip => `
  9664. <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">
  9665. <span>${ip}</span>
  9666. <button onclick="deleteBridgeIP('${b.id}', '${ip}')" class="text-slate-500 hover:text-rose-400 font-bold ml-0.5">×</button>
  9667. </span>
  9668. `).join(' ');
  9669. }
  9670. const runningFlag = b.running ? '<span class="text-emerald-400 font-bold" title="Running (R)">R</span>' : '<span class="text-slate-600">-</span>';
  9671. const disabledFlag = b.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '';
  9672. const flagDisplay = `${runningFlag}${disabledFlag ? ' ' + disabledFlag : ''}`;
  9673. tr.innerHTML = `
  9674. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  9675. <td class="py-2.5 px-3 text-center font-mono">${flagDisplay}</td>
  9676. <td class="py-2.5 px-3 font-bold text-white text-sm">
  9677. <span class="text-sky-400 mr-1.5">🌉</span>${b.name}
  9678. </td>
  9679. <td class="py-2.5 px-3 text-slate-300">${b.mtu}</td>
  9680. <td class="py-2.5 px-3 font-mono text-slate-300 text-[11px]">${b.mac_address || '-'}</td>
  9681. <td class="py-2.5 px-3">
  9682. <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>
  9683. </td>
  9684. <td class="py-2.5 px-3 text-center">
  9685. ${b.vlan_filtering ? '<span class="text-emerald-400 font-bold">yes</span>' : '<span class="text-slate-500">no</span>'}
  9686. </td>
  9687. <td class="py-2.5 px-3 font-mono">${b.pvid || 1}</td>
  9688. <td class="py-2.5 px-3">
  9689. <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>
  9690. </td>
  9691. <td class="py-2.5 px-3">
  9692. <div class="flex items-center gap-1.5 flex-wrap">
  9693. ${ipsHtml}
  9694. <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>
  9695. </div>
  9696. </td>
  9697. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  9698. <span class="text-emerald-400">↓ ${b.rx_human || '0 B'}</span> / <span class="text-cyan-400">↑ ${b.tx_human || '0 B'}</span>
  9699. </td>
  9700. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${b.comment || ''}">${b.comment || '-'}</td>
  9701. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  9702. <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>
  9703. <button onclick="openEditBridgeModal('${b.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  9704. <button onclick="deleteBridge('${b.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  9705. </td>
  9706. `;
  9707. tbody.appendChild(tr);
  9708. });
  9709. }
  9710. function openAddBridgeModal() {
  9711. document.getElementById('bridge-modal-title').innerText = 'Add Bridge Interface';
  9712. document.getElementById('bridge-modal-id').value = '';
  9713. document.getElementById('bridge-modal-name').value = 'bridge1';
  9714. document.getElementById('bridge-modal-name').disabled = false;
  9715. document.getElementById('bridge-modal-mtu').value = '1500';
  9716. document.getElementById('bridge-modal-mac').value = '';
  9717. document.getElementById('bridge-modal-stp').value = 'rstp';
  9718. document.getElementById('bridge-modal-priority').value = '32768';
  9719. document.getElementById('bridge-modal-vlanfiltering').checked = false;
  9720. document.getElementById('bridge-modal-pvid').value = '1';
  9721. document.getElementById('bridge-modal-fastforward').checked = true;
  9722. document.getElementById('bridge-modal-comment').value = '';
  9723. document.getElementById('bridge-modal-disabled').checked = false;
  9724. toggleBridgeModalVlanFiltering();
  9725. document.getElementById('bridge-modal').classList.remove('hidden');
  9726. }
  9727. function openEditBridgeModal(id) {
  9728. const b = (state.bridges || []).find(x => x.id === id);
  9729. if (!b) return;
  9730. document.getElementById('bridge-modal-title').innerText = `Edit Bridge (${b.name})`;
  9731. document.getElementById('bridge-modal-id').value = b.id;
  9732. document.getElementById('bridge-modal-name').value = b.name;
  9733. document.getElementById('bridge-modal-name').disabled = true;
  9734. document.getElementById('bridge-modal-mtu').value = b.mtu || 1500;
  9735. document.getElementById('bridge-modal-mac').value = b.mac_address || '';
  9736. document.getElementById('bridge-modal-stp').value = b.stp || 'rstp';
  9737. document.getElementById('bridge-modal-priority').value = b.priority || 32768;
  9738. document.getElementById('bridge-modal-vlanfiltering').checked = !!b.vlan_filtering;
  9739. document.getElementById('bridge-modal-pvid').value = b.pvid || 1;
  9740. document.getElementById('bridge-modal-fastforward').checked = b.fast_forward !== false;
  9741. document.getElementById('bridge-modal-comment').value = b.comment || '';
  9742. document.getElementById('bridge-modal-disabled').checked = !!b.disabled;
  9743. toggleBridgeModalVlanFiltering();
  9744. document.getElementById('bridge-modal').classList.remove('hidden');
  9745. }
  9746. function closeBridgeModal() {
  9747. document.getElementById('bridge-modal').classList.add('hidden');
  9748. }
  9749. function toggleBridgeModalVlanFiltering() {
  9750. const chk = document.getElementById('bridge-modal-vlanfiltering').checked;
  9751. const pvidBox = document.getElementById('bridge-modal-pvid-box');
  9752. if (pvidBox) {
  9753. if (chk) pvidBox.classList.remove('opacity-40');
  9754. else pvidBox.classList.add('opacity-40');
  9755. }
  9756. }
  9757. async function submitSaveBridge(e) {
  9758. e.preventDefault();
  9759. const id = document.getElementById('bridge-modal-id').value;
  9760. const name = document.getElementById('bridge-modal-name').value.trim();
  9761. const mtu = parseInt(document.getElementById('bridge-modal-mtu').value, 10) || 1500;
  9762. const mac = document.getElementById('bridge-modal-mac').value.trim();
  9763. const stp = document.getElementById('bridge-modal-stp').value;
  9764. const priority = parseInt(document.getElementById('bridge-modal-priority').value, 10) || 32768;
  9765. const vlanFiltering = document.getElementById('bridge-modal-vlanfiltering').checked;
  9766. const pvid = parseInt(document.getElementById('bridge-modal-pvid').value, 10) || 1;
  9767. const fastForward = document.getElementById('bridge-modal-fastforward').checked;
  9768. const comment = document.getElementById('bridge-modal-comment').value.trim();
  9769. const disabled = document.getElementById('bridge-modal-disabled').checked;
  9770. try {
  9771. const res = await fetch(`${API_BASE}/bridge/bridges`, {
  9772. method: 'POST',
  9773. headers: { 'Content-Type': 'application/json' },
  9774. body: JSON.stringify({
  9775. id,
  9776. name,
  9777. mtu,
  9778. mac_address: mac,
  9779. stp,
  9780. priority,
  9781. vlan_filtering: vlanFiltering,
  9782. pvid,
  9783. fast_forward: fastForward,
  9784. comment,
  9785. disabled
  9786. })
  9787. });
  9788. if (res.ok) {
  9789. showToast('Bridge Saved', `Bridge ${name} configured`, 'success');
  9790. closeBridgeModal();
  9791. loadBridge();
  9792. fetchData(false);
  9793. } else {
  9794. const err = await res.json();
  9795. showToast('Error', err.error || err.message || 'Failed to save bridge', 'error');
  9796. }
  9797. } catch (err) {
  9798. showToast('Error', err.message, 'error');
  9799. }
  9800. }
  9801. async function toggleBridgeState(id, disabled) {
  9802. try {
  9803. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/state`, {
  9804. method: 'POST',
  9805. headers: { 'Content-Type': 'application/json' },
  9806. body: JSON.stringify({ disabled })
  9807. });
  9808. if (res.ok) {
  9809. loadBridge();
  9810. fetchData(false);
  9811. }
  9812. } catch (err) {
  9813. showToast('Error', err.message, 'error');
  9814. }
  9815. }
  9816. async function deleteBridge(id) {
  9817. const b = (state.bridges || []).find(x => x.id === id);
  9818. const name = b ? b.name : id;
  9819. if (!confirm(`Are you sure you want to delete bridge '${name}'? All member ports will be detached.`)) return;
  9820. try {
  9821. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9822. if (res.ok) {
  9823. showToast('Deleted', `Bridge ${name} deleted`, 'success');
  9824. loadBridge();
  9825. fetchData(false);
  9826. } else {
  9827. const err = await res.json();
  9828. showToast('Error', err.error || err.message || 'Failed to delete bridge', 'error');
  9829. }
  9830. } catch (err) {
  9831. showToast('Error', err.message, 'error');
  9832. }
  9833. }
  9834. // ----------------- Bridge IP Assignments -----------------
  9835. function openAddBridgeIPModal(id, name) {
  9836. document.getElementById('bridge-ip-modal-id').value = id;
  9837. document.getElementById('bridge-ip-modal-sub').innerText = name;
  9838. document.getElementById('bridge-ip-modal-cidr').value = '';
  9839. document.getElementById('bridge-ip-modal').classList.remove('hidden');
  9840. }
  9841. function closeBridgeIPModal() {
  9842. document.getElementById('bridge-ip-modal').classList.add('hidden');
  9843. }
  9844. async function submitAddBridgeIP(e) {
  9845. e.preventDefault();
  9846. const id = document.getElementById('bridge-ip-modal-id').value;
  9847. const ip = document.getElementById('bridge-ip-modal-cidr').value.trim();
  9848. try {
  9849. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  9850. method: 'POST',
  9851. headers: { 'Content-Type': 'application/json' },
  9852. body: JSON.stringify({ ip })
  9853. });
  9854. if (res.ok) {
  9855. showToast('IP Assigned', `${ip} assigned to bridge`, 'success');
  9856. closeBridgeIPModal();
  9857. loadBridge();
  9858. fetchData(false);
  9859. } else {
  9860. const err = await res.json();
  9861. showToast('Error', err.error || err.message || 'Failed to add IP', 'error');
  9862. }
  9863. } catch (err) {
  9864. showToast('Error', err.message, 'error');
  9865. }
  9866. }
  9867. async function deleteBridgeIP(id, ip) {
  9868. if (!confirm(`Remove IP address ${ip} from bridge?`)) return;
  9869. try {
  9870. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  9871. method: 'DELETE',
  9872. headers: { 'Content-Type': 'application/json' },
  9873. body: JSON.stringify({ ip })
  9874. });
  9875. if (res.ok) {
  9876. showToast('IP Removed', `${ip} removed from bridge`, 'success');
  9877. loadBridge();
  9878. fetchData(false);
  9879. }
  9880. } catch (err) {
  9881. showToast('Error', err.message, 'error');
  9882. }
  9883. }
  9884. // ----------------- Bridge Ports -----------------
  9885. function renderBridgePorts() {
  9886. const tbody = document.getElementById('bridge-ports-table-body');
  9887. const empty = document.getElementById('bridge-empty-ports');
  9888. const countBadge = document.getElementById('bridge-ports-count-badge');
  9889. const filterBridge = document.getElementById('bridge-ports-filter-bridge')?.value || '';
  9890. if (!tbody) return;
  9891. tbody.innerHTML = '';
  9892. // Update filter select
  9893. populateBridgeSelect('bridge-ports-filter-bridge', filterBridge, true);
  9894. const ports = (state.bridgePorts || []).filter(p => !filterBridge || p.bridge === filterBridge);
  9895. if (countBadge) countBadge.innerText = `${ports.length} Ports`;
  9896. if (ports.length === 0) {
  9897. empty?.classList.remove('hidden');
  9898. return;
  9899. }
  9900. empty?.classList.add('hidden');
  9901. ports.forEach((p, idx) => {
  9902. const tr = document.createElement('tr');
  9903. tr.className = `hover:bg-slate-800/40 transition text-xs ${p.disabled ? 'opacity-50' : ''}`;
  9904. const disabledFlag = p.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  9905. tr.innerHTML = `
  9906. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  9907. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  9908. <td class="py-2.5 px-3 font-bold text-white text-sm">
  9909. <span class="text-emerald-400 mr-1.5">🔌</span>${p.interface}
  9910. </td>
  9911. <td class="py-2.5 px-3 font-semibold text-sky-400">${p.bridge}</td>
  9912. <td class="py-2.5 px-3 font-mono">${p.pvid || 1}</td>
  9913. <td class="py-2.5 px-3 text-slate-300">${p.frame_types}</td>
  9914. <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>
  9915. <td class="py-2.5 px-3">
  9916. ${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>'}
  9917. </td>
  9918. <td class="py-2.5 px-3">
  9919. <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>
  9920. </td>
  9921. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${p.comment || ''}">${p.comment || '-'}</td>
  9922. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  9923. <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>
  9924. <button onclick="openEditBridgePortModal('${p.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  9925. <button onclick="deleteBridgePort('${p.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  9926. </td>
  9927. `;
  9928. tbody.appendChild(tr);
  9929. });
  9930. }
  9931. function openAddBridgePortModal() {
  9932. document.getElementById('bridge-port-modal-title').innerText = 'Add Port to Bridge';
  9933. document.getElementById('bridge-port-modal-id').value = '';
  9934. populateBridgeSelect('bridge-port-modal-bridge');
  9935. populateBridgePortCandidateSelect('bridge-port-modal-interface');
  9936. document.getElementById('bridge-port-modal-pvid').value = '1';
  9937. document.getElementById('bridge-port-modal-frametypes').value = 'admit-all';
  9938. document.getElementById('bridge-port-modal-ingressfiltering').checked = false;
  9939. document.getElementById('bridge-port-modal-horizon').value = '0';
  9940. document.getElementById('bridge-port-modal-pathcost').value = '10';
  9941. document.getElementById('bridge-port-modal-priority').value = '128';
  9942. document.getElementById('bridge-port-modal-learn').checked = true;
  9943. document.getElementById('bridge-port-modal-comment').value = '';
  9944. document.getElementById('bridge-port-modal-disabled').checked = false;
  9945. document.getElementById('bridge-port-modal').classList.remove('hidden');
  9946. }
  9947. function openEditBridgePortModal(id) {
  9948. const p = (state.bridgePorts || []).find(x => x.id === id);
  9949. if (!p) return;
  9950. document.getElementById('bridge-port-modal-title').innerText = `Edit Bridge Port (${p.interface})`;
  9951. document.getElementById('bridge-port-modal-id').value = p.id;
  9952. populateBridgeSelect('bridge-port-modal-bridge', p.bridge);
  9953. populateBridgePortCandidateSelect('bridge-port-modal-interface', p.interface);
  9954. document.getElementById('bridge-port-modal-pvid').value = p.pvid || 1;
  9955. document.getElementById('bridge-port-modal-frametypes').value = p.frame_types || 'admit-all';
  9956. document.getElementById('bridge-port-modal-ingressfiltering').checked = !!p.ingress_filtering;
  9957. document.getElementById('bridge-port-modal-horizon').value = p.horizon || 0;
  9958. document.getElementById('bridge-port-modal-pathcost').value = p.path_cost || 10;
  9959. document.getElementById('bridge-port-modal-priority').value = p.priority || 128;
  9960. document.getElementById('bridge-port-modal-learn').checked = p.learn !== false;
  9961. document.getElementById('bridge-port-modal-comment').value = p.comment || '';
  9962. document.getElementById('bridge-port-modal-disabled').checked = !!p.disabled;
  9963. document.getElementById('bridge-port-modal').classList.remove('hidden');
  9964. }
  9965. function closeBridgePortModal() {
  9966. document.getElementById('bridge-port-modal').classList.add('hidden');
  9967. }
  9968. async function submitSaveBridgePort(e) {
  9969. e.preventDefault();
  9970. const id = document.getElementById('bridge-port-modal-id').value;
  9971. const bridge = document.getElementById('bridge-port-modal-bridge').value;
  9972. const iface = document.getElementById('bridge-port-modal-interface').value;
  9973. const pvid = parseInt(document.getElementById('bridge-port-modal-pvid').value, 10) || 1;
  9974. const frameTypes = document.getElementById('bridge-port-modal-frametypes').value;
  9975. const ingressFiltering = document.getElementById('bridge-port-modal-ingressfiltering').checked;
  9976. const horizon = parseInt(document.getElementById('bridge-port-modal-horizon').value, 10) || 0;
  9977. const pathCost = parseInt(document.getElementById('bridge-port-modal-pathcost').value, 10) || 10;
  9978. const priority = parseInt(document.getElementById('bridge-port-modal-priority').value, 10) || 128;
  9979. const learn = document.getElementById('bridge-port-modal-learn').checked;
  9980. const comment = document.getElementById('bridge-port-modal-comment').value.trim();
  9981. const disabled = document.getElementById('bridge-port-modal-disabled').checked;
  9982. try {
  9983. const res = await fetch(`${API_BASE}/bridge/ports`, {
  9984. method: 'POST',
  9985. headers: { 'Content-Type': 'application/json' },
  9986. body: JSON.stringify({
  9987. id,
  9988. bridge,
  9989. interface: iface,
  9990. pvid,
  9991. frame_types: frameTypes,
  9992. ingress_filtering: ingressFiltering,
  9993. horizon,
  9994. path_cost: pathCost,
  9995. priority,
  9996. learn,
  9997. comment,
  9998. disabled
  9999. })
  10000. });
  10001. if (res.ok) {
  10002. showToast('Port Attached', `${iface} added to ${bridge}`, 'success');
  10003. closeBridgePortModal();
  10004. loadBridge();
  10005. fetchData(false);
  10006. } else {
  10007. const err = await res.json();
  10008. showToast('Error', err.error || err.message || 'Failed to save port', 'error');
  10009. }
  10010. } catch (err) {
  10011. showToast('Error', err.message, 'error');
  10012. }
  10013. }
  10014. async function toggleBridgePortState(id, disabled) {
  10015. try {
  10016. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}/state`, {
  10017. method: 'POST',
  10018. headers: { 'Content-Type': 'application/json' },
  10019. body: JSON.stringify({ disabled })
  10020. });
  10021. if (res.ok) {
  10022. loadBridge();
  10023. fetchData(false);
  10024. }
  10025. } catch (err) {
  10026. showToast('Error', err.message, 'error');
  10027. }
  10028. }
  10029. async function deleteBridgePort(id) {
  10030. const p = (state.bridgePorts || []).find(x => x.id === id);
  10031. const iface = p ? p.interface : id;
  10032. if (!confirm(`Detach interface '${iface}' from bridge?`)) return;
  10033. try {
  10034. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10035. if (res.ok) {
  10036. showToast('Port Detached', `${iface} removed from bridge`, 'success');
  10037. loadBridge();
  10038. fetchData(false);
  10039. }
  10040. } catch (err) {
  10041. showToast('Error', err.message, 'error');
  10042. }
  10043. }
  10044. // ----------------- Bridge VLANs -----------------
  10045. function renderBridgeVLANs() {
  10046. const tbody = document.getElementById('bridge-vlans-table-body');
  10047. const empty = document.getElementById('bridge-empty-vlans');
  10048. const countBadge = document.getElementById('bridge-vlans-count-badge');
  10049. const filterBridge = document.getElementById('bridge-vlans-filter-bridge')?.value || '';
  10050. if (!tbody) return;
  10051. tbody.innerHTML = '';
  10052. populateBridgeSelect('bridge-vlans-filter-bridge', filterBridge, true);
  10053. const vlans = (state.bridgeVLANs || []).filter(v => !filterBridge || v.bridge === filterBridge);
  10054. if (countBadge) countBadge.innerText = `${vlans.length} Entries`;
  10055. if (vlans.length === 0) {
  10056. empty?.classList.remove('hidden');
  10057. return;
  10058. }
  10059. empty?.classList.add('hidden');
  10060. vlans.forEach((v, idx) => {
  10061. const tr = document.createElement('tr');
  10062. tr.className = `hover:bg-slate-800/40 transition text-xs ${v.disabled ? 'opacity-50' : ''}`;
  10063. const taggedHtml = (v.tagged && v.tagged.length > 0)
  10064. ? 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(' ')
  10065. : '<span class="text-slate-600">none</span>';
  10066. const untaggedHtml = (v.untagged && v.untagged.length > 0)
  10067. ? 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(' ')
  10068. : '<span class="text-slate-600">none</span>';
  10069. const disabledFlag = v.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  10070. tr.innerHTML = `
  10071. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  10072. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  10073. <td class="py-2.5 px-3 font-semibold text-sky-400">${v.bridge}</td>
  10074. <td class="py-2.5 px-3 font-bold text-white font-mono text-sm">${v.vlan_ids}</td>
  10075. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${taggedHtml}</div></td>
  10076. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${untaggedHtml}</div></td>
  10077. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${v.comment || ''}">${v.comment || '-'}</td>
  10078. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  10079. <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>
  10080. <button onclick="openEditBridgeVLANModal('${v.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  10081. <button onclick="deleteBridgeVLAN('${v.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  10082. </td>
  10083. `;
  10084. tbody.appendChild(tr);
  10085. });
  10086. }
  10087. function openAddBridgeVLANModal() {
  10088. document.getElementById('bridge-vlan-modal-title').innerText = 'Add Bridge VLAN Entry';
  10089. document.getElementById('bridge-vlan-modal-id').value = '';
  10090. populateBridgeSelect('bridge-vlan-modal-bridge');
  10091. document.getElementById('bridge-vlan-modal-vlanids').value = '';
  10092. document.getElementById('bridge-vlan-modal-comment').value = '';
  10093. document.getElementById('bridge-vlan-modal-disabled').checked = false;
  10094. updateBridgeVlanPortCheckboxes();
  10095. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  10096. }
  10097. function openEditBridgeVLANModal(id) {
  10098. const v = (state.bridgeVLANs || []).find(x => x.id === id);
  10099. if (!v) return;
  10100. document.getElementById('bridge-vlan-modal-title').innerText = `Edit Bridge VLAN (${v.vlan_ids})`;
  10101. document.getElementById('bridge-vlan-modal-id').value = v.id;
  10102. populateBridgeSelect('bridge-vlan-modal-bridge', v.bridge);
  10103. document.getElementById('bridge-vlan-modal-vlanids').value = v.vlan_ids;
  10104. document.getElementById('bridge-vlan-modal-comment').value = v.comment || '';
  10105. document.getElementById('bridge-vlan-modal-disabled').checked = !!v.disabled;
  10106. updateBridgeVlanPortCheckboxes(v.tagged || [], v.untagged || []);
  10107. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  10108. }
  10109. function closeBridgeVlanModal() {
  10110. document.getElementById('bridge-vlan-modal').classList.add('hidden');
  10111. }
  10112. function updateBridgeVlanPortCheckboxes(taggedSelected = [], untaggedSelected = []) {
  10113. const selBridge = document.getElementById('bridge-vlan-modal-bridge')?.value || '';
  10114. const taggedBox = document.getElementById('bridge-vlan-tagged-ports');
  10115. const untaggedBox = document.getElementById('bridge-vlan-untagged-ports');
  10116. if (!taggedBox || !untaggedBox) return;
  10117. // Ports belonging to the selected bridge
  10118. const memberPorts = (state.bridgePorts || []).filter(p => !selBridge || p.bridge === selBridge);
  10119. if (memberPorts.length === 0) {
  10120. taggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  10121. untaggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  10122. return;
  10123. }
  10124. taggedBox.innerHTML = memberPorts.map(p => `
  10125. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  10126. <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">
  10127. <span>${p.interface}</span>
  10128. </label>
  10129. `).join('');
  10130. untaggedBox.innerHTML = memberPorts.map(p => `
  10131. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  10132. <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">
  10133. <span>${p.interface}</span>
  10134. </label>
  10135. `).join('');
  10136. }
  10137. async function submitSaveBridgeVLAN(e) {
  10138. e.preventDefault();
  10139. const id = document.getElementById('bridge-vlan-modal-id').value;
  10140. const bridge = document.getElementById('bridge-vlan-modal-bridge').value;
  10141. const vlanIDs = document.getElementById('bridge-vlan-modal-vlanids').value.trim();
  10142. const comment = document.getElementById('bridge-vlan-modal-comment').value.trim();
  10143. const disabled = document.getElementById('bridge-vlan-modal-disabled').checked;
  10144. const tagged = Array.from(document.querySelectorAll('input[name="bvlan-tagged"]:checked')).map(x => x.value);
  10145. const untagged = Array.from(document.querySelectorAll('input[name="bvlan-untagged"]:checked')).map(x => x.value);
  10146. try {
  10147. const res = await fetch(`${API_BASE}/bridge/vlans`, {
  10148. method: 'POST',
  10149. headers: { 'Content-Type': 'application/json' },
  10150. body: JSON.stringify({
  10151. id,
  10152. bridge,
  10153. vlan_ids: vlanIDs,
  10154. tagged,
  10155. untagged,
  10156. comment,
  10157. disabled
  10158. })
  10159. });
  10160. if (res.ok) {
  10161. showToast('VLAN Entry Saved', `VLAN ${vlanIDs} configured on ${bridge}`, 'success');
  10162. closeBridgeVlanModal();
  10163. loadBridge();
  10164. } else {
  10165. const err = await res.json();
  10166. showToast('Error', err.error || err.message || 'Failed to save VLAN entry', 'error');
  10167. }
  10168. } catch (err) {
  10169. showToast('Error', err.message, 'error');
  10170. }
  10171. }
  10172. async function toggleBridgeVLANState(id, disabled) {
  10173. try {
  10174. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}/state`, {
  10175. method: 'POST',
  10176. headers: { 'Content-Type': 'application/json' },
  10177. body: JSON.stringify({ disabled })
  10178. });
  10179. if (res.ok) loadBridge();
  10180. } catch (err) {
  10181. showToast('Error', err.message, 'error');
  10182. }
  10183. }
  10184. async function deleteBridgeVLAN(id) {
  10185. if (!confirm('Delete this bridge VLAN entry?')) return;
  10186. try {
  10187. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10188. if (res.ok) {
  10189. showToast('Deleted', 'VLAN entry removed from bridge', 'success');
  10190. loadBridge();
  10191. }
  10192. } catch (err) {
  10193. showToast('Error', err.message, 'error');
  10194. }
  10195. }
  10196. // ----------------- Hosts / MAC Table -----------------
  10197. async function loadBridgeHosts() {
  10198. const filterBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || '';
  10199. populateBridgeSelect('bridge-hosts-filter-bridge', filterBridge, true);
  10200. try {
  10201. const url = filterBridge ? `${API_BASE}/bridge/hosts?bridge=${encodeURIComponent(filterBridge)}` : `${API_BASE}/bridge/hosts`;
  10202. const res = await fetch(url);
  10203. if (res.ok) {
  10204. state.bridgeHosts = await res.json();
  10205. renderBridgeHosts();
  10206. }
  10207. } catch (err) {
  10208. console.error('Failed to load bridge hosts:', err);
  10209. }
  10210. }
  10211. function renderBridgeHosts() {
  10212. const tbody = document.getElementById('bridge-hosts-table-body');
  10213. const empty = document.getElementById('bridge-empty-hosts');
  10214. const countBadge = document.getElementById('bridge-hosts-count-badge');
  10215. const search = (document.getElementById('bridge-hosts-search')?.value || '').toLowerCase().trim();
  10216. if (!tbody) return;
  10217. tbody.innerHTML = '';
  10218. const hosts = (state.bridgeHosts || []).filter(h => {
  10219. if (!search) return true;
  10220. return (h.mac || '').toLowerCase().includes(search) || (h.interface || '').toLowerCase().includes(search) || (h.bridge || '').toLowerCase().includes(search);
  10221. });
  10222. if (countBadge) countBadge.innerText = `${hosts.length} Hosts`;
  10223. if (hosts.length === 0) {
  10224. empty?.classList.remove('hidden');
  10225. return;
  10226. }
  10227. empty?.classList.add('hidden');
  10228. hosts.forEach(h => {
  10229. const tr = document.createElement('tr');
  10230. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  10231. let flagBadges = '';
  10232. 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>';
  10233. 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>';
  10234. 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>';
  10235. tr.innerHTML = `
  10236. <td class="py-2.5 px-3 font-mono font-bold text-white text-sm">${h.mac}</td>
  10237. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${h.interface || '-'}</td>
  10238. <td class="py-2.5 px-3 font-mono text-sky-400">${h.bridge || '-'}</td>
  10239. <td class="py-2.5 px-3 font-mono">${h.vlan_id || 1}</td>
  10240. <td class="py-2.5 px-3 font-mono text-slate-400">${h.age ? h.age.toFixed(1) + 's' : '-'}</td>
  10241. <td class="py-2.5 px-3">${flagBadges}</td>
  10242. `;
  10243. tbody.appendChild(tr);
  10244. });
  10245. }
  10246. async function flushBridgeHosts() {
  10247. const selBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || (state.bridges[0] ? state.bridges[0].name : '');
  10248. if (!selBridge) {
  10249. showToast('Notice', 'Please select a bridge to flush dynamic MACs', 'info');
  10250. return;
  10251. }
  10252. if (!confirm(`Flush all dynamic learned MAC addresses on bridge '${selBridge}'?`)) return;
  10253. try {
  10254. const res = await fetch(`${API_BASE}/bridge/hosts/flush`, {
  10255. method: 'POST',
  10256. headers: { 'Content-Type': 'application/json' },
  10257. body: JSON.stringify({ bridge: selBridge })
  10258. });
  10259. if (res.ok) {
  10260. showToast('FDB Flushed', `Dynamic MACs flushed on ${selBridge}`, 'success');
  10261. loadBridgeHosts();
  10262. }
  10263. } catch (err) {
  10264. showToast('Error', err.message, 'error');
  10265. }
  10266. }
  10267. // ----------------- Helpers -----------------
  10268. function populateBridgeSelect(selectId, currentVal = '', includeAll = false) {
  10269. const sel = document.getElementById(selectId);
  10270. if (!sel) return;
  10271. const prevVal = currentVal || sel.value;
  10272. sel.innerHTML = includeAll ? '<option value="">All Bridges</option>' : '';
  10273. (state.bridges || []).forEach(b => {
  10274. const opt = document.createElement('option');
  10275. opt.value = b.name;
  10276. opt.innerText = `${b.name} (${b.ports_count} ports)`;
  10277. if (b.name === prevVal) opt.selected = true;
  10278. sel.appendChild(opt);
  10279. });
  10280. }
  10281. function populateBridgePortCandidateSelect(selectId, currentVal = '') {
  10282. const sel = document.getElementById(selectId);
  10283. if (!sel) return;
  10284. sel.innerHTML = '<option value="">(Select Interface...)</option>';
  10285. // 1. Physical Interfaces
  10286. const grpPhys = document.createElement('optgroup');
  10287. grpPhys.label = 'Physical Interfaces';
  10288. (state.interfaces || []).filter(i => i.type !== 'bridge' && i.type !== 'vlan' && i.type !== 'loopback').forEach(i => {
  10289. const opt = document.createElement('option');
  10290. opt.value = i.name;
  10291. opt.innerText = `${i.name} (${i.role || i.type})`;
  10292. if (i.name === currentVal) opt.selected = true;
  10293. grpPhys.appendChild(opt);
  10294. });
  10295. if (grpPhys.children.length > 0) sel.appendChild(grpPhys);
  10296. // 2. VLAN Sub-interfaces
  10297. const grpVlans = document.createElement('optgroup');
  10298. grpVlans.label = 'VLAN Sub-interfaces (802.1Q)';
  10299. (state.vlans || []).forEach(v => {
  10300. const opt = document.createElement('option');
  10301. opt.value = v.name;
  10302. opt.innerText = `${v.name} (VLAN ${v.vlan_id})`;
  10303. if (v.name === currentVal) opt.selected = true;
  10304. grpVlans.appendChild(opt);
  10305. });
  10306. if (grpVlans.children.length > 0) sel.appendChild(grpVlans);
  10307. // 3. EoIP Tunnels (MikroTik EoIP bridging!)
  10308. const grpEoip = document.createElement('optgroup');
  10309. grpEoip.label = 'EoIP Tunnels (Layer 2 VPN)';
  10310. (state.eoipTunnels || []).forEach(t => {
  10311. const opt = document.createElement('option');
  10312. opt.value = t.name;
  10313. opt.innerText = `${t.name} (Tunnel ID: ${t.tunnel_id} -> ${t.remote_address})`;
  10314. if (t.name === currentVal) opt.selected = true;
  10315. grpEoip.appendChild(opt);
  10316. });
  10317. if (grpEoip.children.length > 0) sel.appendChild(grpEoip);
  10318. }
  10319. // -------------------------------------------------------------
  10320. // RouterOS v7 Routing Filters Management (/routing filter)
  10321. // -------------------------------------------------------------
  10322. if (!state.activeRoutingFilterTab) state.activeRoutingFilterTab = 'rules';
  10323. if (!state.selectedFilterRow) state.selectedFilterRow = {};
  10324. if (!state.rfSort) state.rfSort = {};
  10325. function switchRoutingFilterTab(tab) {
  10326. state.activeRoutingFilterTab = tab;
  10327. const tabs = ['rules', 'select-rules', 'community-lists', 'as-lists'];
  10328. tabs.forEach(t => {
  10329. const btn = document.getElementById(`tab-rf-${t}`);
  10330. const content = document.getElementById(`tab-content-rf-${t}`);
  10331. if (btn) {
  10332. if (t === tab) {
  10333. 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';
  10334. } else {
  10335. btn.className = 'px-3 py-1 text-xs font-semibold rounded text-slate-400 hover:text-white hover:bg-slate-800 transition';
  10336. }
  10337. }
  10338. if (content) {
  10339. if (t === tab) content.classList.remove('hidden');
  10340. else content.classList.add('hidden');
  10341. }
  10342. });
  10343. const chainContainer = document.getElementById('rf-chain-filter-container');
  10344. if (chainContainer) {
  10345. if (tab === 'rules' || tab === 'select-rules') chainContainer.classList.remove('hidden');
  10346. else chainContainer.classList.add('hidden');
  10347. }
  10348. renderRoutingFilters();
  10349. }
  10350. function selectFilterRow(tab, id) {
  10351. if (state.selectedFilterRow[tab] === id) {
  10352. delete state.selectedFilterRow[tab];
  10353. } else {
  10354. state.selectedFilterRow[tab] = id;
  10355. }
  10356. if (tab === 'rules') renderRoutingFilterRules();
  10357. else if (tab === 'select-rules') renderRoutingFilterSelectRules();
  10358. else if (tab === 'community-lists') renderRoutingFilterCommunityLists();
  10359. else if (tab === 'as-lists') renderRoutingFilterASLists();
  10360. }
  10361. function openRoutingFilterNewModal() {
  10362. const tab = state.activeRoutingFilterTab || 'rules';
  10363. if (tab === 'rules') openAddRoutingFilterModal();
  10364. else if (tab === 'select-rules') openAddSelectRuleModal();
  10365. else if (tab === 'community-lists') openAddCommunityListModal();
  10366. else if (tab === 'as-lists') openAddASListModal();
  10367. }
  10368. function toggleSelectedRoutingFilter(disabled) {
  10369. const tab = state.activeRoutingFilterTab || 'rules';
  10370. const id = state.selectedFilterRow[tab];
  10371. if (!id) {
  10372. showToast('Select Row', 'Please click on a row to select it first', 'info');
  10373. return;
  10374. }
  10375. if (tab === 'rules') toggleRoutingFilterState(id, disabled);
  10376. else if (tab === 'select-rules') toggleSelectRuleState(id, disabled);
  10377. else if (tab === 'community-lists') toggleCommunityListState(id, disabled);
  10378. else if (tab === 'as-lists') toggleASListState(id, disabled);
  10379. }
  10380. function removeSelectedRoutingFilter() {
  10381. const tab = state.activeRoutingFilterTab || 'rules';
  10382. const id = state.selectedFilterRow[tab];
  10383. if (!id) {
  10384. showToast('Select Row', 'Please click on a row to select it first', 'info');
  10385. return;
  10386. }
  10387. if (tab === 'rules') deleteRoutingFilter(id);
  10388. else if (tab === 'select-rules') deleteSelectRule(id);
  10389. else if (tab === 'community-lists') deleteCommunityList(id);
  10390. else if (tab === 'as-lists') deleteASList(id);
  10391. }
  10392. function searchRoutingFilters(q) {
  10393. state.rfSearchQuery = (q || '').trim().toLowerCase();
  10394. renderRoutingFilters();
  10395. }
  10396. function sortFilterTable(tab, col) {
  10397. if (!state.rfSort) state.rfSort = {};
  10398. if (!state.rfSort[tab]) state.rfSort[tab] = { col: col, asc: true };
  10399. if (state.rfSort[tab].col === col) {
  10400. state.rfSort[tab].asc = !state.rfSort[tab].asc;
  10401. } else {
  10402. state.rfSort[tab].col = col;
  10403. state.rfSort[tab].asc = true;
  10404. }
  10405. const asc = state.rfSort[tab].asc;
  10406. let list = [];
  10407. if (tab === 'rules') list = state.routingFilters || [];
  10408. else if (tab === 'select-rules') list = state.routingSelectRules || [];
  10409. else if (tab === 'community-lists') list = state.routingCommunityLists || [];
  10410. else if (tab === 'as-lists') list = state.routingASLists || [];
  10411. list.sort((a, b) => {
  10412. let valA = a[col] ?? '';
  10413. let valB = b[col] ?? '';
  10414. if (col === 'flags') {
  10415. valA = a.disabled ? 'X' : 'A';
  10416. valB = b.disabled ? 'X' : 'A';
  10417. }
  10418. if (typeof valA === 'number' && typeof valB === 'number') {
  10419. return asc ? valA - valB : valB - valA;
  10420. }
  10421. return asc ? String(valA).localeCompare(String(valB)) : String(valB).localeCompare(String(valA));
  10422. });
  10423. const allCols = ['flags', 'rule_order', 'chain', 'rule', 'name', 'communities', 'range', 'regexp', 'comment'];
  10424. allCols.forEach(c => {
  10425. const el = document.getElementById(`sort-icon-${tab}-${c}`);
  10426. if (el) el.innerText = (c === col) ? (asc ? '▲' : '▼') : '';
  10427. });
  10428. if (tab === 'rules') renderRoutingFilterRules();
  10429. else if (tab === 'select-rules') renderRoutingFilterSelectRules();
  10430. else if (tab === 'community-lists') renderRoutingFilterCommunityLists();
  10431. else if (tab === 'as-lists') renderRoutingFilterASLists();
  10432. }
  10433. function renderRoutingFilters() {
  10434. const navBadge = document.getElementById('badge-filters-count');
  10435. const allRules = state.routingFilters || [];
  10436. if (navBadge) navBadge.innerText = allRules.length;
  10437. // Populate chain filter select options and datalist
  10438. const chainSelect = document.getElementById('routing-filter-chain-select');
  10439. const chainDatalist = document.getElementById('dl-routing-chains');
  10440. const uniqueChains = Array.from(new Set(allRules.map(r => r.chain).filter(Boolean))).sort();
  10441. if (chainSelect) {
  10442. const currentVal = state.filterChainSelected || 'all';
  10443. chainSelect.innerHTML = `<option value="all">All Chains (${allRules.length})</option>` +
  10444. uniqueChains.map(ch => {
  10445. const count = allRules.filter(r => r.chain === ch).length;
  10446. return `<option value="${escapeHtml(ch)}"${currentVal === ch ? ' selected' : ''}>${escapeHtml(ch)} (${count})</option>`;
  10447. }).join('');
  10448. chainSelect.value = currentVal;
  10449. }
  10450. if (chainDatalist) {
  10451. chainDatalist.innerHTML = uniqueChains.map(ch => `<option value="${escapeHtml(ch)}">`).join('');
  10452. }
  10453. renderRoutingFilterRules();
  10454. renderRoutingFilterSelectRules();
  10455. renderRoutingFilterCommunityLists();
  10456. renderRoutingFilterASLists();
  10457. }
  10458. function filterRoutingFiltersByChain(chain) {
  10459. state.filterChainSelected = chain;
  10460. renderRoutingFilters();
  10461. }
  10462. // -------------------------------------------------------------
  10463. // TAB 1: RULES (/routing filter rule)
  10464. // -------------------------------------------------------------
  10465. function renderRoutingFilterRules() {
  10466. const tbody = document.getElementById('routing-filter-rules-tbody');
  10467. if (!tbody) return;
  10468. const empty = document.getElementById('rf-rules-empty');
  10469. const statusCount = document.getElementById('rf-status-count');
  10470. let list = (state.routingFilters || []).slice();
  10471. if (state.filterChainSelected && state.filterChainSelected !== 'all') {
  10472. list = list.filter(r => r.chain === state.filterChainSelected);
  10473. }
  10474. const q = state.rfSearchQuery;
  10475. if (q) {
  10476. list = list.filter(r =>
  10477. (r.chain && r.chain.toLowerCase().includes(q)) ||
  10478. (r.rule && r.rule.toLowerCase().includes(q)) ||
  10479. (r.prefix && r.prefix.toLowerCase().includes(q)) ||
  10480. (r.comment && r.comment.toLowerCase().includes(q))
  10481. );
  10482. }
  10483. if (!state.rfSort?.['rules']) {
  10484. list.sort((a, b) => {
  10485. if (a.chain !== b.chain) return (a.chain || '').localeCompare(b.chain || '');
  10486. return (a.rule_order || 0) - (b.rule_order || 0);
  10487. });
  10488. }
  10489. if (statusCount && (state.activeRoutingFilterTab === 'rules' || !state.activeRoutingFilterTab)) {
  10490. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  10491. }
  10492. if (list.length === 0) {
  10493. tbody.innerHTML = '';
  10494. if (empty) empty.classList.remove('hidden');
  10495. return;
  10496. }
  10497. if (empty) empty.classList.add('hidden');
  10498. tbody.innerHTML = list.map(r => {
  10499. const isSelected = state.selectedFilterRow?.['rules'] === r.id;
  10500. const flagA = !r.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  10501. const flagX = r.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  10502. const flagC = r.comment ? '<span class="text-amber-400 font-bold ml-1" title="Comment">C</span>' : '';
  10503. let ruleDisplay = '';
  10504. if (r.rule && r.rule.trim() !== '') {
  10505. ruleDisplay = `<span class="text-emerald-400 font-mono font-medium">${escapeHtml(r.rule)}</span>`;
  10506. } else {
  10507. let conds = [];
  10508. if (r.prefix) conds.push(`dst in ${escapeHtml(r.prefix)}`);
  10509. if (r.match_protocol && r.match_protocol !== 'any') conds.push(`protocol ${escapeHtml(r.match_protocol)}`);
  10510. let act = r.action || 'accept';
  10511. ruleDisplay = `<span class="text-slate-300 font-mono">if (${conds.length ? conds.join(' && ') : 'true'}) { ${escapeHtml(act)}; }</span>`;
  10512. }
  10513. return `
  10514. <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'}">
  10515. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}${flagC}</td>
  10516. <td class="py-2 px-2 font-mono text-slate-400 font-bold">${r.rule_order || 10}</td>
  10517. <td class="py-2 px-3">
  10518. <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>
  10519. </td>
  10520. <td class="py-2 px-3 break-all max-w-xl">${ruleDisplay}</td>
  10521. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(r.comment || '')}</td>
  10522. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  10523. <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>
  10524. <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>
  10525. <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'}">
  10526. ${r.disabled ? 'Enable' : 'Disable'}
  10527. </button>
  10528. <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">
  10529. Edit
  10530. </button>
  10531. <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">
  10532. ✕
  10533. </button>
  10534. </td>
  10535. </tr>
  10536. `;
  10537. }).join('');
  10538. }
  10539. // -------------------------------------------------------------
  10540. // TAB 2: SELECT RULES (/routing filter select-rule)
  10541. // -------------------------------------------------------------
  10542. function renderRoutingFilterSelectRules() {
  10543. const tbody = document.getElementById('routing-filter-select-rules-tbody');
  10544. if (!tbody) return;
  10545. const empty = document.getElementById('rf-select-rules-empty');
  10546. const statusCount = document.getElementById('rf-status-count');
  10547. let list = (state.routingSelectRules || []).slice();
  10548. if (state.filterChainSelected && state.filterChainSelected !== 'all') {
  10549. list = list.filter(r => r.chain === state.filterChainSelected);
  10550. }
  10551. const q = state.rfSearchQuery;
  10552. if (q) {
  10553. list = list.filter(r =>
  10554. (r.chain && r.chain.toLowerCase().includes(q)) ||
  10555. (r.rule && r.rule.toLowerCase().includes(q)) ||
  10556. (r.comment && r.comment.toLowerCase().includes(q))
  10557. );
  10558. }
  10559. if (statusCount && state.activeRoutingFilterTab === 'select-rules') {
  10560. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  10561. }
  10562. if (list.length === 0) {
  10563. tbody.innerHTML = '';
  10564. if (empty) empty.classList.remove('hidden');
  10565. return;
  10566. }
  10567. if (empty) empty.classList.add('hidden');
  10568. tbody.innerHTML = list.map(r => {
  10569. const isSelected = state.selectedFilterRow?.['select-rules'] === r.id;
  10570. const flagA = !r.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  10571. const flagX = r.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  10572. return `
  10573. <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'}">
  10574. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  10575. <td class="py-2 px-2 font-mono text-slate-400 font-bold">${r.rule_order || 10}</td>
  10576. <td class="py-2 px-3">
  10577. <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>
  10578. </td>
  10579. <td class="py-2 px-3 break-all max-w-xl font-mono text-emerald-400">${escapeHtml(r.rule || '')}</td>
  10580. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(r.comment || '')}</td>
  10581. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  10582. <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'}">
  10583. ${r.disabled ? 'Enable' : 'Disable'}
  10584. </button>
  10585. <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">
  10586. Edit
  10587. </button>
  10588. <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">
  10589. ✕
  10590. </button>
  10591. </td>
  10592. </tr>
  10593. `;
  10594. }).join('');
  10595. }
  10596. // -------------------------------------------------------------
  10597. // TAB 3: COMMUNITY LISTS (/routing filter community-list)
  10598. // -------------------------------------------------------------
  10599. function renderRoutingFilterCommunityLists() {
  10600. const tbody = document.getElementById('routing-filter-comm-lists-tbody');
  10601. if (!tbody) return;
  10602. const empty = document.getElementById('rf-comm-lists-empty');
  10603. const statusCount = document.getElementById('rf-status-count');
  10604. let list = (state.routingCommunityLists || []).slice();
  10605. const q = state.rfSearchQuery;
  10606. if (q) {
  10607. list = list.filter(cl =>
  10608. (cl.name && cl.name.toLowerCase().includes(q)) ||
  10609. (cl.comment && cl.comment.toLowerCase().includes(q)) ||
  10610. (cl.communities && cl.communities.some(c => c.toLowerCase().includes(q)))
  10611. );
  10612. }
  10613. if (statusCount && state.activeRoutingFilterTab === 'community-lists') {
  10614. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  10615. }
  10616. if (list.length === 0) {
  10617. tbody.innerHTML = '';
  10618. if (empty) empty.classList.remove('hidden');
  10619. return;
  10620. }
  10621. if (empty) empty.classList.add('hidden');
  10622. tbody.innerHTML = list.map(cl => {
  10623. const isSelected = state.selectedFilterRow?.['community-lists'] === cl.id;
  10624. const flagA = !cl.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  10625. const flagX = cl.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  10626. const commBadges = (cl.communities || []).map(c =>
  10627. `<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>`
  10628. ).join(' ');
  10629. return `
  10630. <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'}">
  10631. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  10632. <td class="py-2 px-3 font-mono font-bold text-white">${escapeHtml(cl.name)}</td>
  10633. <td class="py-2 px-3 space-x-1">${commBadges || '<span class="text-slate-600">-</span>'}</td>
  10634. <td class="py-2 px-3 font-mono text-slate-400">${escapeHtml(cl.regexp || '-')}</td>
  10635. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(cl.comment || '')}</td>
  10636. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  10637. <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'}">
  10638. ${cl.disabled ? 'Enable' : 'Disable'}
  10639. </button>
  10640. <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">
  10641. Edit
  10642. </button>
  10643. <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">
  10644. ✕
  10645. </button>
  10646. </td>
  10647. </tr>
  10648. `;
  10649. }).join('');
  10650. }
  10651. // -------------------------------------------------------------
  10652. // TAB 4: AS LISTS (/routing filter num-list)
  10653. // -------------------------------------------------------------
  10654. function renderRoutingFilterASLists() {
  10655. const tbody = document.getElementById('routing-filter-as-lists-tbody');
  10656. if (!tbody) return;
  10657. const empty = document.getElementById('rf-as-lists-empty');
  10658. const statusCount = document.getElementById('rf-status-count');
  10659. let list = (state.routingASLists || []).slice();
  10660. const q = state.rfSearchQuery;
  10661. if (q) {
  10662. list = list.filter(al =>
  10663. (al.name && al.name.toLowerCase().includes(q)) ||
  10664. (al.range && al.range.toLowerCase().includes(q)) ||
  10665. (al.comment && al.comment.toLowerCase().includes(q))
  10666. );
  10667. }
  10668. if (statusCount && state.activeRoutingFilterTab === 'as-lists') {
  10669. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  10670. }
  10671. if (list.length === 0) {
  10672. tbody.innerHTML = '';
  10673. if (empty) empty.classList.remove('hidden');
  10674. return;
  10675. }
  10676. if (empty) empty.classList.add('hidden');
  10677. tbody.innerHTML = list.map(al => {
  10678. const isSelected = state.selectedFilterRow?.['as-lists'] === al.id;
  10679. const flagA = !al.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  10680. const flagX = al.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  10681. return `
  10682. <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'}">
  10683. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  10684. <td class="py-2 px-3 font-mono font-bold text-white">${escapeHtml(al.name)}</td>
  10685. <td class="py-2 px-3 font-mono text-purple-300">${escapeHtml(al.range)}</td>
  10686. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(al.comment || '')}</td>
  10687. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  10688. <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'}">
  10689. ${al.disabled ? 'Enable' : 'Disable'}
  10690. </button>
  10691. <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">
  10692. Edit
  10693. </button>
  10694. <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">
  10695. ✕
  10696. </button>
  10697. </td>
  10698. </tr>
  10699. `;
  10700. }).join('');
  10701. }
  10702. // -------------------------------------------------------------
  10703. // SNIPPETS & WIZARD HELPERS
  10704. // -------------------------------------------------------------
  10705. function insertRuleSnippet(type) {
  10706. const textarea = document.getElementById('modal-rf-rule');
  10707. if (!textarea) return;
  10708. let snippet = '';
  10709. switch (type) {
  10710. case 'accept-default':
  10711. snippet = 'if (dst in 0.0.0.0/0) { accept; }';
  10712. break;
  10713. case 'drop-rfc1918':
  10714. snippet = 'if (dst in 10.0.0.0/8 || dst in 172.16.0.0/12 || dst in 192.168.0.0/16) { reject; }';
  10715. break;
  10716. case 'len-24':
  10717. snippet = 'if (dst-len > 24) { reject; }';
  10718. break;
  10719. case 'local-pref-150':
  10720. snippet = 'if (dst in 10.0.0.0/8) { set bgp-local-pref 150; accept; }';
  10721. break;
  10722. case 'as-prepend-2':
  10723. snippet = 'set bgp-path-prepend 2; accept;';
  10724. break;
  10725. case 'set-comm':
  10726. snippet = 'set bgp-communities.add 65000:100; accept;';
  10727. break;
  10728. case 'match-comm':
  10729. snippet = 'if (bgp-communities includes 65000:100) { accept; }';
  10730. break;
  10731. case 'reject-all':
  10732. snippet = 'reject;';
  10733. break;
  10734. }
  10735. if (!snippet) return;
  10736. if (!textarea.value.trim()) {
  10737. textarea.value = snippet;
  10738. } else {
  10739. textarea.value = textarea.value.trim() + '\n' + snippet;
  10740. }
  10741. }
  10742. function generateScriptFromWizard() {
  10743. const pfx = (document.getElementById('modal-rf-prefix')?.value || '').trim();
  10744. const pfxLen = (document.getElementById('modal-rf-prefix-len')?.value || '').trim();
  10745. const proto = document.getElementById('modal-rf-protocol')?.value || 'any';
  10746. const asp = (document.getElementById('modal-rf-as-path')?.value || '').trim();
  10747. const comm = (document.getElementById('modal-rf-community')?.value || '').trim();
  10748. const act = document.getElementById('modal-rf-action')?.value || 'accept';
  10749. const lp = parseInt(document.getElementById('modal-rf-set-local-pref')?.value, 10) || 0;
  10750. const prep = parseInt(document.getElementById('modal-rf-set-as-prepend')?.value, 10) || 0;
  10751. const conds = [];
  10752. if (pfx) {
  10753. if (pfxLen) {
  10754. if (pfxLen.includes('-')) {
  10755. const parts = pfxLen.split('-');
  10756. conds.push(`dst in ${pfx}{${parts[0].trim()},${parts[1].trim()}}`);
  10757. } else {
  10758. conds.push(`dst in ${pfx} && dst-len >= ${pfxLen}`);
  10759. }
  10760. } else {
  10761. conds.push(`dst in ${pfx}`);
  10762. }
  10763. }
  10764. if (proto && proto !== 'any') {
  10765. conds.push(`protocol ${proto}`);
  10766. }
  10767. if (asp) {
  10768. conds.push(`bgp-as-path "${asp}"`);
  10769. }
  10770. if (comm) {
  10771. conds.push(`bgp-communities includes ${comm}`);
  10772. }
  10773. const actions = [];
  10774. if (lp > 0) actions.push(`set bgp-local-pref ${lp};`);
  10775. if (prep > 0) actions.push(`set bgp-path-prepend ${prep};`);
  10776. actions.push(`${act};`);
  10777. let code = '';
  10778. if (conds.length > 0) {
  10779. code = `if (${conds.join(' && ')}) {\n ${actions.join(' ')}\n}`;
  10780. } else {
  10781. code = actions.join(' ');
  10782. }
  10783. const textarea = document.getElementById('modal-rf-rule');
  10784. if (textarea) textarea.value = code;
  10785. }
  10786. // -------------------------------------------------------------
  10787. // MODAL CRUD: RULES (/routing filter rule)
  10788. // -------------------------------------------------------------
  10789. function openAddRoutingFilterModal(defaultChain = '') {
  10790. const form = document.getElementById('routing-filter-form');
  10791. if (form) form.reset();
  10792. const idEl = document.getElementById('modal-rf-id');
  10793. if (idEl) idEl.value = '';
  10794. const titleEl = document.getElementById('modal-rf-title');
  10795. if (titleEl) titleEl.innerText = 'Add Routing Filter Rule';
  10796. const chainEl = document.getElementById('modal-rf-chain');
  10797. if (chainEl) chainEl.value = defaultChain || (state.filterChainSelected && state.filterChainSelected !== 'all' ? state.filterChainSelected : 'bgp-in');
  10798. const orderEl = document.getElementById('modal-rf-order');
  10799. if (orderEl) orderEl.value = ((state.routingFilters || []).length + 1) * 10;
  10800. const ruleEl = document.getElementById('modal-rf-rule');
  10801. if (ruleEl) ruleEl.value = 'if (dst in 10.0.0.0/8) { set bgp-local-pref 150; accept; }';
  10802. const disEl = document.getElementById('modal-rf-disabled');
  10803. if (disEl) disEl.checked = false;
  10804. const modal = document.getElementById('modal-routing-filter');
  10805. if (modal) modal.classList.remove('hidden');
  10806. }
  10807. function openEditRoutingFilterModal(id) {
  10808. const r = (state.routingFilters || []).find(item => item.id === id);
  10809. if (!r) return;
  10810. const idEl = document.getElementById('modal-rf-id');
  10811. if (idEl) idEl.value = r.id;
  10812. const titleEl = document.getElementById('modal-rf-title');
  10813. if (titleEl) titleEl.innerText = 'Edit Routing Filter Rule';
  10814. const chainEl = document.getElementById('modal-rf-chain');
  10815. if (chainEl) chainEl.value = r.chain || '';
  10816. const orderEl = document.getElementById('modal-rf-order');
  10817. if (orderEl) orderEl.value = r.rule_order || 10;
  10818. const ruleEl = document.getElementById('modal-rf-rule');
  10819. if (ruleEl) {
  10820. if (r.rule) {
  10821. ruleEl.value = r.rule;
  10822. } else {
  10823. let conds = [];
  10824. if (r.prefix) conds.push(`dst in ${r.prefix}`);
  10825. if (r.match_protocol && r.match_protocol !== 'any') conds.push(`protocol ${r.match_protocol}`);
  10826. let act = r.action || 'accept';
  10827. ruleEl.value = `if (${conds.length ? conds.join(' && ') : 'true'}) { ${act}; }`;
  10828. }
  10829. }
  10830. const comEl = document.getElementById('modal-rf-comment');
  10831. if (comEl) comEl.value = r.comment || '';
  10832. const disEl = document.getElementById('modal-rf-disabled');
  10833. if (disEl) disEl.checked = !!r.disabled;
  10834. const modal = document.getElementById('modal-routing-filter');
  10835. if (modal) modal.classList.remove('hidden');
  10836. }
  10837. function closeRoutingFilterModal() {
  10838. const modal = document.getElementById('modal-routing-filter');
  10839. if (modal) modal.classList.add('hidden');
  10840. }
  10841. async function submitRoutingFilter(e) {
  10842. if (e) e.preventDefault();
  10843. const payload = {
  10844. id: document.getElementById('modal-rf-id').value,
  10845. chain: document.getElementById('modal-rf-chain').value.trim(),
  10846. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  10847. rule: document.getElementById('modal-rf-rule').value.trim(),
  10848. comment: document.getElementById('modal-rf-comment').value.trim(),
  10849. disabled: document.getElementById('modal-rf-disabled').checked
  10850. };
  10851. try {
  10852. const res = await fetch(`${API_BASE}/routing/filters`, {
  10853. method: 'POST',
  10854. headers: { 'Content-Type': 'application/json' },
  10855. body: JSON.stringify(payload)
  10856. });
  10857. if (res.ok) {
  10858. closeRoutingFilterModal();
  10859. showToast('Success', 'Routing filter rule saved', 'success');
  10860. loadDynamicRouting();
  10861. } else {
  10862. const err = await res.json();
  10863. showToast('Error', err.error || 'Failed to save filter rule', 'error');
  10864. }
  10865. } catch (err) {
  10866. showToast('Error', err.message, 'error');
  10867. }
  10868. }
  10869. async function applyRoutingFilterForm() {
  10870. const payload = {
  10871. id: document.getElementById('modal-rf-id').value,
  10872. chain: document.getElementById('modal-rf-chain').value.trim(),
  10873. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  10874. rule: document.getElementById('modal-rf-rule').value.trim(),
  10875. comment: document.getElementById('modal-rf-comment').value.trim(),
  10876. disabled: document.getElementById('modal-rf-disabled').checked
  10877. };
  10878. try {
  10879. const res = await fetch(`${API_BASE}/routing/filters`, {
  10880. method: 'POST',
  10881. headers: { 'Content-Type': 'application/json' },
  10882. body: JSON.stringify(payload)
  10883. });
  10884. if (res.ok) {
  10885. const data = await res.json();
  10886. if (data.id) document.getElementById('modal-rf-id').value = data.id;
  10887. showToast('Applied', 'Routing filter configuration applied', 'success');
  10888. loadDynamicRouting();
  10889. } else {
  10890. const err = await res.json();
  10891. showToast('Error', err.error || 'Failed to apply filter rule', 'error');
  10892. }
  10893. } catch (err) {
  10894. showToast('Error', err.message, 'error');
  10895. }
  10896. }
  10897. async function moveRoutingFilterOrder(id, delta) {
  10898. const list = state.routingFilters || [];
  10899. const idx = list.findIndex(r => r.id === id);
  10900. if (idx < 0) return;
  10901. const targetIdx = idx + delta;
  10902. if (targetIdx < 0 || targetIdx >= list.length) return;
  10903. const currentOrder = list[idx].rule_order || 10;
  10904. const targetOrder = list[targetIdx].rule_order || 20;
  10905. list[idx].rule_order = targetOrder;
  10906. list[targetIdx].rule_order = currentOrder;
  10907. try {
  10908. await fetch(`${API_BASE}/routing/filters`, {
  10909. method: 'POST',
  10910. headers: { 'Content-Type': 'application/json' },
  10911. body: JSON.stringify(list[idx])
  10912. });
  10913. await fetch(`${API_BASE}/routing/filters`, {
  10914. method: 'POST',
  10915. headers: { 'Content-Type': 'application/json' },
  10916. body: JSON.stringify(list[targetIdx])
  10917. });
  10918. loadDynamicRouting();
  10919. } catch (e) {
  10920. console.error('Reorder error:', e);
  10921. }
  10922. }
  10923. async function deleteRoutingFilter(id) {
  10924. if (!confirm('Are you sure you want to delete this routing filter rule?')) return;
  10925. try {
  10926. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10927. if (res.ok) {
  10928. showToast('Deleted', 'Routing filter rule removed', 'info');
  10929. loadDynamicRouting();
  10930. } else {
  10931. const err = await res.json();
  10932. showToast('Error', err.error || 'Failed to delete rule', 'error');
  10933. }
  10934. } catch (err) {
  10935. showToast('Error', err.message, 'error');
  10936. }
  10937. }
  10938. async function toggleRoutingFilterState(id, disabled) {
  10939. try {
  10940. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}/state`, {
  10941. method: 'POST',
  10942. headers: { 'Content-Type': 'application/json' },
  10943. body: JSON.stringify({ disabled })
  10944. });
  10945. if (res.ok) {
  10946. showToast('Status Updated', `Rule ${disabled ? 'disabled' : 'enabled'}`, 'info');
  10947. loadDynamicRouting();
  10948. } else {
  10949. const err = await res.json();
  10950. showToast('Error', err.error || 'Failed to toggle rule state', 'error');
  10951. }
  10952. } catch (err) {
  10953. showToast('Error', err.message, 'error');
  10954. }
  10955. }
  10956. // -------------------------------------------------------------
  10957. // MODAL CRUD: SELECT RULES (/routing filter select-rule)
  10958. // -------------------------------------------------------------
  10959. function openAddSelectRuleModal() {
  10960. document.getElementById('modal-rf-sr-id').value = '';
  10961. document.getElementById('modal-rf-sr-title').innerText = 'Add Routing Select Rule';
  10962. document.getElementById('modal-rf-sr-chain').value = state.filterChainSelected && state.filterChainSelected !== 'all' ? state.filterChainSelected : 'bgp-out';
  10963. document.getElementById('modal-rf-sr-order').value = ((state.routingSelectRules || []).length + 1) * 10;
  10964. document.getElementById('modal-rf-sr-rule').value = 'if (protocol bgp && dst in 10.0.0.0/8) { accept; }';
  10965. document.getElementById('modal-rf-sr-comment').value = '';
  10966. document.getElementById('modal-rf-sr-disabled').checked = false;
  10967. document.getElementById('modal-rf-select-rule').classList.remove('hidden');
  10968. }
  10969. function openEditSelectRuleModal(id) {
  10970. const r = (state.routingSelectRules || []).find(item => item.id === id);
  10971. if (!r) return;
  10972. document.getElementById('modal-rf-sr-id').value = r.id;
  10973. document.getElementById('modal-rf-sr-title').innerText = 'Edit Routing Select Rule';
  10974. document.getElementById('modal-rf-sr-chain').value = r.chain || '';
  10975. document.getElementById('modal-rf-sr-order').value = r.rule_order || 10;
  10976. document.getElementById('modal-rf-sr-rule').value = r.rule || '';
  10977. document.getElementById('modal-rf-sr-comment').value = r.comment || '';
  10978. document.getElementById('modal-rf-sr-disabled').checked = !!r.disabled;
  10979. document.getElementById('modal-rf-select-rule').classList.remove('hidden');
  10980. }
  10981. function closeSelectRuleModal() {
  10982. document.getElementById('modal-rf-select-rule').classList.add('hidden');
  10983. }
  10984. async function submitSelectRule(e) {
  10985. e.preventDefault();
  10986. const payload = {
  10987. id: document.getElementById('modal-rf-sr-id').value,
  10988. chain: document.getElementById('modal-rf-sr-chain').value.trim(),
  10989. rule_order: parseInt(document.getElementById('modal-rf-sr-order').value, 10) || 10,
  10990. rule: document.getElementById('modal-rf-sr-rule').value.trim(),
  10991. comment: document.getElementById('modal-rf-sr-comment').value.trim(),
  10992. disabled: document.getElementById('modal-rf-sr-disabled').checked
  10993. };
  10994. try {
  10995. const res = await fetch(`${API_BASE}/routing/filters/select-rules`, {
  10996. method: 'POST',
  10997. headers: { 'Content-Type': 'application/json' },
  10998. body: JSON.stringify(payload)
  10999. });
  11000. if (res.ok) {
  11001. closeSelectRuleModal();
  11002. showToast('Success', 'Select rule saved', 'success');
  11003. loadDynamicRouting();
  11004. } else {
  11005. const err = await res.json();
  11006. showToast('Error', err.error || 'Failed to save select rule', 'error');
  11007. }
  11008. } catch (err) {
  11009. showToast('Error', err.message, 'error');
  11010. }
  11011. }
  11012. async function deleteSelectRule(id) {
  11013. if (!confirm('Are you sure you want to delete this select rule?')) return;
  11014. try {
  11015. const res = await fetch(`${API_BASE}/routing/filters/select-rules/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11016. if (res.ok) {
  11017. showToast('Deleted', 'Select rule removed', 'info');
  11018. loadDynamicRouting();
  11019. } else {
  11020. const err = await res.json();
  11021. showToast('Error', err.error || 'Failed to delete select rule', 'error');
  11022. }
  11023. } catch (err) {
  11024. showToast('Error', err.message, 'error');
  11025. }
  11026. }
  11027. async function toggleSelectRuleState(id, disabled) {
  11028. try {
  11029. const res = await fetch(`${API_BASE}/routing/filters/select-rules/${encodeURIComponent(id)}/state`, {
  11030. method: 'POST',
  11031. headers: { 'Content-Type': 'application/json' },
  11032. body: JSON.stringify({ disabled })
  11033. });
  11034. if (res.ok) {
  11035. showToast('Status Updated', `Select rule ${disabled ? 'disabled' : 'enabled'}`, 'info');
  11036. loadDynamicRouting();
  11037. } else {
  11038. const err = await res.json();
  11039. showToast('Error', err.error || 'Failed to update select rule state', 'error');
  11040. }
  11041. } catch (err) {
  11042. showToast('Error', err.message, 'error');
  11043. }
  11044. }
  11045. // -------------------------------------------------------------
  11046. // MODAL CRUD: COMMUNITY LISTS (/routing filter community-list)
  11047. // -------------------------------------------------------------
  11048. function openAddCommunityListModal() {
  11049. document.getElementById('modal-rf-cl-id').value = '';
  11050. document.getElementById('modal-rf-cl-title').innerText = 'Add BGP Community List';
  11051. document.getElementById('modal-rf-cl-name').value = '';
  11052. document.getElementById('modal-rf-cl-communities').value = '';
  11053. document.getElementById('modal-rf-cl-regexp').value = '';
  11054. document.getElementById('modal-rf-cl-comment').value = '';
  11055. document.getElementById('modal-rf-cl-disabled').checked = false;
  11056. document.getElementById('modal-rf-community-list').classList.remove('hidden');
  11057. }
  11058. function openEditCommunityListModal(id) {
  11059. const cl = (state.routingCommunityLists || []).find(item => item.id === id);
  11060. if (!cl) return;
  11061. document.getElementById('modal-rf-cl-id').value = cl.id;
  11062. document.getElementById('modal-rf-cl-title').innerText = 'Edit BGP Community List';
  11063. document.getElementById('modal-rf-cl-name').value = cl.name || '';
  11064. document.getElementById('modal-rf-cl-communities').value = (cl.communities || []).join(', ');
  11065. document.getElementById('modal-rf-cl-regexp').value = cl.regexp || '';
  11066. document.getElementById('modal-rf-cl-comment').value = cl.comment || '';
  11067. document.getElementById('modal-rf-cl-disabled').checked = !!cl.disabled;
  11068. document.getElementById('modal-rf-community-list').classList.remove('hidden');
  11069. }
  11070. function closeCommunityListModal() {
  11071. document.getElementById('modal-rf-community-list').classList.add('hidden');
  11072. }
  11073. async function submitCommunityList(e) {
  11074. e.preventDefault();
  11075. const rawComms = document.getElementById('modal-rf-cl-communities').value;
  11076. const comms = rawComms.split(',').map(c => c.trim()).filter(Boolean);
  11077. const payload = {
  11078. id: document.getElementById('modal-rf-cl-id').value,
  11079. name: document.getElementById('modal-rf-cl-name').value.trim(),
  11080. communities: comms,
  11081. regexp: document.getElementById('modal-rf-cl-regexp').value.trim(),
  11082. comment: document.getElementById('modal-rf-cl-comment').value.trim(),
  11083. disabled: document.getElementById('modal-rf-cl-disabled').checked
  11084. };
  11085. try {
  11086. const res = await fetch(`${API_BASE}/routing/filters/community-lists`, {
  11087. method: 'POST',
  11088. headers: { 'Content-Type': 'application/json' },
  11089. body: JSON.stringify(payload)
  11090. });
  11091. if (res.ok) {
  11092. closeCommunityListModal();
  11093. showToast('Success', 'Community list saved', 'success');
  11094. loadDynamicRouting();
  11095. } else {
  11096. const err = await res.json();
  11097. showToast('Error', err.error || 'Failed to save community list', 'error');
  11098. }
  11099. } catch (err) {
  11100. showToast('Error', err.message, 'error');
  11101. }
  11102. }
  11103. async function deleteCommunityList(id) {
  11104. if (!confirm('Are you sure you want to delete this community list?')) return;
  11105. try {
  11106. const res = await fetch(`${API_BASE}/routing/filters/community-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11107. if (res.ok) {
  11108. showToast('Deleted', 'Community list removed', 'info');
  11109. loadDynamicRouting();
  11110. } else {
  11111. const err = await res.json();
  11112. showToast('Error', err.error || 'Failed to delete community list', 'error');
  11113. }
  11114. } catch (err) {
  11115. showToast('Error', err.message, 'error');
  11116. }
  11117. }
  11118. async function toggleCommunityListState(id, disabled) {
  11119. try {
  11120. const res = await fetch(`${API_BASE}/routing/filters/community-lists/${encodeURIComponent(id)}/state`, {
  11121. method: 'POST',
  11122. headers: { 'Content-Type': 'application/json' },
  11123. body: JSON.stringify({ disabled })
  11124. });
  11125. if (res.ok) {
  11126. showToast('Status Updated', `Community list ${disabled ? 'disabled' : 'enabled'}`, 'info');
  11127. loadDynamicRouting();
  11128. } else {
  11129. const err = await res.json();
  11130. showToast('Error', err.error || 'Failed to update community list state', 'error');
  11131. }
  11132. } catch (err) {
  11133. showToast('Error', err.message, 'error');
  11134. }
  11135. }
  11136. // -------------------------------------------------------------
  11137. // MODAL CRUD: AS LISTS (/routing filter num-list)
  11138. // -------------------------------------------------------------
  11139. function openAddASListModal() {
  11140. document.getElementById('modal-rf-al-id').value = '';
  11141. document.getElementById('modal-rf-al-title').innerText = 'Add AS Number List';
  11142. document.getElementById('modal-rf-al-name').value = '';
  11143. document.getElementById('modal-rf-al-range').value = '';
  11144. document.getElementById('modal-rf-al-comment').value = '';
  11145. document.getElementById('modal-rf-al-disabled').checked = false;
  11146. document.getElementById('modal-rf-as-list').classList.remove('hidden');
  11147. }
  11148. function openEditASListModal(id) {
  11149. const al = (state.routingASLists || []).find(item => item.id === id);
  11150. if (!al) return;
  11151. document.getElementById('modal-rf-al-id').value = al.id;
  11152. document.getElementById('modal-rf-al-title').innerText = 'Edit AS Number List';
  11153. document.getElementById('modal-rf-al-name').value = al.name || '';
  11154. document.getElementById('modal-rf-al-range').value = al.range || '';
  11155. document.getElementById('modal-rf-al-comment').value = al.comment || '';
  11156. document.getElementById('modal-rf-al-disabled').checked = !!al.disabled;
  11157. document.getElementById('modal-rf-as-list').classList.remove('hidden');
  11158. }
  11159. function closeASListModal() {
  11160. document.getElementById('modal-rf-as-list').classList.add('hidden');
  11161. }
  11162. async function submitASList(e) {
  11163. e.preventDefault();
  11164. const payload = {
  11165. id: document.getElementById('modal-rf-al-id').value,
  11166. name: document.getElementById('modal-rf-al-name').value.trim(),
  11167. range: document.getElementById('modal-rf-al-range').value.trim(),
  11168. comment: document.getElementById('modal-rf-al-comment').value.trim(),
  11169. disabled: document.getElementById('modal-rf-al-disabled').checked
  11170. };
  11171. try {
  11172. const res = await fetch(`${API_BASE}/routing/filters/as-lists`, {
  11173. method: 'POST',
  11174. headers: { 'Content-Type': 'application/json' },
  11175. body: JSON.stringify(payload)
  11176. });
  11177. if (res.ok) {
  11178. closeASListModal();
  11179. showToast('Success', 'AS number list saved', 'success');
  11180. loadDynamicRouting();
  11181. } else {
  11182. const err = await res.json();
  11183. showToast('Error', err.error || 'Failed to save AS list', 'error');
  11184. }
  11185. } catch (err) {
  11186. showToast('Error', err.message, 'error');
  11187. }
  11188. }
  11189. async function deleteASList(id) {
  11190. if (!confirm('Are you sure you want to delete this AS list?')) return;
  11191. try {
  11192. const res = await fetch(`${API_BASE}/routing/filters/as-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11193. if (res.ok) {
  11194. showToast('Deleted', 'AS list removed', 'info');
  11195. loadDynamicRouting();
  11196. } else {
  11197. const err = await res.json();
  11198. showToast('Error', err.error || 'Failed to delete AS list', 'error');
  11199. }
  11200. } catch (err) {
  11201. showToast('Error', err.message, 'error');
  11202. }
  11203. }
  11204. async function toggleASListState(id, disabled) {
  11205. try {
  11206. const res = await fetch(`${API_BASE}/routing/filters/as-lists/${encodeURIComponent(id)}/state`, {
  11207. method: 'POST',
  11208. headers: { 'Content-Type': 'application/json' },
  11209. body: JSON.stringify({ disabled })
  11210. });
  11211. if (res.ok) {
  11212. showToast('Status Updated', `AS list ${disabled ? 'disabled' : 'enabled'}`, 'info');
  11213. loadDynamicRouting();
  11214. } else {
  11215. const err = await res.json();
  11216. showToast('Error', err.error || 'Failed to update AS list state', 'error');
  11217. }
  11218. } catch (err) {
  11219. showToast('Error', err.message, 'error');
  11220. }
  11221. }
  11222. // ==========================================
  11223. // TROUBLESHOOT & DIAGNOSTIC TOOLS (/tool)
  11224. // ==========================================
  11225. function loadToolsView() {
  11226. populateToolsInterfaces();
  11227. switchToolsSubTab(state.activeToolsSubTab || 'ping');
  11228. }
  11229. function populateToolsInterfaces() {
  11230. const pingSel = document.getElementById('tools-ping-iface');
  11231. const traceSel = document.getElementById('tools-tr-iface');
  11232. let opts = '<option value="">Auto (Default Route)</option>';
  11233. if (Array.isArray(state.interfaces)) {
  11234. state.interfaces.forEach(iface => {
  11235. if (iface.name) {
  11236. opts += `<option value="${escapeHtml(iface.name)}">${escapeHtml(iface.name)}${iface.ip_address ? ' (' + escapeHtml(iface.ip_address) + ')' : ''}</option>`;
  11237. }
  11238. });
  11239. }
  11240. if (pingSel) {
  11241. const cur = pingSel.value;
  11242. pingSel.innerHTML = opts;
  11243. if (cur) pingSel.value = cur;
  11244. }
  11245. if (traceSel) {
  11246. const cur = traceSel.value;
  11247. traceSel.innerHTML = opts;
  11248. if (cur) traceSel.value = cur;
  11249. }
  11250. }
  11251. function switchToolsSubTab(subTab) {
  11252. state.activeToolsSubTab = subTab;
  11253. const tabs = ['ping', 'traceroute', 'mtr', 'dns', 'port'];
  11254. tabs.forEach(t => {
  11255. const btn = document.getElementById(`tools-subtab-btn-${t}`);
  11256. const view = document.getElementById(`tools-view-${t}`);
  11257. if (btn) {
  11258. if (t === subTab) {
  11259. 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';
  11260. } else {
  11261. 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';
  11262. }
  11263. }
  11264. if (view) {
  11265. if (t === subTab) {
  11266. view.classList.remove('hidden');
  11267. } else {
  11268. view.classList.add('hidden');
  11269. }
  11270. }
  11271. });
  11272. }
  11273. function setPortPreset(port) {
  11274. const input = document.getElementById('tools-port-num');
  11275. if (input) input.value = port;
  11276. }
  11277. let pingAbortController = null;
  11278. let tracerouteAbortController = null;
  11279. function clearPingTable() {
  11280. const tbody = document.getElementById('tools-ping-tbody');
  11281. if (tbody) tbody.innerHTML = '';
  11282. const rawEl = document.getElementById('tools-ping-raw');
  11283. if (rawEl) rawEl.innerText = '';
  11284. const sentEl = document.getElementById('tools-ping-stat-sent');
  11285. if (sentEl) sentEl.innerText = '0';
  11286. const recvEl = document.getElementById('tools-ping-stat-recv');
  11287. if (recvEl) recvEl.innerText = '0';
  11288. const lossEl = document.getElementById('tools-ping-stat-loss');
  11289. if (lossEl) lossEl.innerText = '0%';
  11290. const avgEl = document.getElementById('tools-ping-stat-avg');
  11291. if (avgEl) avgEl.innerText = '0 ms';
  11292. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  11293. if (minMaxEl) minMaxEl.innerText = '-';
  11294. const badge = document.getElementById('tools-ping-status-badge');
  11295. if (badge) {
  11296. badge.className = '';
  11297. badge.innerText = '';
  11298. }
  11299. }
  11300. function clearTracerouteTable() {
  11301. const tbody = document.getElementById('tools-tr-tbody');
  11302. if (tbody) tbody.innerHTML = '';
  11303. const rawEl = document.getElementById('tools-tr-raw');
  11304. if (rawEl) rawEl.innerText = '';
  11305. const statHops = document.getElementById('tools-tr-hops-count');
  11306. if (statHops) statHops.innerText = '0 Hops';
  11307. }
  11308. function resetPingButton() {
  11309. const btn = document.getElementById('tools-ping-btn');
  11310. const btnText = document.getElementById('tools-ping-btn-text');
  11311. const spinner = document.getElementById('tools-ping-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 Ping';
  11317. if (spinner) spinner.classList.add('hidden');
  11318. }
  11319. function setPingRunningButton() {
  11320. const btn = document.getElementById('tools-ping-btn');
  11321. const btnText = document.getElementById('tools-ping-btn-text');
  11322. const spinner = document.getElementById('tools-ping-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 Ping';
  11328. if (spinner) spinner.classList.remove('hidden');
  11329. }
  11330. function resetTracerouteButton() {
  11331. const btn = document.getElementById('tools-tr-btn');
  11332. const btnText = document.getElementById('tools-tr-btn-text');
  11333. const spinner = document.getElementById('tools-tr-spinner');
  11334. if (btn) {
  11335. btn.disabled = false;
  11336. 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';
  11337. }
  11338. if (btnText) btnText.innerText = 'Start Traceroute';
  11339. if (spinner) spinner.classList.add('hidden');
  11340. }
  11341. function setTracerouteRunningButton() {
  11342. const btn = document.getElementById('tools-tr-btn');
  11343. const btnText = document.getElementById('tools-tr-btn-text');
  11344. const spinner = document.getElementById('tools-tr-spinner');
  11345. if (btn) {
  11346. btn.disabled = false;
  11347. 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';
  11348. }
  11349. if (btnText) btnText.innerText = 'Stop Traceroute';
  11350. if (spinner) spinner.classList.remove('hidden');
  11351. }
  11352. async function executePing(e) {
  11353. if (e) e.preventDefault();
  11354. // If already running, clicking the button stops the stream!
  11355. if (pingAbortController) {
  11356. pingAbortController.abort();
  11357. pingAbortController = null;
  11358. resetPingButton();
  11359. showToast('Ping Stopped', 'Live ping stopped by user', 'info');
  11360. return;
  11361. }
  11362. const target = document.getElementById('tools-ping-target')?.value?.trim();
  11363. const count = parseInt(document.getElementById('tools-ping-count')?.value || '4', 10);
  11364. const size = parseInt(document.getElementById('tools-ping-size')?.value || '56', 10);
  11365. const timeout = parseInt(document.getElementById('tools-ping-timeout')?.value || '3', 10);
  11366. const iface = document.getElementById('tools-ping-iface')?.value || '';
  11367. const dontFrag = document.getElementById('tools-ping-df')?.checked || false;
  11368. if (!target) {
  11369. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  11370. return;
  11371. }
  11372. clearPingTable();
  11373. const resCard = document.getElementById('tools-ping-results');
  11374. if (resCard) resCard.classList.remove('hidden');
  11375. pingAbortController = new AbortController();
  11376. setPingRunningButton();
  11377. try {
  11378. const res = await fetch(`${API_BASE}/tools/ping/stream`, {
  11379. method: 'POST',
  11380. headers: { 'Content-Type': 'application/json' },
  11381. body: JSON.stringify({
  11382. target,
  11383. count,
  11384. size,
  11385. timeout,
  11386. interface: iface,
  11387. dont_frag: dontFrag
  11388. }),
  11389. signal: pingAbortController.signal
  11390. });
  11391. if (!res.ok) {
  11392. const errText = await res.text();
  11393. showToast('Ping Error', errText || 'Failed to start live ping', 'error');
  11394. resetPingButton();
  11395. pingAbortController = null;
  11396. return;
  11397. }
  11398. const reader = res.body.getReader();
  11399. const decoder = new TextDecoder('utf-8');
  11400. let buffer = '';
  11401. while (true) {
  11402. const { done, value } = await reader.read();
  11403. if (done) break;
  11404. buffer += decoder.decode(value, { stream: true });
  11405. const blocks = buffer.split('\n\n');
  11406. buffer = blocks.pop() || '';
  11407. for (const block of blocks) {
  11408. const trimmed = block.trim();
  11409. if (!trimmed) continue;
  11410. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  11411. try {
  11412. const evt = JSON.parse(line);
  11413. handleLivePingEvent(evt);
  11414. } catch (parseErr) {
  11415. console.warn('Ping SSE parse error:', parseErr, line);
  11416. }
  11417. }
  11418. }
  11419. } catch (err) {
  11420. if (err.name === 'AbortError') {
  11421. // User aborted normally
  11422. } else {
  11423. showToast('Ping Error', err.message, 'error');
  11424. }
  11425. } finally {
  11426. pingAbortController = null;
  11427. resetPingButton();
  11428. }
  11429. }
  11430. function handleLivePingEvent(evt) {
  11431. const sentEl = document.getElementById('tools-ping-stat-sent');
  11432. const recvEl = document.getElementById('tools-ping-stat-recv');
  11433. const lossEl = document.getElementById('tools-ping-stat-loss');
  11434. const avgEl = document.getElementById('tools-ping-stat-avg');
  11435. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  11436. const badge = document.getElementById('tools-ping-status-badge');
  11437. const tbody = document.getElementById('tools-ping-tbody');
  11438. const rawEl = document.getElementById('tools-ping-raw');
  11439. if (evt.raw && rawEl) {
  11440. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  11441. rawEl.scrollTop = rawEl.scrollHeight;
  11442. }
  11443. if (evt.type === 'reply') {
  11444. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  11445. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  11446. if (lossEl && evt.packet_loss_pct !== undefined) {
  11447. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  11448. lossEl.className = evt.packet_loss_pct === 0
  11449. ? 'text-base font-bold font-mono text-emerald-400 mt-1'
  11450. : (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');
  11451. }
  11452. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  11453. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  11454. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  11455. }
  11456. if (badge) {
  11457. if (evt.packet_loss_pct === 0) {
  11458. 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';
  11459. badge.innerText = '100% OK';
  11460. } else {
  11461. 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';
  11462. badge.innerText = `${evt.packet_loss_pct.toFixed(0)}% LOSS`;
  11463. }
  11464. }
  11465. if (tbody) {
  11466. const tr = document.createElement('tr');
  11467. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  11468. tr.innerHTML = `
  11469. <td class="py-2 px-3 text-slate-300">#${evt.seq}</td>
  11470. <td class="py-2 px-3 font-semibold text-white">${escapeHtml(evt.from)}</td>
  11471. <td class="py-2 px-3 text-slate-400">${evt.bytes} bytes</td>
  11472. <td class="py-2 px-3 text-slate-300">${evt.ttl}</td>
  11473. <td class="py-2 px-3 font-bold text-amber-300">${evt.time_ms.toFixed(2)} ms</td>
  11474. <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>
  11475. `;
  11476. tbody.appendChild(tr);
  11477. }
  11478. } else if (evt.type === 'timeout') {
  11479. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  11480. if (lossEl && evt.packet_loss_pct !== undefined) {
  11481. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  11482. 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';
  11483. }
  11484. if (badge) {
  11485. 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';
  11486. badge.innerText = `${evt.packet_loss_pct?.toFixed(0) || 100}% LOSS`;
  11487. }
  11488. if (tbody) {
  11489. const tr = document.createElement('tr');
  11490. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs opacity-75';
  11491. tr.innerHTML = `
  11492. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  11493. <td class="py-2 px-3 font-semibold text-slate-500 italic">Request timed out</td>
  11494. <td class="py-2 px-3 text-slate-600">--</td>
  11495. <td class="py-2 px-3 text-slate-600">--</td>
  11496. <td class="py-2 px-3 font-bold text-slate-500">* * *</td>
  11497. <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>
  11498. `;
  11499. tbody.appendChild(tr);
  11500. }
  11501. } else if (evt.type === 'unreach') {
  11502. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  11503. if (lossEl && evt.packet_loss_pct !== undefined) {
  11504. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  11505. lossEl.className = 'text-base font-bold font-mono text-rose-400 mt-1';
  11506. }
  11507. if (badge) {
  11508. 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';
  11509. badge.innerText = 'UNREACHABLE';
  11510. }
  11511. if (tbody) {
  11512. const tr = document.createElement('tr');
  11513. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  11514. tr.innerHTML = `
  11515. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  11516. <td class="py-2 px-3 font-semibold text-rose-400">${escapeHtml(evt.from || 'Gateway')}</td>
  11517. <td class="py-2 px-3 text-slate-600">--</td>
  11518. <td class="py-2 px-3 text-slate-600">--</td>
  11519. <td class="py-2 px-3 font-bold text-rose-400 text-xs">${escapeHtml(evt.message || 'Unreachable')}</td>
  11520. <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>
  11521. `;
  11522. tbody.appendChild(tr);
  11523. }
  11524. } else if (evt.type === 'stats') {
  11525. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  11526. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  11527. if (lossEl && evt.packet_loss_pct !== undefined) lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  11528. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  11529. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  11530. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  11531. }
  11532. } else if (evt.type === 'done') {
  11533. 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');
  11534. }
  11535. }
  11536. async function executeTraceroute(e) {
  11537. if (e) e.preventDefault();
  11538. if (tracerouteAbortController) {
  11539. tracerouteAbortController.abort();
  11540. tracerouteAbortController = null;
  11541. resetTracerouteButton();
  11542. showToast('Traceroute Stopped', 'Traceroute stopped by user', 'info');
  11543. return;
  11544. }
  11545. const target = document.getElementById('tools-tr-target')?.value?.trim();
  11546. const maxHops = parseInt(document.getElementById('tools-tr-maxhops')?.value || '15', 10);
  11547. const protocol = document.getElementById('tools-tr-proto')?.value || 'icmp';
  11548. const iface = document.getElementById('tools-tr-iface')?.value || '';
  11549. const resolve = document.getElementById('tools-tr-resolve')?.checked || false;
  11550. if (!target) {
  11551. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  11552. return;
  11553. }
  11554. clearTracerouteTable();
  11555. const resCard = document.getElementById('tools-tr-results');
  11556. if (resCard) resCard.classList.remove('hidden');
  11557. tracerouteAbortController = new AbortController();
  11558. setTracerouteRunningButton();
  11559. try {
  11560. const res = await fetch(`${API_BASE}/tools/traceroute/stream`, {
  11561. method: 'POST',
  11562. headers: { 'Content-Type': 'application/json' },
  11563. body: JSON.stringify({
  11564. target,
  11565. max_hops: maxHops,
  11566. protocol,
  11567. interface: iface,
  11568. resolve
  11569. }),
  11570. signal: tracerouteAbortController.signal
  11571. });
  11572. if (!res.ok) {
  11573. const errText = await res.text();
  11574. showToast('Traceroute Error', errText || 'Failed to start traceroute', 'error');
  11575. resetTracerouteButton();
  11576. tracerouteAbortController = null;
  11577. return;
  11578. }
  11579. const reader = res.body.getReader();
  11580. const decoder = new TextDecoder('utf-8');
  11581. let buffer = '';
  11582. while (true) {
  11583. const { done, value } = await reader.read();
  11584. if (done) break;
  11585. buffer += decoder.decode(value, { stream: true });
  11586. const blocks = buffer.split('\n\n');
  11587. buffer = blocks.pop() || '';
  11588. for (const block of blocks) {
  11589. const trimmed = block.trim();
  11590. if (!trimmed) continue;
  11591. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  11592. try {
  11593. const evt = JSON.parse(line);
  11594. handleLiveTracerouteEvent(evt);
  11595. } catch (parseErr) {
  11596. console.warn('Traceroute SSE parse error:', parseErr, line);
  11597. }
  11598. }
  11599. }
  11600. } catch (err) {
  11601. if (err.name === 'AbortError') {
  11602. // User aborted normally
  11603. } else {
  11604. showToast('Traceroute Error', err.message, 'error');
  11605. }
  11606. } finally {
  11607. tracerouteAbortController = null;
  11608. resetTracerouteButton();
  11609. }
  11610. }
  11611. function handleLiveTracerouteEvent(evt) {
  11612. const statHops = document.getElementById('tools-tr-hops-count');
  11613. const tbody = document.getElementById('tools-tr-tbody');
  11614. const rawEl = document.getElementById('tools-tr-raw');
  11615. if (evt.raw && rawEl) {
  11616. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  11617. rawEl.scrollTop = rawEl.scrollHeight;
  11618. }
  11619. if (evt.hops_count !== undefined && statHops) {
  11620. statHops.innerText = `${evt.hops_count} Hops`;
  11621. }
  11622. if (evt.type === 'hop' && evt.hop && tbody) {
  11623. const h = evt.hop;
  11624. const isTimeout = h.status === 'timeout' || (!h.ip && !h.host);
  11625. const rtt1 = Array.isArray(h.times_ms) && h.times_ms[0] ? `${h.times_ms[0]} ms` : (isTimeout ? '*' : '--');
  11626. const rtt2 = Array.isArray(h.times_ms) && h.times_ms[1] ? `${h.times_ms[1]} ms` : (isTimeout ? '*' : '--');
  11627. const displayHost = h.host && h.host !== h.ip ? `${escapeHtml(h.host)} (${escapeHtml(h.ip || '')})` : escapeHtml(h.ip || (isTimeout ? 'Request timed out' : '--'));
  11628. const tr = document.createElement('tr');
  11629. tr.className = `hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs ${isTimeout ? 'opacity-60' : ''}`;
  11630. tr.innerHTML = `
  11631. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  11632. <td class="py-2.5 px-3 font-semibold ${isTimeout ? 'text-slate-500 italic' : 'text-cyan-300'}">${displayHost}</td>
  11633. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt1)}</td>
  11634. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt2)}</td>
  11635. <td class="py-2.5 px-3 text-right">
  11636. ${isTimeout
  11637. ? '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-slate-800 text-slate-400 border border-slate-700">TIMEOUT</span>'
  11638. : '<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>'}
  11639. </td>
  11640. `;
  11641. tbody.appendChild(tr);
  11642. } else if (evt.type === 'done') {
  11643. showToast('Traceroute Finished', `Traced ${evt.hops_count || 0} hops`, 'info');
  11644. }
  11645. }
  11646. async function executeMTR(e) {
  11647. if (e) e.preventDefault();
  11648. const target = document.getElementById('tools-mtr-target')?.value?.trim();
  11649. const cycles = parseInt(document.getElementById('tools-mtr-count')?.value || '3', 10);
  11650. if (!target) {
  11651. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  11652. return;
  11653. }
  11654. const btn = document.getElementById('tools-mtr-btn');
  11655. const spinner = document.getElementById('tools-mtr-spinner');
  11656. if (btn) btn.disabled = true;
  11657. if (spinner) spinner.classList.remove('hidden');
  11658. try {
  11659. const res = await fetch(`${API_BASE}/tools/mtr`, {
  11660. method: 'POST',
  11661. headers: { 'Content-Type': 'application/json' },
  11662. body: JSON.stringify({ target, count: cycles })
  11663. });
  11664. const data = await res.json();
  11665. if (!res.ok) {
  11666. showToast('MTR Error', data.error || 'Failed to execute MTR', 'error');
  11667. return;
  11668. }
  11669. const resCard = document.getElementById('tools-mtr-results');
  11670. if (resCard) resCard.classList.remove('hidden');
  11671. const hopsCount = Array.isArray(data.hops) ? data.hops.length : 0;
  11672. const statHops = document.getElementById('tools-mtr-hops-count');
  11673. if (statHops) statHops.innerText = `${hopsCount} Hops`;
  11674. const tbody = document.getElementById('tools-mtr-tbody');
  11675. if (tbody) {
  11676. if (hopsCount > 0) {
  11677. tbody.innerHTML = data.hops.map(h => {
  11678. 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');
  11679. return `
  11680. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  11681. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  11682. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(h.host || '--')}</td>
  11683. <td class="py-2.5 px-3 ${lossClass}">${h.loss_pct.toFixed(1)}%</td>
  11684. <td class="py-2.5 px-3 text-slate-300">${h.sent}</td>
  11685. <td class="py-2.5 px-3 text-slate-300">${h.last_ms.toFixed(1)}</td>
  11686. <td class="py-2.5 px-3 font-bold text-amber-300">${h.avg_ms.toFixed(1)}</td>
  11687. <td class="py-2.5 px-3 text-emerald-400">${h.best_ms.toFixed(1)}</td>
  11688. <td class="py-2.5 px-3 text-rose-400">${h.wrst_ms.toFixed(1)}</td>
  11689. <td class="py-2.5 px-3 text-slate-400">${h.stdev_ms.toFixed(1)}</td>
  11690. </tr>
  11691. `;
  11692. }).join('');
  11693. } else {
  11694. tbody.innerHTML = `<tr><td colspan="9" class="p-4 text-center text-xs text-rose-400 font-mono">No MTR data collected</td></tr>`;
  11695. }
  11696. }
  11697. const rawEl = document.getElementById('tools-mtr-raw');
  11698. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  11699. showToast('MTR Finished', `Report completed (${hopsCount} hops discovered)`, 'info');
  11700. } catch (err) {
  11701. showToast('MTR Error', err.message, 'error');
  11702. } finally {
  11703. if (btn) btn.disabled = false;
  11704. if (spinner) spinner.classList.add('hidden');
  11705. }
  11706. }
  11707. async function executeDNS(e) {
  11708. if (e) e.preventDefault();
  11709. const domain = document.getElementById('tools-dns-domain')?.value?.trim();
  11710. const type = document.getElementById('tools-dns-type')?.value || 'A';
  11711. const server = document.getElementById('tools-dns-server')?.value?.trim() || '';
  11712. if (!domain) {
  11713. showToast('Input Required', 'Please enter a hostname or domain', 'warning');
  11714. return;
  11715. }
  11716. const btn = document.getElementById('tools-dns-btn');
  11717. const spinner = document.getElementById('tools-dns-spinner');
  11718. if (btn) btn.disabled = true;
  11719. if (spinner) spinner.classList.remove('hidden');
  11720. try {
  11721. const res = await fetch(`${API_BASE}/tools/dns`, {
  11722. method: 'POST',
  11723. headers: { 'Content-Type': 'application/json' },
  11724. body: JSON.stringify({ domain, type, server })
  11725. });
  11726. const data = await res.json();
  11727. if (!res.ok) {
  11728. showToast('DNS Error', data.error || 'Failed to resolve DNS query', 'error');
  11729. return;
  11730. }
  11731. const resCard = document.getElementById('tools-dns-results');
  11732. if (resCard) resCard.classList.remove('hidden');
  11733. const metaEl = document.getElementById('tools-dns-meta');
  11734. if (metaEl) metaEl.innerText = `Resolved in ${data.query_time_ms ?? 0} ms via ${escapeHtml(data.server || 'System DNS')}`;
  11735. const tbody = document.getElementById('tools-dns-tbody');
  11736. if (tbody) {
  11737. if (Array.isArray(data.records) && data.records.length > 0) {
  11738. tbody.innerHTML = data.records.map(r => `
  11739. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  11740. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.name)}</td>
  11741. <td class="py-2.5 px-3 text-slate-400">${r.ttl}s</td>
  11742. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.class || 'IN')}</td>
  11743. <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>
  11744. <td class="py-2.5 px-3 font-bold text-amber-300 break-all">${escapeHtml(r.value)}</td>
  11745. </tr>
  11746. `).join('');
  11747. } else {
  11748. 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>`;
  11749. }
  11750. }
  11751. const rawEl = document.getElementById('tools-dns-raw');
  11752. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  11753. showToast('DNS Lookup Done', `Resolved ${domain} in ${data.query_time_ms} ms`, 'success');
  11754. } catch (err) {
  11755. showToast('DNS Error', err.message, 'error');
  11756. } finally {
  11757. if (btn) btn.disabled = false;
  11758. if (spinner) spinner.classList.add('hidden');
  11759. }
  11760. }
  11761. async function executePortProbe(e) {
  11762. if (e) e.preventDefault();
  11763. const target = document.getElementById('tools-port-target')?.value?.trim();
  11764. const port = parseInt(document.getElementById('tools-port-num')?.value || '80', 10);
  11765. const timeout = parseInt(document.getElementById('tools-port-timeout')?.value || '3', 10);
  11766. if (!target || !port) {
  11767. showToast('Input Required', 'Please enter a target host and TCP port', 'warning');
  11768. return;
  11769. }
  11770. const btn = document.getElementById('tools-port-btn');
  11771. const spinner = document.getElementById('tools-port-spinner');
  11772. if (btn) btn.disabled = true;
  11773. if (spinner) spinner.classList.remove('hidden');
  11774. try {
  11775. const res = await fetch(`${API_BASE}/tools/port-probe`, {
  11776. method: 'POST',
  11777. headers: { 'Content-Type': 'application/json' },
  11778. body: JSON.stringify({ target, port, timeout })
  11779. });
  11780. const data = await res.json();
  11781. if (!res.ok) {
  11782. showToast('Probe Error', data.error || 'Failed to probe TCP port', 'error');
  11783. return;
  11784. }
  11785. const resCard = document.getElementById('tools-port-results');
  11786. if (resCard) resCard.classList.remove('hidden');
  11787. const banner = document.getElementById('tools-port-banner');
  11788. const icon = document.getElementById('tools-port-icon');
  11789. const title = document.getElementById('tools-port-title');
  11790. const sub = document.getElementById('tools-port-sub');
  11791. const latency = document.getElementById('tools-port-latency');
  11792. if (data.open) {
  11793. if (banner) banner.className = 'rounded-xl p-5 border bg-emerald-950/30 border-emerald-800/50 flex items-center justify-between';
  11794. if (icon) {
  11795. 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';
  11796. icon.innerText = '✓';
  11797. }
  11798. if (title) {
  11799. title.className = 'text-sm font-bold text-emerald-300';
  11800. title.innerText = `PORT ${port} OPEN / LISTENING`;
  11801. }
  11802. if (sub) {
  11803. sub.className = 'text-xs mt-0.5 font-mono text-emerald-400/80';
  11804. sub.innerText = `TCP 3-way handshake established with ${escapeHtml(target)}:${port}${data.service ? ' (' + escapeHtml(data.service) + ')' : ''}`;
  11805. }
  11806. if (latency) {
  11807. latency.className = 'text-base font-bold font-mono text-emerald-300';
  11808. latency.innerText = `${data.latency_ms.toFixed(2)} ms`;
  11809. }
  11810. } else {
  11811. if (banner) banner.className = 'rounded-xl p-5 border bg-rose-950/30 border-rose-800/50 flex items-center justify-between';
  11812. if (icon) {
  11813. 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';
  11814. icon.innerText = '✕';
  11815. }
  11816. if (title) {
  11817. title.className = 'text-sm font-bold text-rose-300';
  11818. title.innerText = `PORT ${port} CLOSED / FILTERED`;
  11819. }
  11820. if (sub) {
  11821. sub.className = 'text-xs mt-0.5 font-mono text-rose-400/80';
  11822. sub.innerText = `Connection failed or timed out to ${escapeHtml(target)}:${port}`;
  11823. }
  11824. if (latency) {
  11825. latency.className = 'text-base font-bold font-mono text-slate-500';
  11826. latency.innerText = '--';
  11827. }
  11828. }
  11829. const rawEl = document.getElementById('tools-port-raw');
  11830. 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'}`);
  11831. showToast('Probe Complete', `Port ${port} is ${data.open ? 'OPEN' : 'CLOSED'}`, data.open ? 'success' : 'warning');
  11832. } catch (err) {
  11833. showToast('Probe Error', err.message, 'error');
  11834. } finally {
  11835. if (btn) btn.disabled = false;
  11836. if (spinner) spinner.classList.add('hidden');
  11837. }
  11838. }
  11839. // ==========================================
  11840. // DHCP CLIENT (/ip dhcp-client) CONTROLLER
  11841. // ==========================================
  11842. async function loadDHCPClients(showToastMsg = false) {
  11843. try {
  11844. const [clientsRes, sumRes] = await Promise.all([
  11845. fetch(`${API_BASE}/dhcp/clients`),
  11846. fetch(`${API_BASE}/dhcp/clients/summary`)
  11847. ]);
  11848. if (clientsRes.ok) {
  11849. state.dhcpClients = await clientsRes.json();
  11850. }
  11851. if (sumRes.ok) {
  11852. state.dhcpSummary = await sumRes.json();
  11853. }
  11854. renderDHCPClients();
  11855. updateDHCPSummaryCards();
  11856. const bDhcp = document.getElementById('badge-dhcp-client-count');
  11857. if (bDhcp && state.dhcpSummary) {
  11858. bDhcp.innerText = state.dhcpSummary.total_clients || 0;
  11859. }
  11860. if (showToastMsg) {
  11861. showToast('Refreshed', 'DHCP Client telemetry updated', 'info');
  11862. }
  11863. } catch (err) {
  11864. console.error('Failed to load DHCP clients:', err);
  11865. if (showToastMsg) {
  11866. showToast('Notice', 'Unable to fetch DHCP client status', 'warning');
  11867. }
  11868. }
  11869. }
  11870. function updateDHCPSummaryCards() {
  11871. const sum = state.dhcpSummary || {
  11872. total_clients: (state.dhcpClients || []).length,
  11873. bound_clients: (state.dhcpClients || []).filter(c => c.status === 'bound').length,
  11874. searching_clients: (state.dhcpClients || []).filter(c => c.status === 'searching').length,
  11875. disabled_clients: (state.dhcpClients || []).filter(c => !c.enabled).length
  11876. };
  11877. const totalEl = document.getElementById('dhcp-stat-total');
  11878. const boundEl = document.getElementById('dhcp-stat-bound');
  11879. const searchEl = document.getElementById('dhcp-stat-searching');
  11880. const disEl = document.getElementById('dhcp-stat-disabled');
  11881. if (totalEl) totalEl.innerText = sum.total_clients ?? 0;
  11882. if (boundEl) boundEl.innerText = sum.bound_clients ?? 0;
  11883. if (searchEl) searchEl.innerText = sum.searching_clients ?? 0;
  11884. if (disEl) disEl.innerText = sum.disabled_clients ?? 0;
  11885. }
  11886. function renderDHCPClients() {
  11887. const tbody = document.getElementById('dhcp-clients-tbody');
  11888. const emptyState = document.getElementById('dhcp-clients-empty');
  11889. if (!tbody) return;
  11890. const clients = Array.isArray(state.dhcpClients) ? state.dhcpClients : [];
  11891. if (clients.length === 0) {
  11892. tbody.innerHTML = '';
  11893. if (emptyState) emptyState.classList.remove('hidden');
  11894. return;
  11895. }
  11896. if (emptyState) emptyState.classList.add('hidden');
  11897. const sig = clients.map(c => `${c.id}:${c.status}:${c.ip_address}:${c.gateway}:${c.enabled}`).join(';');
  11898. if (tbody.dataset.sig === sig) return;
  11899. tbody.dataset.sig = sig;
  11900. tbody.innerHTML = clients.map(c => {
  11901. let statusBadge = '';
  11902. if (!c.enabled) {
  11903. 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>';
  11904. } else if (c.status === 'bound') {
  11905. 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>';
  11906. } else if (c.status === 'searching') {
  11907. 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>';
  11908. } else if (c.status === 'stopped') {
  11909. 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>';
  11910. } else {
  11911. 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>`;
  11912. }
  11913. 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>';
  11914. const gwDisplay = c.gateway ? `<span class="text-slate-300">${escapeHtml(c.gateway)}</span>` : '<span class="text-slate-600">--</span>';
  11915. const srvDisplay = c.dhcp_server ? `<span class="text-slate-300">${escapeHtml(c.dhcp_server)}</span>` : '<span class="text-slate-600">--</span>';
  11916. 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>';
  11917. const expDisplay = c.expires_in ? `<span class="text-purple-300">${escapeHtml(c.expires_in)}</span>` : '<span class="text-slate-600">--</span>';
  11918. // Option flags
  11919. const flags = [];
  11920. 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>');
  11921. 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>');
  11922. 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>');
  11923. 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>`);
  11924. return `
  11925. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 text-xs transition">
  11926. <td class="py-3 px-4">
  11927. <div class="flex items-center gap-2">
  11928. <span class="font-bold text-white text-sm">${escapeHtml(c.interface)}</span>
  11929. ${c.comment ? `<span class="text-[11px] text-slate-400 font-sans italic">(${escapeHtml(c.comment)})</span>` : ''}
  11930. </div>
  11931. </td>
  11932. <td class="py-3 px-4">${statusBadge}</td>
  11933. <td class="py-3 px-4 font-mono">${ipDisplay}</td>
  11934. <td class="py-3 px-4 font-mono">${gwDisplay}</td>
  11935. <td class="py-3 px-4 font-mono">${srvDisplay}</td>
  11936. <td class="py-3 px-4 font-mono text-[11px]">${dnsDisplay}</td>
  11937. <td class="py-3 px-4 font-mono text-[11px]">${expDisplay}</td>
  11938. <td class="py-3 px-4">
  11939. <div class="flex flex-wrap gap-1 font-mono">${flags.join('')}</div>
  11940. </td>
  11941. <td class="py-3 px-4 text-right space-x-1.5 font-sans whitespace-nowrap">
  11942. ${c.enabled ? `
  11943. <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>
  11944. <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>
  11945. <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>
  11946. ` : `
  11947. <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>
  11948. `}
  11949. <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>
  11950. <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>
  11951. </td>
  11952. </tr>
  11953. `;
  11954. }).join('');
  11955. }
  11956. function openDHCPClientModal(clientId = null) {
  11957. const modal = document.getElementById('modal-dhcp-client');
  11958. if (!modal) return;
  11959. const title = document.getElementById('modal-dhcp-title');
  11960. const idInput = document.getElementById('modal-dhcp-id');
  11961. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  11962. const distInput = document.getElementById('modal-dhcp-distance');
  11963. const commentInput = document.getElementById('modal-dhcp-comment');
  11964. const defRouteCheck = document.getElementById('modal-dhcp-def-route');
  11965. const peerDnsCheck = document.getElementById('modal-dhcp-peer-dns');
  11966. const peerNtpCheck = document.getElementById('modal-dhcp-peer-ntp');
  11967. const enabledCheck = document.getElementById('modal-dhcp-enabled');
  11968. // Populate interfaces
  11969. if (ifaceSelect) {
  11970. let opts = '<option value="">Select interface...</option>';
  11971. const allIfaces = state.interfaces || [];
  11972. const allVlans = state.vlans || [];
  11973. const usedIfaces = new Set((state.dhcpClients || []).map(c => c.interface));
  11974. // Group 1: Physical & Bridge Interfaces
  11975. opts += '<optgroup label="Physical & Bridge Interfaces">';
  11976. allIfaces.filter(i => supportsDHCPClient(i)).forEach(i => {
  11977. const isConfigured = usedIfaces.has(i.name) ? ' (Configured)' : '';
  11978. opts += `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)} [${escapeHtml(i.role || i.type)}]${isConfigured}</option>`;
  11979. });
  11980. opts += '</optgroup>';
  11981. // Group 2: VLAN Interfaces
  11982. if (allVlans.length > 0) {
  11983. opts += '<optgroup label="802.1Q VLAN Sub-interfaces">';
  11984. allVlans.forEach(v => {
  11985. const isConfigured = usedIfaces.has(v.name) ? ' (Configured)' : '';
  11986. opts += `<option value="${escapeHtml(v.name)}">${escapeHtml(v.name)} (VLAN ${v.vlan_id})${isConfigured}</option>`;
  11987. });
  11988. opts += '</optgroup>';
  11989. }
  11990. ifaceSelect.innerHTML = opts;
  11991. }
  11992. if (clientId) {
  11993. const client = (state.dhcpClients || []).find(c => c.id === clientId);
  11994. if (client) {
  11995. if (title) title.innerText = `Edit DHCP Client: ${client.interface}`;
  11996. if (idInput) idInput.value = client.id;
  11997. if (ifaceSelect) {
  11998. ifaceSelect.value = client.interface;
  11999. ifaceSelect.disabled = true; // interface cannot be changed on edit
  12000. }
  12001. if (distInput) distInput.value = client.default_route_distance || 1;
  12002. if (commentInput) commentInput.value = client.comment || '';
  12003. if (defRouteCheck) defRouteCheck.checked = client.add_default_route !== false;
  12004. if (peerDnsCheck) peerDnsCheck.checked = client.use_peer_dns !== false;
  12005. if (peerNtpCheck) peerNtpCheck.checked = client.use_peer_ntp !== false;
  12006. if (enabledCheck) enabledCheck.checked = client.enabled !== false;
  12007. }
  12008. } else {
  12009. if (title) title.innerText = 'Add DHCP Client';
  12010. if (idInput) idInput.value = '';
  12011. if (ifaceSelect) {
  12012. ifaceSelect.value = '';
  12013. ifaceSelect.disabled = false;
  12014. }
  12015. if (distInput) distInput.value = 1;
  12016. if (commentInput) commentInput.value = '';
  12017. if (defRouteCheck) defRouteCheck.checked = true;
  12018. if (peerDnsCheck) peerDnsCheck.checked = true;
  12019. if (peerNtpCheck) peerNtpCheck.checked = true;
  12020. if (enabledCheck) enabledCheck.checked = true;
  12021. }
  12022. modal.classList.remove('hidden');
  12023. }
  12024. function openDHCPClientModalForIface(ifaceName) {
  12025. openDHCPClientModal();
  12026. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  12027. if (ifaceSelect && ifaceName) {
  12028. ifaceSelect.value = ifaceName;
  12029. }
  12030. }
  12031. function closeDHCPClientModal() {
  12032. const modal = document.getElementById('modal-dhcp-client');
  12033. if (modal) modal.classList.add('hidden');
  12034. }
  12035. async function submitSaveDHCPClient(e) {
  12036. if (e) e.preventDefault();
  12037. const id = document.getElementById('modal-dhcp-id')?.value;
  12038. const iface = document.getElementById('modal-dhcp-iface')?.value?.trim();
  12039. const distance = parseInt(document.getElementById('modal-dhcp-distance')?.value || '1', 10);
  12040. const comment = document.getElementById('modal-dhcp-comment')?.value?.trim() || '';
  12041. const defRoute = document.getElementById('modal-dhcp-def-route')?.checked ?? true;
  12042. const peerDns = document.getElementById('modal-dhcp-peer-dns')?.checked ?? true;
  12043. const peerNtp = document.getElementById('modal-dhcp-peer-ntp')?.checked ?? true;
  12044. const enabled = document.getElementById('modal-dhcp-enabled')?.checked ?? true;
  12045. if (!id && !iface) {
  12046. showToast('Input Required', 'Please select an interface for the DHCP client', 'warning');
  12047. return;
  12048. }
  12049. try {
  12050. let res;
  12051. if (id) {
  12052. // PUT update
  12053. res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  12054. method: 'PUT',
  12055. headers: { 'Content-Type': 'application/json' },
  12056. body: JSON.stringify({
  12057. enabled,
  12058. add_default_route: defRoute,
  12059. default_route_distance: distance,
  12060. use_peer_dns: peerDns,
  12061. use_peer_ntp: peerNtp,
  12062. comment
  12063. })
  12064. });
  12065. } else {
  12066. // POST create
  12067. res = await fetch(`${API_BASE}/dhcp/clients`, {
  12068. method: 'POST',
  12069. headers: { 'Content-Type': 'application/json' },
  12070. body: JSON.stringify({
  12071. interface: iface,
  12072. enabled,
  12073. add_default_route: defRoute,
  12074. default_route_distance: distance,
  12075. use_peer_dns: peerDns,
  12076. use_peer_ntp: peerNtp,
  12077. comment
  12078. })
  12079. });
  12080. }
  12081. const data = await res.json();
  12082. if (!res.ok) {
  12083. showToast('Error', data.error || 'Failed to save DHCP client', 'error');
  12084. return;
  12085. }
  12086. closeDHCPClientModal();
  12087. showToast('Success', id ? 'DHCP Client updated successfully' : `DHCP Client activated on ${iface}`, 'success');
  12088. await loadDHCPClients();
  12089. fetchData(); // refresh interfaces list with new lease/status
  12090. } catch (err) {
  12091. showToast('Error', err.message, 'error');
  12092. }
  12093. }
  12094. async function toggleDHCPClientState(id, enabled) {
  12095. try {
  12096. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/state`, {
  12097. method: 'POST',
  12098. headers: { 'Content-Type': 'application/json' },
  12099. body: JSON.stringify({ enabled })
  12100. });
  12101. const data = await res.json();
  12102. if (!res.ok) {
  12103. showToast('Error', data.error || 'Failed to toggle client state', 'error');
  12104. return;
  12105. }
  12106. showToast('Updated', `DHCP client ${enabled ? 'enabled' : 'disabled'}`, 'info');
  12107. await loadDHCPClients();
  12108. fetchData();
  12109. } catch (err) {
  12110. showToast('Error', err.message, 'error');
  12111. }
  12112. }
  12113. async function renewDHCPClient(id) {
  12114. try {
  12115. showToast('Renewing...', 'Requesting DHCP lease renewal from upstream server', 'info');
  12116. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/renew`, {
  12117. method: 'POST'
  12118. });
  12119. const data = await res.json();
  12120. if (!res.ok) {
  12121. showToast('Error', data.error || 'Failed to renew lease', 'error');
  12122. return;
  12123. }
  12124. showToast('Lease Renewed', 'DHCP renewal signal sent successfully', 'success');
  12125. setTimeout(() => {
  12126. loadDHCPClients();
  12127. fetchData();
  12128. }, 1500);
  12129. } catch (err) {
  12130. showToast('Error', err.message, 'error');
  12131. }
  12132. }
  12133. async function releaseDHCPClient(id) {
  12134. try {
  12135. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/release`, {
  12136. method: 'POST'
  12137. });
  12138. const data = await res.json();
  12139. if (!res.ok) {
  12140. showToast('Error', data.error || 'Failed to release lease', 'error');
  12141. return;
  12142. }
  12143. showToast('Lease Released', 'DHCP lease released from upstream server', 'info');
  12144. await loadDHCPClients();
  12145. fetchData();
  12146. } catch (err) {
  12147. showToast('Error', err.message, 'error');
  12148. }
  12149. }
  12150. async function deleteDHCPClient(id, ifaceName) {
  12151. if (!confirm(`Are you sure you want to remove the DHCP Client on ${ifaceName}? The interface will release its dynamic IP.`)) {
  12152. return;
  12153. }
  12154. try {
  12155. const res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  12156. method: 'DELETE'
  12157. });
  12158. const data = await res.json();
  12159. if (!res.ok) {
  12160. showToast('Error', data.error || 'Failed to delete DHCP client', 'error');
  12161. return;
  12162. }
  12163. showToast('Deleted', `DHCP client removed from ${ifaceName}`, 'info');
  12164. await loadDHCPClients();
  12165. fetchData();
  12166. } catch (err) {
  12167. showToast('Error', err.message, 'error');
  12168. }
  12169. }
  12170. // ==================== DHCP SERVER (/ip dhcp-server) ====================
  12171. async function loadDHCPServer(populate = true) {
  12172. try {
  12173. const [sumRes, srvRes, netRes, leaseRes, optRes] = await Promise.all([
  12174. fetch(`${API_BASE}/dhcp-server/summary`),
  12175. fetch(`${API_BASE}/dhcp-server/servers`),
  12176. fetch(`${API_BASE}/dhcp-server/networks`),
  12177. fetch(`${API_BASE}/dhcp-server/leases`),
  12178. fetch(`${API_BASE}/dhcp-server/options`)
  12179. ]);
  12180. if (sumRes.ok) state.dhcpServerSummary = await sumRes.json();
  12181. if (srvRes.ok) state.dhcpServers = await srvRes.json();
  12182. if (netRes.ok) state.dhcpNetworks = await netRes.json();
  12183. if (leaseRes.ok) state.dhcpLeases = await leaseRes.json();
  12184. if (optRes.ok) state.dhcpOptions = await optRes.json();
  12185. const sum = state.dhcpServerSummary || {};
  12186. const srvs = state.dhcpServers || [];
  12187. const nets = state.dhcpNetworks || [];
  12188. const leases = state.dhcpLeases || [];
  12189. const opts = state.dhcpOptions || [];
  12190. // KPI Cards
  12191. const statActive = document.getElementById('dhcp-server-stat-active');
  12192. if (statActive) {
  12193. const activeCount = srvs.filter(s => s.running).length;
  12194. statActive.innerText = `${activeCount} / ${srvs.length}`;
  12195. }
  12196. const statLeases = document.getElementById('dhcp-server-stat-leases');
  12197. if (statLeases) {
  12198. statLeases.innerText = leases.length;
  12199. }
  12200. const statLeasesSub = document.getElementById('dhcp-server-stat-leases-sub');
  12201. if (statLeasesSub) {
  12202. const dyn = leases.filter(l => l.dynamic).length;
  12203. const st = leases.filter(l => !l.dynamic).length;
  12204. statLeasesSub.innerText = `${dyn} dynamic, ${st} static`;
  12205. }
  12206. const statNetworks = document.getElementById('dhcp-server-stat-networks');
  12207. if (statNetworks) {
  12208. statNetworks.innerText = nets.length;
  12209. }
  12210. // Subtab Badges
  12211. const bSrv = document.getElementById('dhcp-server-tab-badge-servers');
  12212. if (bSrv) bSrv.innerText = srvs.length;
  12213. const bNet = document.getElementById('dhcp-server-tab-badge-networks');
  12214. if (bNet) bNet.innerText = nets.length;
  12215. const bLease = document.getElementById('dhcp-server-tab-badge-leases');
  12216. if (bLease) bLease.innerText = leases.length;
  12217. const bOpt = document.getElementById('dhcp-server-tab-badge-options');
  12218. if (bOpt) bOpt.innerText = opts.length;
  12219. // Sidebar Badge
  12220. const sideBadge = document.getElementById('badge-dhcp-server-count');
  12221. if (sideBadge) sideBadge.innerText = leases.length || srvs.length;
  12222. renderCurrentDHCPServerTab();
  12223. } catch (err) {
  12224. console.error('Failed to load DHCP Server:', err);
  12225. }
  12226. }
  12227. function switchDHCPServerTab(tab) {
  12228. state.dhcpServerTab = tab;
  12229. const tabs = ['servers', 'networks', 'leases', 'options'];
  12230. tabs.forEach(t => {
  12231. const panel = document.getElementById(`dhcp-server-subtab-${t}`);
  12232. const btn = document.getElementById(`dhcp-server-tab-btn-${t}`);
  12233. if (panel) {
  12234. if (t === tab) panel.classList.remove('hidden');
  12235. else panel.classList.add('hidden');
  12236. }
  12237. if (btn) {
  12238. if (t === tab) {
  12239. 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';
  12240. } else {
  12241. 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';
  12242. }
  12243. }
  12244. });
  12245. const addBtn = document.getElementById('dhcp-server-primary-add-btn');
  12246. if (addBtn) {
  12247. if (tab === 'servers') addBtn.innerHTML = '<span>+ Add Server</span>';
  12248. else if (tab === 'networks') addBtn.innerHTML = '<span>+ Add Network</span>';
  12249. else if (tab === 'leases') addBtn.innerHTML = '<span>+ Add Static Lease</span>';
  12250. else if (tab === 'options') addBtn.innerHTML = '<span>+ Add Option</span>';
  12251. }
  12252. renderCurrentDHCPServerTab();
  12253. }
  12254. function handleDHCPServerPrimaryAdd() {
  12255. const tab = state.dhcpServerTab || 'servers';
  12256. if (tab === 'servers') openAddDHCPServerModal();
  12257. else if (tab === 'networks') openAddDHCPNetworkModal();
  12258. else if (tab === 'leases') openAddDHCPStaticLeaseModal();
  12259. else if (tab === 'options') openAddDHCPOptionModal();
  12260. }
  12261. function renderCurrentDHCPServerTab() {
  12262. const tab = state.dhcpServerTab || 'servers';
  12263. if (tab === 'servers') renderDHCPServers();
  12264. else if (tab === 'networks') renderDHCPNetworks();
  12265. else if (tab === 'leases') renderDHCPLeases();
  12266. else if (tab === 'options') renderDHCPOptions();
  12267. }
  12268. function renderDHCPServers() {
  12269. const tbody = document.getElementById('dhcp-server-tbody');
  12270. const empty = document.getElementById('dhcp-server-empty');
  12271. if (!tbody) return;
  12272. const servers = state.dhcpServers || [];
  12273. if (servers.length === 0) {
  12274. tbody.innerHTML = '';
  12275. empty?.classList.remove('hidden');
  12276. return;
  12277. }
  12278. empty?.classList.add('hidden');
  12279. const sig = servers.map(s => `${s.id}:${s.running}:${s.disabled}:${s.active_leases}:${s.interface}`).join(';');
  12280. if (tbody.dataset.sig === sig) return;
  12281. tbody.dataset.sig = sig;
  12282. tbody.innerHTML = '';
  12283. servers.forEach(s => {
  12284. const tr = document.createElement('tr');
  12285. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  12286. tr.innerHTML = `
  12287. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(s.running, s.disabled)}</td>
  12288. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(s.name)}</td>
  12289. <td class="py-2.5 px-3 font-mono text-cyan-400 font-semibold">${escapeHtml(s.interface)}</td>
  12290. <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>
  12291. <td class="py-2.5 px-3 font-mono text-emerald-400">${escapeHtml(s.address_pool)}</td>
  12292. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(s.lease_time || '12h')}</td>
  12293. <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>
  12294. <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>
  12295. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]" title="${escapeHtml(s.comment || '')}">${escapeHtml(s.comment || '-')}</td>
  12296. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  12297. <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>
  12298. <button onclick="openEditDHCPServerModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  12299. <button onclick="deleteDHCPServer('${s.id}', '${escapeHtml(s.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  12300. </td>
  12301. `;
  12302. tbody.appendChild(tr);
  12303. });
  12304. }
  12305. function renderDHCPNetworks() {
  12306. const tbody = document.getElementById('dhcp-networks-tbody');
  12307. const empty = document.getElementById('dhcp-networks-empty');
  12308. if (!tbody) return;
  12309. tbody.innerHTML = '';
  12310. const networks = state.dhcpNetworks || [];
  12311. if (networks.length === 0) {
  12312. empty?.classList.remove('hidden');
  12313. return;
  12314. }
  12315. empty?.classList.add('hidden');
  12316. networks.forEach(n => {
  12317. const tr = document.createElement('tr');
  12318. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  12319. const dnsStr = (n.dns_servers || []).join(', ') || '-';
  12320. const optionsChips = (n.dhcp_options || []).map(optId => {
  12321. const opt = (state.dhcpOptions || []).find(o => o.id === optId);
  12322. if (!opt) return '';
  12323. 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>`;
  12324. }).filter(Boolean).join('');
  12325. tr.innerHTML = `
  12326. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${escapeHtml(n.address)}</td>
  12327. <td class="py-2.5 px-3 font-mono text-cyan-300 font-semibold">${escapeHtml(n.gateway || '-')}</td>
  12328. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(n.netmask || '-')}</td>
  12329. <td class="py-2.5 px-3 font-mono text-slate-300 truncate max-w-[140px]" title="${escapeHtml(dnsStr)}">${escapeHtml(dnsStr)}</td>
  12330. <td class="py-2.5 px-3 font-mono text-slate-400">${escapeHtml(n.domain || '-')}</td>
  12331. <td class="py-2.5 px-3 font-mono">${optionsChips || '<span class="text-slate-600 font-sans">-</span>'}</td>
  12332. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(n.comment || '')}">${escapeHtml(n.comment || '-')}</td>
  12333. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  12334. <button onclick="openEditDHCPNetworkModal('${n.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  12335. <button onclick="deleteDHCPNetwork('${n.id}', '${escapeHtml(n.address)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  12336. </td>
  12337. `;
  12338. tbody.appendChild(tr);
  12339. });
  12340. }
  12341. function renderDHCPLeases() {
  12342. const tbody = document.getElementById('dhcp-leases-tbody');
  12343. const empty = document.getElementById('dhcp-leases-empty');
  12344. if (!tbody) return;
  12345. tbody.innerHTML = '';
  12346. const leases = state.dhcpLeases || [];
  12347. if (leases.length === 0) {
  12348. empty?.classList.remove('hidden');
  12349. return;
  12350. }
  12351. empty?.classList.add('hidden');
  12352. leases.forEach(l => {
  12353. const tr = document.createElement('tr');
  12354. tr.className = `hover:bg-slate-800/40 transition text-xs ${l.disabled ? 'opacity-50' : ''}`;
  12355. 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>';
  12356. const statusBadge = l.status === 'bound'
  12357. ? '<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>'
  12358. : l.status === 'static'
  12359. ? '<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>'
  12360. : '<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>';
  12361. const makeStaticBtn = l.dynamic
  12362. ? `<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>`
  12363. : `<button onclick="deleteDHCPStaticLease('${l.id}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Remove</button>`;
  12364. tr.innerHTML = `
  12365. <td class="py-2.5 px-3 text-center">${flag}</td>
  12366. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(l.address)}</td>
  12367. <td class="py-2.5 px-3 font-mono text-cyan-300">${escapeHtml(l.mac_address)}</td>
  12368. <td class="py-2.5 px-3 font-sans text-slate-200 font-medium">${escapeHtml(l.hostname || '*')}</td>
  12369. <td class="py-2.5 px-3 font-mono text-slate-400">${escapeHtml(l.server || 'all')}</td>
  12370. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(l.expires_in || 'never')}</td>
  12371. <td class="py-2.5 px-3">${statusBadge}</td>
  12372. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(l.comment || '')}">${escapeHtml(l.comment || '-')}</td>
  12373. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  12374. ${makeStaticBtn}
  12375. </td>
  12376. `;
  12377. tbody.appendChild(tr);
  12378. });
  12379. }
  12380. function renderDHCPOptions() {
  12381. const tbody = document.getElementById('dhcp-options-tbody');
  12382. const empty = document.getElementById('dhcp-options-empty');
  12383. if (!tbody) return;
  12384. tbody.innerHTML = '';
  12385. const options = state.dhcpOptions || [];
  12386. if (options.length === 0) {
  12387. empty?.classList.remove('hidden');
  12388. return;
  12389. }
  12390. empty?.classList.add('hidden');
  12391. options.forEach(o => {
  12392. const tr = document.createElement('tr');
  12393. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  12394. tr.innerHTML = `
  12395. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(o.name)}</td>
  12396. <td class="py-2.5 px-3 font-bold text-cyan-400 font-mono">${o.code}</td>
  12397. <td class="py-2.5 px-3 font-mono text-emerald-400 break-all max-w-xs">${escapeHtml(o.value)}</td>
  12398. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-xs" title="${escapeHtml(o.comment || '')}">${escapeHtml(o.comment || '-')}</td>
  12399. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  12400. <button onclick="openEditDHCPOptionModal('${o.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  12401. <button onclick="deleteDHCPOption('${o.id}', '${escapeHtml(o.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  12402. </td>
  12403. `;
  12404. tbody.appendChild(tr);
  12405. });
  12406. }
  12407. // ==================== MODALS & ACTIONS: SERVER ====================
  12408. function populateDHCPNetworkSelect(elemId, selectedVal) {
  12409. const sel = document.getElementById(elemId);
  12410. if (!sel) return;
  12411. sel.innerHTML = '<option value="">Select network subnet...</option>';
  12412. const networks = state.dhcpNetworks || [];
  12413. networks.forEach(n => {
  12414. const opt = document.createElement('option');
  12415. opt.value = n.address;
  12416. opt.innerText = `${n.address} (Gateway: ${n.gateway || 'None'}${n.comment ? ' - ' + n.comment : ''})`;
  12417. if (selectedVal && (selectedVal === n.address || selectedVal === n.id)) {
  12418. opt.selected = true;
  12419. }
  12420. sel.appendChild(opt);
  12421. });
  12422. }
  12423. function onDHCPServerNetworkChange() {
  12424. const netSel = document.getElementById('dhcp-server-modal-network');
  12425. if (!netSel) return;
  12426. const netVal = netSel.value;
  12427. if (!netVal) return;
  12428. const poolInput = document.getElementById('dhcp-server-modal-pool');
  12429. if (!poolInput) return;
  12430. // Auto-calculate suggested address pool based on subnet CIDR
  12431. const parts = netVal.split('/');
  12432. const ip = parts[0];
  12433. const cidr = parseInt(parts[1] || '24', 10);
  12434. if (cidr === 24) {
  12435. const octets = ip.split('.');
  12436. if (octets.length === 4) {
  12437. const base = `${octets[0]}.${octets[1]}.${octets[2]}`;
  12438. poolInput.value = `${base}.10-${base}.254`;
  12439. }
  12440. }
  12441. }
  12442. function openAddDHCPServerModal() {
  12443. document.getElementById('dhcp-server-modal-title').innerText = 'Add DHCP Server';
  12444. document.getElementById('dhcp-server-modal-id').value = '';
  12445. document.getElementById('dhcp-server-modal-name').value = `dhcp${(state.dhcpServers || []).length + 1}`;
  12446. document.getElementById('dhcp-server-modal-pool').value = '192.168.88.10-192.168.88.254';
  12447. document.getElementById('dhcp-server-modal-leasetime').value = '12h';
  12448. document.getElementById('dhcp-server-modal-comment').value = '';
  12449. document.getElementById('dhcp-server-modal-authoritative').checked = true;
  12450. document.getElementById('dhcp-server-modal-disabled').checked = false;
  12451. populateDHCPIfaceSelect('dhcp-server-modal-iface', '');
  12452. const networks = state.dhcpNetworks || [];
  12453. const defaultNet = networks.length > 0 ? networks[0].address : '';
  12454. populateDHCPNetworkSelect('dhcp-server-modal-network', defaultNet);
  12455. if (defaultNet) {
  12456. onDHCPServerNetworkChange();
  12457. }
  12458. document.getElementById('dhcp-server-instance-modal').classList.remove('hidden');
  12459. }
  12460. function openEditDHCPServerModal(id) {
  12461. const s = (state.dhcpServers || []).find(item => item.id === id);
  12462. if (!s) return;
  12463. document.getElementById('dhcp-server-modal-title').innerText = `Edit DHCP Server (${s.name})`;
  12464. document.getElementById('dhcp-server-modal-id').value = s.id;
  12465. document.getElementById('dhcp-server-modal-name').value = s.name;
  12466. document.getElementById('dhcp-server-modal-pool').value = s.address_pool;
  12467. document.getElementById('dhcp-server-modal-leasetime').value = s.lease_time || '12h';
  12468. document.getElementById('dhcp-server-modal-comment').value = s.comment || '';
  12469. document.getElementById('dhcp-server-modal-authoritative').checked = s.authoritative !== false;
  12470. document.getElementById('dhcp-server-modal-disabled').checked = !!s.disabled;
  12471. populateDHCPIfaceSelect('dhcp-server-modal-iface', s.interface);
  12472. populateDHCPNetworkSelect('dhcp-server-modal-network', s.network || '');
  12473. document.getElementById('dhcp-server-instance-modal').classList.remove('hidden');
  12474. }
  12475. function closeDHCPServerModal() {
  12476. document.getElementById('dhcp-server-instance-modal').classList.add('hidden');
  12477. }
  12478. async function submitSaveDHCPServer(e) {
  12479. e.preventDefault();
  12480. const id = document.getElementById('dhcp-server-modal-id').value;
  12481. const name = document.getElementById('dhcp-server-modal-name').value.trim();
  12482. const iface = document.getElementById('dhcp-server-modal-iface').value;
  12483. const network = document.getElementById('dhcp-server-modal-network').value.trim();
  12484. const pool = document.getElementById('dhcp-server-modal-pool').value.trim();
  12485. const leaseTime = document.getElementById('dhcp-server-modal-leasetime').value.trim() || '12h';
  12486. const comment = document.getElementById('dhcp-server-modal-comment').value.trim();
  12487. const authoritative = document.getElementById('dhcp-server-modal-authoritative').checked;
  12488. const disabled = document.getElementById('dhcp-server-modal-disabled').checked;
  12489. try {
  12490. const res = await fetch(`${API_BASE}/dhcp-server/servers`, {
  12491. method: 'POST',
  12492. headers: { 'Content-Type': 'application/json' },
  12493. body: JSON.stringify({
  12494. id,
  12495. name,
  12496. interface: iface,
  12497. network,
  12498. address_pool: pool,
  12499. lease_time: leaseTime,
  12500. authoritative,
  12501. disabled,
  12502. comment
  12503. })
  12504. });
  12505. if (res.ok) {
  12506. showToast('DHCP Server Saved', `Server ${name} configured successfully`, 'success');
  12507. closeDHCPServerModal();
  12508. loadDHCPServer(false);
  12509. fetchData(false);
  12510. } else {
  12511. const err = await res.text();
  12512. showToast('Error', err, 'error');
  12513. }
  12514. } catch (err) {
  12515. showToast('Error', err.message, 'error');
  12516. }
  12517. }
  12518. async function toggleDHCPServerState(id, disabled) {
  12519. try {
  12520. const res = await fetch(`${API_BASE}/dhcp-server/servers/${encodeURIComponent(id)}/state`, {
  12521. method: 'POST',
  12522. headers: { 'Content-Type': 'application/json' },
  12523. body: JSON.stringify({ disabled })
  12524. });
  12525. if (res.ok) {
  12526. showToast('State Updated', disabled ? 'Server disabled' : 'Server enabled', 'info');
  12527. loadDHCPServer(false);
  12528. fetchData(false);
  12529. }
  12530. } catch (err) {
  12531. showToast('Error', err.message, 'error');
  12532. }
  12533. }
  12534. async function deleteDHCPServer(id, name) {
  12535. if (!confirm(`Are you sure you want to delete DHCP Server "${name}"?`)) return;
  12536. try {
  12537. const res = await fetch(`${API_BASE}/dhcp-server/servers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12538. if (res.ok) {
  12539. showToast('Deleted', `DHCP Server ${name} removed`, 'success');
  12540. loadDHCPServer(false);
  12541. fetchData(false);
  12542. }
  12543. } catch (err) {
  12544. showToast('Error', err.message, 'error');
  12545. }
  12546. }
  12547. // ==================== MODALS & ACTIONS: NETWORKS ====================
  12548. function openAddDHCPNetworkModal() {
  12549. document.getElementById('dhcp-network-modal-title').innerText = 'Add DHCP Network';
  12550. document.getElementById('dhcp-network-modal-id').value = '';
  12551. document.getElementById('dhcp-network-modal-address').value = '192.168.88.0/24';
  12552. document.getElementById('dhcp-network-modal-gateway').value = '192.168.88.1';
  12553. document.getElementById('dhcp-network-modal-dns').value = '192.168.88.1, 1.1.1.1, 8.8.8.8';
  12554. document.getElementById('dhcp-network-modal-domain').value = 'lan';
  12555. document.getElementById('dhcp-network-modal-netmask').value = '';
  12556. document.getElementById('dhcp-network-modal-comment').value = '';
  12557. renderDHCPNetworkOptionsCheckboxes([]);
  12558. document.getElementById('dhcp-network-modal').classList.remove('hidden');
  12559. }
  12560. function openEditDHCPNetworkModal(id) {
  12561. const n = (state.dhcpNetworks || []).find(item => item.id === id);
  12562. if (!n) return;
  12563. document.getElementById('dhcp-network-modal-title').innerText = `Edit DHCP Network (${n.address})`;
  12564. document.getElementById('dhcp-network-modal-id').value = n.id;
  12565. document.getElementById('dhcp-network-modal-address').value = n.address;
  12566. document.getElementById('dhcp-network-modal-gateway').value = n.gateway || '';
  12567. document.getElementById('dhcp-network-modal-dns').value = (n.dns_servers || []).join(', ');
  12568. document.getElementById('dhcp-network-modal-domain').value = n.domain || '';
  12569. document.getElementById('dhcp-network-modal-netmask').value = n.netmask || '';
  12570. document.getElementById('dhcp-network-modal-comment').value = n.comment || '';
  12571. renderDHCPNetworkOptionsCheckboxes(n.dhcp_options || []);
  12572. document.getElementById('dhcp-network-modal').classList.remove('hidden');
  12573. }
  12574. function renderDHCPNetworkOptionsCheckboxes(selectedIds) {
  12575. const container = document.getElementById('dhcp-network-modal-options-list');
  12576. if (!container) return;
  12577. container.innerHTML = '';
  12578. const opts = state.dhcpOptions || [];
  12579. if (opts.length === 0) {
  12580. container.innerHTML = '<span class="text-slate-500 text-[11px] col-span-2">No custom options configured. Add some in the "Options" tab.</span>';
  12581. return;
  12582. }
  12583. opts.forEach(o => {
  12584. const isChecked = selectedIds.includes(o.id);
  12585. const label = document.createElement('label');
  12586. label.className = 'flex items-center space-x-2 text-slate-300 hover:text-white cursor-pointer';
  12587. label.innerHTML = `
  12588. <input type="checkbox" name="dhcp-net-opt" value="${o.id}" ${isChecked ? 'checked' : ''} class="rounded bg-slate-800 border-slate-700 text-emerald-600">
  12589. <span class="truncate" title="${escapeHtml(o.name)} (Code ${o.code})">${escapeHtml(o.name)} <span class="text-cyan-400">#${o.code}</span></span>
  12590. `;
  12591. container.appendChild(label);
  12592. });
  12593. }
  12594. function closeDHCPNetworkModal() {
  12595. document.getElementById('dhcp-network-modal').classList.add('hidden');
  12596. }
  12597. async function submitSaveDHCPNetwork(e) {
  12598. e.preventDefault();
  12599. const id = document.getElementById('dhcp-network-modal-id').value;
  12600. const address = document.getElementById('dhcp-network-modal-address').value.trim();
  12601. const gateway = document.getElementById('dhcp-network-modal-gateway').value.trim();
  12602. const dnsStr = document.getElementById('dhcp-network-modal-dns').value.trim();
  12603. const domain = document.getElementById('dhcp-network-modal-domain').value.trim();
  12604. const netmask = document.getElementById('dhcp-network-modal-netmask').value.trim();
  12605. const comment = document.getElementById('dhcp-network-modal-comment').value.trim();
  12606. const selectedOpts = [];
  12607. document.querySelectorAll('input[name="dhcp-net-opt"]:checked').forEach(cb => selectedOpts.push(cb.value));
  12608. const dnsServers = dnsStr ? dnsStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  12609. try {
  12610. const res = await fetch(`${API_BASE}/dhcp-server/networks`, {
  12611. method: 'POST',
  12612. headers: { 'Content-Type': 'application/json' },
  12613. body: JSON.stringify({
  12614. id,
  12615. address,
  12616. gateway,
  12617. netmask,
  12618. dns_servers: dnsServers,
  12619. domain,
  12620. dhcp_options: selectedOpts,
  12621. comment
  12622. })
  12623. });
  12624. if (res.ok) {
  12625. showToast('Network Saved', `Subnet ${address} configured successfully`, 'success');
  12626. closeDHCPNetworkModal();
  12627. loadDHCPServer(false);
  12628. fetchData(false);
  12629. } else {
  12630. const err = await res.text();
  12631. showToast('Error', err, 'error');
  12632. }
  12633. } catch (err) {
  12634. showToast('Error', err.message, 'error');
  12635. }
  12636. }
  12637. async function deleteDHCPNetwork(id, addr) {
  12638. if (!confirm(`Are you sure you want to delete DHCP Network "${addr}"?`)) return;
  12639. try {
  12640. const res = await fetch(`${API_BASE}/dhcp-server/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12641. if (res.ok) {
  12642. showToast('Deleted', `Network ${addr} removed`, 'success');
  12643. loadDHCPServer(false);
  12644. fetchData(false);
  12645. }
  12646. } catch (err) {
  12647. showToast('Error', err.message, 'error');
  12648. }
  12649. }
  12650. // ==================== MODALS & ACTIONS: LEASES ====================
  12651. function openAddDHCPStaticLeaseModal() {
  12652. document.getElementById('dhcp-static-lease-modal-title').innerText = 'Add Static Lease Reservation';
  12653. document.getElementById('dhcp-static-lease-modal-id').value = '';
  12654. document.getElementById('dhcp-static-lease-modal-mac').value = '';
  12655. document.getElementById('dhcp-static-lease-modal-ip').value = '';
  12656. document.getElementById('dhcp-static-lease-modal-hostname').value = '';
  12657. document.getElementById('dhcp-static-lease-modal-server').value = 'all';
  12658. document.getElementById('dhcp-static-lease-modal-comment').value = '';
  12659. document.getElementById('dhcp-static-lease-modal-disabled').checked = false;
  12660. document.getElementById('dhcp-static-lease-modal').classList.remove('hidden');
  12661. }
  12662. function closeDHCPStaticLeaseModal() {
  12663. document.getElementById('dhcp-static-lease-modal').classList.add('hidden');
  12664. }
  12665. async function submitSaveDHCPStaticLease(e) {
  12666. e.preventDefault();
  12667. const id = document.getElementById('dhcp-static-lease-modal-id').value;
  12668. const mac = document.getElementById('dhcp-static-lease-modal-mac').value.trim();
  12669. const ip = document.getElementById('dhcp-static-lease-modal-ip').value.trim();
  12670. const hostname = document.getElementById('dhcp-static-lease-modal-hostname').value.trim();
  12671. const server = document.getElementById('dhcp-static-lease-modal-server').value.trim() || 'all';
  12672. const comment = document.getElementById('dhcp-static-lease-modal-comment').value.trim();
  12673. const disabled = document.getElementById('dhcp-static-lease-modal-disabled').checked;
  12674. try {
  12675. const res = await fetch(`${API_BASE}/dhcp-server/leases/static`, {
  12676. method: 'POST',
  12677. headers: { 'Content-Type': 'application/json' },
  12678. body: JSON.stringify({
  12679. id,
  12680. mac_address: mac,
  12681. address: ip,
  12682. hostname,
  12683. server,
  12684. comment,
  12685. disabled
  12686. })
  12687. });
  12688. if (res.ok) {
  12689. showToast('Static Lease Saved', `IP ${ip} reserved for ${mac}`, 'success');
  12690. closeDHCPStaticLeaseModal();
  12691. loadDHCPServer(false);
  12692. fetchData(false);
  12693. } else {
  12694. const err = await res.text();
  12695. showToast('Error', err, 'error');
  12696. }
  12697. } catch (err) {
  12698. showToast('Error', err.message, 'error');
  12699. }
  12700. }
  12701. async function deleteDHCPStaticLease(id) {
  12702. if (!confirm('Are you sure you want to remove this static reservation?')) return;
  12703. try {
  12704. const res = await fetch(`${API_BASE}/dhcp-server/leases/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12705. if (res.ok) {
  12706. showToast('Deleted', 'Static lease removed', 'success');
  12707. loadDHCPServer(false);
  12708. fetchData(false);
  12709. }
  12710. } catch (err) {
  12711. showToast('Error', err.message, 'error');
  12712. }
  12713. }
  12714. async function makeDHCPLeaseStatic(mac, ip, hostname, comment) {
  12715. try {
  12716. const res = await fetch(`${API_BASE}/dhcp-server/leases/make-static`, {
  12717. method: 'POST',
  12718. headers: { 'Content-Type': 'application/json' },
  12719. body: JSON.stringify({
  12720. mac_address: mac,
  12721. address: ip,
  12722. hostname,
  12723. comment: comment || 'Converted to static'
  12724. })
  12725. });
  12726. if (res.ok) {
  12727. showToast('Lease Made Static', `IP ${ip} permanently reserved for ${mac}`, 'success');
  12728. loadDHCPServer(false);
  12729. fetchData(false);
  12730. } else {
  12731. const err = await res.text();
  12732. showToast('Error', err, 'error');
  12733. }
  12734. } catch (err) {
  12735. showToast('Error', err.message, 'error');
  12736. }
  12737. }
  12738. // ==================== MODALS & ACTIONS: OPTIONS ====================
  12739. function openAddDHCPOptionModal() {
  12740. document.getElementById('dhcp-option-modal-title').innerText = 'Add DHCP Option';
  12741. document.getElementById('dhcp-option-modal-id').value = '';
  12742. document.getElementById('dhcp-option-modal-name').value = '';
  12743. document.getElementById('dhcp-option-modal-code').value = '';
  12744. document.getElementById('dhcp-option-modal-value').value = '';
  12745. document.getElementById('dhcp-option-modal-comment').value = '';
  12746. document.getElementById('dhcp-option-modal').classList.remove('hidden');
  12747. }
  12748. function openEditDHCPOptionModal(id) {
  12749. const o = (state.dhcpOptions || []).find(item => item.id === id);
  12750. if (!o) return;
  12751. document.getElementById('dhcp-option-modal-title').innerText = `Edit DHCP Option (${o.name})`;
  12752. document.getElementById('dhcp-option-modal-id').value = o.id;
  12753. document.getElementById('dhcp-option-modal-name').value = o.name;
  12754. document.getElementById('dhcp-option-modal-code').value = o.code;
  12755. document.getElementById('dhcp-option-modal-value').value = o.value;
  12756. document.getElementById('dhcp-option-modal-comment').value = o.comment || '';
  12757. document.getElementById('dhcp-option-modal').classList.remove('hidden');
  12758. }
  12759. function closeDHCPOptionModal() {
  12760. document.getElementById('dhcp-option-modal').classList.add('hidden');
  12761. }
  12762. async function submitSaveDHCPOption(e) {
  12763. e.preventDefault();
  12764. const id = document.getElementById('dhcp-option-modal-id').value;
  12765. const name = document.getElementById('dhcp-option-modal-name').value.trim();
  12766. const code = parseInt(document.getElementById('dhcp-option-modal-code').value);
  12767. const value = document.getElementById('dhcp-option-modal-value').value.trim();
  12768. const comment = document.getElementById('dhcp-option-modal-comment').value.trim();
  12769. try {
  12770. const res = await fetch(`${API_BASE}/dhcp-server/options`, {
  12771. method: 'POST',
  12772. headers: { 'Content-Type': 'application/json' },
  12773. body: JSON.stringify({ id, name, code, value, comment })
  12774. });
  12775. if (res.ok) {
  12776. showToast('Option Saved', `DHCP option ${name} (#${code}) configured`, 'success');
  12777. closeDHCPOptionModal();
  12778. loadDHCPServer(false);
  12779. fetchData(false);
  12780. } else {
  12781. const err = await res.text();
  12782. showToast('Error', err, 'error');
  12783. }
  12784. } catch (err) {
  12785. showToast('Error', err.message, 'error');
  12786. }
  12787. }
  12788. async function deleteDHCPOption(id, name) {
  12789. if (!confirm(`Are you sure you want to delete DHCP Option "${name}"?`)) return;
  12790. try {
  12791. const res = await fetch(`${API_BASE}/dhcp-server/options/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12792. if (res.ok) {
  12793. showToast('Deleted', `Option ${name} removed`, 'success');
  12794. loadDHCPServer(false);
  12795. fetchData(false);
  12796. }
  12797. } catch (err) {
  12798. showToast('Error', err.message, 'error');
  12799. }
  12800. }
  12801. // ==================== WIZARD: DHCP SETUP (MikroTik style) ====================
  12802. function openDHCPServerSetupModal() {
  12803. populateDHCPIfaceSelect('dhcp-wizard-iface', '');
  12804. onDHCPWizardIfaceChange();
  12805. document.getElementById('dhcp-setup-wizard-modal').classList.remove('hidden');
  12806. }
  12807. function closeDHCPServerSetupModal() {
  12808. document.getElementById('dhcp-setup-wizard-modal').classList.add('hidden');
  12809. }
  12810. function onDHCPWizardIfaceChange() {
  12811. const ifaceName = document.getElementById('dhcp-wizard-iface').value;
  12812. const iface = (state.interfaces || []).find(i => i.name === ifaceName);
  12813. let ip = '192.168.88.1';
  12814. let prefix = '24';
  12815. if (iface && iface.ip_address) {
  12816. const parts = iface.ip_address.split('/');
  12817. ip = parts[0];
  12818. if (parts.length > 1) prefix = parts[1];
  12819. }
  12820. // Calculate subnet base (e.g. 192.168.88.0/24)
  12821. const ipParts = ip.split('.');
  12822. if (ipParts.length === 4) {
  12823. const baseSpace = `${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.0/${prefix}`;
  12824. const pool = `${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.10-${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.254`;
  12825. document.getElementById('dhcp-wizard-space').value = baseSpace;
  12826. document.getElementById('dhcp-wizard-gateway').value = ip;
  12827. document.getElementById('dhcp-wizard-pool').value = pool;
  12828. document.getElementById('dhcp-wizard-dns').value = `${ip}, 1.1.1.1, 8.8.8.8`;
  12829. document.getElementById('dhcp-wizard-ntp').value = `${ip}`;
  12830. }
  12831. }
  12832. async function submitDHCPServerSetupWizard(e) {
  12833. e.preventDefault();
  12834. const iface = document.getElementById('dhcp-wizard-iface').value;
  12835. const space = document.getElementById('dhcp-wizard-space').value.trim();
  12836. const gw = document.getElementById('dhcp-wizard-gateway').value.trim();
  12837. const pool = document.getElementById('dhcp-wizard-pool').value.trim();
  12838. const dnsStr = document.getElementById('dhcp-wizard-dns').value.trim();
  12839. const leaseTime = document.getElementById('dhcp-wizard-leasetime').value.trim() || '12h';
  12840. const ntpStr = document.getElementById('dhcp-wizard-ntp').value.trim();
  12841. const tftp = document.getElementById('dhcp-wizard-tftp').value.trim();
  12842. const dnsServers = dnsStr ? dnsStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  12843. const ntpServers = ntpStr ? ntpStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  12844. try {
  12845. const res = await fetch(`${API_BASE}/dhcp-server/setup`, {
  12846. method: 'POST',
  12847. headers: { 'Content-Type': 'application/json' },
  12848. body: JSON.stringify({
  12849. interface: iface,
  12850. address_space: space,
  12851. gateway: gw,
  12852. address_pool: pool,
  12853. dns_servers: dnsServers,
  12854. lease_time: leaseTime,
  12855. ntp_servers: ntpServers,
  12856. next_server: tftp
  12857. })
  12858. });
  12859. if (res.ok) {
  12860. showToast('DHCP Setup Complete', `DHCP Server setup finished on ${iface}`, 'success');
  12861. closeDHCPServerSetupModal();
  12862. loadDHCPServer(false);
  12863. fetchData(false);
  12864. } else {
  12865. const err = await res.text();
  12866. showToast('Error', err, 'error');
  12867. }
  12868. } catch (err) {
  12869. showToast('Error', err.message, 'error');
  12870. }
  12871. }
  12872. function populateDHCPIfaceSelect(elemId, selectedVal) {
  12873. const sel = document.getElementById(elemId);
  12874. if (!sel) return;
  12875. sel.innerHTML = '<option value="">Select interface...</option>';
  12876. const ifaces = state.interfaces || [];
  12877. ifaces.forEach(i => {
  12878. if (i.name === 'lo') return;
  12879. const opt = document.createElement('option');
  12880. opt.value = i.name;
  12881. const ipStr = i.ip_address ? ` (${i.ip_address})` : '';
  12882. opt.textContent = `${i.name}${ipStr} [${i.role || i.type || 'interface'}]`;
  12883. if (i.name === selectedVal) opt.selected = true;
  12884. sel.appendChild(opt);
  12885. });
  12886. }
  12887. // ==================== UNIVERSAL TABLE ORDERING / SORTING (WINBOX / WEBFIG STYLE) ====================
  12888. function initTableSorting() {
  12889. document.querySelectorAll('table').forEach(setupSortableTable);
  12890. }
  12891. function setupSortableTable(table) {
  12892. const thead = table.querySelector('thead');
  12893. const tbody = table.querySelector('tbody');
  12894. if (!thead || !tbody) return;
  12895. const headerRows = thead.querySelectorAll('tr');
  12896. if (headerRows.length === 0) return;
  12897. const ths = headerRows[headerRows.length - 1].querySelectorAll('th');
  12898. ths.forEach((th, colIdx) => {
  12899. if (th._sortBound) return;
  12900. th._sortBound = true;
  12901. const rawText = th.innerText.trim().toLowerCase();
  12902. const isActionsCol = rawText === 'actions' || (rawText === 'action' && th.classList.contains('text-right'));
  12903. const isCheckboxCol = !!th.querySelector('input[type="checkbox"]');
  12904. const isExpandCol = (th.classList.contains('w-8') || th.classList.contains('w-6')) && !rawText;
  12905. const isExplicitNoSort = th.classList.contains('no-sort') || th.getAttribute('data-sortable') === 'false';
  12906. if (isActionsCol || isCheckboxCol || isExpandCol || isExplicitNoSort) {
  12907. return;
  12908. }
  12909. th.classList.add('table-sortable', 'group');
  12910. if (!th.title) th.title = 'Click to sort (Ascending / Descending / Default)';
  12911. let icon = th.querySelector('.table-sort-icon');
  12912. if (!icon) {
  12913. icon = document.createElement('span');
  12914. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  12915. icon.innerHTML = '⇅';
  12916. th.appendChild(icon);
  12917. }
  12918. th.addEventListener('click', (e) => {
  12919. if (e.target.tagName === 'INPUT' || e.target.tagName === 'BUTTON' || e.target.closest('button, input')) return;
  12920. handleHeaderClick(table, th, colIdx);
  12921. });
  12922. });
  12923. if (!tbody._sortObserved) {
  12924. tbody._sortObserved = true;
  12925. let sortDebounceTimer = null;
  12926. const observer = new MutationObserver((mutations) => {
  12927. if (tbody._isSorting) return;
  12928. const hasChildChanges = mutations.some(m => m.type === 'childList' && m.addedNodes.length > 0);
  12929. if (!hasChildChanges) return;
  12930. clearTimeout(sortDebounceTimer);
  12931. sortDebounceTimer = setTimeout(() => {
  12932. if (tbody._isSorting) return;
  12933. if (table._activeSort && table._activeSort.dir !== 'none') {
  12934. applyTableSort(table, table._activeSort.colIdx, table._activeSort.dir, false);
  12935. } else {
  12936. tagOriginalRowOrder(tbody);
  12937. }
  12938. }, 50);
  12939. });
  12940. tbody._sortObserver = observer;
  12941. observer.observe(tbody, { childList: true });
  12942. }
  12943. tagOriginalRowOrder(tbody);
  12944. }
  12945. function tagOriginalRowOrder(tbody) {
  12946. let idx = 0;
  12947. Array.from(tbody.children).forEach(tr => {
  12948. if (!tr.querySelector('td[colspan]')) {
  12949. if (!tr.hasAttribute('data-orig-idx')) {
  12950. tr.setAttribute('data-orig-idx', idx++);
  12951. }
  12952. }
  12953. });
  12954. }
  12955. function handleHeaderClick(table, th, colIdx) {
  12956. const currentSort = table._activeSort || { colIdx: -1, dir: 'none' };
  12957. let newDir = 'asc';
  12958. if (currentSort.colIdx === colIdx) {
  12959. if (currentSort.dir === 'asc') newDir = 'desc';
  12960. else if (currentSort.dir === 'desc') newDir = 'none';
  12961. else newDir = 'asc';
  12962. } else {
  12963. newDir = 'asc';
  12964. }
  12965. table._activeSort = { colIdx, dir: newDir };
  12966. updateHeaderIcons(table, colIdx, newDir);
  12967. applyTableSort(table, colIdx, newDir, true);
  12968. }
  12969. function updateHeaderIcons(table, activeColIdx, dir) {
  12970. const thead = table.querySelector('thead');
  12971. if (!thead) return;
  12972. const ths = thead.querySelectorAll('th');
  12973. ths.forEach((th, idx) => {
  12974. const icon = th.querySelector('.table-sort-icon');
  12975. if (!icon) return;
  12976. if (idx === activeColIdx && dir !== 'none') {
  12977. icon.innerHTML = dir === 'asc' ? '▲' : '▼';
  12978. icon.className = 'table-sort-icon text-cyan-400 font-bold opacity-100';
  12979. th.classList.add('table-sorted-active');
  12980. } else {
  12981. icon.innerHTML = '⇅';
  12982. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  12983. th.classList.remove('table-sorted-active');
  12984. }
  12985. });
  12986. }
  12987. function applyTableSort(table, colIdx, dir, userInitiated) {
  12988. const tbody = table.querySelector('tbody');
  12989. if (!tbody || tbody.children.length <= 1) return;
  12990. tbody._isSorting = true;
  12991. tagOriginalRowOrder(tbody);
  12992. // Group parent rows and any attached drawer/sub-rows
  12993. const groups = [];
  12994. let currentGroup = null;
  12995. Array.from(tbody.children).forEach(tr => {
  12996. if (tr.querySelector('td[colspan]')) {
  12997. if (currentGroup) {
  12998. currentGroup.subRows.push(tr);
  12999. } else {
  13000. groups.push({ mainRow: tr, subRows: [] });
  13001. }
  13002. } else {
  13003. currentGroup = { mainRow: tr, subRows: [] };
  13004. groups.push(currentGroup);
  13005. }
  13006. });
  13007. if (dir === 'none') {
  13008. groups.sort((a, b) => {
  13009. const idxA = parseInt(a.mainRow.getAttribute('data-orig-idx') || '0', 10);
  13010. const idxB = parseInt(b.mainRow.getAttribute('data-orig-idx') || '0', 10);
  13011. return idxA - idxB;
  13012. });
  13013. } else {
  13014. groups.sort((a, b) => {
  13015. const cellA = a.mainRow.children[colIdx];
  13016. const cellB = b.mainRow.children[colIdx];
  13017. const res = compareTableCells(cellA, cellB);
  13018. return dir === 'asc' ? res : -res;
  13019. });
  13020. }
  13021. // Check if rows are already in correct order to avoid modifying DOM
  13022. let alreadyOrdered = true;
  13023. let childIdx = 0;
  13024. for (const g of groups) {
  13025. if (tbody.children[childIdx] !== g.mainRow) {
  13026. alreadyOrdered = false;
  13027. break;
  13028. }
  13029. childIdx++;
  13030. for (const sub of g.subRows) {
  13031. if (tbody.children[childIdx] !== sub) {
  13032. alreadyOrdered = false;
  13033. break;
  13034. }
  13035. childIdx++;
  13036. }
  13037. }
  13038. if (alreadyOrdered) {
  13039. tbody._isSorting = false;
  13040. return;
  13041. }
  13042. // Disconnect observer while re-ordering to prevent recursion and thrashing
  13043. if (tbody._sortObserver) {
  13044. tbody._sortObserver.disconnect();
  13045. }
  13046. // Re-append rows in sorted order
  13047. groups.forEach(g => {
  13048. tbody.appendChild(g.mainRow);
  13049. g.subRows.forEach(sub => tbody.appendChild(sub));
  13050. });
  13051. // Drain any queued mutations and re-connect observer
  13052. if (tbody._sortObserver) {
  13053. tbody._sortObserver.takeRecords();
  13054. tbody._sortObserver.observe(tbody, { childList: true });
  13055. }
  13056. tbody._isSorting = false;
  13057. }
  13058. function getCellRawText(cell) {
  13059. if (!cell) return '';
  13060. if (cell.hasAttribute('data-sort-value')) return cell.getAttribute('data-sort-value');
  13061. const input = cell.querySelector('input, select');
  13062. if (input) {
  13063. if (input.type === 'checkbox') return input.checked ? '1' : '0';
  13064. return input.value;
  13065. }
  13066. return cell.innerText.trim();
  13067. }
  13068. function parseTrafficToNumber(str) {
  13069. const m = str.match(/^([\d.,]+)\s*([KMGTkmgt]?[iI]?[Bb](?:ps|\/s)?)/);
  13070. if (!m) return null;
  13071. const num = parseFloat(m[1].replace(/,/g, ''));
  13072. if (isNaN(num)) return null;
  13073. const unit = m[2].toUpperCase();
  13074. let mult = 1;
  13075. if (unit.startsWith('K')) mult = 1024;
  13076. else if (unit.startsWith('M')) mult = 1024 * 1024;
  13077. else if (unit.startsWith('G')) mult = 1024 * 1024 * 1024;
  13078. else if (unit.startsWith('T')) mult = 1024 * 1024 * 1024 * 1024;
  13079. return num * mult;
  13080. }
  13081. function parseIpToNumber(str) {
  13082. const clean = str.replace(/^[!~]/, '').trim();
  13083. const m = clean.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(?:\/(\d{1,2}))?/);
  13084. if (!m) return null;
  13085. const o1 = parseInt(m[1], 10);
  13086. const o2 = parseInt(m[2], 10);
  13087. const o3 = parseInt(m[3], 10);
  13088. const o4 = parseInt(m[4], 10);
  13089. if (o1 > 255 || o2 > 255 || o3 > 255 || o4 > 255) return null;
  13090. return ((o1 * 256 + o2) * 256 + o3) * 256 + o4;
  13091. }
  13092. function parseCompoundPackets(str) {
  13093. const m = str.match(/^([\d,]+)p/);
  13094. if (!m) return null;
  13095. return parseInt(m[1].replace(/,/g, ''), 10);
  13096. }
  13097. function compareTableCells(cellA, cellB) {
  13098. const a = getCellRawText(cellA);
  13099. const b = getCellRawText(cellB);
  13100. if (a === '' && b !== '') return 1;
  13101. if (b === '' && a !== '') return -1;
  13102. if (a === b) return 0;
  13103. // 1. IP Addresses / CIDR
  13104. const ipA = parseIpToNumber(a);
  13105. const ipB = parseIpToNumber(b);
  13106. if (ipA !== null && ipB !== null) return ipA - ipB;
  13107. // 2. Packet counts (e.g. "1,250p / 45 KB")
  13108. const pktA = parseCompoundPackets(a);
  13109. const pktB = parseCompoundPackets(b);
  13110. if (pktA !== null && pktB !== null) return pktA - pktB;
  13111. // 3. Traffic / Throughput / Bytes (e.g. "1.2 MB", "500 KiB", "10 Gbps")
  13112. const trafA = parseTrafficToNumber(a);
  13113. const trafB = parseTrafficToNumber(b);
  13114. if (trafA !== null && trafB !== null) return trafA - trafB;
  13115. // 4. Numbers with '#' or formatted with commas (e.g. "#1", "24", "1,200")
  13116. const cleanNumA = a.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  13117. const cleanNumB = b.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  13118. const numA = Number(cleanNumA);
  13119. const numB = Number(cleanNumB);
  13120. if (!isNaN(numA) && !isNaN(numB) && cleanNumA !== '' && cleanNumB !== '') {
  13121. return numA - numB;
  13122. }
  13123. // 5. Natural case-insensitive string compare
  13124. return a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' });
  13125. }
  13126. // ==================== VRRP HIGH AVAILABILITY CONTROLLER ====================
  13127. async function loadVRRP(showToastNotification = false) {
  13128. try {
  13129. const [instRes, sumRes] = await Promise.all([
  13130. fetch(`${API_BASE}/vrrp/instances`),
  13131. fetch(`${API_BASE}/vrrp/summary`)
  13132. ]);
  13133. if (instRes.ok) {
  13134. state.vrrpInstances = await instRes.json();
  13135. renderVRRP();
  13136. }
  13137. if (sumRes.ok) {
  13138. state.vrrpSummary = await sumRes.json();
  13139. renderVRRPSummary();
  13140. }
  13141. if (showToastNotification) {
  13142. showToast('Refreshed', 'VRRP telemetry refreshed', 'info');
  13143. }
  13144. } catch (err) {
  13145. console.error('Failed to load VRRP:', err);
  13146. }
  13147. }
  13148. function renderVRRPSummary() {
  13149. const s = state.vrrpSummary || { total_instances: 0, master_instances: 0, backup_instances: 0 };
  13150. const elTotal = document.getElementById('vrrp-stat-total');
  13151. if (elTotal) elTotal.innerText = s.total_instances || 0;
  13152. const elMaster = document.getElementById('vrrp-stat-master');
  13153. if (elMaster) elMaster.innerText = s.master_instances || 0;
  13154. const elBackup = document.getElementById('vrrp-stat-backup');
  13155. if (elBackup) elBackup.innerText = s.backup_instances || 0;
  13156. const bCount = document.getElementById('badge-vrrp-count');
  13157. if (bCount) bCount.innerText = s.total_instances || 0;
  13158. const dot = document.getElementById('badge-vrrp-dot');
  13159. if (dot) {
  13160. if (s.master_instances > 0) {
  13161. dot.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  13162. } else if (s.backup_instances > 0) {
  13163. dot.className = 'w-2 h-2 rounded-full bg-sky-400';
  13164. } else {
  13165. dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  13166. }
  13167. }
  13168. }
  13169. function renderVRRP() {
  13170. const tbody = document.getElementById('vrrp-table-tbody');
  13171. const empty = document.getElementById('vrrp-table-empty');
  13172. if (!tbody) return;
  13173. tbody.innerHTML = '';
  13174. const instances = state.vrrpInstances || [];
  13175. if (instances.length === 0) {
  13176. empty?.classList.remove('hidden');
  13177. return;
  13178. }
  13179. empty?.classList.add('hidden');
  13180. instances.forEach(inst => {
  13181. const tr = document.createElement('tr');
  13182. tr.className = `hover:bg-slate-800/40 transition text-xs ${inst.disabled ? 'opacity-50' : ''}`;
  13183. // Render Flag: M (Master), B (Backup), F (Fault), X (Disabled)
  13184. 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>`;
  13185. if (inst.disabled) {
  13186. 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>`;
  13187. } else if (inst.state === 'MASTER') {
  13188. 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>`;
  13189. } else if (inst.state === 'BACKUP') {
  13190. 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>`;
  13191. } else if (inst.state === 'FAULT') {
  13192. 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>`;
  13193. }
  13194. // Render State Badge
  13195. let stateBadge = `<span class="px-2 py-0.5 rounded text-[10px] bg-slate-800 text-slate-400 border border-slate-700">DISABLED</span>`;
  13196. if (!inst.disabled) {
  13197. if (inst.state === 'MASTER') {
  13198. 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>`;
  13199. } else if (inst.state === 'BACKUP') {
  13200. 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>`;
  13201. } else if (inst.state === 'FAULT') {
  13202. 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>`;
  13203. }
  13204. }
  13205. const vipsStr = (inst.virtual_ips || []).join(', ') || '-';
  13206. tr.innerHTML = `
  13207. <td class="py-2.5 px-3 text-center">${flagHtml}</td>
  13208. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(inst.name)}</td>
  13209. <td class="py-2.5 px-3 font-mono text-cyan-400 font-semibold">${escapeHtml(inst.interface)}</td>
  13210. <td class="py-2.5 px-3 font-mono font-bold text-center text-white">${inst.vrid}</td>
  13211. <td class="py-2.5 px-3 font-mono text-center text-slate-300 font-semibold">${inst.priority}</td>
  13212. <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>
  13213. <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>
  13214. <td class="py-2.5 px-3 font-mono text-slate-400 text-[11px]">${escapeHtml(inst.virtual_mac || '-')}</td>
  13215. <td class="py-2.5 px-3 text-center">${stateBadge}</td>
  13216. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]" title="${escapeHtml(inst.comment || '')}">${escapeHtml(inst.comment || '-')}</td>
  13217. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  13218. <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>
  13219. <button onclick="openEditVRRPModal('${inst.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  13220. <button onclick="deleteVRRP('${inst.id}', '${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  13221. </td>
  13222. `;
  13223. tbody.appendChild(tr);
  13224. });
  13225. }
  13226. function populateVRRPIfaceSelect(elemId, selectedIface) {
  13227. const sel = document.getElementById(elemId);
  13228. if (!sel) return;
  13229. sel.innerHTML = '<option value="">Select interface...</option>';
  13230. const ifaces = state.interfaces || [];
  13231. ifaces.forEach(i => {
  13232. const opt = document.createElement('option');
  13233. opt.value = i.name;
  13234. opt.innerText = `${i.name} (${i.type || 'net'}${i.ip ? ' - ' + i.ip : ''})`;
  13235. if (selectedIface && selectedIface === i.name) opt.selected = true;
  13236. sel.appendChild(opt);
  13237. });
  13238. }
  13239. function openAddVRRPModal() {
  13240. document.getElementById('modal-vrrp-title').innerText = 'Add VRRP Instance';
  13241. document.getElementById('modal-vrrp-id').value = '';
  13242. document.getElementById('modal-vrrp-name').value = `vrrp${(state.vrrpInstances || []).length + 1}`;
  13243. document.getElementById('modal-vrrp-vrid').value = 10 + (state.vrrpInstances || []).length;
  13244. document.getElementById('modal-vrrp-priority').value = 100;
  13245. document.getElementById('modal-vrrp-vip').value = '192.168.88.254/24';
  13246. document.getElementById('modal-vrrp-version').value = '3';
  13247. document.getElementById('modal-vrrp-interval').value = 1;
  13248. document.getElementById('modal-vrrp-authtype').value = 'none';
  13249. document.getElementById('modal-vrrp-authpass').value = '';
  13250. document.getElementById('modal-vrrp-comment').value = '';
  13251. document.getElementById('modal-vrrp-preempt').checked = true;
  13252. document.getElementById('modal-vrrp-disabled').checked = false;
  13253. populateVRRPIfaceSelect('modal-vrrp-iface', '');
  13254. document.getElementById('modal-vrrp-instance').classList.remove('hidden');
  13255. }
  13256. function openEditVRRPModal(id) {
  13257. const inst = (state.vrrpInstances || []).find(item => item.id === id);
  13258. if (!inst) return;
  13259. document.getElementById('modal-vrrp-title').innerText = `Edit VRRP Instance (${inst.name})`;
  13260. document.getElementById('modal-vrrp-id').value = inst.id;
  13261. document.getElementById('modal-vrrp-name').value = inst.name;
  13262. document.getElementById('modal-vrrp-vrid').value = inst.vrid;
  13263. document.getElementById('modal-vrrp-priority').value = inst.priority;
  13264. document.getElementById('modal-vrrp-vip').value = (inst.virtual_ips || []).join(', ');
  13265. document.getElementById('modal-vrrp-version').value = String(inst.version || 3);
  13266. document.getElementById('modal-vrrp-interval').value = inst.interval || 1;
  13267. document.getElementById('modal-vrrp-authtype').value = inst.auth_type || 'none';
  13268. document.getElementById('modal-vrrp-authpass').value = inst.auth_password || '';
  13269. document.getElementById('modal-vrrp-comment').value = inst.comment || '';
  13270. document.getElementById('modal-vrrp-preempt').checked = inst.preempt !== false;
  13271. document.getElementById('modal-vrrp-disabled').checked = !!inst.disabled;
  13272. populateVRRPIfaceSelect('modal-vrrp-iface', inst.interface);
  13273. document.getElementById('modal-vrrp-instance').classList.remove('hidden');
  13274. }
  13275. function closeVRRPModal() {
  13276. document.getElementById('modal-vrrp-instance').classList.add('hidden');
  13277. }
  13278. async function submitSaveVRRP(e) {
  13279. e.preventDefault();
  13280. const id = document.getElementById('modal-vrrp-id').value;
  13281. const name = document.getElementById('modal-vrrp-name').value.trim();
  13282. const iface = document.getElementById('modal-vrrp-iface').value;
  13283. const vrid = parseInt(document.getElementById('modal-vrrp-vrid').value, 10) || 1;
  13284. const priority = parseInt(document.getElementById('modal-vrrp-priority').value, 10) || 100;
  13285. const vipRaw = document.getElementById('modal-vrrp-vip').value.trim();
  13286. const version = parseInt(document.getElementById('modal-vrrp-version').value, 10) || 3;
  13287. const interval = parseInt(document.getElementById('modal-vrrp-interval').value, 10) || 1;
  13288. const authType = document.getElementById('modal-vrrp-authtype').value;
  13289. const authPass = document.getElementById('modal-vrrp-authpass').value.trim();
  13290. const comment = document.getElementById('modal-vrrp-comment').value.trim();
  13291. const preempt = document.getElementById('modal-vrrp-preempt').checked;
  13292. const disabled = document.getElementById('modal-vrrp-disabled').checked;
  13293. const vips = vipRaw.split(',').map(s => s.trim()).filter(Boolean);
  13294. try {
  13295. const res = await fetch(`${API_BASE}/vrrp/instances`, {
  13296. method: 'POST',
  13297. headers: { 'Content-Type': 'application/json' },
  13298. body: JSON.stringify({
  13299. id,
  13300. name,
  13301. interface: iface,
  13302. vrid,
  13303. priority,
  13304. virtual_ips: vips,
  13305. version,
  13306. interval,
  13307. auth_type: authType,
  13308. auth_password: authPass,
  13309. comment,
  13310. preempt,
  13311. disabled
  13312. })
  13313. });
  13314. if (res.ok) {
  13315. showToast('VRRP Saved', `VRRP instance ${name} configured`, 'success');
  13316. closeVRRPModal();
  13317. loadVRRP(false);
  13318. fetchData(false);
  13319. } else {
  13320. const err = await res.text();
  13321. showToast('Error', err, 'error');
  13322. }
  13323. } catch (err) {
  13324. showToast('Error', err.message, 'error');
  13325. }
  13326. }
  13327. async function deleteVRRP(id, name) {
  13328. if (!confirm(`Delete VRRP instance "${name}"?`)) return;
  13329. try {
  13330. const res = await fetch(`${API_BASE}/vrrp/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  13331. if (res.ok) {
  13332. showToast('Deleted', `VRRP instance ${name} removed`, 'info');
  13333. loadVRRP(false);
  13334. fetchData(false);
  13335. } else {
  13336. const err = await res.text();
  13337. showToast('Error', err, 'error');
  13338. }
  13339. } catch (err) {
  13340. showToast('Error', err.message, 'error');
  13341. }
  13342. }
  13343. async function toggleVRRPState(id, disabled) {
  13344. try {
  13345. const res = await fetch(`${API_BASE}/vrrp/instances/${encodeURIComponent(id)}/state`, {
  13346. method: 'POST',
  13347. headers: { 'Content-Type': 'application/json' },
  13348. body: JSON.stringify({ disabled })
  13349. });
  13350. if (res.ok) {
  13351. showToast('State Updated', disabled ? 'VRRP disabled' : 'VRRP enabled', 'info');
  13352. loadVRRP(false);
  13353. fetchData(false);
  13354. } else {
  13355. const err = await res.text();
  13356. showToast('Error', err, 'error');
  13357. }
  13358. } catch (err) {
  13359. showToast('Error', err.message, 'error');
  13360. }
  13361. }
  13362. // Global observer for dynamically injected tables (e.g. inside modals or drawers)
  13363. if (typeof MutationObserver !== 'undefined' && typeof document !== 'undefined') {
  13364. let docSortDebounce = null;
  13365. const docTableObserver = new MutationObserver((mutations) => {
  13366. let needsInit = false;
  13367. for (const m of mutations) {
  13368. for (const node of m.addedNodes) {
  13369. if (node.nodeType === 1) {
  13370. if (node.tagName === 'TABLE' && !node.closest('tbody, thead')) {
  13371. needsInit = true;
  13372. break;
  13373. } else if (node.querySelector && !node.closest('table') && node.querySelector('table')) {
  13374. needsInit = true;
  13375. break;
  13376. }
  13377. }
  13378. }
  13379. if (needsInit) break;
  13380. }
  13381. if (needsInit) {
  13382. clearTimeout(docSortDebounce);
  13383. docSortDebounce = setTimeout(initTableSorting, 100);
  13384. }
  13385. });
  13386. docTableObserver.observe(document.body || document.documentElement, { childList: true, subtree: true });
  13387. }
  13388. // =========================================================================
  13389. // BANDWIDTH TEST (BwTest) BENCHMARK ENGINE
  13390. // =========================================================================
  13391. const bwtestState = {
  13392. running: false,
  13393. pollTimer: null,
  13394. eventSource: null,
  13395. chartPoints: [],
  13396. maxChartPoints: 60,
  13397. serverConfig: null,
  13398. peakTx: 0,
  13399. peakRx: 0,
  13400. targetDuration: 10,
  13401. lastSampleIndex: 0
  13402. };
  13403. async function loadBwTestView() {
  13404. fetchBwTestServerStatus();
  13405. loadBwTestHistory();
  13406. resizeBwTestCanvas();
  13407. checkActiveBwTest();
  13408. }
  13409. async function fetchBwTestServerStatus() {
  13410. try {
  13411. const res = await fetch(`${API_BASE}/tools/bwtest/server`);
  13412. if (!res.ok) return;
  13413. const s = await res.json();
  13414. bwtestState.serverConfig = s;
  13415. // Update indicator and badges
  13416. const indicator = document.getElementById('bwtest-server-indicator');
  13417. const badge = document.getElementById('bwtest-server-badge');
  13418. const sideBadge = document.getElementById('badge-bwtest-server');
  13419. if (s.enabled && s.running) {
  13420. if (indicator) indicator.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  13421. if (badge) {
  13422. badge.innerText = `Port ${s.port} (Active)`;
  13423. badge.className = 'text-emerald-400 font-bold';
  13424. }
  13425. if (sideBadge) {
  13426. sideBadge.innerText = s.port;
  13427. 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';
  13428. }
  13429. } else {
  13430. if (indicator) indicator.className = 'w-2 h-2 rounded-full bg-slate-600';
  13431. if (badge) {
  13432. badge.innerText = `Disabled`;
  13433. badge.className = 'text-slate-500 font-bold';
  13434. }
  13435. if (sideBadge) {
  13436. sideBadge.innerText = 'Off';
  13437. sideBadge.className = 'text-[10px] bg-slate-800 text-slate-500 border border-slate-700 px-1.5 py-0.2 rounded-full font-mono';
  13438. }
  13439. }
  13440. // Modal fields
  13441. const toggle = document.getElementById('bwtest-server-enable-toggle');
  13442. if (toggle) toggle.checked = !!s.enabled;
  13443. const portInp = document.getElementById('bwtest-server-port-input');
  13444. if (portInp) portInp.value = s.port || 2000;
  13445. const actSess = document.getElementById('bwtest-modal-active-sessions');
  13446. if (actSess) actSess.innerText = s.active_sessions || 0;
  13447. const totServ = document.getElementById('bwtest-modal-total-served');
  13448. if (totServ) totServ.innerText = s.total_sessions_served || 0;
  13449. const totBytes = document.getElementById('bwtest-modal-total-bytes');
  13450. if (totBytes) totBytes.innerText = formatBytes(s.total_bytes_processed || 0);
  13451. } catch (err) {
  13452. console.error('Failed to fetch BwTest server status:', err);
  13453. }
  13454. }
  13455. function openBwTestServerModal() {
  13456. fetchBwTestServerStatus();
  13457. document.getElementById('modal-bwtest-server')?.classList.remove('hidden');
  13458. }
  13459. function closeBwTestServerModal() {
  13460. document.getElementById('modal-bwtest-server')?.classList.add('hidden');
  13461. }
  13462. async function submitBwTestServerSettings(e) {
  13463. e.preventDefault();
  13464. const enabled = document.getElementById('bwtest-server-enable-toggle').checked;
  13465. const port = parseInt(document.getElementById('bwtest-server-port-input').value, 10) || 2000;
  13466. try {
  13467. const res = await fetch(`${API_BASE}/tools/bwtest/server`, {
  13468. method: 'POST',
  13469. headers: { 'Content-Type': 'application/json' },
  13470. body: JSON.stringify({ enabled, port, listen_addr: '0.0.0.0', allow_anonymous: true })
  13471. });
  13472. if (!res.ok) {
  13473. const err = await res.json();
  13474. throw new Error(err.error || 'Failed to update server configuration');
  13475. }
  13476. showToast('BwTest Server', `Bandwidth Test server updated (Port ${port})`, 'success');
  13477. closeBwTestServerModal();
  13478. fetchBwTestServerStatus();
  13479. } catch (err) {
  13480. showToast('Server Configuration Error', err.message, 'error');
  13481. }
  13482. }
  13483. function setBwTestTarget(target) {
  13484. const inp = document.getElementById('bwtest-input-target');
  13485. if (inp) inp.value = target;
  13486. }
  13487. function setBwTestProtocol(proto) {
  13488. const hiddenInp = document.getElementById('bwtest-input-protocol');
  13489. if (hiddenInp) hiddenInp.value = proto;
  13490. const btnUdp = document.getElementById('bwtest-proto-udp');
  13491. const btnTcp = document.getElementById('bwtest-proto-tcp');
  13492. const badge = document.getElementById('bwtest-proto-badge');
  13493. const pktField = document.getElementById('bwtest-field-pktsize');
  13494. 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';
  13495. 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';
  13496. 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';
  13497. if (proto === 'udp') {
  13498. if (btnUdp) {
  13499. btnUdp.className = activeUdpCls;
  13500. const dot = btnUdp.querySelector('span');
  13501. if (dot) dot.className = 'w-2 h-2 rounded-full bg-emerald-400';
  13502. }
  13503. if (btnTcp) {
  13504. btnTcp.className = inactiveCls;
  13505. const dot = btnTcp.querySelector('span');
  13506. if (dot) dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  13507. }
  13508. if (badge) {
  13509. badge.innerText = 'UDP Mode (RFC 3550 Jitter + Loss %)';
  13510. badge.className = 'text-[10px] font-mono text-emerald-400 bg-emerald-500/10 px-2 py-0.5 rounded border border-emerald-500/20';
  13511. }
  13512. if (pktField) pktField.classList.remove('opacity-40');
  13513. } else {
  13514. if (btnUdp) {
  13515. btnUdp.className = inactiveCls;
  13516. const dot = btnUdp.querySelector('span');
  13517. if (dot) dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  13518. }
  13519. if (btnTcp) {
  13520. btnTcp.className = activeTcpCls;
  13521. const dot = btnTcp.querySelector('span');
  13522. if (dot) dot.className = 'w-2 h-2 rounded-full bg-blue-400';
  13523. }
  13524. if (badge) {
  13525. badge.innerText = 'TCP Mode (Sliding Window Throughput)';
  13526. badge.className = 'text-[10px] font-mono text-blue-400 bg-blue-500/10 px-2 py-0.5 rounded border border-blue-500/20';
  13527. }
  13528. if (pktField) pktField.classList.add('opacity-40');
  13529. }
  13530. }
  13531. function setBwTestDirection(dir) {
  13532. const hiddenInp = document.getElementById('bwtest-input-direction');
  13533. if (hiddenInp) hiddenInp.value = dir;
  13534. const btnBoth = document.getElementById('bwtest-dir-both');
  13535. const btnTx = document.getElementById('bwtest-dir-tx');
  13536. const btnRx = document.getElementById('bwtest-dir-rx');
  13537. 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';
  13538. 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';
  13539. if (btnBoth) btnBoth.className = dir === 'both' ? activeCls : inactiveCls;
  13540. if (btnTx) btnTx.className = dir === 'tx' ? activeCls : inactiveCls;
  13541. if (btnRx) btnRx.className = dir === 'rx' ? activeCls : inactiveCls;
  13542. }
  13543. function setBwTestLimit(bps) {
  13544. const sel = document.getElementById('bwtest-input-limit');
  13545. if (sel) sel.value = String(bps);
  13546. }
  13547. async function checkActiveBwTest() {
  13548. try {
  13549. const res = await fetch(`${API_BASE}/tools/bwtest/status`);
  13550. if (!res.ok) return;
  13551. const st = await res.json();
  13552. if (st.running) {
  13553. setBwTestRunningUI(true);
  13554. if (st.current_sample) handleBwTestSample(st.current_sample);
  13555. startBwTestTelemetry();
  13556. }
  13557. } catch (err) {
  13558. console.error('Failed to check active BwTest:', err);
  13559. }
  13560. }
  13561. async function startBwTest(e) {
  13562. if (e && e.preventDefault) e.preventDefault();
  13563. const target = document.getElementById('bwtest-input-target').value.trim() || '127.0.0.1';
  13564. const port = parseInt(document.getElementById('bwtest-input-port').value, 10) || 2000;
  13565. const direction = document.getElementById('bwtest-input-direction').value || 'both';
  13566. const protocol = document.getElementById('bwtest-input-protocol').value || 'udp';
  13567. const bandwidth_limit = parseInt(document.getElementById('bwtest-input-limit').value, 10) || 0;
  13568. const packet_size = parseInt(document.getElementById('bwtest-input-pktsize').value, 10) || 1472;
  13569. const streams = parseInt(document.getElementById('bwtest-input-streams').value, 10) || 1;
  13570. const duration = parseInt(document.getElementById('bwtest-input-duration').value, 10);
  13571. bwtestState.targetDuration = duration;
  13572. bwtestState.chartPoints = [];
  13573. bwtestState.peakTx = 0;
  13574. bwtestState.peakRx = 0;
  13575. bwtestState.lastSampleIndex = 0;
  13576. // Clear UI elements
  13577. document.getElementById('bwtest-stat-tx-mbps').innerText = '0.00';
  13578. document.getElementById('bwtest-stat-tx-peak').innerText = '0.00 Mbps';
  13579. document.getElementById('bwtest-stat-tx-pkts').innerText = '0';
  13580. document.getElementById('bwtest-stat-rx-mbps').innerText = '0.00';
  13581. document.getElementById('bwtest-stat-rx-peak').innerText = '0.00 Mbps';
  13582. document.getElementById('bwtest-stat-rx-pkts').innerText = '0';
  13583. document.getElementById('bwtest-stat-loss').innerText = '0.0%';
  13584. document.getElementById('bwtest-stat-jitter').innerText = '0.00 ms';
  13585. document.getElementById('bwtest-stat-time').innerText = '0.0s';
  13586. document.getElementById('bwtest-stat-data').innerText = '0.0 MB';
  13587. document.getElementById('bwtest-stat-target-dur').innerText = duration > 0 ? `/ ${duration}s` : '/ ∞';
  13588. const tbody = document.getElementById('bwtest-samples-tbody');
  13589. if (tbody) tbody.innerHTML = '';
  13590. document.getElementById('bwtest-sample-count').innerText = '0 samples';
  13591. setBwTestRunningUI(true);
  13592. try {
  13593. const res = await fetch(`${API_BASE}/tools/bwtest/start`, {
  13594. method: 'POST',
  13595. headers: { 'Content-Type': 'application/json' },
  13596. body: JSON.stringify({
  13597. target,
  13598. port,
  13599. direction,
  13600. protocol,
  13601. bandwidth_limit,
  13602. packet_size,
  13603. streams,
  13604. duration
  13605. })
  13606. });
  13607. if (!res.ok) {
  13608. const err = await res.json();
  13609. throw new Error(err.error || 'Failed to start bandwidth test');
  13610. }
  13611. showToast('Benchmark Started', `Target: ${target}:${port} (${direction.toUpperCase()}, ${protocol.toUpperCase()})`, 'info');
  13612. startBwTestTelemetry();
  13613. } catch (err) {
  13614. setBwTestRunningUI(false);
  13615. showToast('Start Failed', err.message, 'error');
  13616. }
  13617. }
  13618. function setBwTestRunningUI(running) {
  13619. bwtestState.running = running;
  13620. const startBtn = document.getElementById('bwtest-btn-start');
  13621. const stopBtn = document.getElementById('bwtest-btn-stop');
  13622. const badge = document.getElementById('bwtest-run-status-badge');
  13623. const ph = document.getElementById('bwtest-chart-placeholder');
  13624. if (running) {
  13625. if (startBtn) {
  13626. startBtn.disabled = true;
  13627. startBtn.classList.add('opacity-50', 'cursor-not-allowed');
  13628. }
  13629. if (stopBtn) {
  13630. stopBtn.disabled = false;
  13631. stopBtn.classList.remove('opacity-40');
  13632. }
  13633. if (badge) {
  13634. badge.innerText = 'TESTING...';
  13635. 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';
  13636. }
  13637. if (ph) ph.style.display = 'none';
  13638. } else {
  13639. if (startBtn) {
  13640. startBtn.disabled = false;
  13641. startBtn.classList.remove('opacity-50', 'cursor-not-allowed');
  13642. }
  13643. if (stopBtn) {
  13644. stopBtn.disabled = true;
  13645. stopBtn.classList.add('opacity-40');
  13646. }
  13647. if (badge) {
  13648. badge.innerText = 'IDLE';
  13649. badge.className = 'px-2 py-0.5 rounded text-[10px] font-mono bg-slate-800 text-slate-400 border border-slate-700 font-semibold';
  13650. }
  13651. }
  13652. }
  13653. async function stopBwTest() {
  13654. try {
  13655. await fetch(`${API_BASE}/tools/bwtest/stop`, { method: 'POST' });
  13656. showToast('Test Stopped', 'Bandwidth test terminated by user', 'info');
  13657. } catch (err) {
  13658. console.error('Failed to stop test:', err);
  13659. }
  13660. }
  13661. function startBwTestTelemetry() {
  13662. if (bwtestState.pollTimer) clearInterval(bwtestState.pollTimer);
  13663. bwtestState.pollTimer = setInterval(async () => {
  13664. try {
  13665. const res = await fetch(`${API_BASE}/tools/bwtest/status`);
  13666. if (!res.ok) return;
  13667. const st = await res.json();
  13668. if (st.recent_samples && st.recent_samples.length > 0) {
  13669. // Process new samples
  13670. const newSamples = st.recent_samples.slice(bwtestState.lastSampleIndex);
  13671. newSamples.forEach(s => handleBwTestSample(s));
  13672. bwtestState.lastSampleIndex = st.recent_samples.length;
  13673. }
  13674. if (!st.running) {
  13675. clearInterval(bwtestState.pollTimer);
  13676. bwtestState.pollTimer = null;
  13677. setBwTestRunningUI(false);
  13678. handleBwTestFinish(st.summary, st.error);
  13679. }
  13680. } catch (err) {
  13681. console.error('BwTest polling error:', err);
  13682. }
  13683. }, 400);
  13684. }
  13685. function handleBwTestSample(s) {
  13686. if (!s) return;
  13687. const txMbps = s.tx_mbps || 0;
  13688. const rxMbps = s.rx_mbps || 0;
  13689. if (txMbps > bwtestState.peakTx) bwtestState.peakTx = txMbps;
  13690. if (rxMbps > bwtestState.peakRx) bwtestState.peakRx = rxMbps;
  13691. // KPI updates
  13692. const elTx = document.getElementById('bwtest-stat-tx-mbps');
  13693. if (elTx) elTx.innerText = txMbps.toFixed(2);
  13694. const elTxPeak = document.getElementById('bwtest-stat-tx-peak');
  13695. if (elTxPeak) elTxPeak.innerText = `${bwtestState.peakTx.toFixed(2)} Mbps`;
  13696. const elTxPkts = document.getElementById('bwtest-stat-tx-pkts');
  13697. if (elTxPkts) elTxPkts.innerText = s.tx_packets || 0;
  13698. const elRx = document.getElementById('bwtest-stat-rx-mbps');
  13699. if (elRx) elRx.innerText = rxMbps.toFixed(2);
  13700. const elRxPeak = document.getElementById('bwtest-stat-rx-peak');
  13701. if (elRxPeak) elRxPeak.innerText = `${bwtestState.peakRx.toFixed(2)} Mbps`;
  13702. const elRxPkts = document.getElementById('bwtest-stat-rx-pkts');
  13703. if (elRxPkts) elRxPkts.innerText = s.rx_packets || 0;
  13704. const elLoss = document.getElementById('bwtest-stat-loss');
  13705. if (elLoss) {
  13706. elLoss.innerText = `${(s.loss_pct || 0).toFixed(1)}%`;
  13707. elLoss.className = (s.loss_pct > 1.0) ? 'text-2xl font-bold text-rose-400' : 'text-2xl font-bold text-emerald-400';
  13708. }
  13709. const elLostPkts = document.getElementById('bwtest-stat-lost-pkts');
  13710. if (elLostPkts) elLostPkts.innerText = s.lost_packets || 0;
  13711. const elJitter = document.getElementById('bwtest-stat-jitter');
  13712. if (elJitter) elJitter.innerText = `${(s.jitter_ms || 0).toFixed(2)} ms`;
  13713. const elTime = document.getElementById('bwtest-stat-time');
  13714. if (elTime) elTime.innerText = `${(s.elapsed_sec || 0).toFixed(1)}s`;
  13715. const elData = document.getElementById('bwtest-stat-data');
  13716. if (elData) elData.innerText = formatBytes((s.tx_bytes || 0) + (s.rx_bytes || 0));
  13717. const elGraphRate = document.getElementById('bwtest-graph-rate');
  13718. if (elGraphRate) elGraphRate.innerText = `TX: ${txMbps.toFixed(1)} Mbps • RX: ${rxMbps.toFixed(1)} Mbps`;
  13719. // Append point to chart buffer
  13720. bwtestState.chartPoints.push({
  13721. elapsed: s.elapsed_sec || 0,
  13722. tx: txMbps,
  13723. rx: rxMbps
  13724. });
  13725. if (bwtestState.chartPoints.length > bwtestState.maxChartPoints) {
  13726. bwtestState.chartPoints.shift();
  13727. }
  13728. drawBwTestChart();
  13729. // Add row to breakdown table
  13730. const tbody = document.getElementById('bwtest-samples-tbody');
  13731. if (tbody) {
  13732. const tr = document.createElement('tr');
  13733. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  13734. tr.innerHTML = `
  13735. <td class="py-1.5 px-3 font-semibold text-white">${(s.elapsed_sec || 0).toFixed(1)}s</td>
  13736. <td class="py-1.5 px-3 font-bold text-cyan-400">${txMbps.toFixed(2)} Mbps</td>
  13737. <td class="py-1.5 px-3 font-bold text-purple-400">${rxMbps.toFixed(2)} Mbps</td>
  13738. <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>
  13739. <td class="py-1.5 px-3 text-slate-300">${(s.jitter_ms || 0).toFixed(2)} ms</td>
  13740. <td class="py-1.5 px-3 text-slate-400">${formatBytes((s.tx_bytes || 0) + (s.rx_bytes || 0))}</td>
  13741. `;
  13742. tbody.insertBefore(tr, tbody.firstChild);
  13743. const countEl = document.getElementById('bwtest-sample-count');
  13744. if (countEl) countEl.innerText = `${tbody.children.length} samples`;
  13745. }
  13746. }
  13747. function handleBwTestFinish(summary, error) {
  13748. const badge = document.getElementById('bwtest-run-status-badge');
  13749. if (error) {
  13750. showToast('Benchmark Error', error, 'error');
  13751. if (badge) {
  13752. badge.innerText = 'ERROR';
  13753. 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';
  13754. }
  13755. } else if (summary) {
  13756. const avgTx = summary.avg_tx_mbps.toFixed(1);
  13757. const avgRx = summary.avg_rx_mbps.toFixed(1);
  13758. showToast('Benchmark Complete', `Average TX: ${avgTx} Mbps | RX: ${avgRx} Mbps (Loss: ${summary.avg_loss_pct.toFixed(1)}%)`, 'success');
  13759. if (badge) {
  13760. badge.innerText = 'COMPLETED';
  13761. 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';
  13762. }
  13763. }
  13764. loadBwTestHistory();
  13765. fetchBwTestServerStatus();
  13766. }
  13767. function resizeBwTestCanvas() {
  13768. const canvas = document.getElementById('bwtest-chart');
  13769. if (!canvas || !canvas.parentElement) return;
  13770. const rect = canvas.parentElement.getBoundingClientRect();
  13771. const dpr = window.devicePixelRatio || 1;
  13772. canvas.width = rect.width * dpr;
  13773. canvas.height = rect.height * dpr;
  13774. const ctx = canvas.getContext('2d');
  13775. ctx.scale(dpr, dpr);
  13776. drawBwTestChart();
  13777. }
  13778. window.addEventListener('resize', () => {
  13779. if (state.activeTab === 'bwtest') resizeBwTestCanvas();
  13780. });
  13781. function drawBwTestChart() {
  13782. const canvas = document.getElementById('bwtest-chart');
  13783. if (!canvas) return;
  13784. const ctx = canvas.getContext('2d');
  13785. const dpr = window.devicePixelRatio || 1;
  13786. const width = canvas.width / dpr;
  13787. const height = canvas.height / dpr;
  13788. ctx.clearRect(0, 0, width, height);
  13789. const points = bwtestState.chartPoints;
  13790. if (!points || points.length === 0) return;
  13791. // Determine scale ceiling
  13792. let maxRate = 10;
  13793. for (const p of points) {
  13794. if (p.tx > maxRate) maxRate = p.tx;
  13795. if (p.rx > maxRate) maxRate = p.rx;
  13796. }
  13797. maxRate = Math.ceil(maxRate * 1.25); // 25% headroom
  13798. const paddingLeft = 55;
  13799. const paddingBottom = 24;
  13800. const paddingTop = 12;
  13801. const paddingRight = 16;
  13802. const chartW = width - paddingLeft - paddingRight;
  13803. const chartH = height - paddingTop - paddingBottom;
  13804. // Grid Lines and Y-Axis labels
  13805. ctx.strokeStyle = 'rgba(51, 65, 85, 0.4)';
  13806. ctx.lineWidth = 1;
  13807. ctx.fillStyle = '#94a3b8';
  13808. ctx.font = '10px monospace';
  13809. ctx.textAlign = 'right';
  13810. const gridSteps = 4;
  13811. for (let i = 0; i <= gridSteps; i++) {
  13812. const val = (maxRate / gridSteps) * i;
  13813. const y = paddingTop + chartH - (i / gridSteps) * chartH;
  13814. ctx.beginPath();
  13815. ctx.moveTo(paddingLeft, y);
  13816. ctx.lineTo(width - paddingRight, y);
  13817. ctx.stroke();
  13818. ctx.fillText(`${Math.round(val)}M`, paddingLeft - 8, y + 3);
  13819. }
  13820. // Draw TX Line (Cyan #22d3ee)
  13821. drawSeries(ctx, points, p => p.tx, maxRate, paddingLeft, paddingTop, chartW, chartH, '#22d3ee', 'rgba(34, 211, 238, 0.15)');
  13822. // Draw RX Line (Purple #a855f7)
  13823. drawSeries(ctx, points, p => p.rx, maxRate, paddingLeft, paddingTop, chartW, chartH, '#a855f7', 'rgba(168, 85, 247, 0.15)');
  13824. }
  13825. function drawSeries(ctx, points, valFn, maxVal, left, top, w, h, strokeColor, fillColor) {
  13826. if (points.length < 2) return;
  13827. const stepX = w / Math.max(points.length - 1, 1);
  13828. // Gradient area fill
  13829. const grad = ctx.createLinearGradient(0, top, 0, top + h);
  13830. grad.addColorStop(0, fillColor);
  13831. grad.addColorStop(1, 'rgba(0, 0, 0, 0)');
  13832. ctx.beginPath();
  13833. points.forEach((p, idx) => {
  13834. const x = left + idx * stepX;
  13835. const val = valFn(p);
  13836. const y = top + h - (val / maxVal) * h;
  13837. if (idx === 0) {
  13838. ctx.moveTo(x, y);
  13839. } else {
  13840. ctx.lineTo(x, y);
  13841. }
  13842. });
  13843. // Complete path for fill
  13844. ctx.lineTo(left + (points.length - 1) * stepX, top + h);
  13845. ctx.lineTo(left, top + h);
  13846. ctx.closePath();
  13847. ctx.fillStyle = grad;
  13848. ctx.fill();
  13849. // Draw line stroke
  13850. ctx.beginPath();
  13851. ctx.lineWidth = 2.5;
  13852. ctx.strokeStyle = strokeColor;
  13853. points.forEach((p, idx) => {
  13854. const x = left + idx * stepX;
  13855. const val = valFn(p);
  13856. const y = top + h - (val / maxVal) * h;
  13857. if (idx === 0) {
  13858. ctx.moveTo(x, y);
  13859. } else {
  13860. ctx.lineTo(x, y);
  13861. }
  13862. });
  13863. ctx.stroke();
  13864. // Draw end point halo
  13865. const lastP = points[points.length - 1];
  13866. const lastX = left + (points.length - 1) * stepX;
  13867. const lastY = top + h - (valFn(lastP) / maxVal) * h;
  13868. ctx.fillStyle = strokeColor;
  13869. ctx.beginPath();
  13870. ctx.arc(lastX, lastY, 4, 0, 2 * Math.PI);
  13871. ctx.fill();
  13872. }
  13873. async function loadBwTestHistory() {
  13874. try {
  13875. const res = await fetch(`${API_BASE}/tools/bwtest/history`);
  13876. if (!res.ok) return;
  13877. const list = await res.json();
  13878. renderBwTestHistory(Array.isArray(list) ? list : []);
  13879. } catch (err) {
  13880. console.error('Failed to load BwTest history:', err);
  13881. }
  13882. }
  13883. function renderBwTestHistory(list) {
  13884. const tbody = document.getElementById('bwtest-history-tbody');
  13885. if (!tbody) return;
  13886. if (list.length === 0) {
  13887. 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>`;
  13888. return;
  13889. }
  13890. tbody.innerHTML = '';
  13891. list.forEach(item => {
  13892. const s = item.summary || {};
  13893. const tr = document.createElement('tr');
  13894. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  13895. const dirBadge = item.direction === 'both'
  13896. ? `<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>`
  13897. : item.direction === 'tx'
  13898. ? `<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>`
  13899. : `<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>`;
  13900. const protoBadge = item.protocol === 'tcp'
  13901. ? `<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>`
  13902. : `<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>`;
  13903. const dateStr = item.timestamp ? new Date(item.timestamp).toLocaleString() : '-';
  13904. tr.innerHTML = `
  13905. <td class="py-2.5 px-4 font-bold text-white font-mono text-[11px]">${escapeHtml(item.id || '-')}</td>
  13906. <td class="py-2.5 px-4 text-emerald-400 font-mono font-medium">${escapeHtml(item.target || '-')}</td>
  13907. <td class="py-2.5 px-4">${protoBadge}</td>
  13908. <td class="py-2.5 px-4">${dirBadge}</td>
  13909. <td class="py-2.5 px-4 text-slate-300">${(s.duration_sec || 0).toFixed(1)}s</td>
  13910. <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>
  13911. <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>
  13912. <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>
  13913. <td class="py-2.5 px-4 text-slate-300 font-mono">${(s.avg_jitter_ms || 0).toFixed(2)} ms</td>
  13914. <td class="py-2.5 px-4 text-slate-400 text-[11px] font-sans">${escapeHtml(dateStr)}</td>
  13915. `;
  13916. tbody.appendChild(tr);
  13917. });
  13918. }
  13919. // ======================== SETTINGS & ROUTER DNS ========================
  13920. state.settingsSubTab = 'dns';
  13921. state.dnsSettings = null;
  13922. state.dnsStaticRecords = [];
  13923. state.dnsStatus = null;
  13924. function switchSettingsSubTab(sub) {
  13925. state.settingsSubTab = sub;
  13926. const btnDns = document.getElementById('btn-settings-subtab-dns');
  13927. const btnSys = document.getElementById('btn-settings-subtab-system');
  13928. const tabDns = document.getElementById('settings-subtab-dns');
  13929. const tabSys = document.getElementById('settings-subtab-system');
  13930. if (sub === 'dns') {
  13931. if (btnDns) {
  13932. 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';
  13933. }
  13934. if (btnSys) {
  13935. 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';
  13936. }
  13937. tabDns?.classList.remove('hidden');
  13938. tabSys?.classList.add('hidden');
  13939. loadDNSSettings();
  13940. } else {
  13941. if (btnSys) {
  13942. 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';
  13943. }
  13944. if (btnDns) {
  13945. 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';
  13946. }
  13947. tabSys?.classList.remove('hidden');
  13948. tabDns?.classList.add('hidden');
  13949. loadSystemSettings();
  13950. }
  13951. }
  13952. async function loadSettingsData(showLoading = false) {
  13953. if (state.settingsSubTab === 'system') {
  13954. await loadSystemSettings();
  13955. } else {
  13956. await loadDNSSettings();
  13957. }
  13958. }
  13959. async function loadDNSSettings() {
  13960. try {
  13961. const [settingsRes, staticRes, statusRes] = await Promise.all([
  13962. fetch(`${API_BASE}/dns/settings`),
  13963. fetch(`${API_BASE}/dns/static`),
  13964. fetch(`${API_BASE}/dns/status`)
  13965. ]);
  13966. if (settingsRes.ok) {
  13967. state.dnsSettings = await settingsRes.json();
  13968. populateDNSSettingsForm(state.dnsSettings);
  13969. }
  13970. if (staticRes.ok) {
  13971. state.dnsStaticRecords = await staticRes.json();
  13972. renderStaticDNSList();
  13973. }
  13974. if (statusRes.ok) {
  13975. state.dnsStatus = await statusRes.json();
  13976. updateDNSStatusView(state.dnsStatus);
  13977. }
  13978. } catch (err) {
  13979. console.error('Failed to load DNS settings:', err);
  13980. }
  13981. }
  13982. function populateDNSSettingsForm(s) {
  13983. if (!s) return;
  13984. const dnsForm = document.getElementById('form-dns-settings');
  13985. const isEditing = dnsForm && (dnsForm.contains(document.activeElement) || dnsForm.dataset.dirty === 'true');
  13986. const dynamicEl = document.getElementById('dns-dynamic-servers-list');
  13987. if (dynamicEl) {
  13988. if (Array.isArray(s.dynamic_servers) && s.dynamic_servers.length > 0) {
  13989. 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(' ');
  13990. } else {
  13991. dynamicEl.innerText = 'None';
  13992. }
  13993. }
  13994. // If user is actively typing or editing in the form, do not overwrite their inputs!
  13995. if (isEditing) return;
  13996. const serversInput = document.getElementById('dns-servers-input');
  13997. if (serversInput) serversInput.value = (s.servers || []).join(', ');
  13998. const cacheSizeInput = document.getElementById('dns-cache-size-input');
  13999. if (cacheSizeInput) cacheSizeInput.value = s.cache_size || 2048;
  14000. const domainInput = document.getElementById('dns-domain-input');
  14001. if (domainInput) domainInput.value = s.domain || '';
  14002. const allowRemoteInput = document.getElementById('dns-allow-remote-input');
  14003. if (allowRemoteInput) allowRemoteInput.checked = s.allow_remote_requests !== false;
  14004. }
  14005. function updateDNSStatusView(st) {
  14006. if (!st) return;
  14007. const preview = document.getElementById('dns-resolv-preview');
  14008. if (preview) preview.innerText = st.resolv_conf_content || '(empty)';
  14009. const pillText = document.getElementById('dns-live-status-text');
  14010. const pill = document.getElementById('dns-live-status-pill');
  14011. if (pill && pillText) {
  14012. if (st.service_running) {
  14013. 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';
  14014. pillText.innerText = 'DNS Service Active';
  14015. } else {
  14016. 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';
  14017. pillText.innerText = 'DNS Service Inactive';
  14018. }
  14019. }
  14020. }
  14021. function appendDNSPreset(preset) {
  14022. const input = document.getElementById('dns-servers-input');
  14023. if (!input) return;
  14024. const dnsForm = document.getElementById('form-dns-settings');
  14025. if (dnsForm) dnsForm.dataset.dirty = 'true';
  14026. const current = input.value.trim();
  14027. if (!current) {
  14028. input.value = preset;
  14029. } else {
  14030. const existing = current.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  14031. const toAdd = preset.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  14032. toAdd.forEach(ip => {
  14033. if (!existing.includes(ip)) existing.push(ip);
  14034. });
  14035. input.value = existing.join(', ');
  14036. }
  14037. }
  14038. async function saveDNSSettings(e) {
  14039. e.preventDefault();
  14040. const rawServers = document.getElementById('dns-servers-input')?.value || '';
  14041. const servers = rawServers.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  14042. if (servers.length === 0) {
  14043. showToast('Validation Error', 'Please enter at least one upstream DNS server IP', 'error');
  14044. return;
  14045. }
  14046. const cacheSize = parseInt(document.getElementById('dns-cache-size-input')?.value || '2048', 10);
  14047. const domain = (document.getElementById('dns-domain-input')?.value || '').trim();
  14048. const allowRemote = document.getElementById('dns-allow-remote-input')?.checked ?? true;
  14049. try {
  14050. const res = await fetch(`${API_BASE}/dns/settings`, {
  14051. method: 'POST',
  14052. headers: { 'Content-Type': 'application/json' },
  14053. body: JSON.stringify({
  14054. servers: servers,
  14055. cache_size: cacheSize,
  14056. domain: domain,
  14057. allow_remote_requests: allowRemote
  14058. })
  14059. });
  14060. const data = await res.json();
  14061. if (res.ok) {
  14062. const dnsForm = document.getElementById('form-dns-settings');
  14063. if (dnsForm) dnsForm.dataset.dirty = 'false';
  14064. showToast('DNS Applied', 'Router DNS forwarders and resolver settings updated successfully', 'success');
  14065. loadDNSSettings();
  14066. } else {
  14067. showToast('Error', data.error || data.message || 'Failed to save DNS settings', 'error');
  14068. }
  14069. } catch (err) {
  14070. showToast('Error', err.message, 'error');
  14071. }
  14072. }
  14073. async function flushDNSCache() {
  14074. try {
  14075. const res = await fetch(`${API_BASE}/dns/flush`, { method: 'POST' });
  14076. if (res.ok) {
  14077. showToast('Cache Flushed', 'Router DNS cache cleared and static hosts reloaded', 'success');
  14078. loadDNSSettings();
  14079. } else {
  14080. const err = await res.json();
  14081. showToast('Error', err.error || 'Failed to flush cache', 'error');
  14082. }
  14083. } catch (err) {
  14084. showToast('Error', err.message, 'error');
  14085. }
  14086. }
  14087. function renderStaticDNSList() {
  14088. const tbody = document.getElementById('dns-static-tbody');
  14089. const empty = document.getElementById('dns-static-empty');
  14090. const badge = document.getElementById('dns-static-count-badge');
  14091. if (!tbody) return;
  14092. tbody.innerHTML = '';
  14093. const records = state.dnsStaticRecords || [];
  14094. if (badge) badge.innerText = `${records.length} Records`;
  14095. if (records.length === 0) {
  14096. empty?.classList.remove('hidden');
  14097. return;
  14098. }
  14099. empty?.classList.add('hidden');
  14100. records.forEach(rec => {
  14101. const tr = document.createElement('tr');
  14102. tr.className = `hover:bg-slate-800/40 transition text-xs ${rec.disabled ? 'opacity-50' : ''}`;
  14103. tr.innerHTML = `
  14104. <td class="py-2.5 px-4 font-bold text-white">${escapeHtml(rec.name)}</td>
  14105. <td class="py-2.5 px-4">
  14106. <span class="px-2 py-0.5 rounded text-[10px] font-bold ${
  14107. rec.type === 'CNAME' ? 'bg-purple-950 text-purple-300 border border-purple-800' :
  14108. (rec.type === 'AAAA' ? 'bg-blue-950 text-blue-300 border border-blue-800' : 'bg-cyan-950 text-cyan-300 border border-cyan-800')
  14109. }">
  14110. ${rec.type || 'A'}
  14111. </span>
  14112. </td>
  14113. <td class="py-2.5 px-4 text-emerald-400 font-mono">${escapeHtml(rec.address)}</td>
  14114. <td class="py-2.5 px-4 text-slate-400 font-mono">${rec.ttl || 3600}s</td>
  14115. <td class="py-2.5 px-4 text-slate-400 italic truncate max-w-[140px]">${escapeHtml(rec.comment || '-')}</td>
  14116. <td class="py-2.5 px-4">
  14117. <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'}">
  14118. ${rec.disabled ? 'Disabled' : 'Active'}
  14119. </span>
  14120. </td>
  14121. <td class="py-2.5 px-4 text-right space-x-2 font-sans whitespace-nowrap">
  14122. <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>
  14123. <button onclick="openStaticDNSModal('${rec.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold">Edit</button>
  14124. <button onclick="deleteStaticDNS('${rec.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  14125. </td>
  14126. `;
  14127. tbody.appendChild(tr);
  14128. });
  14129. }
  14130. function openStaticDNSModal(id = null) {
  14131. const modal = document.getElementById('modal-static-dns');
  14132. const title = document.getElementById('modal-static-dns-title');
  14133. const form = document.getElementById('form-static-dns');
  14134. if (!modal || !form) return;
  14135. form.reset();
  14136. document.getElementById('modal-static-dns-id').value = '';
  14137. if (id) {
  14138. const rec = (state.dnsStaticRecords || []).find(r => r.id === id);
  14139. if (rec) {
  14140. if (title) title.innerText = 'Edit Static DNS Record';
  14141. document.getElementById('modal-static-dns-id').value = rec.id;
  14142. document.getElementById('modal-static-dns-name').value = rec.name;
  14143. document.getElementById('modal-static-dns-type').value = rec.type || 'A';
  14144. document.getElementById('modal-static-dns-addr').value = rec.address;
  14145. document.getElementById('modal-static-dns-ttl').value = rec.ttl || 3600;
  14146. document.getElementById('modal-static-dns-comment').value = rec.comment || '';
  14147. document.getElementById('modal-static-dns-disabled').checked = !!rec.disabled;
  14148. }
  14149. } else {
  14150. if (title) title.innerText = 'Add Static DNS Record';
  14151. }
  14152. modal.classList.remove('hidden');
  14153. }
  14154. function closeStaticDNSModal() {
  14155. document.getElementById('modal-static-dns')?.classList.add('hidden');
  14156. }
  14157. async function submitSaveStaticDNS(e) {
  14158. e.preventDefault();
  14159. const id = document.getElementById('modal-static-dns-id')?.value || '';
  14160. const name = (document.getElementById('modal-static-dns-name')?.value || '').trim();
  14161. const type = document.getElementById('modal-static-dns-type')?.value || 'A';
  14162. const address = (document.getElementById('modal-static-dns-addr')?.value || '').trim();
  14163. const ttl = parseInt(document.getElementById('modal-static-dns-ttl')?.value || '3600', 10);
  14164. const comment = (document.getElementById('modal-static-dns-comment')?.value || '').trim();
  14165. const disabled = document.getElementById('modal-static-dns-disabled')?.checked ?? false;
  14166. if (!name || !address) {
  14167. showToast('Validation Error', 'Name and Target Address are required', 'error');
  14168. return;
  14169. }
  14170. try {
  14171. const res = await fetch(`${API_BASE}/dns/static`, {
  14172. method: 'POST',
  14173. headers: { 'Content-Type': 'application/json' },
  14174. body: JSON.stringify({ id, name, type, address, ttl, comment, disabled })
  14175. });
  14176. const data = await res.json();
  14177. if (res.ok) {
  14178. showToast('Static DNS Saved', `Saved record ${name} -> ${address}`, 'success');
  14179. closeStaticDNSModal();
  14180. loadDNSSettings();
  14181. } else {
  14182. showToast('Error', data.error || data.message || 'Failed to save record', 'error');
  14183. }
  14184. } catch (err) {
  14185. showToast('Error', err.message, 'error');
  14186. }
  14187. }
  14188. async function deleteStaticDNS(id) {
  14189. if (!confirm('Are you sure you want to delete this static DNS entry?')) return;
  14190. try {
  14191. const res = await fetch(`${API_BASE}/dns/static/${encodeURIComponent(id)}`, { method: 'DELETE' });
  14192. if (res.ok) {
  14193. showToast('Deleted', 'Static DNS record deleted', 'success');
  14194. loadDNSSettings();
  14195. }
  14196. } catch (err) {
  14197. showToast('Error', err.message, 'error');
  14198. }
  14199. }
  14200. async function toggleStaticDNS(id, disabled) {
  14201. try {
  14202. const res = await fetch(`${API_BASE}/dns/static/${encodeURIComponent(id)}/state`, {
  14203. method: 'POST',
  14204. headers: { 'Content-Type': 'application/json' },
  14205. body: JSON.stringify({ disabled })
  14206. });
  14207. if (res.ok) {
  14208. showToast('Updated', `Record ${disabled ? 'disabled' : 'enabled'}`, 'success');
  14209. loadDNSSettings();
  14210. }
  14211. } catch (err) {
  14212. showToast('Error', err.message, 'error');
  14213. }
  14214. }
  14215. async function loadSystemSettings() {
  14216. try {
  14217. const sysForm = document.getElementById('form-system-settings');
  14218. const isEditing = sysForm && (sysForm.contains(document.activeElement) || sysForm.dataset.dirty === 'true');
  14219. const res = await fetch(`${API_BASE}/system/settings`);
  14220. if (res.ok) {
  14221. const data = await res.json();
  14222. if (!isEditing) {
  14223. const hostInput = document.getElementById('system-hostname-input');
  14224. if (hostInput) hostInput.value = data.hostname || '';
  14225. const tzInput = document.getElementById('system-timezone-input');
  14226. if (tzInput && data.timezone) tzInput.value = data.timezone;
  14227. }
  14228. }
  14229. } catch (err) {
  14230. console.error('Failed to load system settings:', err);
  14231. }
  14232. }
  14233. async function saveSystemSettings(e) {
  14234. e.preventDefault();
  14235. const hostname = (document.getElementById('system-hostname-input')?.value || '').trim();
  14236. const timezone = document.getElementById('system-timezone-input')?.value || 'UTC';
  14237. try {
  14238. const res = await fetch(`${API_BASE}/system/settings`, {
  14239. method: 'POST',
  14240. headers: { 'Content-Type': 'application/json' },
  14241. body: JSON.stringify({ hostname, timezone })
  14242. });
  14243. const data = await res.json();
  14244. if (res.ok) {
  14245. const sysForm = document.getElementById('form-system-settings');
  14246. if (sysForm) sysForm.dataset.dirty = 'false';
  14247. showToast('System Updated', 'Hostname and timezone saved successfully', 'success');
  14248. const sideH = document.getElementById('side-hostname');
  14249. if (sideH) sideH.innerText = data.hostname;
  14250. } else {
  14251. showToast('Error', data.error || 'Failed to save system settings', 'error');
  14252. }
  14253. } catch (err) {
  14254. showToast('Error', err.message, 'error');
  14255. }
  14256. }
  14257. // =============================================================================
  14258. // AUTHENTICATION & USER MANAGER
  14259. // =============================================================================
  14260. async function checkAuthStatus() {
  14261. try {
  14262. const res = await originalFetch(`${API_BASE}/auth/me`, {
  14263. headers: {
  14264. 'Authorization': `Bearer ${localStorage.getItem('debtik_token') || ''}`
  14265. }
  14266. });
  14267. if (res.ok) {
  14268. const user = await res.json();
  14269. state.currentUser = user;
  14270. updateUserProfileHeader(user);
  14271. hideLoginScreen();
  14272. state.isPolling = true;
  14273. fetchData();
  14274. initLiveTrafficStream();
  14275. return true;
  14276. } else {
  14277. showLoginScreen(false);
  14278. return false;
  14279. }
  14280. } catch (err) {
  14281. showLoginScreen(false);
  14282. return false;
  14283. }
  14284. }
  14285. function showLoginScreen(isExpired = false) {
  14286. const el = document.getElementById('login-screen');
  14287. if (el) el.classList.remove('hidden');
  14288. const errEl = document.getElementById('login-error');
  14289. const errTxt = document.getElementById('login-error-text');
  14290. if (isExpired && errEl && errTxt) {
  14291. errTxt.innerText = 'Session expired. Please sign in again.';
  14292. errEl.classList.remove('hidden');
  14293. } else if (errEl) {
  14294. errEl.classList.add('hidden');
  14295. }
  14296. const pwInput = document.getElementById('login-password');
  14297. if (pwInput) pwInput.value = '';
  14298. const userInput = document.getElementById('login-username');
  14299. if (userInput && !userInput.value) userInput.focus();
  14300. else if (pwInput) pwInput.focus();
  14301. }
  14302. function hideLoginScreen() {
  14303. const el = document.getElementById('login-screen');
  14304. if (el) el.classList.add('hidden');
  14305. const errEl = document.getElementById('login-error');
  14306. if (errEl) errEl.classList.add('hidden');
  14307. }
  14308. async function handleLoginSubmit(event) {
  14309. event.preventDefault();
  14310. const username = (document.getElementById('login-username')?.value || '').trim();
  14311. const password = document.getElementById('login-password')?.value || '';
  14312. const errEl = document.getElementById('login-error');
  14313. const errTxt = document.getElementById('login-error-text');
  14314. const btn = document.getElementById('login-submit-btn');
  14315. const btnText = document.getElementById('login-btn-text');
  14316. const spinner = document.getElementById('login-btn-spinner');
  14317. if (!username || !password) {
  14318. if (errTxt) errTxt.innerText = 'Username and password are required.';
  14319. if (errEl) errEl.classList.remove('hidden');
  14320. return;
  14321. }
  14322. if (errEl) errEl.classList.add('hidden');
  14323. if (btn) btn.disabled = true;
  14324. if (btnText) btnText.innerText = 'Authenticating...';
  14325. if (spinner) spinner.classList.remove('hidden');
  14326. try {
  14327. const res = await originalFetch(`${API_BASE}/auth/login`, {
  14328. method: 'POST',
  14329. headers: { 'Content-Type': 'application/json' },
  14330. body: JSON.stringify({ username, password })
  14331. });
  14332. const data = await res.json();
  14333. if (res.ok && data.success) {
  14334. localStorage.setItem('debtik_token', data.token);
  14335. state.currentUser = data.user;
  14336. updateUserProfileHeader(data.user);
  14337. hideLoginScreen();
  14338. state.isPolling = true;
  14339. showToast('Authenticated', `Signed in as ${data.user.username}`, 'success');
  14340. const hash = window.location.hash.replace('#', '') || 'dashboard';
  14341. navigate(hash);
  14342. fetchData();
  14343. initLiveTrafficStream();
  14344. // Ensure background telemetry polling is active
  14345. if (!window._telemetryInterval) {
  14346. window._telemetryInterval = setInterval(() => {
  14347. if (state.isPolling && state.currentUser) {
  14348. fetchData(false);
  14349. }
  14350. }, 5000);
  14351. }
  14352. } else {
  14353. if (errTxt) errTxt.innerText = data.message || 'Invalid username or password';
  14354. if (errEl) errEl.classList.remove('hidden');
  14355. }
  14356. } catch (err) {
  14357. if (errTxt) errTxt.innerText = err.message || 'Failed to connect to router';
  14358. if (errEl) errEl.classList.remove('hidden');
  14359. } finally {
  14360. if (btn) btn.disabled = false;
  14361. if (btnText) btnText.innerText = 'Sign In to Controller';
  14362. if (spinner) spinner.classList.add('hidden');
  14363. }
  14364. }
  14365. async function handleLogoutClick() {
  14366. try {
  14367. await originalFetch(`${API_BASE}/auth/logout`, {
  14368. method: 'POST',
  14369. headers: {
  14370. 'Authorization': `Bearer ${localStorage.getItem('debtik_token') || ''}`
  14371. }
  14372. });
  14373. } catch (e) {}
  14374. localStorage.removeItem('debtik_token');
  14375. state.currentUser = null;
  14376. state.isPolling = false;
  14377. if (window._telemetryInterval) {
  14378. clearInterval(window._telemetryInterval);
  14379. window._telemetryInterval = null;
  14380. }
  14381. if (trafficEventSource) {
  14382. trafficEventSource.close();
  14383. trafficEventSource = null;
  14384. }
  14385. if (trafficPollFallback) {
  14386. clearInterval(trafficPollFallback);
  14387. trafficPollFallback = null;
  14388. }
  14389. showLoginScreen(false);
  14390. showToast('Signed Out', 'You have been signed out successfully', 'info');
  14391. }
  14392. function togglePasswordVisibility(id) {
  14393. const input = document.getElementById(id);
  14394. if (!input) return;
  14395. input.type = input.type === 'password' ? 'text' : 'password';
  14396. }
  14397. function toggleUserMenu() {
  14398. const menu = document.getElementById('user-menu-dropdown');
  14399. if (menu) menu.classList.toggle('hidden');
  14400. }
  14401. function closeUserMenu() {
  14402. const menu = document.getElementById('user-menu-dropdown');
  14403. if (menu) menu.classList.add('hidden');
  14404. }
  14405. // Close user menu on outside click
  14406. document.addEventListener('click', (e) => {
  14407. const menu = document.getElementById('user-menu-dropdown');
  14408. if (!menu || menu.classList.contains('hidden')) return;
  14409. if (!e.target.closest('#user-menu-dropdown') && !e.target.closest('button[onclick*="toggleUserMenu"]')) {
  14410. menu.classList.add('hidden');
  14411. }
  14412. });
  14413. function updateUserProfileHeader(user) {
  14414. if (!user) return;
  14415. const navName = document.getElementById('nav-user-name');
  14416. if (navName) navName.innerText = user.username;
  14417. const dropName = document.getElementById('dropdown-user-name');
  14418. if (dropName) dropName.innerText = user.username;
  14419. const navRole = document.getElementById('nav-user-role');
  14420. if (navRole) navRole.innerText = (user.role || 'read').toUpperCase();
  14421. const navAvatar = document.getElementById('nav-user-avatar');
  14422. if (navAvatar) {
  14423. const initials = (user.username || 'AD').slice(0, 2).toUpperCase();
  14424. navAvatar.innerText = initials;
  14425. }
  14426. const statCurUser = document.getElementById('stat-current-user');
  14427. if (statCurUser) statCurUser.innerText = user.username;
  14428. const statCurRole = document.getElementById('stat-current-role');
  14429. if (statCurRole) statCurRole.innerText = (user.role || 'read').toUpperCase();
  14430. // Role permissions UI visibility: hide user management for non-admins
  14431. const isFullAdmin = user.role === 'full';
  14432. const navUsers = document.getElementById('nav-users');
  14433. if (navUsers) {
  14434. if (isFullAdmin) navUsers.classList.remove('hidden');
  14435. else navUsers.classList.add('hidden');
  14436. }
  14437. const dropdownUsers = document.getElementById('dropdown-item-users');
  14438. if (dropdownUsers) {
  14439. if (isFullAdmin) dropdownUsers.classList.remove('hidden');
  14440. else dropdownUsers.classList.add('hidden');
  14441. }
  14442. }
  14443. // ================= User Management CRUD =================
  14444. async function loadUsers(isManual = false) {
  14445. try {
  14446. const res = await fetch(`${API_BASE}/users`);
  14447. if (res.status === 403) {
  14448. const tbody = document.getElementById('users-table-tbody');
  14449. if (tbody) {
  14450. tbody.innerHTML = `
  14451. <tr>
  14452. <td colspan="6" class="p-6 text-center text-amber-400 font-sans">
  14453. <div class="inline-flex items-center gap-2">
  14454. <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>
  14455. <span>Viewing and managing users requires Super Administrator (full) permissions.</span>
  14456. </div>
  14457. </td>
  14458. </tr>
  14459. `;
  14460. }
  14461. return;
  14462. }
  14463. if (res.ok) {
  14464. state.users = await res.json();
  14465. renderUsersTable();
  14466. const totalUsers = document.getElementById('stat-total-users');
  14467. if (totalUsers) totalUsers.innerText = state.users.length;
  14468. const adminCount = state.users.filter(u => u.role === 'full' && !u.disabled).length;
  14469. const adminUsers = document.getElementById('stat-admin-users');
  14470. if (adminUsers) adminUsers.innerText = adminCount;
  14471. const badgeCount = document.getElementById('badge-users-count');
  14472. if (badgeCount) badgeCount.innerText = state.users.length;
  14473. if (isManual) showToast('Refreshed', 'User list updated', 'info');
  14474. }
  14475. } catch (err) {
  14476. console.error('Failed to load users:', err);
  14477. }
  14478. }
  14479. function renderUsersTable() {
  14480. const tbody = document.getElementById('users-table-tbody');
  14481. const emptyState = document.getElementById('users-empty-state');
  14482. if (!tbody) return;
  14483. tbody.innerHTML = '';
  14484. const query = (document.getElementById('users-search-input')?.value || '').trim().toLowerCase();
  14485. const filtered = (state.users || []).filter(u => {
  14486. if (!query) return true;
  14487. return u.username.toLowerCase().includes(query) ||
  14488. (u.role || '').toLowerCase().includes(query) ||
  14489. (u.comment || '').toLowerCase().includes(query);
  14490. });
  14491. if (filtered.length === 0) {
  14492. if (emptyState) emptyState.classList.remove('hidden');
  14493. return;
  14494. }
  14495. if (emptyState) emptyState.classList.add('hidden');
  14496. const currentAuthUser = state.currentUser?.username || '';
  14497. filtered.forEach(u => {
  14498. const isSelf = u.username === currentAuthUser;
  14499. const isFull = u.role === 'full';
  14500. const isWrite = u.role === 'write';
  14501. 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>`;
  14502. if (isFull) {
  14503. 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>`;
  14504. } else if (isWrite) {
  14505. 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>`;
  14506. }
  14507. const statusBadge = u.disabled
  14508. ? `<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>`
  14509. : `<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>`;
  14510. let lastLoginText = 'Never';
  14511. if (u.last_login_at && !u.last_login_at.startsWith('0001-01-01')) {
  14512. const dt = new Date(u.last_login_at);
  14513. lastLoginText = dt.toLocaleString();
  14514. }
  14515. const initials = u.username.slice(0, 2).toUpperCase();
  14516. const tr = document.createElement('tr');
  14517. tr.className = 'hover:bg-slate-800/40 transition group';
  14518. tr.innerHTML = `
  14519. <td class="py-3 px-4">
  14520. <div class="flex items-center gap-3">
  14521. <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">
  14522. ${initials}
  14523. </div>
  14524. <div>
  14525. <div class="font-bold text-white text-xs flex items-center gap-2">
  14526. <span>${escapeHtml(u.username)}</span>
  14527. ${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>' : ''}
  14528. </div>
  14529. <div class="text-[10px] text-slate-500 font-sans">Created: ${u.created_at ? new Date(u.created_at).toLocaleDateString() : '-'}</div>
  14530. </div>
  14531. </div>
  14532. </td>
  14533. <td class="py-3 px-4 font-sans">
  14534. ${roleBadge}
  14535. </td>
  14536. <td class="py-3 px-4 font-sans">
  14537. ${statusBadge}
  14538. </td>
  14539. <td class="py-3 px-4 text-slate-300 font-sans text-xs">
  14540. ${escapeHtml(u.comment) || '<span class="text-slate-600">-</span>'}
  14541. </td>
  14542. <td class="py-3 px-4 text-slate-400 text-xs">
  14543. ${lastLoginText}
  14544. </td>
  14545. <td class="py-3 px-4 text-right space-x-1.5 font-sans">
  14546. <button onclick="openAdminResetPasswordModal('${escapeHtml(u.username)}')"
  14547. class="p-1.5 rounded-lg text-slate-400 hover:text-amber-400 hover:bg-slate-800 transition" title="Reset User Password">
  14548. <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="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>
  14549. </button>
  14550. <button onclick="openEditUserModal('${escapeHtml(u.username)}')"
  14551. class="p-1.5 rounded-lg text-slate-400 hover:text-cyan-400 hover:bg-slate-800 transition" title="Edit User">
  14552. <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>
  14553. </button>
  14554. ${!isSelf ? `
  14555. <button onclick="deleteUser('${escapeHtml(u.username)}')"
  14556. class="p-1.5 rounded-lg text-slate-400 hover:text-rose-400 hover:bg-slate-800 transition" title="Delete User">
  14557. <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>
  14558. </button>
  14559. ` : ''}
  14560. </td>
  14561. `;
  14562. tbody.appendChild(tr);
  14563. });
  14564. }
  14565. function openAddUserModal() {
  14566. document.getElementById('user-add-username').value = '';
  14567. document.getElementById('user-add-password').value = '';
  14568. document.getElementById('user-add-confirm').value = '';
  14569. document.getElementById('user-add-role').value = 'full';
  14570. document.getElementById('user-add-comment').value = '';
  14571. document.getElementById('modal-add-user')?.classList.remove('hidden');
  14572. document.getElementById('user-add-username')?.focus();
  14573. }
  14574. function closeAddUserModal() {
  14575. document.getElementById('modal-add-user')?.classList.add('hidden');
  14576. }
  14577. async function submitAddUser(event) {
  14578. event.preventDefault();
  14579. const username = (document.getElementById('user-add-username')?.value || '').trim();
  14580. const password = document.getElementById('user-add-password')?.value || '';
  14581. const confirm = document.getElementById('user-add-confirm')?.value || '';
  14582. const role = document.getElementById('user-add-role')?.value || 'full';
  14583. const comment = (document.getElementById('user-add-comment')?.value || '').trim();
  14584. if (password !== confirm) {
  14585. showToast('Validation Error', 'Passwords do not match', 'warning');
  14586. return;
  14587. }
  14588. if (password.length < 4) {
  14589. showToast('Validation Error', 'Password must be at least 4 characters', 'warning');
  14590. return;
  14591. }
  14592. try {
  14593. const res = await fetch(`${API_BASE}/users`, {
  14594. method: 'POST',
  14595. headers: { 'Content-Type': 'application/json' },
  14596. body: JSON.stringify({ username, password, role, comment })
  14597. });
  14598. const data = await res.json();
  14599. if (res.ok) {
  14600. showToast('User Created', `Created user ${username} with ${role.toUpperCase()} permissions`, 'success');
  14601. closeAddUserModal();
  14602. loadUsers(false);
  14603. } else {
  14604. showToast('Error', data.message || 'Failed to create user', 'error');
  14605. }
  14606. } catch (err) {
  14607. showToast('Error', err.message, 'error');
  14608. }
  14609. }
  14610. function openEditUserModal(username) {
  14611. const user = (state.users || []).find(u => u.username === username);
  14612. if (!user) return;
  14613. document.getElementById('user-edit-username').value = user.username;
  14614. document.getElementById('user-edit-username-title').innerText = `@${user.username}`;
  14615. document.getElementById('user-edit-role').value = user.role || 'read';
  14616. document.getElementById('user-edit-comment').value = user.comment || '';
  14617. document.getElementById('user-edit-disabled').checked = !!user.disabled;
  14618. document.getElementById('modal-edit-user')?.classList.remove('hidden');
  14619. }
  14620. function closeEditUserModal() {
  14621. document.getElementById('modal-edit-user')?.classList.add('hidden');
  14622. }
  14623. async function submitEditUser(event) {
  14624. event.preventDefault();
  14625. const username = document.getElementById('user-edit-username')?.value;
  14626. const role = document.getElementById('user-edit-role')?.value || 'read';
  14627. const comment = (document.getElementById('user-edit-comment')?.value || '').trim();
  14628. const disabled = document.getElementById('user-edit-disabled')?.checked || false;
  14629. try {
  14630. const res = await fetch(`${API_BASE}/users/${encodeURIComponent(username)}`, {
  14631. method: 'PUT',
  14632. headers: { 'Content-Type': 'application/json' },
  14633. body: JSON.stringify({ role, comment, disabled })
  14634. });
  14635. const data = await res.json();
  14636. if (res.ok) {
  14637. showToast('User Updated', `Updated settings for ${username}`, 'success');
  14638. closeEditUserModal();
  14639. loadUsers(false);
  14640. // If updated own role/disabled status, refresh self profile
  14641. if (username === state.currentUser?.username) {
  14642. checkAuthStatus();
  14643. }
  14644. } else {
  14645. showToast('Error', data.message || 'Failed to update user', 'error');
  14646. }
  14647. } catch (err) {
  14648. showToast('Error', err.message, 'error');
  14649. }
  14650. }
  14651. function openAdminResetPasswordModal(username) {
  14652. document.getElementById('admin-reset-username').value = username;
  14653. document.getElementById('admin-reset-username-title').innerText = `@${username}`;
  14654. document.getElementById('admin-reset-new-pw').value = '';
  14655. document.getElementById('admin-reset-confirm-pw').value = '';
  14656. document.getElementById('modal-admin-reset-pw')?.classList.remove('hidden');
  14657. document.getElementById('admin-reset-new-pw')?.focus();
  14658. }
  14659. function closeAdminResetPasswordModal() {
  14660. document.getElementById('modal-admin-reset-pw')?.classList.add('hidden');
  14661. }
  14662. async function submitAdminResetPassword(event) {
  14663. event.preventDefault();
  14664. const username = document.getElementById('admin-reset-username')?.value;
  14665. const newPassword = document.getElementById('admin-reset-new-pw')?.value || '';
  14666. const confirm = document.getElementById('admin-reset-confirm-pw')?.value || '';
  14667. if (newPassword !== confirm) {
  14668. showToast('Validation Error', 'Passwords do not match', 'warning');
  14669. return;
  14670. }
  14671. if (newPassword.length < 4) {
  14672. showToast('Validation Error', 'Password must be at least 4 characters', 'warning');
  14673. return;
  14674. }
  14675. try {
  14676. const res = await fetch(`${API_BASE}/users/${encodeURIComponent(username)}/password`, {
  14677. method: 'POST',
  14678. headers: { 'Content-Type': 'application/json' },
  14679. body: JSON.stringify({ new_password: newPassword })
  14680. });
  14681. const data = await res.json();
  14682. if (res.ok) {
  14683. showToast('Password Reset', `Password for user ${username} updated successfully`, 'success');
  14684. closeAdminResetPasswordModal();
  14685. } else {
  14686. showToast('Error', data.message || 'Failed to reset password', 'error');
  14687. }
  14688. } catch (err) {
  14689. showToast('Error', err.message, 'error');
  14690. }
  14691. }
  14692. async function deleteUser(username) {
  14693. if (username === state.currentUser?.username) {
  14694. showToast('Action Forbidden', 'You cannot delete your own account', 'warning');
  14695. return;
  14696. }
  14697. if (!confirm(`Are you sure you want to completely remove user "${username}"?`)) {
  14698. return;
  14699. }
  14700. try {
  14701. const res = await fetch(`${API_BASE}/users/${encodeURIComponent(username)}`, {
  14702. method: 'DELETE'
  14703. });
  14704. const data = await res.json();
  14705. if (res.ok) {
  14706. showToast('User Deleted', `User ${username} has been removed`, 'success');
  14707. loadUsers(false);
  14708. } else {
  14709. showToast('Error', data.message || 'Failed to delete user', 'error');
  14710. }
  14711. } catch (err) {
  14712. showToast('Error', err.message, 'error');
  14713. }
  14714. }
  14715. function openSelfPasswordModal() {
  14716. document.getElementById('self-current-password').value = '';
  14717. document.getElementById('self-new-password').value = '';
  14718. document.getElementById('self-confirm-password').value = '';
  14719. document.getElementById('modal-self-password')?.classList.remove('hidden');
  14720. document.getElementById('self-current-password')?.focus();
  14721. }
  14722. function closeSelfPasswordModal() {
  14723. document.getElementById('modal-self-password')?.classList.add('hidden');
  14724. }
  14725. async function submitSelfPassword(event) {
  14726. event.preventDefault();
  14727. const oldPassword = document.getElementById('self-current-password')?.value || '';
  14728. const newPassword = document.getElementById('self-new-password')?.value || '';
  14729. const confirm = document.getElementById('self-confirm-password')?.value || '';
  14730. if (newPassword !== confirm) {
  14731. showToast('Validation Error', 'New passwords do not match', 'warning');
  14732. return;
  14733. }
  14734. if (newPassword.length < 4) {
  14735. showToast('Validation Error', 'Password must be at least 4 characters', 'warning');
  14736. return;
  14737. }
  14738. try {
  14739. const res = await fetch(`${API_BASE}/auth/change-password`, {
  14740. method: 'POST',
  14741. headers: { 'Content-Type': 'application/json' },
  14742. body: JSON.stringify({ old_password: oldPassword, new_password: newPassword })
  14743. });
  14744. const data = await res.json();
  14745. if (res.ok) {
  14746. showToast('Password Changed', 'Your password has been changed successfully', 'success');
  14747. closeSelfPasswordModal();
  14748. } else {
  14749. showToast('Error', data.message || 'Failed to change password', 'error');
  14750. }
  14751. } catch (err) {
  14752. showToast('Error', err.message, 'error');
  14753. }
  14754. }
  14755. // ==================== MANAGEMENT SERVICES (/ip service) ====================
  14756. state.services = [];
  14757. async function loadServices(manual = false) {
  14758. try {
  14759. const res = await fetch(`${API_BASE}/system/services`);
  14760. if (!res.ok) throw new Error('Failed to load services');
  14761. const data = await res.json();
  14762. state.services = data || [];
  14763. renderServicesTable();
  14764. if (manual) showToast('Services Updated', 'Service status synchronized', 'success');
  14765. } catch (err) {
  14766. if (manual) showToast('Error', err.message, 'error');
  14767. }
  14768. }
  14769. function renderServicesTable() {
  14770. const tbody = document.getElementById('services-table-body');
  14771. if (!tbody) return;
  14772. if (!state.services || state.services.length === 0) {
  14773. tbody.innerHTML = '<tr><td colspan="5" class="py-6 text-center text-slate-500 text-xs">No services configured.</td></tr>';
  14774. return;
  14775. }
  14776. tbody.innerHTML = state.services.map(s => {
  14777. const isOff = s.disabled;
  14778. const statusBadge = isOff
  14779. ? '<span class="px-2 py-0.5 rounded text-[10px] bg-rose-500/20 text-rose-300 border border-rose-500/30 font-bold uppercase">Disabled</span>'
  14780. : '<span class="px-2 py-0.5 rounded text-[10px] bg-emerald-500/20 text-emerald-300 border border-emerald-500/30 font-bold uppercase">Active</span>';
  14781. const toggleBtn = isOff
  14782. ? `<button onclick="toggleServiceState('${s.name}', false)" class="px-2.5 py-1 rounded-lg bg-emerald-500/20 text-emerald-300 hover:bg-emerald-500/30 border border-emerald-500/40 text-[11px] font-bold transition">Enable</button>`
  14783. : `<button onclick="toggleServiceState('${s.name}', true)" class="px-2.5 py-1 rounded-lg bg-rose-500/20 text-rose-300 hover:bg-rose-500/30 border border-rose-500/40 text-[11px] font-bold transition">Disable</button>`;
  14784. return `
  14785. <tr class="hover:bg-slate-800/40 transition">
  14786. <td class="py-3 px-4 font-bold text-white uppercase">${s.name}</td>
  14787. <td class="py-3 px-4">
  14788. <div class="flex items-center gap-2">
  14789. <span class="text-cyan-400 font-mono font-bold">${s.port}</span>
  14790. <button onclick="openEditServiceModal('${s.name}', ${s.port}, ${s.disabled})" title="Edit Port" class="text-slate-500 hover:text-cyan-400 p-1 rounded hover:bg-slate-800/80 transition">
  14791. <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>
  14792. </button>
  14793. </div>
  14794. </td>
  14795. <td class="py-3 px-4">${statusBadge}</td>
  14796. <td class="py-3 px-4 text-slate-400 text-xs font-sans">${s.comment || '-'}</td>
  14797. <td class="py-3 px-4 text-right">
  14798. <div class="flex items-center justify-end gap-2">
  14799. <button onclick="openEditServiceModal('${s.name}', ${s.port}, ${s.disabled})" class="px-2.5 py-1 rounded-lg bg-slate-800 hover:bg-slate-700 text-slate-300 hover:text-white border border-slate-700 text-[11px] font-medium transition inline-flex items-center gap-1">
  14800. <svg class="w-3.5 h-3.5 text-slate-400" 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>
  14801. <span>Edit Port</span>
  14802. </button>
  14803. ${toggleBtn}
  14804. </div>
  14805. </td>
  14806. </tr>
  14807. `;
  14808. }).join('');
  14809. }
  14810. function openEditServiceModal(serviceName, currentPort, isDisabled) {
  14811. document.getElementById('modal-service-name').value = serviceName;
  14812. document.getElementById('modal-service-disabled').value = String(isDisabled);
  14813. document.getElementById('modal-service-display-name').textContent = serviceName.toUpperCase();
  14814. document.getElementById('modal-service-port').value = currentPort;
  14815. const hintEl = document.getElementById('modal-service-port-hint');
  14816. const warnEl = document.getElementById('modal-service-warning');
  14817. if (serviceName === 'www') {
  14818. hintEl.textContent = 'Default HTTP web port: 80';
  14819. warnEl.classList.remove('hidden');
  14820. } else if (serviceName === 'telnet') {
  14821. hintEl.textContent = 'Default Telnet / debtik-cli console port: 8282';
  14822. warnEl.classList.add('hidden');
  14823. } else if (serviceName === 'ssh') {
  14824. hintEl.textContent = 'Default CLI SSH port: 2222';
  14825. warnEl.classList.add('hidden');
  14826. } else {
  14827. hintEl.textContent = '';
  14828. warnEl.classList.add('hidden');
  14829. }
  14830. const modal = document.getElementById('modal-service-edit');
  14831. modal.classList.remove('hidden');
  14832. setTimeout(() => document.getElementById('modal-service-port').focus(), 50);
  14833. }
  14834. function closeEditServiceModal() {
  14835. const modal = document.getElementById('modal-service-edit');
  14836. if (modal) modal.classList.add('hidden');
  14837. }
  14838. async function submitSaveServicePort(event) {
  14839. event.preventDefault();
  14840. const name = document.getElementById('modal-service-name').value;
  14841. const disabled = document.getElementById('modal-service-disabled').value === 'true';
  14842. const port = parseInt(document.getElementById('modal-service-port').value, 10);
  14843. if (isNaN(port) || port < 1 || port > 65535) {
  14844. showToast('Invalid Port', 'Port must be a valid number between 1 and 65535', 'error');
  14845. return;
  14846. }
  14847. try {
  14848. const res = await fetch(`${API_BASE}/system/services/${name}`, {
  14849. method: 'POST',
  14850. headers: { 'Content-Type': 'application/json' },
  14851. body: JSON.stringify({ port: port, disabled: disabled })
  14852. });
  14853. if (!res.ok) {
  14854. const errData = await res.json();
  14855. throw new Error(errData.message || 'Failed to update service port');
  14856. }
  14857. closeEditServiceModal();
  14858. showToast('Port Updated', `Service ${name.toUpperCase()} port changed to ${port}`, 'success');
  14859. await loadServices();
  14860. } catch (err) {
  14861. showToast('Error', err.message, 'error');
  14862. }
  14863. }
  14864. async function toggleServiceState(serviceName, newDisabled) {
  14865. if (serviceName === 'www' && newDisabled) {
  14866. if (!confirm("WARNING: Disabling the Web service ('www') will turn off this Web UI and REST API. You will only be able to re-enable it via SSH (port 2222) or Telnet (port 8282) using 'ip service enable www'. Continue?")) {
  14867. return;
  14868. }
  14869. }
  14870. try {
  14871. const res = await fetch(`${API_BASE}/system/services/${serviceName}/state`, {
  14872. method: 'POST',
  14873. headers: { 'Content-Type': 'application/json' },
  14874. body: JSON.stringify({ disabled: newDisabled })
  14875. });
  14876. if (!res.ok) {
  14877. const errData = await res.json();
  14878. throw new Error(errData.message || 'Failed to update service');
  14879. }
  14880. showToast('Service Updated', `Service ${serviceName} is now ${newDisabled ? 'disabled' : 'enabled'}`, 'success');
  14881. await loadServices();
  14882. } catch (err) {
  14883. showToast('Error', err.message, 'error');
  14884. }
  14885. }
  14886. // ==================== SYSTEM LOGS (/log) ====================
  14887. state.logs = [];
  14888. let logsTimer = null;
  14889. async function loadLogs(manual = false) {
  14890. const limitEl = document.getElementById('logs-limit-select');
  14891. const limit = limitEl ? limitEl.value : '100';
  14892. try {
  14893. const res = await fetch(`${API_BASE}/system/logs?limit=${limit}`);
  14894. if (!res.ok) throw new Error('Failed to load logs');
  14895. const data = await res.json();
  14896. state.logs = data.logs || [];
  14897. renderLogsTable();
  14898. if (manual) showToast('Logs Refreshed', `Fetched ${state.logs.length} log records`, 'success');
  14899. } catch (err) {
  14900. if (manual) showToast('Error', err.message, 'error');
  14901. }
  14902. // Setup auto-refresh if enabled and on logs tab
  14903. if (!logsTimer) {
  14904. logsTimer = setInterval(() => {
  14905. if (state.activeTab === 'logs') {
  14906. const auto = document.getElementById('logs-auto-refresh');
  14907. if (auto && auto.checked) {
  14908. loadLogs(false);
  14909. }
  14910. }
  14911. }, 3000);
  14912. }
  14913. }
  14914. function renderLogsTable() {
  14915. const tbody = document.getElementById('logs-table-body');
  14916. if (!tbody) return;
  14917. const search = (document.getElementById('logs-search-input')?.value || '').toLowerCase();
  14918. const topicFilter = (document.getElementById('logs-topic-filter')?.value || '').toLowerCase();
  14919. const filtered = state.logs.filter(entry => {
  14920. if (topicFilter && !entry.topics.toLowerCase().includes(topicFilter)) {
  14921. return false;
  14922. }
  14923. if (search && !entry.message.toLowerCase().includes(search) && !entry.topics.toLowerCase().includes(search)) {
  14924. return false;
  14925. }
  14926. return true;
  14927. });
  14928. if (filtered.length === 0) {
  14929. tbody.innerHTML = '<tr><td colspan="4" class="py-8 text-center text-slate-500 text-xs">No matching log entries found.</td></tr>';
  14930. return;
  14931. }
  14932. tbody.innerHTML = filtered.map(l => {
  14933. let topicColor = 'bg-slate-800 text-slate-300 border-slate-700';
  14934. const topLower = l.topics.toLowerCase();
  14935. if (topLower.includes('auth')) {
  14936. topicColor = 'bg-amber-500/20 text-amber-300 border-amber-500/30';
  14937. } else if (topLower.includes('dhcp')) {
  14938. topicColor = 'bg-cyan-500/20 text-cyan-300 border-cyan-500/30';
  14939. } else if (topLower.includes('route')) {
  14940. topicColor = 'bg-blue-500/20 text-blue-300 border-blue-500/30';
  14941. } else if (topLower.includes('firewall')) {
  14942. topicColor = 'bg-rose-500/20 text-rose-300 border-rose-500/30';
  14943. } else if (topLower.includes('error')) {
  14944. topicColor = 'bg-red-500/20 text-red-300 border-red-500/30';
  14945. } else if (topLower.includes('system')) {
  14946. topicColor = 'bg-emerald-500/20 text-emerald-300 border-emerald-500/30';
  14947. }
  14948. const d = new Date(l.time);
  14949. const timeStr = d.toLocaleDateString('en-US', { month: 'short', day: '2-digit' }) + ' ' + d.toLocaleTimeString('en-US', { hour12: false });
  14950. return `
  14951. <tr class="hover:bg-slate-800/40 transition">
  14952. <td class="py-2 px-3 text-slate-500 font-mono">${l.id}</td>
  14953. <td class="py-2 px-3 text-slate-400 font-mono whitespace-nowrap">${timeStr}</td>
  14954. <td class="py-2 px-3 whitespace-nowrap">
  14955. <span class="px-2 py-0.5 rounded text-[10px] font-bold border ${topicColor}">${l.topics}</span>
  14956. </td>
  14957. <td class="py-2 px-3 text-slate-200 font-mono break-all">${escapeHtml(l.message)}</td>
  14958. </tr>
  14959. `;
  14960. }).join('');
  14961. }