app.js 741 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476
  1. // DebTik - Debian Linux Router Frontend Application Logic
  2. // ================= Interceptor: Automatic Auth Bearer & 401 Handling =================
  3. const originalFetch = window.fetch.bind(window);
  4. const pendingAPIReads = new Map();
  5. const telemetryHealth = { lastSuccess: 0, failures: new Map() };
  6. let coreRefreshPromise = null;
  7. let lastSummaryRefresh = 0;
  8. function renderTelemetryHealth() {
  9. const el = document.getElementById('telemetry-health');
  10. if (!el) return;
  11. const failures = [...telemetryHealth.failures.entries()];
  12. const seconds = telemetryHealth.lastSuccess ? Math.floor((Date.now() - telemetryHealth.lastSuccess) / 1000) : null;
  13. const stale = seconds === null || seconds > 15;
  14. el.textContent = failures.length ? `Data unavailable / incomplete${seconds === null ? '' : ` · updated ${seconds}s ago`}` : stale ? 'Waiting for fresh data' : `Updated ${seconds}s ago`;
  15. el.className = `text-[10px] font-mono ${failures.length || stale ? 'text-amber-400' : 'text-emerald-400'}`;
  16. el.title = failures.length ? failures.map(([path, error]) => `${path}: ${error}`).join('\n') : telemetryHealth.lastSuccess ? `Last successful update: ${new Date(telemetryHealth.lastSuccess).toLocaleTimeString()}` : 'No successful update yet';
  17. }
  18. function stopSessionPolling() {
  19. if (window._telemetryInterval) clearInterval(window._telemetryInterval);
  20. window._telemetryInterval = null;
  21. if (trafficEventSource) trafficEventSource.close();
  22. trafficEventSource = null;
  23. if (trafficPollFallback) clearInterval(trafficPollFallback);
  24. trafficPollFallback = null;
  25. if (bwtestState.pollTimer) clearInterval(bwtestState.pollTimer);
  26. bwtestState.pollTimer = null;
  27. if (logsTimer) clearInterval(logsTimer);
  28. logsTimer = null;
  29. stopFwStatPolling();
  30. stopNATStatPolling();
  31. stopMangleStatPolling();
  32. telemetryHealth.failures.clear();
  33. telemetryHealth.lastSuccess = 0;
  34. lastSummaryRefresh = 0;
  35. }
  36. window.fetch = async function(resource, options = {}) {
  37. const url = new URL(resource instanceof Request ? resource.url : resource, window.location.href);
  38. const isAPI = url.origin === window.location.origin && url.pathname.startsWith('/api/');
  39. if (!isAPI) return originalFetch(resource, options);
  40. const config = { ...options, headers: new Headers(options.headers || (resource instanceof Request ? resource.headers : undefined)) };
  41. const token = localStorage.getItem('debtik_token');
  42. if (token && !config.headers.has('Authorization')) config.headers.set('Authorization', `Bearer ${token}`);
  43. const method = (config.method || (resource instanceof Request ? resource.method : 'GET')).toUpperCase();
  44. const isRead = method === 'GET' && !url.pathname.includes('/stream') && !url.pathname.startsWith('/api/auth/');
  45. const key = `${url.href}|${JSON.stringify([...config.headers])}`;
  46. if (isRead && pendingAPIReads.has(key)) return (await pendingAPIReads.get(key)).clone();
  47. const perform = async () => {
  48. let timeout;
  49. if (isRead && !config.signal) {
  50. const controller = new AbortController();
  51. config.signal = controller.signal;
  52. timeout = setTimeout(() => controller.abort(), 15000);
  53. }
  54. try {
  55. const response = await originalFetch(resource, config);
  56. if (isRead) {
  57. if (response.ok) {
  58. telemetryHealth.lastSuccess = Date.now();
  59. telemetryHealth.failures.delete(url.pathname);
  60. } else {
  61. telemetryHealth.failures.set(url.pathname, `HTTP ${response.status}; displayed values may be old`);
  62. }
  63. renderTelemetryHealth();
  64. }
  65. if (response.status === 401 && url.pathname !== '/api/auth/login' && state.currentUser && token === localStorage.getItem('debtik_token')) {
  66. stopSessionPolling();
  67. state.isPolling = false;
  68. state.currentUser = null;
  69. localStorage.removeItem('debtik_token');
  70. showLoginScreen(true);
  71. }
  72. return response;
  73. } catch (err) {
  74. if (isRead) {
  75. telemetryHealth.failures.set(url.pathname, err.name === 'AbortError' ? 'Request timed out' : 'Connection failed; displayed values may be old');
  76. renderTelemetryHealth();
  77. }
  78. throw err;
  79. } finally {
  80. if (timeout) clearTimeout(timeout);
  81. }
  82. };
  83. if (!isRead) return perform();
  84. const request = perform();
  85. pendingAPIReads.set(key, request);
  86. try { return (await request).clone(); }
  87. finally { if (pendingAPIReads.get(key) === request) pendingAPIReads.delete(key); }
  88. };
  89. let state = {
  90. currentUser: null,
  91. users: [],
  92. interfaces: [],
  93. vlans: [],
  94. systemStatus: null,
  95. vpnStatus: null,
  96. routes: [],
  97. activeTab: 'dashboard',
  98. fwSubTab: 'filter',
  99. bridgeSubTab: 'bridges',
  100. bridges: [],
  101. bridgePorts: [],
  102. bridgeVLANs: [],
  103. bridgeHosts: [],
  104. bridgeSummary: null,
  105. routesSubTab: 'routes',
  106. pppSubTab: 'secrets',
  107. eoipTunnels: [],
  108. pppSecrets: [],
  109. pppProfiles: [],
  110. pppActiveSessions: [],
  111. pppoeServer: null,
  112. pptpServer: null,
  113. l2tpServer: null,
  114. ipsecServer: null,
  115. ifaceFilter: 'all',
  116. currentModalIface: null,
  117. isPolling: false,
  118. expandedParents: new Set(['eth0']),
  119. pppoeData: null,
  120. wgData: null,
  121. ipsecData: null,
  122. l2tpData: null,
  123. pptpData: null,
  124. fwSummary: null,
  125. filterRules: [],
  126. natRules: [],
  127. mangleRules: [],
  128. addressLists: [],
  129. connections: [],
  130. policyRules: [],
  131. routingTables: [],
  132. routingFilters: [],
  133. filterChainSelected: 'all',
  134. activeToolsSubTab: 'ping',
  135. dhcpClients: [],
  136. dhcpSummary: null,
  137. dhcpServerTab: 'servers',
  138. dhcpServers: [],
  139. dhcpNetworks: [],
  140. dhcpLeases: [],
  141. dhcpOptions: [],
  142. dhcpServerSummary: null
  143. };
  144. const API_BASE = '/api';
  145. function escapeHtml(str) {
  146. if (str === null || str === undefined) return '';
  147. return String(str)
  148. .replace(/&/g, '&')
  149. .replace(/</g, '&lt;')
  150. .replace(/>/g, '&gt;')
  151. .replace(/"/g, '&quot;')
  152. .replace(/'/g, '&#039;');
  153. }
  154. function formatBytes(bytes) {
  155. if (bytes === undefined || bytes === null || isNaN(bytes) || bytes === 0) return '0 B';
  156. const k = 1024;
  157. const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
  158. const i = Math.floor(Math.log(bytes) / Math.log(k));
  159. if (i < 0 || i >= sizes.length) return `${bytes} B`;
  160. return `${parseFloat((bytes / Math.pow(k, i)).toFixed(2))} ${sizes[i]}`;
  161. }
  162. // Initialize on page load
  163. document.addEventListener('DOMContentLoaded', async () => {
  164. initTableSorting();
  165. // Verify authentication before bootstrapping telemetry and views
  166. const isAuthenticated = await checkAuthStatus();
  167. if (isAuthenticated) {
  168. const hash = window.location.hash.replace('#', '') || 'dashboard';
  169. navigate(hash);
  170. // Full state telemetry polling every 5 seconds (smooth & flicker-free)
  171. if (!window._telemetryInterval) {
  172. window._telemetryInterval = setInterval(() => {
  173. if (state.isPolling && state.currentUser && !document.hidden) {
  174. fetchData(false);
  175. }
  176. }, 5000);
  177. }
  178. }
  179. });
  180. let trafficEventSource = null;
  181. let trafficPollFallback = null;
  182. function initLiveTrafficStream() {
  183. if (trafficEventSource) {
  184. try { trafficEventSource.close(); } catch(e) {}
  185. trafficEventSource = null;
  186. }
  187. if (trafficPollFallback) {
  188. clearInterval(trafficPollFallback);
  189. trafficPollFallback = null;
  190. }
  191. if (window.EventSource) {
  192. try {
  193. trafficEventSource = new EventSource(`${API_BASE}/interfaces/traffic/stream`);
  194. trafficEventSource.onmessage = (event) => {
  195. try {
  196. const data = JSON.parse(event.data);
  197. updateLiveInterfaceTraffic(data);
  198. } catch (e) {
  199. console.error('Error parsing live traffic event:', e);
  200. }
  201. };
  202. trafficEventSource.onerror = () => {
  203. // Fallback polling if SSE disconnects
  204. if (!trafficPollFallback) {
  205. trafficPollFallback = setInterval(pollLiveTrafficSnapshot, 1000);
  206. }
  207. };
  208. trafficEventSource.onopen = () => {
  209. if (trafficPollFallback) {
  210. clearInterval(trafficPollFallback);
  211. trafficPollFallback = null;
  212. }
  213. };
  214. return;
  215. } catch (e) {
  216. console.warn('EventSource failed, using 1s polling fallback:', e);
  217. }
  218. }
  219. // Fallback if EventSource is unavailable
  220. trafficPollFallback = setInterval(pollLiveTrafficSnapshot, 1000);
  221. }
  222. async function pollLiveTrafficSnapshot() {
  223. try {
  224. const res = await fetch(`${API_BASE}/interfaces/traffic/rates`);
  225. if (res.ok) {
  226. const data = await res.json();
  227. updateLiveInterfaceTraffic(data);
  228. }
  229. } catch (e) {}
  230. }
  231. function updateLiveInterfaceTraffic(data) {
  232. if (!data || !data.interfaces) return;
  233. state.latestTraffic = data;
  234. // 1. Update Top & Dashboard Total Bandwidth Indicators
  235. const rxHuman = data.total_rx_human || '0 B/s';
  236. const txHuman = data.total_tx_human || '0 B/s';
  237. const statRx = document.getElementById('stat-traffic-rx');
  238. if (statRx && statRx.innerText !== rxHuman) statRx.innerText = rxHuman;
  239. const statTx = document.getElementById('stat-traffic-tx');
  240. if (statTx && statTx.innerText !== txHuman) statTx.innerText = txHuman;
  241. // 2. Update state.interfaces rates in-memory
  242. if (Array.isArray(state.interfaces)) {
  243. state.interfaces.forEach(i => {
  244. const live = data.interfaces[i.name];
  245. if (live) {
  246. i.rate = {
  247. rx_bytes_sec: live.rx_bytes_sec,
  248. tx_bytes_sec: live.tx_bytes_sec,
  249. rx_human: live.rx_human,
  250. tx_human: live.tx_human
  251. };
  252. i.stats = {
  253. rx_bytes: live.rx_bytes,
  254. tx_bytes: live.tx_bytes,
  255. rx_packets: live.rx_packets,
  256. tx_packets: live.tx_packets,
  257. rx_errors: live.rx_errors,
  258. tx_errors: live.tx_errors,
  259. rx_dropped: live.rx_dropped,
  260. tx_dropped: live.tx_dropped
  261. };
  262. }
  263. });
  264. }
  265. // 3. Update all live UI rate spans in-place (ZERO flicker)
  266. Object.keys(data.interfaces).forEach(name => {
  267. const live = data.interfaces[name];
  268. // Dashboard Port Matrix Card
  269. const cardRate = document.getElementById(`port-card-rate-${name}`);
  270. if (cardRate && cardRate.innerText !== live.rx_human) {
  271. cardRate.innerText = live.rx_human;
  272. }
  273. // Dashboard Quick Interfaces Table
  274. const quickRx = document.getElementById(`quick-rx-${name}`);
  275. if (quickRx) quickRx.innerText = `↓ ${live.rx_human}`;
  276. const quickTx = document.getElementById(`quick-tx-${name}`);
  277. if (quickTx) quickTx.innerText = `↑ ${live.tx_human}`;
  278. // Main Interfaces Tree Table
  279. const ifaceRx = document.getElementById(`iface-rate-rx-${name}`);
  280. if (ifaceRx) ifaceRx.innerText = `↓ ${live.rx_human}`;
  281. const ifaceTx = document.getElementById(`iface-rate-tx-${name}`);
  282. if (ifaceTx) ifaceTx.innerText = `↑ ${live.tx_human}`;
  283. // VLAN Sub-interfaces Table
  284. const vlanRx = document.getElementById(`vlan-rate-rx-${name}`);
  285. if (vlanRx) vlanRx.innerText = `↓ ${live.rx_human}`;
  286. const vlanTx = document.getElementById(`vlan-rate-tx-${name}`);
  287. if (vlanTx) vlanTx.innerText = `↑ ${live.tx_human}`;
  288. // VLAN Page Table
  289. const vlanPageRx = document.getElementById(`vlan-page-rate-rx-${name}`);
  290. if (vlanPageRx) vlanPageRx.innerText = `↓ ${live.rx_human}`;
  291. const vlanPageTx = document.getElementById(`vlan-page-rate-tx-${name}`);
  292. if (vlanPageTx) vlanPageTx.innerText = `↑ ${live.tx_human}`;
  293. });
  294. }
  295. // Navigation Handler
  296. function navigate(tabName) {
  297. if (tabName === 'dynamic-routing' || tabName === 'routing') {
  298. navigate('bgp');
  299. return;
  300. }
  301. if (tabName === 'vlans') {
  302. navigate('interfaces');
  303. return;
  304. }
  305. if (tabName === 'persistence') {
  306. navigate('dashboard');
  307. return;
  308. }
  309. stopFwStatPolling();
  310. stopNATStatPolling();
  311. stopMangleStatPolling();
  312. state.activeTab = tabName;
  313. window.location.hash = tabName;
  314. // Update nav links styling
  315. document.querySelectorAll('.nav-link').forEach(link => {
  316. 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';
  317. });
  318. const activeNav = document.getElementById(`nav-${tabName}`);
  319. if (activeNav) {
  320. 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';
  321. }
  322. // Update page headers
  323. const titles = {
  324. dashboard: { title: 'Dashboard Overview', sub: 'Live router performance and network telemetry' },
  325. interfaces: { title: 'Network Interfaces', sub: 'Interface Table View' },
  326. 'dhcp-client': { title: 'DHCP Client', sub: 'DHCP Client List' },
  327. 'dhcp-server': { title: 'DHCP Server & Subnets', sub: 'DHCP Server instances, subnet networks (NTP, TFTP, DNS), dynamic leases & static reservations' },
  328. bridge: { title: 'Bridge Interfaces', sub: 'IEEE 802.1D / 802.1Q VLAN-aware Layer 2 switching, RSTP & hardware forwarding (FDB)' },
  329. vlans: { title: 'VLAN Virtual Networks', sub: 'IEEE 802.1Q sub-interface segmentation and routing' },
  330. firewall: { title: 'Network Firewall', sub: 'Stateful packet inspection, NAT, traffic mangle, address lists & connection tracking' },
  331. routes: { title: 'Routing & Policy', sub: 'Routing tables, static routes (DAS/DAC), and policy routing rules' },
  332. bgp: { title: 'BGP Dynamic Routing', sub: 'BGP multi-instance peering sessions, advertised networks, and routing table (RIB)' },
  333. ospf: { title: 'OSPF Dynamic Routing', sub: 'OSPFv2 link-state routing, dynamic neighbor adjacencies, and multi-area topology' },
  334. 'routing-filters': { title: 'Routing Policy Filters', sub: 'Route filter chains, prefix matching, BGP community maps & policy-based path control' },
  335. 'dynamic-routing': { title: 'BGP Dynamic Routing', sub: 'Dynamic routing engine and peering sessions' },
  336. ppp: { title: 'PPP Servers & Secrets', sub: 'Subscriber authentication, dynamic IP pools and VPN access concentrators' },
  337. eoip: { title: 'EoIP Tunnels', sub: 'Ethernet over IP (EoIP / GRETAP) Layer 2 encapsulation & transparent network bridging' },
  338. aerotun: { title: 'AeroTUN High-Speed VPN', sub: 'Layer 3 encrypted tunnel with XChaCha20-Poly1305 and adaptive LZ4 compression' },
  339. pppoe: { title: 'PPPoE Client WAN', sub: 'Point-to-Point Protocol over Ethernet WAN access' },
  340. wireguard: { title: 'WireGuard VPN', sub: 'High-performance cryptographic Layer 3 tunnels with ChaCha20-Poly1305 key exchange' },
  341. ipsec: { title: 'IPSec (IKEv2) strongSwan', sub: 'Enterprise Site-to-Site & Roadwarrior IPSec controller' },
  342. l2tp: { title: 'L2TP VPN Client', sub: 'Layer 2 Tunneling Protocol via xl2tpd' },
  343. pptp: { title: 'PPTP VPN Client', sub: 'Point-to-Point Tunneling Protocol with MPPE-128 encryption' },
  344. vrrp: { title: 'VRRP High Availability', sub: 'Virtual Router Redundancy Protocol, active-backup gateway failover & Virtual IP (VIP) routing' },
  345. bwtest: { title: 'Bandwidth Test Benchmark', sub: 'High-speed line-rate throughput benchmark, token-bucket rate limiting, loss & jitter telemetry' },
  346. tools: { title: 'Diagnostic & Troubleshooting Tools', sub: 'Network latency analysis, ICMP/MTR telemetry, path tracing, DNS resolution and TCP probing' },
  347. settings: { title: 'Router Settings & DNS', sub: 'System DNS forwarder, upstream resolvers, static host mappings, and appliance identity' },
  348. users: { title: 'Local User Manager', sub: 'Manage local system administrator credentials and access permissions' },
  349. certificates: { title: 'Certificates & SSL/TLS', sub: 'Root Certificate Authorities (CA), Server/Client certificates and automated Let\'s Encrypt' },
  350. services: { title: 'Management Services', sub: 'Enable or disable Web, SSH, and Telnet management listeners and listening ports' },
  351. updates: { title: 'Git Updates', sub: 'Check, install and restore appliance software' },
  352. logs: { title: 'System Activity Logs', sub: 'Real-time circular buffer log viewer and topic-based event monitoring' }
  353. };
  354. const header = titles[tabName] || titles.dashboard;
  355. const pTitle = document.getElementById('page-title');
  356. if (pTitle) pTitle.innerText = header.title;
  357. const pSub = document.getElementById('page-subtitle');
  358. if (pSub) pSub.innerText = header.sub;
  359. // Toggle sections dynamically for all section elements
  360. document.querySelectorAll('main section[id^="section-"]').forEach(el => {
  361. if (el.id === `section-${tabName}`) {
  362. el.classList.remove('hidden');
  363. } else {
  364. el.classList.add('hidden');
  365. }
  366. });
  367. if (tabName === 'interfaces') {
  368. loadRoles();
  369. if (state.activeIfaceSubTab === 'roles') switchIfaceSubTab('roles');
  370. else switchIfaceSubTab('tree');
  371. }
  372. if (tabName === 'bridge') loadBridge();
  373. if (tabName === 'firewall') loadFirewall();
  374. if (tabName === 'routes') loadRoutes();
  375. if (tabName === 'bgp') {
  376. loadDynamicRouting();
  377. switchBgpSubTab(state.activeBgpSubTab || 'bgp-peers');
  378. }
  379. if (tabName === 'ospf') {
  380. loadDynamicRouting();
  381. switchOspfTab(state.activeOspfTab || 'instances');
  382. }
  383. if (tabName === 'routing-filters') loadDynamicRouting();
  384. if (tabName === 'dynamic-routing') loadDynamicRouting();
  385. if (tabName === 'ppp') loadPPP();
  386. if (tabName === 'eoip') loadEoIP();
  387. if (tabName === 'aerotun') loadAeroTUN();
  388. if (tabName === 'pppoe') loadPPPoE();
  389. if (tabName === 'wireguard') loadWireGuard();
  390. if (tabName === 'ipsec') loadIPSec();
  391. if (tabName === 'l2tp') loadL2TP();
  392. if (tabName === 'pptp') loadPPTP();
  393. if (tabName === 'tools') loadToolsView();
  394. if (tabName === 'dhcp-client') loadDHCPClients();
  395. if (tabName === 'dhcp-server') loadDHCPServer();
  396. if (tabName === 'vrrp') loadVRRP();
  397. if (tabName === 'bwtest') loadBwTestView();
  398. if (tabName === 'settings') loadSettingsData();
  399. if (tabName === 'users') loadUsers();
  400. if (tabName === 'certificates') loadCertificates();
  401. if (tabName === 'services') loadServices();
  402. if (tabName === 'updates') loadUpdateStatus();
  403. if (tabName === 'logs') loadLogs();
  404. setTimeout(initTableSorting, 50);
  405. }
  406. // Fetch all core system, network and VPN telemetry
  407. function fetchData(isManual = false) {
  408. if (coreRefreshPromise) return coreRefreshPromise;
  409. coreRefreshPromise = refreshCoreData(isManual).finally(() => { coreRefreshPromise = null; });
  410. return coreRefreshPromise;
  411. }
  412. async function refreshCoreData(isManual = false) {
  413. const spinner = document.getElementById('refresh-spinner');
  414. if (isManual && spinner) spinner.classList.add('animate-spin');
  415. try {
  416. const refreshSummaries = isManual || Date.now() - lastSummaryRefresh > 30000;
  417. const summaryFetch = path => (refreshSummaries || (state.activeTab === 'interfaces' && ['/vlans', '/roles'].includes(path))) ? fetch(`${API_BASE}${path}`).catch(() => ({ ok: false })) : Promise.resolve({ ok: false });
  418. const [statusRes, ifacesRes, vlansRes, vpnRes, fwRes, dynRes, brSummaryRes, dhcpSumRes, dhcpClientsRes, vrrpSumRes, rolesRes] = await Promise.all([
  419. fetch(`${API_BASE}/system/status`).catch(() => ({ ok: false })),
  420. fetch(`${API_BASE}/interfaces`).catch(() => ({ ok: false })),
  421. summaryFetch('/vlans'),
  422. summaryFetch('/vpn/status'),
  423. summaryFetch('/firewall/summary'),
  424. summaryFetch('/routing/dynamic/summary'),
  425. summaryFetch('/bridge/summary'),
  426. summaryFetch('/dhcp/clients/summary'),
  427. summaryFetch('/dhcp/clients'),
  428. summaryFetch('/vrrp/summary').catch(() => null),
  429. summaryFetch('/roles').catch(() => null)
  430. ]);
  431. if (refreshSummaries && [vlansRes, vpnRes, fwRes, dynRes, brSummaryRes, dhcpSumRes, dhcpClientsRes, vrrpSumRes, rolesRes].every(r => r && r.ok)) lastSummaryRefresh = Date.now();
  432. if (rolesRes && rolesRes.ok) {
  433. state.roles = await rolesRes.json();
  434. const countEl = document.getElementById('badge-roles-count');
  435. if (countEl) countEl.innerText = (state.roles || []).length;
  436. }
  437. if (vrrpSumRes && vrrpSumRes.ok) {
  438. state.vrrpSummary = await vrrpSumRes.json();
  439. renderVRRPSummary();
  440. }
  441. if (dhcpSumRes && dhcpSumRes.ok) {
  442. state.dhcpSummary = await dhcpSumRes.json();
  443. const bDhcp = document.getElementById('badge-dhcp-client-count');
  444. if (bDhcp) bDhcp.innerText = state.dhcpSummary?.total_clients || 0;
  445. }
  446. if (dhcpClientsRes && dhcpClientsRes.ok) {
  447. state.dhcpClients = await dhcpClientsRes.json();
  448. }
  449. if (brSummaryRes.ok) {
  450. state.bridgeSummary = await brSummaryRes.json();
  451. const bBridge = document.getElementById('badge-bridge-count');
  452. if (bBridge) bBridge.innerText = state.bridgeSummary?.bridges_count || 0;
  453. const sBr = document.getElementById('bridge-stat-bridges');
  454. if (sBr) sBr.innerText = state.bridgeSummary?.bridges_count || 0;
  455. const sPorts = document.getElementById('bridge-stat-ports');
  456. if (sPorts) sPorts.innerText = state.bridgeSummary?.ports_count || 0;
  457. const sHosts = document.getElementById('bridge-stat-hosts');
  458. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  459. }
  460. if (statusRes.ok) state.systemStatus = await statusRes.json();
  461. if (ifacesRes.ok) {
  462. const ifacesData = await ifacesRes.json();
  463. const rawIfaces = Array.isArray(ifacesData) ? ifacesData : [];
  464. state.interfaces = rawIfaces.filter(i => {
  465. if (!i.name) return false;
  466. if (i.name.startsWith('ep_')) return false;
  467. return !['gre0', 'gretap0', 'erspan0', 'sit0', 'tunl0', 'ip6tnl0', 'ip6gre0', 'ip6erspan0'].includes(i.name);
  468. });
  469. try { populateToolsInterfaces(); } catch (e) {}
  470. }
  471. if (vlansRes.ok) {
  472. const vlansData = await vlansRes.json();
  473. state.vlans = Array.isArray(vlansData) ? vlansData : [];
  474. }
  475. if (vpnRes.ok) state.vpnStatus = await vpnRes.json();
  476. if (fwRes && fwRes.ok) state.fwSummary = await fwRes.json();
  477. if (dynRes && dynRes.ok) state.dynSummary = await dynRes.json();
  478. updateSystemMetrics();
  479. updateBadges();
  480. if (state.activeTab === 'dashboard') renderDashboard();
  481. if (state.activeTab === 'interfaces') {
  482. if (state.activeIfaceSubTab === 'roles') renderRolesTable();
  483. else renderInterfacesList();
  484. }
  485. if (state.activeTab === 'vlans') renderVlansList();
  486. if (state.activeTab === 'firewall') await loadFirewall(false);
  487. if (state.activeTab === 'routes') await loadRoutes(false);
  488. if (state.activeTab === 'dynamic-routing' || state.activeTab === 'bgp' || state.activeTab === 'ospf') await loadDynamicRouting(false);
  489. if (state.activeTab === 'ppp') await loadPPP(false);
  490. if (state.activeTab === 'eoip') await loadEoIP(false);
  491. if (state.activeTab === 'aerotun') await loadAeroTUN(false);
  492. if (state.activeTab === 'pppoe') await loadPPPoE(false);
  493. if (state.activeTab === 'wireguard') await loadWireGuard(false);
  494. if (state.activeTab === 'ipsec') await loadIPSec(false);
  495. if (state.activeTab === 'l2tp') await loadL2TP(false);
  496. if (state.activeTab === 'pptp') await loadPPTP(false);
  497. if (state.activeTab === 'dhcp-client') await loadDHCPClients(false);
  498. if (state.activeTab === 'dhcp-server') await loadDHCPServer(false);
  499. if (state.activeTab === 'vrrp') await loadVRRP(false);
  500. if (state.activeTab === 'settings') await loadSettingsData(false);
  501. if (state.activeTab === 'users') await loadUsers(false);
  502. if (state.activeTab === 'certificates') await loadCertificates(false);
  503. if (state.activeTab === 'services') await loadServices(false);
  504. if (state.activeTab === 'updates') await loadUpdateStatus(false);
  505. if (state.activeTab === 'bwtest') await fetchBwTestServerStatus();
  506. } catch (err) {
  507. console.error('Failed to fetch router state:', err);
  508. } finally {
  509. if (isManual && spinner) {
  510. setTimeout(() => spinner.classList.remove('animate-spin'), 300);
  511. }
  512. }
  513. }
  514. // Update Top KPI and Sidebar Telemetry
  515. function updateSystemMetrics() {
  516. const s = state.systemStatus;
  517. const v = state.vpnStatus;
  518. if (!s) return;
  519. // Sidebar Host & Uptime
  520. const sideHost = document.getElementById('side-hostname');
  521. if (sideHost) sideHost.innerText = s.hostname || 'debian-lxc';
  522. const sideUp = document.getElementById('side-uptime');
  523. if (sideUp) sideUp.innerText = s.uptime_human || '0m';
  524. const sideGw = document.getElementById('side-gateway-ip');
  525. if (sideGw) sideGw.innerText = s.default_gateway ? `GW: ${s.default_gateway}` : 'GW: Isolated';
  526. // Compute CPU Metrics
  527. let cpuPct = 0;
  528. if (s.cpu_pct !== undefined) {
  529. cpuPct = s.cpu_pct;
  530. } else if (s.cpu_load && s.cpu_load.length > 0) {
  531. const cores = s.cpu_cores || 1;
  532. cpuPct = Math.min(100, Math.round((parseFloat(s.cpu_load[0]) / cores) * 100));
  533. }
  534. const cpuPctStr = `${cpuPct.toFixed(1)}%`;
  535. const cpuWidth = `${Math.max(3, Math.min(100, cpuPct))}%`;
  536. const loadStr = s.cpu_load ? s.cpu_load.join(', ') : '-';
  537. // Sidebar CPU
  538. const sideCpuVal = document.getElementById('side-cpu-val');
  539. if (sideCpuVal) sideCpuVal.innerText = cpuPctStr;
  540. const sideCpuBar = document.getElementById('side-cpu-bar');
  541. if (sideCpuBar) {
  542. sideCpuBar.style.width = cpuWidth;
  543. sideCpuBar.title = `Container: ${cpuPctStr} | Host Loadavg: ${loadStr} (${s.cpu_cores || 1} cores)`;
  544. }
  545. // Dashboard CPU Card
  546. const dashCpuVal = document.getElementById('dash-cpu-val');
  547. if (dashCpuVal) dashCpuVal.innerText = cpuPctStr;
  548. const dashCpuBar = document.getElementById('dash-cpu-bar');
  549. if (dashCpuBar) {
  550. dashCpuBar.style.width = cpuWidth;
  551. if (cpuPct > 85) {
  552. dashCpuBar.className = 'h-full rounded-full bg-rose-500 transition-all duration-500';
  553. } else if (cpuPct > 65) {
  554. dashCpuBar.className = 'h-full rounded-full bg-amber-500 transition-all duration-500';
  555. } else {
  556. dashCpuBar.className = 'h-full rounded-full bg-emerald-500 transition-all duration-500';
  557. }
  558. }
  559. const dashCpuCores = document.getElementById('dash-cpu-cores');
  560. if (dashCpuCores) dashCpuCores.innerText = `${s.cpu_cores || 1} Cores`;
  561. const dashCpuLoad = document.getElementById('dash-cpu-load');
  562. if (dashCpuLoad) dashCpuLoad.innerText = loadStr;
  563. const dashCpuStatus = document.getElementById('dash-cpu-status');
  564. if (dashCpuStatus) {
  565. if (cpuPct > 85) {
  566. dashCpuStatus.innerText = 'High';
  567. dashCpuStatus.className = 'text-[11px] font-semibold text-rose-400 uppercase px-2 py-0.5 rounded bg-rose-500/10';
  568. } else if (cpuPct > 65) {
  569. dashCpuStatus.innerText = 'Heavy';
  570. dashCpuStatus.className = 'text-[11px] font-semibold text-amber-400 uppercase px-2 py-0.5 rounded bg-amber-500/10';
  571. } else {
  572. dashCpuStatus.innerText = 'Normal';
  573. dashCpuStatus.className = 'text-[11px] font-semibold text-emerald-400 uppercase px-2 py-0.5 rounded bg-emerald-500/10';
  574. }
  575. }
  576. // Compute RAM Metrics
  577. const memPct = Math.round(s.mem_usage_pct || 0);
  578. const memPctStr = `${memPct}%`;
  579. const memWidth = `${Math.max(3, Math.min(100, memPct))}%`;
  580. const usedMB = s.mem_used_mb || 0;
  581. const totalMB = s.mem_total_mb || 0;
  582. const freeMB = totalMB > usedMB ? totalMB - usedMB : 0;
  583. function fmtMemMB(mb) {
  584. if (mb >= 1024) {
  585. return `${(mb / 1024).toFixed(1)} GB`;
  586. }
  587. return `${mb} MB`;
  588. }
  589. // Sidebar RAM
  590. const sideRamVal = document.getElementById('side-ram-val');
  591. if (sideRamVal) sideRamVal.innerText = memPctStr;
  592. const sideRamBar = document.getElementById('side-ram-bar');
  593. if (sideRamBar) sideRamBar.style.width = memWidth;
  594. // Dashboard RAM Card
  595. const dashRamVal = document.getElementById('dash-ram-val');
  596. if (dashRamVal) dashRamVal.innerText = memPctStr;
  597. const dashRamBar = document.getElementById('dash-ram-bar');
  598. if (dashRamBar) {
  599. dashRamBar.style.width = memWidth;
  600. if (memPct > 85) {
  601. dashRamBar.className = 'h-full rounded-full bg-rose-500 transition-all duration-500';
  602. } else if (memPct > 70) {
  603. dashRamBar.className = 'h-full rounded-full bg-amber-500 transition-all duration-500';
  604. } else {
  605. dashRamBar.className = 'h-full rounded-full bg-indigo-500 transition-all duration-500';
  606. }
  607. }
  608. const dashRamUsedTotal = document.getElementById('dash-ram-used-total');
  609. if (dashRamUsedTotal) {
  610. dashRamUsedTotal.innerText = `${fmtMemMB(usedMB)} / ${fmtMemMB(totalMB)}`;
  611. }
  612. const dashRamFree = document.getElementById('dash-ram-free');
  613. if (dashRamFree) {
  614. dashRamFree.innerText = fmtMemMB(freeMB);
  615. }
  616. const dashRamStatus = document.getElementById('dash-ram-status');
  617. if (dashRamStatus) {
  618. if (memPct > 85) {
  619. dashRamStatus.innerText = 'High';
  620. dashRamStatus.className = 'text-[11px] font-semibold text-rose-400 uppercase px-2 py-0.5 rounded bg-rose-500/10';
  621. } else {
  622. dashRamStatus.innerText = 'Active';
  623. dashRamStatus.className = 'text-[11px] font-semibold text-indigo-400 uppercase px-2 py-0.5 rounded bg-indigo-500/10';
  624. }
  625. }
  626. // Legacy Dashboard Stats (Safe checks)
  627. const elIfacesUp = document.getElementById('stat-ifaces-up');
  628. if (elIfacesUp) elIfacesUp.innerText = s.up_ifaces || 0;
  629. const elIfacesTot = document.getElementById('stat-ifaces-total');
  630. if (elIfacesTot) elIfacesTot.innerText = `${s.total_ifaces || 0} Total`;
  631. const elIfacesDown = document.getElementById('stat-ifaces-down');
  632. if (elIfacesDown) elIfacesDown.innerText = `${s.down_ifaces || 0} DOWN`;
  633. const elVlans = document.getElementById('stat-vlans-count');
  634. if (elVlans) elVlans.innerText = s.vlan_ifaces || 0;
  635. // VPN Status Indicators
  636. if (v) {
  637. const totalActive = v.total_active_tunnels || 0;
  638. const statVpnActive = document.getElementById('stat-vpn-active');
  639. if (statVpnActive) statVpnActive.innerText = totalActive;
  640. const tunnelsDot = document.getElementById('tunnels-dot');
  641. const tunnelsLabel = document.getElementById('tunnels-label');
  642. if (tunnelsDot && tunnelsLabel) {
  643. if (totalActive > 0) {
  644. tunnelsDot.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  645. tunnelsLabel.innerText = `${totalActive} Active VPN Tunnel${totalActive > 1 ? 's' : ''}`;
  646. } else {
  647. tunnelsDot.className = 'w-2 h-2 rounded-full bg-slate-500';
  648. tunnelsLabel.innerText = '0 Active VPN Tunnels';
  649. }
  650. }
  651. setDotBadge('badge-pppoe-status', (v.active_pppoe || 0) > 0 || v.pppoe_connected);
  652. setDotBadge('badge-wg-status', (v.active_wireguard || 0) > 0 || v.wireguard_active);
  653. setDotBadge('badge-ipsec-status', (v.active_ipsec || 0) > 0 || v.ipsec_active);
  654. setDotBadge('badge-l2tp-status', (v.active_l2tp || 0) > 0 || v.l2tp_connected);
  655. setDotBadge('badge-pptp-status', (v.active_pptp || 0) > 0 || v.pptp_connected);
  656. }
  657. // Total Live Bandwidth Rate
  658. let totalRx = 0;
  659. let totalTx = 0;
  660. (state.interfaces || []).forEach(i => {
  661. if (i.rate) {
  662. totalRx += i.rate.rx_bytes_sec || 0;
  663. totalTx += i.rate.tx_bytes_sec || 0;
  664. }
  665. });
  666. document.getElementById('stat-traffic-rx').innerText = formatTraffic(totalRx);
  667. document.getElementById('stat-traffic-tx').innerText = formatTraffic(totalTx);
  668. }
  669. function setDotBadge(id, active) {
  670. const el = document.getElementById(id);
  671. if (!el) return;
  672. if (active) {
  673. el.className = 'w-2 h-2 rounded-full bg-emerald-400 shadow-sm shadow-emerald-400/80';
  674. } else {
  675. el.className = 'w-2 h-2 rounded-full bg-slate-600';
  676. }
  677. }
  678. function updateBadges() {
  679. const bIfaces = document.getElementById('badge-ifaces-count');
  680. if (bIfaces) bIfaces.innerText = (state.interfaces || []).length;
  681. const bVlans = document.getElementById('badge-vlans-count');
  682. if (bVlans) bVlans.innerText = (state.vlans || []).length;
  683. if (state.fwSummary) {
  684. const totalFwRules = (state.fwSummary.filter_rules_count || 0) + (state.fwSummary.nat_rules_count || 0) + (state.fwSummary.mangle_rules_count || 0);
  685. const badgeFw = document.getElementById('badge-firewall-count');
  686. if (badgeFw) badgeFw.innerText = totalFwRules;
  687. }
  688. if (state.vpnStatus) {
  689. const v = state.vpnStatus;
  690. const bEoIP = document.getElementById('badge-eoip-count');
  691. if (bEoIP) bEoIP.innerText = v.total_eoip || 0;
  692. const bAero = document.getElementById('badge-aerotun-count');
  693. if (bAero) bAero.innerText = v.total_aerotun || 0;
  694. const bPPPSess = document.getElementById('badge-ppp-sessions');
  695. if (bPPPSess) bPPPSess.innerText = v.total_ppp_sessions || 0;
  696. setDotBadge('badge-pppoe-status', v.active_pppoe > 0 || v.pppoe_server_running);
  697. setDotBadge('badge-wg-status', v.active_wireguard > 0);
  698. setDotBadge('badge-ipsec-status', v.active_ipsec > 0 || v.ipsec_server_running);
  699. setDotBadge('badge-l2tp-status', v.active_l2tp > 0 || v.l2tp_server_running);
  700. setDotBadge('badge-pptp-status', v.active_pptp > 0 || v.pptp_server_running);
  701. }
  702. if (state.dynSummary) {
  703. const d = state.dynSummary;
  704. setDotBadge('badge-bgp-dot', d.bgp_running);
  705. setDotBadge('badge-ospf-dot', d.ospf_running);
  706. const bBgp = document.getElementById('badge-bgp-count');
  707. if (bBgp) bBgp.innerText = (state.bgpPeers || []).length;
  708. const bOspf = document.getElementById('badge-ospf-count');
  709. if (bOspf) bOspf.innerText = (state.ospfInterfaces || []).length;
  710. const bFilters = document.getElementById('badge-filters-count');
  711. if (bFilters) bFilters.innerText = (state.routingFilters || []).length;
  712. }
  713. const bDhcpServer = document.getElementById('badge-dhcp-server-count');
  714. if (bDhcpServer) {
  715. bDhcpServer.innerText = state.dhcpServerSummary ? (state.dhcpServerSummary.active_leases || state.dhcpServerSummary.total_servers || 0) : (state.dhcpServers || []).length;
  716. }
  717. }
  718. // Render Dashboard View
  719. function renderDashboard() {
  720. const matrix = document.getElementById('port-matrix');
  721. if (!matrix) return;
  722. const ifaces = state.interfaces || [];
  723. const sig = ifaces.map(i => `${i.name}:${i.state}:${(i.ipv4 || []).join(',')}:${i.type}:${i.is_vlan}`).join(';');
  724. if (matrix.dataset.sig === sig) {
  725. return; // Structure & link states haven't changed! Do not rebuild or flicker!
  726. }
  727. matrix.dataset.sig = sig;
  728. matrix.innerHTML = '';
  729. (state.interfaces || []).forEach(iface => {
  730. const isUp = iface.state === 'UP';
  731. const isVlan = iface.is_vlan;
  732. const portCard = document.createElement('div');
  733. portCard.className = `p-3 rounded-xl border transition-all cursor-pointer select-none group ${
  734. isUp
  735. ? (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')
  736. : 'bg-slate-900/40 border-slate-800/60 opacity-60 hover:opacity-100 hover:border-slate-700'
  737. }`;
  738. portCard.onclick = () => openIfaceModal(iface.name);
  739. let statusPillClass = isUp ? 'bg-emerald-500 shadow-sm shadow-emerald-500/50' : 'bg-rose-500';
  740. if (isVlan) statusPillClass = isUp ? 'bg-cyan-400 shadow-sm shadow-cyan-400/50' : 'bg-rose-500';
  741. portCard.innerHTML = `
  742. <div class="flex items-center justify-between mb-2">
  743. <span class="font-bold text-xs font-mono text-white group-hover:text-brand-400 transition truncate">${iface.name}</span>
  744. <span class="w-2 h-2 rounded-full ${statusPillClass}"></span>
  745. </div>
  746. <div class="text-[11px] font-mono text-slate-300 truncate">${iface.ipv4 && iface.ipv4.length > 0 ? iface.ipv4[0] : (iface.mac || 'No IP')}</div>
  747. <div class="mt-2 flex items-center justify-between text-[10px] text-slate-400">
  748. <span class="uppercase tracking-wider font-semibold">${isVlan ? `VLAN ${iface.vlan_id}` : iface.type}</span>
  749. <span id="port-card-rate-${iface.name}">${iface.rate?.rx_human || '0 B/s'}</span>
  750. </div>
  751. `;
  752. matrix.appendChild(portCard);
  753. });
  754. const ifaceTbody = document.getElementById('quick-interfaces-table');
  755. if (ifaceTbody) {
  756. ifaceTbody.innerHTML = '';
  757. (state.interfaces || []).forEach(i => {
  758. const isUp = i.state === 'UP';
  759. const tr = document.createElement('tr');
  760. tr.className = 'hover:bg-slate-800/40 transition cursor-pointer';
  761. tr.onclick = () => openIfaceModal(i.name);
  762. const rxStr = i.rate?.rx_human || '0 B/s';
  763. const txStr = i.rate?.tx_human || '0 B/s';
  764. tr.innerHTML = `
  765. <td class="py-2.5 font-bold text-white flex items-center gap-2">
  766. <span class="w-2 h-2 rounded-full ${isUp ? 'bg-emerald-400 shadow-sm shadow-emerald-400/50' : 'bg-rose-400'}"></span>
  767. <span>${i.name}</span>
  768. </td>
  769. <td class="py-2.5 text-slate-300 font-sans">
  770. ${getRoleBadge(i.role || 'LAN')}
  771. </td>
  772. <td class="py-2.5 text-slate-400 text-[11px] font-mono">${i.mac || '-'}</td>
  773. <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>
  774. <td class="py-2.5 text-slate-300 text-[11px] font-mono">
  775. <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>
  776. </td>
  777. <td class="py-2.5 text-right font-sans font-semibold">
  778. <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>
  779. </td>
  780. `;
  781. ifaceTbody.appendChild(tr);
  782. });
  783. }
  784. const vlanTbody = document.getElementById('quick-vlans-table');
  785. if (vlanTbody) {
  786. vlanTbody.innerHTML = '';
  787. }
  788. }
  789. // Expand / Collapse Handlers
  790. function toggleExpand(parentName) {
  791. if (state.expandedParents.has(parentName)) {
  792. state.expandedParents.delete(parentName);
  793. } else {
  794. state.expandedParents.add(parentName);
  795. }
  796. renderInterfacesList();
  797. }
  798. // VLAN Support Checker: 802.1Q sub-interfaces are only supported on physical ethernet, veth, bridge, bond
  799. function supportsVLAN(iface) {
  800. if (!iface) return false;
  801. if (iface.is_vlan) return false;
  802. const name = (iface.name || '').toLowerCase();
  803. const type = (iface.type || '').toLowerCase();
  804. const role = (iface.role || '').toLowerCase();
  805. // Exclude loopback
  806. if (name === 'lo' || type === 'loopback' || role === 'loopback') return false;
  807. // Exclude WireGuard (Layer 3 tunnel, no 802.1Q support)
  808. if (type === 'wireguard' || name.startsWith('wg')) return false;
  809. // Exclude PPP / PPPoE
  810. if (type === 'ppp' || name.startsWith('ppp')) return false;
  811. // Exclude other Layer 3 tunnels and dummy devices
  812. if (type === 'dummy' || type === 'gre' || type === 'sit' || type === 'tun' || type === 'tap' ||
  813. name.startsWith('gre') || name.startsWith('sit') || name.startsWith('ipsec') || name.startsWith('xfrm') || name.startsWith('dummy')) {
  814. return false;
  815. }
  816. // If name already contains a dot, it's already a sub-interface
  817. if (name.includes('.')) return false;
  818. return true;
  819. }
  820. // DHCP Client Support Checker: Only broadcast-capable layer-2 interfaces (Ethernet, veth, VLAN, bridge, bond)
  821. function supportsDHCPClient(iface) {
  822. if (!iface) return false;
  823. const name = (iface.name || '').toLowerCase();
  824. const type = (iface.type || '').toLowerCase();
  825. const role = (iface.role || '').toLowerCase();
  826. // Exclude loopback
  827. if (name === 'lo' || type === 'loopback' || role === 'loopback') return false;
  828. // Exclude WireGuard (Layer 3 point-to-point tunnel, no broadcast/DHCP)
  829. if (type === 'wireguard' || name.startsWith('wg')) return false;
  830. // Exclude PPP / PPPoE / L2TP / PPTP tunnels
  831. if (type === 'ppp' || name.startsWith('ppp') || name.startsWith('l2tp') || name.startsWith('pptp')) return false;
  832. // Exclude other Layer 3 tunnels and dummy devices
  833. if (type === 'dummy' || type === 'gre' || type === 'sit' || type === 'tun' || type === 'tap' ||
  834. name.startsWith('gre') || name.startsWith('sit') || name.startsWith('ipsec') || name.startsWith('xfrm') || name.startsWith('dummy')) {
  835. return false;
  836. }
  837. // Exclude bridge member/slave ports (bridge itself handles IP / DHCP)
  838. const isBridgePort = (state.bridgePorts || []).some(bp => bp.interface === iface.name);
  839. if (isBridgePort) return false;
  840. return true;
  841. }
  842. // Expand / Collapse Handlers
  843. function toggleExpand(parentName) {
  844. const childVlans = (state.vlans || []).filter(v => v.parent_name === parentName || v.name.startsWith(parentName + '.'));
  845. if (childVlans.length === 0) {
  846. // Cannot expand an interface with no VLANs
  847. state.expandedParents.delete(parentName);
  848. return;
  849. }
  850. if (state.expandedParents.has(parentName)) {
  851. state.expandedParents.delete(parentName);
  852. } else {
  853. state.expandedParents.add(parentName);
  854. }
  855. renderInterfacesList();
  856. }
  857. function expandAllIfaces(expand) {
  858. if (expand) {
  859. (state.interfaces || []).forEach(i => {
  860. const hasVlans = (state.vlans || []).some(v => v.parent_name === i.name || v.name.startsWith(i.name + '.'));
  861. if (!i.is_vlan && hasVlans) state.expandedParents.add(i.name);
  862. });
  863. } else {
  864. state.expandedParents.clear();
  865. }
  866. renderInterfacesList();
  867. }
  868. // =========================================================================
  869. // INTERFACE ROLE TAGS MANAGEMENT
  870. // =========================================================================
  871. const ROLE_COLORS = {
  872. amber: { bg: 'bg-amber-500/20', text: 'text-amber-300', border: 'border-amber-500/30' },
  873. blue: { bg: 'bg-blue-500/20', text: 'text-blue-300', border: 'border-blue-500/30' },
  874. cyan: { bg: 'bg-cyan-500/20', text: 'text-cyan-300', border: 'border-cyan-500/30' },
  875. emerald: { bg: 'bg-emerald-500/20', text: 'text-emerald-300', border: 'border-emerald-500/30' },
  876. purple: { bg: 'bg-purple-500/20', text: 'text-purple-300', border: 'border-purple-500/30' },
  877. rose: { bg: 'bg-rose-500/20', text: 'text-rose-300', border: 'border-rose-500/30' },
  878. indigo: { bg: 'bg-indigo-500/20', text: 'text-indigo-300', border: 'border-indigo-500/30' },
  879. sky: { bg: 'bg-sky-500/20', text: 'text-sky-300', border: 'border-sky-500/30' },
  880. slate: { bg: 'bg-slate-800', text: 'text-slate-300', border: 'border-slate-700' }
  881. };
  882. function getRoleBadge(roleName) {
  883. const name = roleName || 'LAN';
  884. const role = (state.roles || []).find(r => r.name.toLowerCase() === name.toLowerCase() || r.id.toLowerCase() === name.toLowerCase());
  885. const colorKey = (role?.color || 'blue').toLowerCase();
  886. const theme = ROLE_COLORS[colorKey] || ROLE_COLORS.blue;
  887. 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>`;
  888. }
  889. function switchIfaceSubTab(subTab) {
  890. state.activeIfaceSubTab = subTab;
  891. const treeTab = document.getElementById('ifaces-subtab-tree');
  892. const rolesTab = document.getElementById('ifaces-subtab-roles');
  893. const btnTree = document.getElementById('ifaces-subtab-btn-tree');
  894. const btnRoles = document.getElementById('ifaces-subtab-btn-roles');
  895. if (subTab === 'roles') {
  896. treeTab?.classList.add('hidden');
  897. rolesTab?.classList.remove('hidden');
  898. if (btnRoles) {
  899. 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';
  900. }
  901. if (btnTree) {
  902. 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';
  903. }
  904. loadRoles();
  905. } else {
  906. rolesTab?.classList.add('hidden');
  907. treeTab?.classList.remove('hidden');
  908. if (btnTree) {
  909. 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';
  910. }
  911. if (btnRoles) {
  912. 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';
  913. }
  914. renderInterfacesList();
  915. }
  916. }
  917. async function loadRoles() {
  918. try {
  919. const res = await fetch(`${API_BASE}/roles`);
  920. if (res.ok) {
  921. state.roles = await res.json();
  922. const countEl = document.getElementById('badge-roles-count');
  923. if (countEl) countEl.innerText = (state.roles || []).length;
  924. renderRolesTable();
  925. populateRoleSelects();
  926. }
  927. } catch (err) {
  928. console.error('Failed to load role tags:', err);
  929. }
  930. }
  931. function renderRolesTable() {
  932. const tbody = document.getElementById('roles-table-body');
  933. const empty = document.getElementById('roles-empty-state');
  934. if (!tbody) return;
  935. const roles = state.roles || [];
  936. if (roles.length === 0) {
  937. tbody.innerHTML = '';
  938. empty?.classList.remove('hidden');
  939. return;
  940. }
  941. empty?.classList.add('hidden');
  942. const sig = roles.map(r => `${r.id}:${r.name}:${r.color}:${r.description}:${(r.interfaces||[]).join(',')}`).join(';');
  943. if (tbody.dataset.sig === sig) return;
  944. tbody.dataset.sig = sig;
  945. tbody.innerHTML = roles.map(r => {
  946. const colorKey = (r.color || 'blue').toLowerCase();
  947. const theme = ROLE_COLORS[colorKey] || ROLE_COLORS.blue;
  948. const ifaces = Array.isArray(r.interfaces) ? r.interfaces : [];
  949. const ifacesChips = ifaces.length > 0
  950. ? 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('')
  951. : '<span class="text-slate-600 font-sans text-xs italic">Unassigned (0)</span>';
  952. return `
  953. <tr class="hover:bg-slate-800/40 transition">
  954. <td class="py-3 px-4">
  955. <span class="px-2.5 py-1 rounded text-xs font-semibold ${theme.bg} ${theme.text} border ${theme.border}">
  956. ${escapeHtml(r.name)}
  957. </span>
  958. </td>
  959. <td class="py-3 px-4 font-bold text-white font-mono flex items-center gap-2">
  960. <span>${escapeHtml(r.name)}</span>
  961. ${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>' : ''}
  962. </td>
  963. <td class="py-3 px-4 font-sans capitalize text-slate-300">
  964. <span class="inline-flex items-center gap-1.5">
  965. <span class="w-2 h-2 rounded-full ${theme.bg.replace('/20', '')}"></span>
  966. <span>${escapeHtml(r.color || 'blue')}</span>
  967. </span>
  968. </td>
  969. <td class="py-3 px-4 font-sans text-slate-400 text-xs">${escapeHtml(r.description || '-')}</td>
  970. <td class="py-3 px-4 font-sans">
  971. <div class="flex flex-wrap items-center">
  972. ${ifacesChips}
  973. </div>
  974. </td>
  975. <td class="py-3 px-4 text-right space-x-2 font-sans whitespace-nowrap">
  976. <button onclick="openRoleModal('${escapeHtml(r.id)}')"
  977. class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold px-2 py-1 rounded hover:bg-slate-800 transition">
  978. Edit
  979. </button>
  980. <button onclick="deleteRoleTag('${escapeHtml(r.id)}', '${escapeHtml(r.name)}')"
  981. class="text-xs text-rose-400 hover:text-rose-300 font-semibold px-2 py-1 rounded hover:bg-slate-800 transition">
  982. Delete
  983. </button>
  984. </td>
  985. </tr>
  986. `;
  987. }).join('');
  988. }
  989. function openRoleModal(id = null) {
  990. const modal = document.getElementById('role-modal');
  991. if (!modal) return;
  992. const idInput = document.getElementById('role-modal-id');
  993. const nameInput = document.getElementById('role-modal-name');
  994. const colorSelect = document.getElementById('role-modal-color');
  995. const descInput = document.getElementById('role-modal-desc');
  996. const title = document.getElementById('role-modal-title');
  997. if (id) {
  998. const role = (state.roles || []).find(r => r.id === id);
  999. if (role) {
  1000. if (title) title.innerText = `Edit Role Tag: ${role.name}`;
  1001. if (idInput) idInput.value = role.id;
  1002. if (nameInput) nameInput.value = role.name;
  1003. if (colorSelect) colorSelect.value = role.color || 'blue';
  1004. if (descInput) descInput.value = role.description || '';
  1005. }
  1006. } else {
  1007. if (title) title.innerText = 'Add Role Tag';
  1008. if (idInput) idInput.value = '';
  1009. if (nameInput) nameInput.value = '';
  1010. if (colorSelect) colorSelect.value = 'blue';
  1011. if (descInput) descInput.value = '';
  1012. }
  1013. updateRoleModalPreview();
  1014. modal.classList.remove('hidden');
  1015. }
  1016. function closeRoleModal() {
  1017. const modal = document.getElementById('role-modal');
  1018. if (modal) modal.classList.add('hidden');
  1019. }
  1020. function updateRoleModalPreview() {
  1021. const name = document.getElementById('role-modal-name')?.value.trim() || 'Preview';
  1022. const colorKey = (document.getElementById('role-modal-color')?.value || 'blue').toLowerCase();
  1023. const theme = ROLE_COLORS[colorKey] || ROLE_COLORS.blue;
  1024. const preview = document.getElementById('role-modal-preview');
  1025. if (preview) {
  1026. preview.innerText = name;
  1027. preview.className = `px-2.5 py-1 rounded text-xs font-semibold ${theme.bg} ${theme.text} border ${theme.border}`;
  1028. }
  1029. }
  1030. async function submitSaveRole(e) {
  1031. e.preventDefault();
  1032. const id = document.getElementById('role-modal-id')?.value;
  1033. const name = document.getElementById('role-modal-name')?.value.trim();
  1034. const color = document.getElementById('role-modal-color')?.value;
  1035. const desc = document.getElementById('role-modal-desc')?.value.trim();
  1036. if (!name) return;
  1037. try {
  1038. const payload = { id, name, color, description: desc };
  1039. const method = id ? 'PUT' : 'POST';
  1040. const url = id ? `${API_BASE}/roles/${encodeURIComponent(id)}` : `${API_BASE}/roles`;
  1041. const res = await fetch(url, {
  1042. method,
  1043. headers: { 'Content-Type': 'application/json' },
  1044. body: JSON.stringify(payload)
  1045. });
  1046. if (res.ok) {
  1047. showToast('Role Tag Saved', `Role tag "${name}" saved successfully`, 'success');
  1048. closeRoleModal();
  1049. await loadRoles();
  1050. fetchData(false);
  1051. } else {
  1052. const err = await res.json();
  1053. showToast('Error', err.error || err.message || 'Failed to save role tag', 'error');
  1054. }
  1055. } catch (err) {
  1056. showToast('Error', err.message, 'error');
  1057. }
  1058. }
  1059. async function deleteRoleTag(id, name) {
  1060. if (!confirm(`Are you sure you want to delete role tag "${name}"?\nInterfaces assigned to this role will default to LAN.`)) return;
  1061. try {
  1062. const res = await fetch(`${API_BASE}/roles/${encodeURIComponent(id)}`, {
  1063. method: 'DELETE'
  1064. });
  1065. if (res.ok) {
  1066. showToast('Role Tag Deleted', `Role tag "${name}" removed`, 'success');
  1067. await loadRoles();
  1068. fetchData(false);
  1069. } else {
  1070. const err = await res.json();
  1071. showToast('Error', err.error || err.message || 'Failed to delete role tag', 'error');
  1072. }
  1073. } catch (err) {
  1074. showToast('Error', err.message, 'error');
  1075. }
  1076. }
  1077. function populateRoleSelects(selectedRole = '') {
  1078. const ifaceSelect = document.getElementById('modal-iface-role');
  1079. const vlanSelect = document.getElementById('vlan-role');
  1080. const roles = state.roles || [];
  1081. const optionsHtml = roles.map(r => `<option value="${escapeHtml(r.name)}">${escapeHtml(r.name)}${r.description ? ` (${escapeHtml(r.description)})` : ''}</option>`).join('');
  1082. if (ifaceSelect) {
  1083. const currentVal = selectedRole || ifaceSelect.value || 'LAN';
  1084. if (ifaceSelect.dataset.optionsSig !== optionsHtml) {
  1085. ifaceSelect.innerHTML = optionsHtml;
  1086. ifaceSelect.dataset.optionsSig = optionsHtml;
  1087. }
  1088. if (currentVal) ifaceSelect.value = currentVal;
  1089. }
  1090. if (vlanSelect) {
  1091. const currentVal = selectedRole || vlanSelect.value || 'LAN';
  1092. if (vlanSelect.dataset.optionsSig !== optionsHtml) {
  1093. vlanSelect.innerHTML = optionsHtml;
  1094. vlanSelect.dataset.optionsSig = optionsHtml;
  1095. }
  1096. if (currentVal) vlanSelect.value = currentVal;
  1097. }
  1098. }
  1099. // Filter and Render Hierarchical Interfaces List
  1100. function filterIfaces(filter) {
  1101. state.ifaceFilter = filter || 'all';
  1102. renderInterfacesList();
  1103. }
  1104. function renderInterfacesList() {
  1105. const tbody = document.getElementById('interfaces-tree-tbody');
  1106. const emptyState = document.getElementById('interfaces-empty-state');
  1107. const summary = document.getElementById('ifaces-list-summary');
  1108. const query = (document.getElementById('iface-search')?.value || '').trim().toLowerCase();
  1109. const allIfaces = state.interfaces || [];
  1110. const allVlans = state.vlans || [];
  1111. const parentIfaces = allIfaces.filter(i => !i.is_vlan);
  1112. const filteredParents = parentIfaces.filter(parent => {
  1113. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  1114. if (query) {
  1115. const matchName = parent.name.toLowerCase().includes(query);
  1116. const matchIp = (parent.ipv4 || []).some(ip => ip.toLowerCase().includes(query));
  1117. const matchRole = (parent.role || '').toLowerCase().includes(query);
  1118. const matchType = (parent.type || '').toLowerCase().includes(query);
  1119. const matchVlan = childVlans.some(v =>
  1120. v.name.toLowerCase().includes(query) ||
  1121. String(v.vlan_id).includes(query) ||
  1122. (v.ipv4 || []).some(ip => ip.toLowerCase().includes(query)) ||
  1123. (v.description || '').toLowerCase().includes(query)
  1124. );
  1125. if (!matchName && !matchIp && !matchRole && !matchType && !matchVlan) return false;
  1126. }
  1127. if (state.ifaceFilter === 'has_vlans') return childVlans.length > 0;
  1128. if (state.ifaceFilter === 'physical') return parent.type !== 'loopback';
  1129. if (state.ifaceFilter === 'up') return parent.state === 'UP';
  1130. return true;
  1131. });
  1132. if (summary) {
  1133. summary.innerText = `${parentIfaces.length} Interfaces • ${allVlans.length} Active VLANs`;
  1134. }
  1135. if (filteredParents.length === 0) {
  1136. emptyState?.classList.remove('hidden');
  1137. tbody.innerHTML = '';
  1138. return;
  1139. }
  1140. emptyState?.classList.add('hidden');
  1141. const sig = `${state.ifaceFilter}|${query}|` + filteredParents.map(p => {
  1142. const cVlans = allVlans.filter(v => v.parent_name === p.name || v.name.startsWith(p.name + '.'));
  1143. const dhcp = (state.dhcpClients || []).find(dc => dc.interface === p.name);
  1144. return `${p.name}:${p.state}:${p.role||'LAN'}:${(p.ipv4||[]).join(',')}:${p.mtu}:${cVlans.length}:${state.expandedParents.has(p.name)}:${dhcp?.status || ''}`;
  1145. }).join(';');
  1146. if (tbody.dataset.sig === sig) {
  1147. return; // ZERO changes to structure, links, IPs or VLANs! Do not rebuild DOM!
  1148. }
  1149. tbody.dataset.sig = sig;
  1150. tbody.innerHTML = '';
  1151. filteredParents.forEach(parent => {
  1152. const isUp = parent.state === 'UP';
  1153. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  1154. const hasVlans = childVlans.length > 0;
  1155. const isExpanded = hasVlans && state.expandedParents.has(parent.name);
  1156. const canHaveVlan = supportsVLAN(parent);
  1157. const parentRow = document.createElement('tr');
  1158. parentRow.className = `hover:bg-slate-800/50 transition border-b border-slate-800/80 ${isExpanded ? 'bg-slate-900/80' : ''}`;
  1159. parentRow.innerHTML = `
  1160. <td class="py-3 px-3 text-center">
  1161. ${hasVlans ? `
  1162. <button onclick="toggleExpand('${parent.name}')" title="${isExpanded ? 'Collapse VLANs' : 'Expand VLANs'}"
  1163. class="w-6 h-6 rounded flex items-center justify-center hover:bg-slate-800 text-slate-400 hover:text-white transition">
  1164. <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">
  1165. <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M9 5l7 7-7 7" />
  1166. </svg>
  1167. </button>
  1168. ` : `
  1169. <div class="w-6 h-6 flex items-center justify-center text-slate-700 select-none">
  1170. <span class="w-1.5 h-1.5 rounded-full bg-slate-800"></span>
  1171. </div>
  1172. `}
  1173. </td>
  1174. <td class="py-3 px-4">
  1175. <div class="flex items-center space-x-2.5">
  1176. <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">
  1177. ${parent.type === 'loopback' ? 'LO' : (parent.type === 'wireguard' ? 'WG' : (parent.type === 'bridge' ? 'BR' : 'NIC'))}
  1178. </div>
  1179. <div>
  1180. <div class="flex items-center gap-2">
  1181. <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'}">
  1182. <span>${parent.name}</span>
  1183. <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>
  1184. </span>
  1185. ${hasVlans ? `
  1186. <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>
  1187. ` : `
  1188. <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>
  1189. `}
  1190. </div>
  1191. <div class="text-[10px] text-slate-500 font-sans mt-0.5">${parent.type}</div>
  1192. </div>
  1193. </div>
  1194. </td>
  1195. <td class="py-3 px-4 font-sans">
  1196. <div class="flex items-center gap-1.5">
  1197. ${getRoleBadge(parent.role || 'LAN')}
  1198. <span class="text-xs text-slate-400 truncate max-w-[120px]">${parent.description || '-'}</span>
  1199. </div>
  1200. </td>
  1201. <td class="py-3 px-4">
  1202. ${parent.ipv4 && parent.ipv4.length > 0
  1203. ? `<div class="text-white font-medium">${parent.ipv4[0]}</div>`
  1204. : '<span class="text-slate-600 font-sans">Unassigned</span>'
  1205. }
  1206. ${(() => {
  1207. const c = (state.dhcpClients || []).find(dc => dc.interface === parent.name);
  1208. if (!c) return '';
  1209. 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');
  1210. 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>`;
  1211. })()}
  1212. </td>
  1213. <td class="py-3 px-4 text-slate-400 text-[11px]">
  1214. <div>${parent.mac || 'N/A'}</div>
  1215. <div class="text-[10px] text-slate-500">MTU ${parent.mtu}</div>
  1216. </td>
  1217. <td class="py-3 px-4 text-[11px]">
  1218. <div class="flex items-center space-x-2">
  1219. <span id="iface-rate-rx-${parent.name}" class="text-emerald-400">↓ ${parent.rate?.rx_human || '0 B/s'}</span>
  1220. <span id="iface-rate-tx-${parent.name}" class="text-cyan-400">↑ ${parent.rate?.tx_human || '0 B/s'}</span>
  1221. </div>
  1222. </td>
  1223. <td class="py-3 px-4 font-sans">
  1224. <button onclick="toggleInterfaceState('${parent.name}', '${isUp ? 'down' : 'up'}')"
  1225. class="flex items-center gap-1.5 text-xs font-semibold px-2.5 py-1 rounded-full transition ${
  1226. 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'
  1227. }" title="Click to toggle link status">
  1228. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  1229. <span>${parent.state}</span>
  1230. </button>
  1231. </td>
  1232. <td class="py-3 px-4 text-right space-x-2 font-sans">
  1233. ${(() => {
  1234. const c = (state.dhcpClients || []).find(dc => dc.interface === parent.name);
  1235. if (c) {
  1236. 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>`;
  1237. }
  1238. if (!supportsDHCPClient(parent)) {
  1239. return '';
  1240. }
  1241. 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>`;
  1242. })()}
  1243. ${canHaveVlan ? `
  1244. <button onclick="openVlanModal('${parent.name}')"
  1245. 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">
  1246. + Add VLAN
  1247. </button>
  1248. ` : ''}
  1249. <button onclick="openIfaceModal('${parent.name}')"
  1250. 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">
  1251. Edit
  1252. </button>
  1253. </td>
  1254. `;
  1255. tbody.appendChild(parentRow);
  1256. if (isExpanded) {
  1257. const drawerRow = document.createElement('tr');
  1258. drawerRow.className = 'bg-slate-950/80 border-b border-slate-800/90';
  1259. const drawerCell = document.createElement('td');
  1260. drawerCell.colSpan = 8;
  1261. drawerCell.className = 'p-0';
  1262. drawerCell.innerHTML = `
  1263. <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">
  1264. <div class="flex items-center justify-between mb-3">
  1265. <div class="flex items-center space-x-3">
  1266. <span class="font-bold text-xs text-white uppercase tracking-wider flex items-center gap-1.5 font-sans">
  1267. <span>VLAN Sub-interfaces on <code class="text-cyan-300 lowercase">${parent.name}</code></span>
  1268. </span>
  1269. <span class="text-[11px] bg-cyan-950 text-cyan-400 px-2 py-0.5 rounded-full border border-cyan-800/60 font-mono">
  1270. ${childVlans.length} Attached
  1271. </span>
  1272. </div>
  1273. <button onclick="openVlanModal('${parent.name}')"
  1274. 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">
  1275. <span>+ Create VLAN on ${parent.name}</span>
  1276. </button>
  1277. </div>
  1278. ${childVlans.length === 0 ? `
  1279. <div class="p-6 text-center border border-dashed border-slate-800 rounded-xl bg-slate-900/40 font-sans">
  1280. <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>
  1281. <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">
  1282. <span>+ Create Your First VLAN on ${parent.name}</span>
  1283. </button>
  1284. </div>
  1285. ` : `
  1286. <div class="overflow-x-auto rounded-lg border border-slate-800 bg-slate-900/90 shadow-inner">
  1287. <table class="w-full text-left text-xs font-mono">
  1288. <thead class="text-slate-400 bg-slate-950/70 border-b border-slate-800 uppercase tracking-wider text-[10px] font-sans">
  1289. <tr>
  1290. <th class="py-2.5 px-4">VLAN ID</th>
  1291. <th class="py-2.5 px-4">Interface Device</th>
  1292. <th class="py-2.5 px-4">Subnet Gateway</th>
  1293. <th class="py-2.5 px-4">Role / Alias</th>
  1294. <th class="py-2.5 px-4">MTU</th>
  1295. <th class="py-2.5 px-4">Throughput</th>
  1296. <th class="py-2.5 px-4">Status</th>
  1297. <th class="py-2.5 px-4 text-right">Actions</th>
  1298. </tr>
  1299. </thead>
  1300. <tbody class="divide-y divide-slate-800/70">
  1301. ${childVlans.map(v => {
  1302. const isVlanUp = v.state === 'UP';
  1303. return `
  1304. <tr class="hover:bg-slate-800/40 transition">
  1305. <td class="py-2.5 px-4">
  1306. <span class="px-2 py-0.5 rounded text-xs font-bold bg-cyan-950 text-cyan-300 border border-cyan-800 shadow-sm">
  1307. VLAN ${v.vlan_id}
  1308. </span>
  1309. </td>
  1310. <td class="py-2.5 px-4 font-bold text-white flex items-center gap-1.5">
  1311. <span class="text-cyan-500">└─</span>
  1312. <span class="cursor-pointer hover:text-cyan-400 flex items-center gap-1" onclick="openIfaceModal('${v.name}')" title="Configure / Rename ${v.name}">
  1313. <span>${v.name}</span>
  1314. <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>
  1315. </span>
  1316. </td>
  1317. <td class="py-2.5 px-4 text-emerald-400 font-medium">
  1318. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  1319. ${(() => {
  1320. const c = (state.dhcpClients || []).find(dc => dc.interface === v.name);
  1321. if (!c) return '';
  1322. 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';
  1323. 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>`;
  1324. })()}
  1325. </td>
  1326. <td class="py-2.5 px-4 font-sans text-slate-300">
  1327. <div class="flex items-center gap-1.5">
  1328. ${getRoleBadge(v.role || 'LAN')}
  1329. <span class="text-slate-400 text-xs">${v.description || '-'}</span>
  1330. </div>
  1331. </td>
  1332. <td class="py-2.5 px-4 text-slate-400">${v.mtu}</td>
  1333. <td class="py-2.5 px-4 text-[11px]">
  1334. <span id="vlan-rate-rx-${v.name}" class="text-emerald-400">↓ ${v.rate?.rx_human || '0 B/s'}</span>
  1335. <span id="vlan-rate-tx-${v.name}" class="text-cyan-400 ml-1.5">↑ ${v.rate?.tx_human || '0 B/s'}</span>
  1336. </td>
  1337. <td class="py-2.5 px-4 font-sans">
  1338. <button onclick="toggleInterfaceState('${v.name}', '${isVlanUp ? 'down' : 'up'}')"
  1339. class="flex items-center gap-1 text-[11px] font-semibold px-2 py-0.5 rounded-full ${
  1340. 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'
  1341. }">
  1342. <span class="w-1.5 h-1.5 rounded-full ${isVlanUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  1343. <span>${v.state}</span>
  1344. </button>
  1345. </td>
  1346. <td class="py-2.5 px-4 text-right space-x-1.5 font-sans">
  1347. ${(() => {
  1348. const c = (state.dhcpClients || []).find(dc => dc.interface === v.name);
  1349. if (c) {
  1350. 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>`;
  1351. }
  1352. if (!supportsDHCPClient(v)) {
  1353. return '';
  1354. }
  1355. 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>`;
  1356. })()}
  1357. <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>
  1358. <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>
  1359. </td>
  1360. </tr>
  1361. `;
  1362. }).join('')}
  1363. </tbody>
  1364. </table>
  1365. </div>
  1366. `}
  1367. </div>
  1368. `;
  1369. drawerRow.appendChild(drawerCell);
  1370. tbody.appendChild(drawerRow);
  1371. }
  1372. });
  1373. }
  1374. // Render VLANs Dedicated View
  1375. function renderVlansList() {
  1376. const tbody = document.getElementById('vlans-table-body');
  1377. if (!tbody) return;
  1378. const emptyState = document.getElementById('vlans-empty-state');
  1379. const countBadge = document.getElementById('vlans-table-count');
  1380. const query = (document.getElementById('vlan-search')?.value || '').toLowerCase();
  1381. const allVlans = state.vlans || [];
  1382. if (countBadge) countBadge.innerText = allVlans.length;
  1383. const filtered = allVlans.filter(v => {
  1384. if (!query) return true;
  1385. return v.name.toLowerCase().includes(query) ||
  1386. String(v.vlan_id).includes(query) ||
  1387. (v.description || '').toLowerCase().includes(query) ||
  1388. (v.ipv4 && v.ipv4.some(ip => ip.includes(query)));
  1389. });
  1390. if (allVlans.length === 0) {
  1391. emptyState.classList.remove('hidden');
  1392. tbody.innerHTML = '';
  1393. return;
  1394. }
  1395. emptyState.classList.add('hidden');
  1396. const sig = `${query}|` + filtered.map(v => `${v.name}:${v.state}:${(v.ipv4||[]).join(',')}:${v.vlan_id}:${v.mtu}`).join(';');
  1397. if (tbody.dataset.sig === sig) return;
  1398. tbody.dataset.sig = sig;
  1399. tbody.innerHTML = '';
  1400. filtered.forEach(v => {
  1401. const isUp = v.state === 'UP';
  1402. const tr = document.createElement('tr');
  1403. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  1404. tr.innerHTML = `
  1405. <td class="py-3 px-4">
  1406. <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">
  1407. VLAN ${v.vlan_id}
  1408. </span>
  1409. </td>
  1410. <td class="py-3 px-4 font-bold text-white">
  1411. <span class="cursor-pointer hover:text-cyan-400 flex items-center gap-1.5" onclick="openIfaceModal('${v.name}')" title="Configure / Rename ${v.name}">
  1412. <span>${v.name}</span>
  1413. <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>
  1414. </span>
  1415. </td>
  1416. <td class="py-3 px-4 text-slate-300">
  1417. <span class="bg-slate-800 text-slate-200 px-2 py-0.5 rounded text-[11px]">${v.parent_name || 'eth0'}</span>
  1418. </td>
  1419. <td class="py-3 px-4 text-emerald-400 font-medium">
  1420. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  1421. </td>
  1422. <td class="py-3 px-4 text-slate-300 font-sans">
  1423. <span class="text-slate-400 text-xs">${v.description || v.role || '-'}</span>
  1424. </td>
  1425. <td class="py-3 px-4 text-slate-400">${v.mtu}</td>
  1426. <td class="py-3 px-4 font-sans">
  1427. <button onclick="toggleInterfaceState('${v.name}', '${isUp ? 'down' : 'up'}')"
  1428. class="flex items-center gap-1.5 text-xs font-semibold px-2 py-0.5 rounded-full ${
  1429. 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'
  1430. }">
  1431. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  1432. <span>${v.state}</span>
  1433. </button>
  1434. </td>
  1435. <td class="py-3 px-4 text-right space-x-2 font-sans">
  1436. <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>
  1437. <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>
  1438. </td>
  1439. `;
  1440. tbody.appendChild(tr);
  1441. });
  1442. }
  1443. // Toggle interface UP / DOWN
  1444. async function toggleInterfaceState(name, newState) {
  1445. try {
  1446. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(name)}/state`, {
  1447. method: 'POST',
  1448. headers: { 'Content-Type': 'application/json' },
  1449. body: JSON.stringify({ state: newState })
  1450. });
  1451. const data = await res.json();
  1452. if (res.ok) {
  1453. showToast('Interface Updated', `Interface ${name} is now ${newState.toUpperCase()}`, 'success');
  1454. fetchData(false);
  1455. } else {
  1456. showToast('Error', data.message || 'Failed to toggle interface state', 'error');
  1457. }
  1458. } catch (err) {
  1459. showToast('Error', err.message, 'error');
  1460. }
  1461. }
  1462. // ---------------- MikroTik Flag & Utilities ----------------
  1463. function renderMikroTikFlag(running, disabled) {
  1464. if (running) {
  1465. 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>`;
  1466. }
  1467. if (disabled) {
  1468. 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>`;
  1469. }
  1470. 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>`;
  1471. }
  1472. function copyToClipboard(text, label = 'Text') {
  1473. navigator.clipboard.writeText(text).then(() => {
  1474. showToast('Copied', `${label} copied to clipboard`, 'success');
  1475. }).catch(() => {
  1476. prompt('Copy value:', text);
  1477. });
  1478. }
  1479. // ======================== PPP Profiles Shared Helper ========================
  1480. async function fetchPPPProfilesList() {
  1481. try {
  1482. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`);
  1483. if (res.ok) {
  1484. state.pppProfiles = await res.json();
  1485. }
  1486. } catch (err) {
  1487. console.error('Failed to load PPP profiles:', err);
  1488. }
  1489. }
  1490. function populateProfileSelect(selectId, selectedVal, defaultVal = 'default') {
  1491. const sel = document.getElementById(selectId);
  1492. if (!sel) return;
  1493. const profiles = (state.pppProfiles && state.pppProfiles.length > 0) ? state.pppProfiles : [
  1494. { name: 'default', use_encryption: 'no' },
  1495. { name: 'default-encryption', use_encryption: 'required' }
  1496. ];
  1497. sel.innerHTML = '';
  1498. profiles.forEach(p => {
  1499. const opt = document.createElement('option');
  1500. opt.value = p.name;
  1501. const encBadge = p.use_encryption === 'required' ? ' (MPPE-128)' : (p.use_encryption === 'yes' ? ' (MPPE)' : '');
  1502. opt.innerText = `${p.name}${encBadge}`;
  1503. sel.appendChild(opt);
  1504. });
  1505. if (selectedVal) {
  1506. sel.value = selectedVal;
  1507. } else {
  1508. sel.value = defaultVal;
  1509. }
  1510. if (!sel.value && sel.options.length > 0) {
  1511. sel.selectedIndex = 0;
  1512. }
  1513. }
  1514. // ======================== PPPoE Multi-Instance ========================
  1515. async function loadPPPoE(populateInputs = true) {
  1516. try {
  1517. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  1518. await fetchPPPProfilesList();
  1519. }
  1520. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`);
  1521. const list = await res.json();
  1522. state.pppoeList = Array.isArray(list) ? list : [];
  1523. const badge = document.getElementById('pppoe-count-badge');
  1524. if (badge) badge.innerText = `${state.pppoeList.length} Interface${state.pppoeList.length !== 1 ? 's' : ''}`;
  1525. const tbody = document.getElementById('pppoe-table-body');
  1526. const empty = document.getElementById('pppoe-empty');
  1527. if (!tbody) return;
  1528. tbody.innerHTML = '';
  1529. if (state.pppoeList.length === 0) {
  1530. if (empty) empty.classList.remove('hidden');
  1531. } else {
  1532. if (empty) empty.classList.add('hidden');
  1533. state.pppoeList.forEach(inst => {
  1534. const tr = document.createElement('tr');
  1535. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1536. tr.innerHTML = `
  1537. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  1538. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  1539. <td class="py-2.5 px-3 text-cyan-400 font-mono">${escapeHtml(inst.interface)}</td>
  1540. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  1541. <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>
  1542. <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>
  1543. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  1544. <td class="py-2.5 px-3 text-center">
  1545. <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'}">
  1546. ${inst.default_route ? 'Yes' : 'No'}
  1547. </span>
  1548. </td>
  1549. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  1550. ${inst.running ? `
  1551. <button onclick="disconnectPPPoEInstance('${inst.name}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  1552. ` : `
  1553. <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>
  1554. `}
  1555. <button onclick="togglePPPoEState('${inst.name}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  1556. ${inst.disabled ? 'Enable' : 'Disable'}
  1557. </button>
  1558. <button onclick="openEditPPPoEModal('${inst.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  1559. <button onclick="deletePPPoEInstance('${inst.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  1560. </td>
  1561. `;
  1562. tbody.appendChild(tr);
  1563. });
  1564. }
  1565. } catch (err) {
  1566. console.error('Failed to load PPPoE:', err);
  1567. }
  1568. }
  1569. function openAddPPPoEModal() {
  1570. document.getElementById('pppoe-modal-title').innerText = 'Add PPPoE Client Interface';
  1571. document.getElementById('pppoe-modal-edit-orig').value = '';
  1572. document.getElementById('pppoe-modal-name').value = `pppoe-out${(state.pppoeList || []).length + 1}`;
  1573. document.getElementById('pppoe-modal-name').readOnly = false;
  1574. document.getElementById('pppoe-modal-user').value = '';
  1575. document.getElementById('pppoe-modal-pass').value = '';
  1576. document.getElementById('pppoe-modal-service').value = '';
  1577. document.getElementById('pppoe-modal-mtu').value = '1492';
  1578. document.getElementById('pppoe-modal-defroute').checked = true;
  1579. document.getElementById('pppoe-modal-reconnect').checked = true;
  1580. document.getElementById('pppoe-modal-disabled').checked = false;
  1581. // Populate profiles
  1582. populateProfileSelect('pppoe-modal-profile', 'default', 'default');
  1583. // Populate interfaces
  1584. const sel = document.getElementById('pppoe-modal-iface');
  1585. sel.innerHTML = '';
  1586. (state.interfaces || []).forEach(i => {
  1587. if (i.name === 'lo') return;
  1588. const opt = document.createElement('option');
  1589. opt.value = i.name;
  1590. opt.innerText = `${i.name} (${i.role || i.type})`;
  1591. sel.appendChild(opt);
  1592. });
  1593. document.getElementById('pppoe-modal').classList.remove('hidden');
  1594. }
  1595. function openEditPPPoEModal(name) {
  1596. const inst = (state.pppoeList || []).find(i => i.name === name);
  1597. if (!inst) return;
  1598. document.getElementById('pppoe-modal-title').innerText = `Edit PPPoE Client: ${name}`;
  1599. document.getElementById('pppoe-modal-edit-orig').value = name;
  1600. document.getElementById('pppoe-modal-name').value = inst.name;
  1601. document.getElementById('pppoe-modal-name').readOnly = true;
  1602. document.getElementById('pppoe-modal-user').value = inst.username || '';
  1603. document.getElementById('pppoe-modal-pass').value = inst.password || '';
  1604. document.getElementById('pppoe-modal-service').value = inst.service_name || '';
  1605. document.getElementById('pppoe-modal-mtu').value = inst.mtu || 1492;
  1606. document.getElementById('pppoe-modal-defroute').checked = inst.default_route ?? true;
  1607. document.getElementById('pppoe-modal-reconnect').checked = inst.auto_reconnect ?? true;
  1608. document.getElementById('pppoe-modal-disabled').checked = !!inst.disabled;
  1609. // Populate profiles
  1610. populateProfileSelect('pppoe-modal-profile', inst.profile || 'default', 'default');
  1611. const sel = document.getElementById('pppoe-modal-iface');
  1612. sel.innerHTML = '';
  1613. (state.interfaces || []).forEach(i => {
  1614. if (i.name === 'lo') return;
  1615. const opt = document.createElement('option');
  1616. opt.value = i.name;
  1617. opt.innerText = `${i.name} (${i.role || i.type})`;
  1618. if (i.name === inst.interface) opt.selected = true;
  1619. sel.appendChild(opt);
  1620. });
  1621. document.getElementById('pppoe-modal').classList.remove('hidden');
  1622. }
  1623. function closePPPoEModal() {
  1624. document.getElementById('pppoe-modal').classList.add('hidden');
  1625. }
  1626. async function submitSavePPPoE(e) {
  1627. e.preventDefault();
  1628. const name = document.getElementById('pppoe-modal-name').value.trim();
  1629. const iface = document.getElementById('pppoe-modal-iface').value;
  1630. const user = document.getElementById('pppoe-modal-user').value.trim();
  1631. const pass = document.getElementById('pppoe-modal-pass').value;
  1632. const profile = document.getElementById('pppoe-modal-profile')?.value || 'default';
  1633. const service = document.getElementById('pppoe-modal-service').value.trim();
  1634. const mtu = parseInt(document.getElementById('pppoe-modal-mtu').value, 10) || 1492;
  1635. const defRoute = document.getElementById('pppoe-modal-defroute').checked;
  1636. const reconnect = document.getElementById('pppoe-modal-reconnect').checked;
  1637. const disabled = document.getElementById('pppoe-modal-disabled').checked;
  1638. try {
  1639. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`, {
  1640. method: 'POST',
  1641. headers: { 'Content-Type': 'application/json' },
  1642. body: JSON.stringify({
  1643. name,
  1644. interface: iface,
  1645. username: user,
  1646. password: pass,
  1647. profile: profile,
  1648. service_name: service,
  1649. mtu,
  1650. default_route: defRoute,
  1651. auto_reconnect: reconnect,
  1652. disabled
  1653. })
  1654. });
  1655. if (res.ok) {
  1656. showToast('PPPoE Saved', `Configuration for ${name} saved`, 'success');
  1657. closePPPoEModal();
  1658. loadPPPoE(false);
  1659. fetchData(false);
  1660. } else {
  1661. const err = await res.json();
  1662. showToast('Error', err.message || 'Failed to save PPPoE', 'error');
  1663. }
  1664. } catch (err) {
  1665. showToast('Error', err.message, 'error');
  1666. }
  1667. }
  1668. async function connectPPPoEInstance(name) {
  1669. try {
  1670. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  1671. if (res.ok) {
  1672. showToast('Connecting', `Dialing ${name}...`, 'info');
  1673. setTimeout(() => loadPPPoE(false), 2000);
  1674. }
  1675. } catch (err) {
  1676. showToast('Error', err.message, 'error');
  1677. }
  1678. }
  1679. async function disconnectPPPoEInstance(name) {
  1680. try {
  1681. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  1682. if (res.ok) {
  1683. showToast('Disconnected', `${name} session terminated`, 'info');
  1684. setTimeout(() => loadPPPoE(false), 1000);
  1685. }
  1686. } catch (err) {
  1687. showToast('Error', err.message, 'error');
  1688. }
  1689. }
  1690. async function togglePPPoEState(name, enable) {
  1691. try {
  1692. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/state`, {
  1693. method: 'POST',
  1694. headers: { 'Content-Type': 'application/json' },
  1695. body: JSON.stringify({ enabled: enable })
  1696. });
  1697. if (res.ok) {
  1698. showToast(enable ? 'Enabled' : 'Disabled', `${name} is now ${enable ? 'enabled' : 'disabled'}`, 'info');
  1699. loadPPPoE(false);
  1700. }
  1701. } catch (err) {
  1702. showToast('Error', err.message, 'error');
  1703. }
  1704. }
  1705. async function deletePPPoEInstance(name) {
  1706. if (!confirm(`Are you sure you want to delete PPPoE client ${name}?`)) return;
  1707. try {
  1708. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1709. if (res.ok) {
  1710. showToast('Deleted', `PPPoE client ${name} removed`, 'success');
  1711. loadPPPoE(false);
  1712. fetchData(false);
  1713. }
  1714. } catch (err) {
  1715. showToast('Error', err.message, 'error');
  1716. }
  1717. }
  1718. // ======================== WireGuard Multi-Interface & Multi-Peer ========================
  1719. state.wgSubTab = 'ifaces';
  1720. function switchWGSubTab(tab) {
  1721. state.wgSubTab = tab;
  1722. const ifacesPanel = document.getElementById('wg-subtab-ifaces');
  1723. const peersPanel = document.getElementById('wg-subtab-peers');
  1724. const ifacesBtn = document.getElementById('wg-subtab-btn-ifaces');
  1725. const peersBtn = document.getElementById('wg-subtab-btn-peers');
  1726. if (tab === 'ifaces') {
  1727. ifacesPanel?.classList.remove('hidden');
  1728. peersPanel?.classList.add('hidden');
  1729. 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';
  1730. 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';
  1731. } else {
  1732. ifacesPanel?.classList.add('hidden');
  1733. peersPanel?.classList.remove('hidden');
  1734. 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';
  1735. 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';
  1736. renderWGPeers();
  1737. }
  1738. }
  1739. async function loadWireGuard(populateInputs = true) {
  1740. try {
  1741. const [ifacesRes, peersRes] = await Promise.all([
  1742. fetch(`${API_BASE}/vpn/wireguard/interfaces`),
  1743. fetch(`${API_BASE}/vpn/wireguard/peers`)
  1744. ]);
  1745. const ifaces = ifacesRes.ok ? await ifacesRes.json() : [];
  1746. const peers = peersRes.ok ? await peersRes.json() : [];
  1747. state.wgInterfaces = Array.isArray(ifaces) ? ifaces : [];
  1748. state.wgPeers = Array.isArray(peers) ? peers : [];
  1749. // Badges
  1750. const ifacesCountBadge = document.getElementById('wg-ifaces-count');
  1751. if (ifacesCountBadge) ifacesCountBadge.innerText = `${state.wgInterfaces.length} Interfaces`;
  1752. const peersCountBadge = document.getElementById('wg-peers-count');
  1753. if (peersCountBadge) peersCountBadge.innerText = `${state.wgPeers.length} Peers`;
  1754. const subTabIfaces = document.getElementById('wg-subtab-badge-ifaces');
  1755. if (subTabIfaces) subTabIfaces.innerText = state.wgInterfaces.length;
  1756. const subTabPeers = document.getElementById('wg-subtab-badge-peers');
  1757. if (subTabPeers) subTabPeers.innerText = state.wgPeers.length;
  1758. // Render Interfaces
  1759. const ifacesTbody = document.getElementById('wg-ifaces-table-body');
  1760. const ifacesEmpty = document.getElementById('wg-ifaces-empty');
  1761. if (ifacesTbody) {
  1762. ifacesTbody.innerHTML = '';
  1763. if (state.wgInterfaces.length === 0) {
  1764. if (ifacesEmpty) ifacesEmpty.classList.remove('hidden');
  1765. } else {
  1766. if (ifacesEmpty) ifacesEmpty.classList.add('hidden');
  1767. state.wgInterfaces.forEach(iface => {
  1768. const peersOnIface = state.wgPeers.filter(p => p.interface === iface.name).length;
  1769. const tr = document.createElement('tr');
  1770. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1771. tr.innerHTML = `
  1772. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(iface.running, iface.disabled)}</td>
  1773. <td class="py-2.5 px-3">
  1774. <div class="flex items-center gap-1.5">
  1775. <span class="font-bold text-white">${escapeHtml(iface.name)}</span>
  1776. ${iface.comment ? `<span class="text-[10px] text-slate-400 font-sans italic">(${escapeHtml(iface.comment)})</span>` : ''}
  1777. </div>
  1778. </td>
  1779. <td class="py-2.5 px-3 text-amber-400 font-mono">${iface.listen_port}</td>
  1780. <td class="py-2.5 px-3 text-emerald-400 font-mono">${iface.address || '<span class="text-slate-600 font-sans">--</span>'}</td>
  1781. <td class="py-2.5 px-3 text-slate-300 font-mono">
  1782. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${iface.public_key}', 'Public Key')" title="Click to copy: ${iface.public_key}">
  1783. ${(iface.public_key || '').substring(0, 10)}... 📋
  1784. </span>
  1785. </td>
  1786. <td class="py-2.5 px-3 text-slate-400 font-mono">${iface.mtu || 1420}</td>
  1787. <td class="py-2.5 px-3 text-center">
  1788. <span class="px-2 py-0.5 rounded text-[10px] font-sans bg-slate-800 text-slate-300">${peersOnIface} peer${peersOnIface !== 1 ? 's' : ''}</span>
  1789. </td>
  1790. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  1791. ${iface.running ? `
  1792. <button onclick="stopWGInterface('${iface.name}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Stop</button>
  1793. ` : `
  1794. <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>
  1795. `}
  1796. <button onclick="toggleWGInterfaceState('${iface.name}', ${iface.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white font-medium">
  1797. ${iface.disabled ? 'Enable' : 'Disable'}
  1798. </button>
  1799. <button onclick="openEditWGInterfaceModal('${iface.name}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Edit</button>
  1800. <button onclick="deleteWGInterface('${iface.name}')" class="text-xs text-slate-500 hover:text-rose-400 font-medium">Delete</button>
  1801. </td>
  1802. `;
  1803. ifacesTbody.appendChild(tr);
  1804. });
  1805. }
  1806. }
  1807. // Populate filter dropdown in peers tab
  1808. const filterSel = document.getElementById('wg-peers-filter-iface');
  1809. if (filterSel) {
  1810. const currentVal = filterSel.value;
  1811. filterSel.innerHTML = '<option value="">All Interfaces</option>';
  1812. state.wgInterfaces.forEach(i => {
  1813. const opt = document.createElement('option');
  1814. opt.value = i.name;
  1815. opt.innerText = i.name;
  1816. if (i.name === currentVal) opt.selected = true;
  1817. filterSel.appendChild(opt);
  1818. });
  1819. }
  1820. renderWGPeers();
  1821. } catch (err) {
  1822. console.error('Failed to load WireGuard:', err);
  1823. }
  1824. }
  1825. function formatWGPeerEndpoint(address, port) {
  1826. if (!address || address === '(none)') return '--';
  1827. let addr = address.trim();
  1828. let p = port || 0;
  1829. while (addr.includes(':') && !addr.startsWith('[')) {
  1830. const lastColon = addr.lastIndexOf(':');
  1831. const maybePort = addr.substring(lastColon + 1);
  1832. if (!isNaN(parseInt(maybePort, 10)) && parseInt(maybePort, 10) > 0) {
  1833. if (!p) p = parseInt(maybePort, 10);
  1834. addr = addr.substring(0, lastColon);
  1835. } else {
  1836. break;
  1837. }
  1838. }
  1839. return p ? `${addr}:${p}` : addr;
  1840. }
  1841. function renderWGPeers() {
  1842. const filterSel = document.getElementById('wg-peers-filter-iface');
  1843. const selectedIface = filterSel ? filterSel.value : '';
  1844. const tbody = document.getElementById('wg-peers-table-body');
  1845. const empty = document.getElementById('wg-peers-empty');
  1846. if (!tbody) return;
  1847. tbody.innerHTML = '';
  1848. const filtered = selectedIface ? state.wgPeers.filter(p => p.interface === selectedIface) : state.wgPeers;
  1849. if (filtered.length === 0) {
  1850. if (empty) empty.classList.remove('hidden');
  1851. } else {
  1852. if (empty) empty.classList.add('hidden');
  1853. filtered.forEach(p => {
  1854. const isOnline = p.latest_handshake && !p.latest_handshake.includes('Never');
  1855. const tr = document.createElement('tr');
  1856. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1857. tr.innerHTML = `
  1858. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(isOnline, p.disabled)}</td>
  1859. <td class="py-2.5 px-3 font-mono font-bold text-rose-400">${escapeHtml(p.interface)}</td>
  1860. <td class="py-2.5 px-3 font-bold text-white font-sans">${escapeHtml(p.name || 'Unnamed')}</td>
  1861. <td class="py-2.5 px-3 text-slate-300 font-mono">
  1862. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${p.public_key}', 'Peer Public Key')" title="${p.public_key}">
  1863. ${(p.public_key || '').substring(0, 10)}... 📋
  1864. </span>
  1865. </td>
  1866. <td class="py-2.5 px-3 text-emerald-400 font-mono font-semibold">${(p.allowed_ips || []).join(', ')}</td>
  1867. <td class="py-2.5 px-3 text-slate-400 font-mono">${formatWGPeerEndpoint(p.endpoint_address, p.endpoint_port)}</td>
  1868. <td class="py-2.5 px-3 text-slate-300 font-sans">${p.latest_handshake || 'Never'}</td>
  1869. <td class="py-2.5 px-3 font-mono text-[11px]">
  1870. <span class="text-emerald-400">↓ ${p.transfer_rx_human || '0 B'}</span>
  1871. <span class="text-cyan-400 ml-1">↑ ${p.transfer_tx_human || '0 B'}</span>
  1872. </td>
  1873. <td class="py-2.5 px-3 text-right font-sans space-x-2 whitespace-nowrap">
  1874. <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">
  1875. ${p.disabled ? 'Enable' : 'Disable'}
  1876. </button>
  1877. <button onclick="openEditWGPeerModal('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Edit</button>
  1878. <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>
  1879. <button onclick="deleteWGPeer('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Delete</button>
  1880. </td>
  1881. `;
  1882. tbody.appendChild(tr);
  1883. });
  1884. }
  1885. }
  1886. function openAddWGInterfaceModal() {
  1887. document.getElementById('wg-iface-modal-title').innerText = 'Add WireGuard Interface';
  1888. document.getElementById('wg-iface-modal-edit-orig').value = '';
  1889. const nameEl = document.getElementById('wg-iface-modal-name');
  1890. nameEl.value = `wg${(state.wgInterfaces || []).length}`;
  1891. nameEl.readOnly = false;
  1892. document.getElementById('wg-iface-modal-port').value = 51820 + (state.wgInterfaces || []).length;
  1893. document.getElementById('wg-iface-modal-addr').value = `10.${10 + (state.wgInterfaces || []).length}.0.1/24`;
  1894. document.getElementById('wg-iface-modal-mtu').value = '1420';
  1895. document.getElementById('wg-iface-modal-comment').value = '';
  1896. document.getElementById('wg-iface-modal-pubkey').value = '';
  1897. document.getElementById('wg-iface-modal-privkey').value = '';
  1898. document.getElementById('wg-iface-modal-disabled').checked = false;
  1899. generateWGInterfaceKeys();
  1900. document.getElementById('wg-iface-modal').classList.remove('hidden');
  1901. }
  1902. function openEditWGInterfaceModal(name) {
  1903. const iface = (state.wgInterfaces || []).find(i => i.name === name);
  1904. if (!iface) return;
  1905. document.getElementById('wg-iface-modal-title').innerText = `Edit WireGuard Interface: ${name}`;
  1906. document.getElementById('wg-iface-modal-edit-orig').value = name;
  1907. const nameEl = document.getElementById('wg-iface-modal-name');
  1908. nameEl.value = iface.name;
  1909. nameEl.readOnly = false; // ALLOW RENAMING
  1910. document.getElementById('wg-iface-modal-port').value = iface.listen_port || 51820;
  1911. document.getElementById('wg-iface-modal-addr').value = iface.address || '';
  1912. document.getElementById('wg-iface-modal-mtu').value = iface.mtu || 1420;
  1913. document.getElementById('wg-iface-modal-comment').value = iface.comment || '';
  1914. document.getElementById('wg-iface-modal-pubkey').value = iface.public_key || '';
  1915. document.getElementById('wg-iface-modal-privkey').value = iface.private_key || '';
  1916. document.getElementById('wg-iface-modal-disabled').checked = !!iface.disabled;
  1917. document.getElementById('wg-iface-modal').classList.remove('hidden');
  1918. }
  1919. function closeAddWGInterfaceModal() {
  1920. document.getElementById('wg-iface-modal').classList.add('hidden');
  1921. }
  1922. async function generateWGInterfaceKeys() {
  1923. try {
  1924. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  1925. const keys = await res.json();
  1926. if (res.ok) {
  1927. document.getElementById('wg-iface-modal-privkey').value = keys.private_key;
  1928. document.getElementById('wg-iface-modal-pubkey').value = keys.public_key;
  1929. }
  1930. } catch (err) {
  1931. showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
  1932. }
  1933. }
  1934. async function onWGInterfacePrivKeyInput() {
  1935. const privKey = document.getElementById('wg-iface-modal-privkey').value.trim();
  1936. if (!privKey) return;
  1937. try {
  1938. const res = await fetch(`${API_BASE}/vpn/wireguard/calc-pubkey`, {
  1939. method: 'POST',
  1940. headers: { 'Content-Type': 'application/json' },
  1941. body: JSON.stringify({ private_key: privKey })
  1942. });
  1943. if (res.ok) {
  1944. const data = await res.json();
  1945. if (data.public_key) {
  1946. document.getElementById('wg-iface-modal-pubkey').value = data.public_key;
  1947. }
  1948. }
  1949. } catch (err) {
  1950. // Ignore while typing
  1951. }
  1952. }
  1953. function toggleWGPrivKeyVisibility() {
  1954. const el = document.getElementById('wg-iface-modal-privkey');
  1955. const btn = document.getElementById('btn-toggle-wg-privkey');
  1956. if (el.type === 'password') {
  1957. el.type = 'text';
  1958. btn.innerText = '🙈 Hide';
  1959. } else {
  1960. el.type = 'password';
  1961. btn.innerText = '👁️ Show';
  1962. }
  1963. }
  1964. function copyWGInterfacePubKey() {
  1965. const pub = document.getElementById('wg-iface-modal-pubkey').value;
  1966. if (pub) copyToClipboard(pub, 'Interface Public Key');
  1967. }
  1968. async function submitSaveWGInterface(e) {
  1969. e.preventDefault();
  1970. const origName = document.getElementById('wg-iface-modal-edit-orig').value.trim();
  1971. const name = document.getElementById('wg-iface-modal-name').value.trim();
  1972. const port = parseInt(document.getElementById('wg-iface-modal-port').value, 10) || 51820;
  1973. const addr = document.getElementById('wg-iface-modal-addr').value.trim();
  1974. const mtu = parseInt(document.getElementById('wg-iface-modal-mtu').value, 10) || 1420;
  1975. const comment = document.getElementById('wg-iface-modal-comment').value.trim();
  1976. const pub = document.getElementById('wg-iface-modal-pubkey').value.trim();
  1977. const priv = document.getElementById('wg-iface-modal-privkey').value.trim();
  1978. const disabled = document.getElementById('wg-iface-modal-disabled').checked;
  1979. try {
  1980. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces`, {
  1981. method: 'POST',
  1982. headers: { 'Content-Type': 'application/json' },
  1983. body: JSON.stringify({
  1984. orig_name: origName,
  1985. name,
  1986. listen_port: port,
  1987. address: addr,
  1988. mtu,
  1989. comment,
  1990. public_key: pub,
  1991. private_key: priv,
  1992. disabled
  1993. })
  1994. });
  1995. const data = await res.json();
  1996. if (res.ok) {
  1997. showToast('WireGuard Saved', `Interface ${name} configured successfully`, 'success');
  1998. closeAddWGInterfaceModal();
  1999. loadWireGuard(false);
  2000. fetchData(false);
  2001. } else {
  2002. showToast('Error', data.error || 'Failed to save interface', 'error');
  2003. }
  2004. } catch (err) {
  2005. showToast('Error', err.message, 'error');
  2006. }
  2007. }
  2008. async function startWGInterface(name) {
  2009. try {
  2010. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/start`, { method: 'POST' });
  2011. if (res.ok) {
  2012. showToast('Interface UP', `Started WireGuard interface ${name}`, 'success');
  2013. loadWireGuard(false);
  2014. fetchData(false);
  2015. }
  2016. } catch (err) {
  2017. showToast('Error', err.message, 'error');
  2018. }
  2019. }
  2020. async function stopWGInterface(name) {
  2021. try {
  2022. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  2023. if (res.ok) {
  2024. showToast('Interface DOWN', `Stopped WireGuard interface ${name}`, 'info');
  2025. loadWireGuard(false);
  2026. fetchData(false);
  2027. }
  2028. } catch (err) {
  2029. showToast('Error', err.message, 'error');
  2030. }
  2031. }
  2032. async function toggleWGInterfaceState(name, enable) {
  2033. try {
  2034. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/state`, {
  2035. method: 'POST',
  2036. headers: { 'Content-Type': 'application/json' },
  2037. body: JSON.stringify({ enabled: enable })
  2038. });
  2039. if (res.ok) {
  2040. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  2041. loadWireGuard(false);
  2042. fetchData(false);
  2043. }
  2044. } catch (err) {
  2045. showToast('Error', err.message, 'error');
  2046. }
  2047. }
  2048. async function deleteWGInterface(name) {
  2049. if (!confirm(`Are you sure you want to delete WireGuard interface ${name}? All associated peers will also be removed.`)) return;
  2050. try {
  2051. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2052. if (res.ok) {
  2053. showToast('Deleted', `Interface ${name} removed`, 'success');
  2054. loadWireGuard(false);
  2055. fetchData(false);
  2056. }
  2057. } catch (err) {
  2058. showToast('Error', err.message, 'error');
  2059. }
  2060. }
  2061. function populateWGPeerIfaceSelect(selectedIface = '') {
  2062. const sel = document.getElementById('wg-peer-modal-iface');
  2063. if (!sel) return;
  2064. sel.innerHTML = '';
  2065. (state.wgInterfaces || []).forEach(i => {
  2066. const opt = document.createElement('option');
  2067. opt.value = i.name;
  2068. opt.innerText = `${i.name} (${i.address || 'No IP'})`;
  2069. if (i.name === selectedIface) opt.selected = true;
  2070. sel.appendChild(opt);
  2071. });
  2072. }
  2073. function openAddWGPeerModal() {
  2074. if ((state.wgInterfaces || []).length === 0) {
  2075. showToast('No Interfaces', 'Please add a WireGuard interface first before adding peers', 'warning');
  2076. openAddWGInterfaceModal();
  2077. return;
  2078. }
  2079. document.getElementById('wg-peer-modal-title').innerText = 'Add WireGuard Peer';
  2080. document.getElementById('wg-peer-modal-edit-orig-iface').value = '';
  2081. document.getElementById('wg-peer-modal-edit-orig-pubkey').value = '';
  2082. populateWGPeerIfaceSelect();
  2083. document.getElementById('wg-peer-modal-name').value = '';
  2084. document.getElementById('wg-peer-modal-pubkey').value = '';
  2085. document.getElementById('wg-peer-modal-allowedips').value = '10.10.0.2/32';
  2086. document.getElementById('wg-peer-modal-endpoint').value = '';
  2087. document.getElementById('wg-peer-modal-port').value = '';
  2088. document.getElementById('wg-peer-modal-keepalive').value = '25';
  2089. document.getElementById('wg-peer-modal-preshared').value = '';
  2090. document.getElementById('wg-peer-modal-disabled').checked = false;
  2091. document.getElementById('wg-peer-key-warning').classList.add('hidden');
  2092. document.getElementById('wg-peer-gen-key-box').classList.add('hidden');
  2093. document.getElementById('wg-peer-modal').classList.remove('hidden');
  2094. }
  2095. function openEditWGPeerModal(ifaceName, pubKey) {
  2096. const peer = (state.wgPeers || []).find(p => p.interface === ifaceName && p.public_key === pubKey);
  2097. if (!peer) {
  2098. showToast('Not Found', 'Peer not found', 'warning');
  2099. return;
  2100. }
  2101. document.getElementById('wg-peer-modal-title').innerText = `Edit WireGuard Peer (${peer.name || ifaceName})`;
  2102. document.getElementById('wg-peer-modal-edit-orig-iface').value = peer.interface;
  2103. document.getElementById('wg-peer-modal-edit-orig-pubkey').value = peer.public_key;
  2104. populateWGPeerIfaceSelect(peer.interface);
  2105. document.getElementById('wg-peer-modal-name').value = peer.name || '';
  2106. document.getElementById('wg-peer-modal-pubkey').value = peer.public_key || '';
  2107. document.getElementById('wg-peer-modal-allowedips').value = (peer.allowed_ips || []).join(', ');
  2108. let epHost = (peer.endpoint_address || '').trim();
  2109. let epPort = peer.endpoint_port || '';
  2110. while (epHost.includes(':') && !epHost.startsWith('[')) {
  2111. const lastColon = epHost.lastIndexOf(':');
  2112. const maybePort = epHost.substring(lastColon + 1);
  2113. if (!isNaN(parseInt(maybePort, 10)) && parseInt(maybePort, 10) > 0) {
  2114. if (!epPort) epPort = parseInt(maybePort, 10);
  2115. epHost = epHost.substring(0, lastColon);
  2116. } else {
  2117. break;
  2118. }
  2119. }
  2120. document.getElementById('wg-peer-modal-endpoint').value = epHost;
  2121. document.getElementById('wg-peer-modal-port').value = epPort;
  2122. document.getElementById('wg-peer-modal-keepalive').value = peer.persistent_keepalive ?? 25;
  2123. document.getElementById('wg-peer-modal-preshared').value = peer.preshared_key || '';
  2124. document.getElementById('wg-peer-modal-disabled').checked = !!peer.disabled;
  2125. document.getElementById('wg-peer-key-warning').classList.add('hidden');
  2126. document.getElementById('wg-peer-gen-key-box').classList.add('hidden');
  2127. document.getElementById('wg-peer-modal').classList.remove('hidden');
  2128. }
  2129. function closeAddWGPeerModal() {
  2130. document.getElementById('wg-peer-modal').classList.add('hidden');
  2131. }
  2132. async function generatePeerKeypairHelper() {
  2133. try {
  2134. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  2135. const keys = await res.json();
  2136. if (res.ok) {
  2137. document.getElementById('wg-peer-modal-pubkey').value = keys.public_key;
  2138. document.getElementById('wg-peer-gen-privkey').value = keys.private_key;
  2139. document.getElementById('wg-peer-gen-key-box').classList.remove('hidden');
  2140. checkWGPeerKeyValidity();
  2141. showToast('Keypair Generated', 'Public key inserted and client private key ready to copy', 'info');
  2142. }
  2143. } catch (err) {
  2144. showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
  2145. }
  2146. }
  2147. function copyGeneratedPeerPrivKey() {
  2148. const priv = document.getElementById('wg-peer-gen-privkey').value;
  2149. if (priv) copyToClipboard(priv, 'Client Private Key');
  2150. }
  2151. async function generatePeerPSK() {
  2152. try {
  2153. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  2154. const keys = await res.json();
  2155. if (res.ok && keys.private_key) {
  2156. document.getElementById('wg-peer-modal-preshared').value = keys.private_key;
  2157. showToast('PSK Generated', 'Generated 256-bit preshared key', 'info');
  2158. }
  2159. } catch (err) {
  2160. showToast('Error', err.message, 'error');
  2161. }
  2162. }
  2163. function checkWGPeerKeyValidity() {
  2164. const ifaceName = document.getElementById('wg-peer-modal-iface').value;
  2165. const peerPubKey = document.getElementById('wg-peer-modal-pubkey').value.trim();
  2166. const warningEl = document.getElementById('wg-peer-key-warning');
  2167. if (!warningEl) return;
  2168. const targetIface = (state.wgInterfaces || []).find(i => i.name === ifaceName);
  2169. if (targetIface && targetIface.public_key && peerPubKey && targetIface.public_key === peerPubKey) {
  2170. warningEl.classList.remove('hidden');
  2171. } else {
  2172. warningEl.classList.add('hidden');
  2173. }
  2174. }
  2175. async function submitSaveWGPeer(e) {
  2176. e.preventDefault();
  2177. const origIface = document.getElementById('wg-peer-modal-edit-orig-iface').value.trim();
  2178. const origPubKey = document.getElementById('wg-peer-modal-edit-orig-pubkey').value.trim();
  2179. const iface = document.getElementById('wg-peer-modal-iface').value;
  2180. const name = document.getElementById('wg-peer-modal-name').value.trim();
  2181. const pub = document.getElementById('wg-peer-modal-pubkey').value.trim();
  2182. const allowed = document.getElementById('wg-peer-modal-allowedips').value
  2183. .split(',')
  2184. .map(s => s.trim())
  2185. .filter(s => s.length > 0);
  2186. let epHost = document.getElementById('wg-peer-modal-endpoint').value.trim();
  2187. let epPort = parseInt(document.getElementById('wg-peer-modal-port').value, 10) || 0;
  2188. while (epHost.includes(':') && !epHost.startsWith('[')) {
  2189. const lastColon = epHost.lastIndexOf(':');
  2190. const maybePort = epHost.substring(lastColon + 1);
  2191. if (!isNaN(parseInt(maybePort, 10)) && parseInt(maybePort, 10) > 0) {
  2192. if (!epPort) epPort = parseInt(maybePort, 10);
  2193. epHost = epHost.substring(0, lastColon);
  2194. } else {
  2195. break;
  2196. }
  2197. }
  2198. const keepalive = parseInt(document.getElementById('wg-peer-modal-keepalive').value, 10) || 0;
  2199. const psk = document.getElementById('wg-peer-modal-preshared').value.trim();
  2200. const disabled = document.getElementById('wg-peer-modal-disabled').checked;
  2201. // Validation
  2202. const targetIface = (state.wgInterfaces || []).find(i => i.name === iface);
  2203. if (targetIface && targetIface.public_key === pub) {
  2204. showToast('Invalid Peer Key', 'Peer public key cannot be the same as the interface public key!', 'error');
  2205. return;
  2206. }
  2207. try {
  2208. const res = await fetch(`${API_BASE}/vpn/wireguard/peers`, {
  2209. method: 'POST',
  2210. headers: { 'Content-Type': 'application/json' },
  2211. body: JSON.stringify({
  2212. orig_interface: origIface,
  2213. orig_public_key: origPubKey,
  2214. interface: iface,
  2215. name,
  2216. public_key: pub,
  2217. allowed_ips: allowed,
  2218. endpoint_address: epHost,
  2219. endpoint_port: epPort,
  2220. persistent_keepalive: keepalive,
  2221. preshared_key: psk,
  2222. disabled
  2223. })
  2224. });
  2225. const data = await res.json();
  2226. if (res.ok) {
  2227. showToast('Peer Saved', `Peer ${name} saved on ${iface}`, 'success');
  2228. closeAddWGPeerModal();
  2229. loadWireGuard(false);
  2230. } else {
  2231. showToast('Error', data.error || 'Failed to save peer', 'error');
  2232. }
  2233. } catch (err) {
  2234. showToast('Error', err.message, 'error');
  2235. }
  2236. }
  2237. async function toggleWGPeerState(iface, pubkey, enable) {
  2238. try {
  2239. const res = await fetch(`${API_BASE}/vpn/wireguard/peers/state`, {
  2240. method: 'POST',
  2241. headers: { 'Content-Type': 'application/json' },
  2242. body: JSON.stringify({ interface: iface, public_key: pubkey, enabled: enable })
  2243. });
  2244. const data = await res.json();
  2245. if (res.ok) {
  2246. showToast(enable ? 'Peer Enabled' : 'Peer Disabled', `Peer state updated on ${iface}`, 'info');
  2247. loadWireGuard(false);
  2248. } else {
  2249. showToast('Error', data.error || 'Failed to update peer state', 'error');
  2250. }
  2251. } catch (err) {
  2252. showToast('Error', err.message, 'error');
  2253. }
  2254. }
  2255. async function deleteWGPeer(iface, pubkey) {
  2256. if (!confirm(`Are you sure you want to remove peer from ${iface}?`)) return;
  2257. try {
  2258. const res = await fetch(`${API_BASE}/vpn/wireguard/peers/delete`, {
  2259. method: 'POST',
  2260. headers: { 'Content-Type': 'application/json' },
  2261. body: JSON.stringify({ interface: iface, public_key: pubkey })
  2262. });
  2263. const data = await res.json();
  2264. if (res.ok) {
  2265. showToast('Peer Deleted', 'WireGuard peer removed', 'success');
  2266. loadWireGuard(false);
  2267. } else {
  2268. showToast('Error', data.error || 'Failed to remove peer', 'error');
  2269. }
  2270. } catch (err) {
  2271. showToast('Error', err.message, 'error');
  2272. }
  2273. }
  2274. // ======================== IPSec FortiGate Phase 1 & 2 Multi-Tunnel Engine ========================
  2275. function switchIpsecModalTab(tab) {
  2276. const p1Tab = document.getElementById('tab-btn-ipsec-p1');
  2277. const p2Tab = document.getElementById('tab-btn-ipsec-p2');
  2278. const p1Content = document.getElementById('ipsec-tab-content-p1');
  2279. const p2Content = document.getElementById('ipsec-tab-content-p2');
  2280. const stepBtn = document.getElementById('btn-ipsec-switch-step');
  2281. if (tab === 'p1') {
  2282. if (p1Tab) {
  2283. 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';
  2284. }
  2285. if (p2Tab) {
  2286. 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';
  2287. }
  2288. if (p1Content) p1Content.classList.remove('hidden');
  2289. if (p2Content) p2Content.classList.add('hidden');
  2290. if (stepBtn) stepBtn.innerHTML = 'Next: Phase 2 Selectors &rarr;';
  2291. } else {
  2292. if (p1Tab) {
  2293. 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';
  2294. }
  2295. if (p2Tab) {
  2296. 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';
  2297. }
  2298. if (p1Content) p1Content.classList.add('hidden');
  2299. if (p2Content) p2Content.classList.remove('hidden');
  2300. if (stepBtn) stepBtn.innerHTML = '&larr; Back: Phase 1 (IKE)';
  2301. }
  2302. }
  2303. function toggleIpsecPhaseStep() {
  2304. const p1Content = document.getElementById('ipsec-tab-content-p1');
  2305. if (p1Content && !p1Content.classList.contains('hidden')) {
  2306. switchIpsecModalTab('p2');
  2307. } else {
  2308. switchIpsecModalTab('p1');
  2309. }
  2310. }
  2311. function toggleIpsecPskVisibility() {
  2312. const pskInput = document.getElementById('ipsec-modal-psk');
  2313. if (!pskInput) return;
  2314. pskInput.type = pskInput.type === 'password' ? 'text' : 'password';
  2315. }
  2316. function addIpsecLocalSubnet(val = '') {
  2317. const container = document.getElementById('ipsec-modal-local-subnets-container');
  2318. if (!container) return;
  2319. const row = document.createElement('div');
  2320. row.className = 'flex items-center gap-2 ipsec-subnet-row';
  2321. row.innerHTML = `
  2322. <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">
  2323. <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>
  2324. `;
  2325. container.appendChild(row);
  2326. }
  2327. function addIpsecRemoteSubnet(val = '') {
  2328. const container = document.getElementById('ipsec-modal-remote-subnets-container');
  2329. if (!container) return;
  2330. const row = document.createElement('div');
  2331. row.className = 'flex items-center gap-2 ipsec-subnet-row';
  2332. row.innerHTML = `
  2333. <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">
  2334. <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>
  2335. `;
  2336. container.appendChild(row);
  2337. }
  2338. function updateIpsecEspProposalFromPFS(val) {
  2339. const prop = document.getElementById('ipsec-modal-espprop');
  2340. if (!prop) return;
  2341. if (val === 'none') {
  2342. prop.value = 'aes256-sha256,aes128-sha256,default';
  2343. } else {
  2344. prop.value = `aes256-sha256-${val},aes128-sha256-${val},default`;
  2345. }
  2346. }
  2347. function updateIpsecIkeProposalFromDH(dh) {
  2348. const el = document.getElementById('ipsec-modal-ikeprop');
  2349. if (el) {
  2350. el.value = `aes256-sha256-${dh},aes128-sha256-${dh},default`;
  2351. }
  2352. }
  2353. function safeSetVal(id, val) {
  2354. const el = document.getElementById(id);
  2355. if (el) el.value = val;
  2356. }
  2357. function safeSetChecked(id, val) {
  2358. const el = document.getElementById(id);
  2359. if (el) el.checked = !!val;
  2360. }
  2361. function safeGetVal(id, def = '') {
  2362. const el = document.getElementById(id);
  2363. return el ? el.value : def;
  2364. }
  2365. async function loadIPSec(populateInputs = true) {
  2366. try {
  2367. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`);
  2368. const list = await res.json();
  2369. state.ipsecTunnels = Array.isArray(list) ? list : [];
  2370. const activeCount = state.ipsecTunnels.filter(t => t.running || t.status === 'ESTABLISHED').length;
  2371. const badge = document.getElementById('ipsec-sas-badge');
  2372. if (badge) badge.innerText = `${activeCount} Active SAs`;
  2373. const tbody = document.getElementById('ipsec-table-body');
  2374. const empty = document.getElementById('ipsec-empty');
  2375. if (!tbody) return;
  2376. tbody.innerHTML = '';
  2377. if (state.ipsecTunnels.length === 0) {
  2378. if (empty) empty.classList.remove('hidden');
  2379. } else {
  2380. if (empty) empty.classList.add('hidden');
  2381. state.ipsecTunnels.forEach(c => {
  2382. const isEstablished = c.running || c.status === 'ESTABLISHED';
  2383. const tr = document.createElement('tr');
  2384. tr.className = 'hover:bg-slate-800/40 transition text-xs select-none';
  2385. // Local subnets tags
  2386. const localList = (c.local_subnets && c.local_subnets.length > 0) ? c.local_subnets : (c.local_subnet ? [c.local_subnet] : ['0.0.0.0/0']);
  2387. 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('');
  2388. // Remote subnets tags
  2389. const remoteList = (c.remote_subnets && c.remote_subnets.length > 0) ? c.remote_subnets : (c.remote_subnet ? [c.remote_subnet] : ['0.0.0.0/0']);
  2390. 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('');
  2391. const ikeVersionBadge = (c.ike_version || 'ikev2').toUpperCase();
  2392. const p2Name = c.phase2_name || `${c.name}_p2`;
  2393. tr.innerHTML = `
  2394. <td class="py-2.5 px-3 text-center">
  2395. ${isEstablished ? `
  2396. <span class="inline-flex items-center gap-1.5 text-emerald-400 font-mono font-bold text-[11px]" title="Active SA Established">
  2397. <span class="w-2.5 h-2.5 rounded-full bg-emerald-400 animate-pulse"></span>
  2398. <span>UP</span>
  2399. </span>
  2400. ` : (c.disabled ? `
  2401. <span class="inline-flex items-center gap-1.5 text-slate-500 font-mono text-[11px]" title="Tunnel Disabled">
  2402. <span class="w-2 h-2 rounded-full bg-rose-500"></span>
  2403. <span>DOWN</span>
  2404. </span>
  2405. ` : `
  2406. <span class="inline-flex items-center gap-1.5 text-amber-400 font-mono text-[11px]" title="Disconnected / Idle">
  2407. <span class="w-2 h-2 rounded-full bg-amber-400"></span>
  2408. <span>IDLE</span>
  2409. </span>
  2410. `)}
  2411. </td>
  2412. <td class="py-2.5 px-4 font-bold text-white">
  2413. <div class="flex items-center gap-2">
  2414. <span class="text-amber-400">🛡</span>
  2415. <div>
  2416. <div>${escapeHtml(c.name)}</div>
  2417. <div class="text-[10px] text-slate-500 font-normal">P2: ${escapeHtml(p2Name)}</div>
  2418. </div>
  2419. </div>
  2420. </td>
  2421. <td class="py-2.5 px-4 text-slate-300 font-mono font-medium">${escapeHtml(c.remote_addrs || '%any')}</td>
  2422. <td class="py-2.5 px-4 font-sans">
  2423. <div class="flex items-center gap-1.5">
  2424. <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>
  2425. <span class="text-[10px] text-slate-400">${c.auth_method || 'PSK'}</span>
  2426. </div>
  2427. </td>
  2428. <td class="py-2.5 px-4">
  2429. <div class="space-y-1">
  2430. <div class="flex items-center flex-wrap gap-1">
  2431. <span class="text-[9px] text-cyan-400 uppercase font-bold mr-1">Local:</span>
  2432. ${localBadges}
  2433. </div>
  2434. <div class="flex items-center flex-wrap gap-1">
  2435. <span class="text-[9px] text-purple-400 uppercase font-bold mr-1">Remote:</span>
  2436. ${remoteBadges}
  2437. </div>
  2438. </div>
  2439. </td>
  2440. <td class="py-2.5 px-4 font-mono text-[11px] text-slate-400">
  2441. <div class="truncate max-w-[140px]" title="${escapeHtml(c.esp_proposals || '')}">
  2442. ${escapeHtml(c.esp_proposals || 'aes256-sha256')}
  2443. </div>
  2444. <div class="text-[10px] text-slate-500">PFS: ${escapeHtml(c.pfs_group || 'modp2048')}</div>
  2445. </td>
  2446. <td class="py-2.5 px-4 text-right space-x-2 font-sans">
  2447. ${isEstablished ? `
  2448. <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>
  2449. ` : `
  2450. <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>
  2451. `}
  2452. <button onclick="toggleIPSecState('${c.name}', ${c.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  2453. ${c.disabled ? 'Enable' : 'Disable'}
  2454. </button>
  2455. <button onclick="openEditIPSecModal('${c.name}')" class="text-xs text-amber-400 hover:text-amber-300">Edit</button>
  2456. <button onclick="deleteIPSecConn('${c.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2457. </td>
  2458. `;
  2459. tbody.appendChild(tr);
  2460. });
  2461. }
  2462. } catch (err) {
  2463. console.error('Failed to load IPSec:', err);
  2464. }
  2465. }
  2466. function openAddIPSecModal() {
  2467. const modal = document.getElementById('ipsec-modal');
  2468. if (!modal) return;
  2469. const title = document.getElementById('ipsec-modal-title');
  2470. if (title) title.innerText = 'Configure IPSec Site-to-Site Tunnel';
  2471. // Phase 1 Fields
  2472. safeSetVal('ipsec-modal-name', `tunnel-${(state.ipsecTunnels || []).length + 1}`);
  2473. const nameEl = document.getElementById('ipsec-modal-name');
  2474. if (nameEl) nameEl.readOnly = false;
  2475. safeSetVal('ipsec-modal-ikeversion', 'ikev2');
  2476. safeSetVal('ipsec-modal-ikever', 'ikev2');
  2477. safeSetVal('ipsec-modal-remotegw', '');
  2478. safeSetVal('ipsec-modal-localaddrs', '');
  2479. safeSetVal('ipsec-modal-comments', '');
  2480. safeSetVal('ipsec-modal-psk', '');
  2481. safeSetVal('ipsec-modal-ikeprop', 'aes256-sha256-modp2048,aes128-sha256-modp2048,default');
  2482. safeSetVal('ipsec-modal-dhgroup', 'modp2048');
  2483. safeSetVal('ipsec-modal-ikekeylife', '86400');
  2484. safeSetVal('ipsec-modal-localid', '');
  2485. safeSetVal('ipsec-modal-remoteid', '');
  2486. safeSetVal('ipsec-modal-dpd', 'on-demand');
  2487. // Phase 2 Fields
  2488. safeSetVal('ipsec-modal-p2name', `tunnel-${(state.ipsecTunnels || []).length + 1}_p2`);
  2489. safeSetVal('ipsec-modal-espkeylife', '28800');
  2490. safeSetVal('ipsec-modal-espprop', 'aes256-sha256-modp2048,aes128-sha256-modp2048,default');
  2491. safeSetVal('ipsec-modal-pfsgroup', 'modp2048');
  2492. safeSetChecked('ipsec-modal-autostart', true);
  2493. safeSetChecked('ipsec-modal-disabled', false);
  2494. // Clear & Populate default dynamic subnets
  2495. const localContainer = document.getElementById('ipsec-modal-local-subnets-container');
  2496. const remoteContainer = document.getElementById('ipsec-modal-remote-subnets-container');
  2497. if (localContainer) {
  2498. localContainer.innerHTML = '';
  2499. addIpsecLocalSubnet('192.168.10.0/24');
  2500. }
  2501. if (remoteContainer) {
  2502. remoteContainer.innerHTML = '';
  2503. addIpsecRemoteSubnet('192.168.20.0/24');
  2504. }
  2505. switchIpsecModalTab('p1');
  2506. modal.classList.remove('hidden');
  2507. }
  2508. function openEditIPSecModal(name) {
  2509. const modal = document.getElementById('ipsec-modal');
  2510. if (!modal) return;
  2511. const conn = (state.ipsecTunnels || []).find(c => c.name === name);
  2512. if (!conn) return;
  2513. const title = document.getElementById('ipsec-modal-title');
  2514. if (title) title.innerText = `Edit IPSec Tunnel: ${name}`;
  2515. // Phase 1 Fields
  2516. safeSetVal('ipsec-modal-name', conn.name);
  2517. const nameEl = document.getElementById('ipsec-modal-name');
  2518. if (nameEl) nameEl.readOnly = true;
  2519. safeSetVal('ipsec-modal-ikeversion', conn.ike_version || 'ikev2');
  2520. safeSetVal('ipsec-modal-ikever', conn.ike_version || 'ikev2');
  2521. safeSetVal('ipsec-modal-remotegw', conn.remote_addrs || '');
  2522. safeSetVal('ipsec-modal-localaddrs', conn.local_addrs || '');
  2523. safeSetVal('ipsec-modal-comments', conn.comment || '');
  2524. safeSetVal('ipsec-modal-psk', conn.preshared_key || '');
  2525. safeSetVal('ipsec-modal-ikeprop', conn.ike_proposals || 'aes256-sha256-modp2048,default');
  2526. safeSetVal('ipsec-modal-ikekeylife', conn.ike_keylife || 86400);
  2527. safeSetVal('ipsec-modal-localid', conn.local_id || '');
  2528. safeSetVal('ipsec-modal-remoteid', conn.remote_id || '');
  2529. safeSetVal('ipsec-modal-dpd', conn.dpd || 'on-demand');
  2530. // Phase 2 Fields
  2531. safeSetVal('ipsec-modal-p2name', conn.phase2_name || `${conn.name}_p2`);
  2532. safeSetVal('ipsec-modal-espkeylife', conn.esp_keylife || 28800);
  2533. safeSetVal('ipsec-modal-espprop', conn.esp_proposals || 'aes256-sha256-modp2048,default');
  2534. safeSetVal('ipsec-modal-pfsgroup', conn.pfs_group || 'modp2048');
  2535. safeSetChecked('ipsec-modal-autostart', conn.auto_start ?? true);
  2536. safeSetChecked('ipsec-modal-disabled', !!conn.disabled);
  2537. // Populate dynamic subnets
  2538. const localContainer = document.getElementById('ipsec-modal-local-subnets-container');
  2539. const remoteContainer = document.getElementById('ipsec-modal-remote-subnets-container');
  2540. if (localContainer) {
  2541. localContainer.innerHTML = '';
  2542. const locals = (conn.local_subnets && conn.local_subnets.length > 0) ? conn.local_subnets : (conn.local_subnet ? [conn.local_subnet] : ['192.168.10.0/24']);
  2543. locals.forEach(s => addIpsecLocalSubnet(s));
  2544. }
  2545. if (remoteContainer) {
  2546. remoteContainer.innerHTML = '';
  2547. const remotes = (conn.remote_subnets && conn.remote_subnets.length > 0) ? conn.remote_subnets : (conn.remote_subnet ? [conn.remote_subnet] : ['192.168.20.0/24']);
  2548. remotes.forEach(s => addIpsecRemoteSubnet(s));
  2549. }
  2550. switchIpsecModalTab('p1');
  2551. modal.classList.remove('hidden');
  2552. }
  2553. function closeAddIPSecModal() {
  2554. const modal = document.getElementById('ipsec-modal');
  2555. if (modal) modal.classList.add('hidden');
  2556. }
  2557. async function submitSaveIPSec(e) {
  2558. if (e) e.preventDefault();
  2559. const name = safeGetVal('ipsec-modal-name').trim();
  2560. if (!name) {
  2561. showToast('Error', 'Tunnel name is required', 'error');
  2562. return;
  2563. }
  2564. const ikeVersion = safeGetVal('ipsec-modal-ikeversion') || safeGetVal('ipsec-modal-ikever', 'ikev2');
  2565. const remotegw = safeGetVal('ipsec-modal-remotegw').trim();
  2566. const localAddrs = safeGetVal('ipsec-modal-localaddrs').trim() || '%any';
  2567. const comments = safeGetVal('ipsec-modal-comments').trim();
  2568. const psk = safeGetVal('ipsec-modal-psk');
  2569. const ikeProposals = safeGetVal('ipsec-modal-ikeprop', 'aes256-sha256-modp2048,default').trim();
  2570. const ikeKeylife = parseInt(safeGetVal('ipsec-modal-ikekeylife', '86400'), 10) || 86400;
  2571. const localId = safeGetVal('ipsec-modal-localid').trim();
  2572. const remoteId = safeGetVal('ipsec-modal-remoteid').trim();
  2573. const dpd = safeGetVal('ipsec-modal-dpd', 'on-demand');
  2574. const phase2Name = safeGetVal('ipsec-modal-p2name').trim() || `${name}_p2`;
  2575. const espProposals = safeGetVal('ipsec-modal-espprop', 'aes256-sha256-modp2048,default').trim();
  2576. const espKeylife = parseInt(safeGetVal('ipsec-modal-espkeylife', '28800'), 10) || 28800;
  2577. const pfsGroup = safeGetVal('ipsec-modal-pfsgroup', 'modp2048');
  2578. const autostart = document.getElementById('ipsec-modal-autostart')?.checked ?? true;
  2579. const disabled = document.getElementById('ipsec-modal-disabled')?.checked ?? false;
  2580. // Scrape dynamic local and remote subnets
  2581. const localInputs = document.querySelectorAll('#ipsec-modal-local-subnets-container input');
  2582. const localSubnets = [];
  2583. localInputs.forEach(inp => {
  2584. const v = inp.value.trim();
  2585. if (v) localSubnets.push(v);
  2586. });
  2587. const remoteInputs = document.querySelectorAll('#ipsec-modal-remote-subnets-container input');
  2588. const remoteSubnets = [];
  2589. remoteInputs.forEach(inp => {
  2590. const v = inp.value.trim();
  2591. if (v) remoteSubnets.push(v);
  2592. });
  2593. try {
  2594. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`, {
  2595. method: 'POST',
  2596. headers: { 'Content-Type': 'application/json' },
  2597. body: JSON.stringify({
  2598. name,
  2599. comment: comments,
  2600. ike_version: ikeVersion,
  2601. local_addrs: localAddrs,
  2602. remote_addrs: remotegw,
  2603. preshared_key: psk,
  2604. ike_proposals: ikeProposals,
  2605. ike_keylife: ikeKeylife,
  2606. local_id: localId,
  2607. remote_id: remoteId,
  2608. dpd: dpd,
  2609. phase2_name: phase2Name,
  2610. esp_proposals: espProposals,
  2611. esp_keylife: espKeylife,
  2612. pfs_group: pfsGroup,
  2613. pfs: pfsGroup !== 'none',
  2614. local_subnets: localSubnets,
  2615. remote_subnets: remoteSubnets,
  2616. local_subnet: localSubnets[0] || '0.0.0.0/0',
  2617. remote_subnet: remoteSubnets[0] || '0.0.0.0/0',
  2618. auto_start: autostart,
  2619. disabled
  2620. })
  2621. });
  2622. if (res.ok) {
  2623. showToast('IPSec Saved', `FortiGate Tunnel ${name} configured`, 'success');
  2624. closeAddIPSecModal();
  2625. loadIPSec(false);
  2626. } else {
  2627. const err = await res.json();
  2628. showToast('Error', err.error || 'Failed to save IPSec tunnel', 'error');
  2629. }
  2630. } catch (err) {
  2631. showToast('Error', err.message, 'error');
  2632. }
  2633. }
  2634. async function startIPSecTunnel(name) {
  2635. try {
  2636. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/start`, { method: 'POST' });
  2637. if (res.ok) {
  2638. showToast('Initiating Tunnel', `Attempting SA handshake for ${name}...`, 'info');
  2639. setTimeout(() => loadIPSec(false), 2000);
  2640. }
  2641. } catch (err) {
  2642. showToast('Error', err.message, 'error');
  2643. }
  2644. }
  2645. async function stopIPSecTunnel(name) {
  2646. try {
  2647. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  2648. if (res.ok) {
  2649. showToast('Terminated', `IPSec SA for ${name} closed`, 'info');
  2650. loadIPSec(false);
  2651. }
  2652. } catch (err) {
  2653. showToast('Error', err.message, 'error');
  2654. }
  2655. }
  2656. async function toggleIPSecState(name, enable) {
  2657. try {
  2658. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/state`, {
  2659. method: 'POST',
  2660. headers: { 'Content-Type': 'application/json' },
  2661. body: JSON.stringify({ enabled: enable })
  2662. });
  2663. if (res.ok) {
  2664. showToast(enable ? 'Enabled' : 'Disabled', `IPSec tunnel ${name} updated`, 'info');
  2665. loadIPSec(false);
  2666. }
  2667. } catch (err) {
  2668. showToast('Error', err.message, 'error');
  2669. }
  2670. }
  2671. async function deleteIPSecConn(name) {
  2672. if (!confirm(`Are you sure you want to delete IPSec tunnel ${name}?`)) return;
  2673. try {
  2674. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2675. if (res.ok) {
  2676. showToast('Deleted', `IPSec connection ${name} removed`, 'success');
  2677. loadIPSec(false);
  2678. fetchData(false);
  2679. }
  2680. } catch (err) {
  2681. showToast('Error', err.message, 'error');
  2682. }
  2683. }
  2684. // ======================== L2TP Multi-Instance ========================
  2685. async function loadL2TP(populateInputs = true) {
  2686. try {
  2687. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2688. await fetchPPPProfilesList();
  2689. }
  2690. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`);
  2691. const list = await res.json();
  2692. state.l2tpList = Array.isArray(list) ? list : [];
  2693. const badge = document.getElementById('l2tp-count-badge');
  2694. if (badge) badge.innerText = `${state.l2tpList.length} Client${state.l2tpList.length !== 1 ? 's' : ''}`;
  2695. const tbody = document.getElementById('l2tp-table-body');
  2696. const empty = document.getElementById('l2tp-empty');
  2697. if (!tbody) return;
  2698. tbody.innerHTML = '';
  2699. if (state.l2tpList.length === 0) {
  2700. if (empty) empty.classList.remove('hidden');
  2701. } else {
  2702. if (empty) empty.classList.add('hidden');
  2703. state.l2tpList.forEach(inst => {
  2704. const tr = document.createElement('tr');
  2705. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  2706. tr.innerHTML = `
  2707. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  2708. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  2709. <td class="py-2.5 px-3 text-cyan-400 font-mono">${escapeHtml(inst.connect_to)}</td>
  2710. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  2711. <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>
  2712. <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>
  2713. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  2714. <td class="py-2.5 px-3 text-center">
  2715. <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'}">
  2716. ${inst.default_route ? 'Yes' : 'No'}
  2717. </span>
  2718. </td>
  2719. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  2720. ${inst.running ? `
  2721. <button onclick="disconnectL2TPInstance('${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  2722. ` : `
  2723. <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>
  2724. `}
  2725. <button onclick="toggleL2TPState('${escapeHtml(inst.name)}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  2726. ${inst.disabled ? 'Enable' : 'Disable'}
  2727. </button>
  2728. <button onclick="openEditL2TPModal('${escapeHtml(inst.name)}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2729. <button onclick="deleteL2TPInstance('${escapeHtml(inst.name)}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2730. </td>
  2731. `;
  2732. tbody.appendChild(tr);
  2733. });
  2734. }
  2735. } catch (err) {
  2736. console.error('Failed to load L2TP:', err);
  2737. }
  2738. }
  2739. async function openAddL2TPModal() {
  2740. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2741. await fetchPPPProfilesList();
  2742. }
  2743. document.getElementById('l2tp-modal-title').innerText = 'Add L2TP Client Interface';
  2744. document.getElementById('l2tp-modal-name').value = `l2tp-out${(state.l2tpList || []).length + 1}`;
  2745. document.getElementById('l2tp-modal-name').readOnly = false;
  2746. document.getElementById('l2tp-modal-server').value = '';
  2747. document.getElementById('l2tp-modal-user').value = '';
  2748. document.getElementById('l2tp-modal-pass').value = '';
  2749. document.getElementById('l2tp-modal-ipsec').value = '';
  2750. document.getElementById('l2tp-modal-defroute').checked = true;
  2751. document.getElementById('l2tp-modal-disabled').checked = false;
  2752. populateProfileSelect('l2tp-modal-profile', 'default-encryption', 'default-encryption');
  2753. document.getElementById('l2tp-modal').classList.remove('hidden');
  2754. }
  2755. async function openEditL2TPModal(name) {
  2756. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2757. await fetchPPPProfilesList();
  2758. }
  2759. const inst = (state.l2tpList || []).find(i => i.name === name);
  2760. if (!inst) return;
  2761. document.getElementById('l2tp-modal-title').innerText = `Edit L2TP Client: ${name}`;
  2762. document.getElementById('l2tp-modal-name').value = inst.name;
  2763. document.getElementById('l2tp-modal-name').readOnly = true;
  2764. document.getElementById('l2tp-modal-server').value = inst.connect_to || '';
  2765. document.getElementById('l2tp-modal-user').value = inst.username || '';
  2766. document.getElementById('l2tp-modal-pass').value = inst.password || '';
  2767. document.getElementById('l2tp-modal-ipsec').value = inst.ipsec_secret || '';
  2768. document.getElementById('l2tp-modal-defroute').checked = inst.default_route ?? true;
  2769. document.getElementById('l2tp-modal-disabled').checked = !!inst.disabled;
  2770. populateProfileSelect('l2tp-modal-profile', inst.profile || 'default-encryption', 'default-encryption');
  2771. document.getElementById('l2tp-modal').classList.remove('hidden');
  2772. }
  2773. function closeL2TPModal() {
  2774. document.getElementById('l2tp-modal').classList.add('hidden');
  2775. }
  2776. async function submitSaveL2TP(e) {
  2777. e.preventDefault();
  2778. const name = document.getElementById('l2tp-modal-name').value.trim();
  2779. const server = document.getElementById('l2tp-modal-server').value.trim();
  2780. const user = document.getElementById('l2tp-modal-user').value.trim();
  2781. const pass = document.getElementById('l2tp-modal-pass').value;
  2782. const profile = document.getElementById('l2tp-modal-profile')?.value || 'default-encryption';
  2783. const ipsec = document.getElementById('l2tp-modal-ipsec').value;
  2784. const defRoute = document.getElementById('l2tp-modal-defroute').checked;
  2785. const disabled = document.getElementById('l2tp-modal-disabled').checked;
  2786. try {
  2787. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`, {
  2788. method: 'POST',
  2789. headers: { 'Content-Type': 'application/json' },
  2790. body: JSON.stringify({
  2791. name,
  2792. connect_to: server,
  2793. username: user,
  2794. password: pass,
  2795. profile: profile,
  2796. ipsec_secret: ipsec,
  2797. default_route: defRoute,
  2798. disabled
  2799. })
  2800. });
  2801. if (res.ok) {
  2802. showToast('L2TP Saved', `Client ${name} configuration saved`, 'success');
  2803. closeL2TPModal();
  2804. loadL2TP(false);
  2805. fetchData(false);
  2806. }
  2807. } catch (err) {
  2808. showToast('Error', err.message, 'error');
  2809. }
  2810. }
  2811. async function connectL2TPInstance(name) {
  2812. try {
  2813. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  2814. if (res.ok) {
  2815. showToast('Connecting', `Dialing L2TP ${name}...`, 'info');
  2816. setTimeout(() => loadL2TP(false), 2000);
  2817. }
  2818. } catch (err) {
  2819. showToast('Error', err.message, 'error');
  2820. }
  2821. }
  2822. async function disconnectL2TPInstance(name) {
  2823. try {
  2824. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  2825. if (res.ok) {
  2826. showToast('Disconnected', `L2TP tunnel ${name} terminated`, 'info');
  2827. loadL2TP(false);
  2828. }
  2829. } catch (err) {
  2830. showToast('Error', err.message, 'error');
  2831. }
  2832. }
  2833. async function toggleL2TPState(name, enable) {
  2834. try {
  2835. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/state`, {
  2836. method: 'POST',
  2837. headers: { 'Content-Type': 'application/json' },
  2838. body: JSON.stringify({ enabled: enable })
  2839. });
  2840. if (res.ok) {
  2841. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  2842. loadL2TP(false);
  2843. }
  2844. } catch (err) {
  2845. showToast('Error', err.message, 'error');
  2846. }
  2847. }
  2848. async function deleteL2TPInstance(name) {
  2849. if (!confirm(`Are you sure you want to delete L2TP client ${name}?`)) return;
  2850. try {
  2851. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2852. if (res.ok) {
  2853. showToast('Deleted', `L2TP client ${name} removed`, 'success');
  2854. loadL2TP(false);
  2855. fetchData(false);
  2856. }
  2857. } catch (err) {
  2858. showToast('Error', err.message, 'error');
  2859. }
  2860. }
  2861. // ======================== PPTP Multi-Instance ========================
  2862. async function loadPPTP(populateInputs = true) {
  2863. try {
  2864. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2865. await fetchPPPProfilesList();
  2866. }
  2867. const res = await fetch(`${API_BASE}/vpn/pptp/clients`);
  2868. const list = await res.json();
  2869. state.pptpList = Array.isArray(list) ? list : [];
  2870. const badge = document.getElementById('pptp-count-badge');
  2871. if (badge) badge.innerText = `${state.pptpList.length} Client${state.pptpList.length !== 1 ? 's' : ''}`;
  2872. const tbody = document.getElementById('pptp-table-body');
  2873. const empty = document.getElementById('pptp-empty');
  2874. if (!tbody) return;
  2875. tbody.innerHTML = '';
  2876. if (state.pptpList.length === 0) {
  2877. if (empty) empty.classList.remove('hidden');
  2878. } else {
  2879. if (empty) empty.classList.add('hidden');
  2880. state.pptpList.forEach(inst => {
  2881. const tr = document.createElement('tr');
  2882. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  2883. tr.innerHTML = `
  2884. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  2885. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  2886. <td class="py-2.5 px-3 text-purple-400 font-mono">${escapeHtml(inst.connect_to)}</td>
  2887. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  2888. <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>
  2889. <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>
  2890. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  2891. <td class="py-2.5 px-3 text-center">
  2892. <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'}">
  2893. ${inst.require_mppe ? 'MPPE-128' : 'None'}
  2894. </span>
  2895. </td>
  2896. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  2897. ${inst.running ? `
  2898. <button onclick="disconnectPPTPInstance('${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  2899. ` : `
  2900. <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>
  2901. `}
  2902. <button onclick="togglePPTPState('${escapeHtml(inst.name)}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  2903. ${inst.disabled ? 'Enable' : 'Disable'}
  2904. </button>
  2905. <button onclick="openEditPPTPModal('${escapeHtml(inst.name)}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2906. <button onclick="deletePPTPInstance('${escapeHtml(inst.name)}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2907. </td>
  2908. `;
  2909. tbody.appendChild(tr);
  2910. });
  2911. }
  2912. } catch (err) {
  2913. console.error('Failed to load PPTP:', err);
  2914. }
  2915. }
  2916. async function openAddPPTPModal() {
  2917. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2918. await fetchPPPProfilesList();
  2919. }
  2920. document.getElementById('pptp-modal-title').innerText = 'Add PPTP Client Interface';
  2921. document.getElementById('pptp-modal-name').value = `pptp-out${(state.pptpList || []).length + 1}`;
  2922. document.getElementById('pptp-modal-name').readOnly = false;
  2923. document.getElementById('pptp-modal-server').value = '';
  2924. document.getElementById('pptp-modal-user').value = '';
  2925. document.getElementById('pptp-modal-pass').value = '';
  2926. document.getElementById('pptp-modal-mppe').checked = true;
  2927. document.getElementById('pptp-modal-defroute').checked = true;
  2928. document.getElementById('pptp-modal-disabled').checked = false;
  2929. populateProfileSelect('pptp-modal-profile', 'default-encryption', 'default-encryption');
  2930. document.getElementById('pptp-modal').classList.remove('hidden');
  2931. }
  2932. async function openEditPPTPModal(name) {
  2933. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2934. await fetchPPPProfilesList();
  2935. }
  2936. const inst = (state.pptpList || []).find(i => i.name === name);
  2937. if (!inst) return;
  2938. document.getElementById('pptp-modal-title').innerText = `Edit PPTP Client: ${name}`;
  2939. document.getElementById('pptp-modal-name').value = inst.name;
  2940. document.getElementById('pptp-modal-name').readOnly = true;
  2941. document.getElementById('pptp-modal-server').value = inst.connect_to || '';
  2942. document.getElementById('pptp-modal-user').value = inst.username || '';
  2943. document.getElementById('pptp-modal-pass').value = inst.password || '';
  2944. document.getElementById('pptp-modal-mppe').checked = inst.require_mppe ?? true;
  2945. document.getElementById('pptp-modal-defroute').checked = inst.default_route ?? true;
  2946. document.getElementById('pptp-modal-disabled').checked = !!inst.disabled;
  2947. populateProfileSelect('pptp-modal-profile', inst.profile || 'default-encryption', 'default-encryption');
  2948. document.getElementById('pptp-modal').classList.remove('hidden');
  2949. }
  2950. function closePPTPModal() {
  2951. document.getElementById('pptp-modal').classList.add('hidden');
  2952. }
  2953. async function submitSavePPTP(e) {
  2954. e.preventDefault();
  2955. const name = document.getElementById('pptp-modal-name').value.trim();
  2956. const server = document.getElementById('pptp-modal-server').value.trim();
  2957. const user = document.getElementById('pptp-modal-user').value.trim();
  2958. const pass = document.getElementById('pptp-modal-pass').value;
  2959. const profile = document.getElementById('pptp-modal-profile')?.value || 'default-encryption';
  2960. const mppe = document.getElementById('pptp-modal-mppe').checked;
  2961. const defRoute = document.getElementById('pptp-modal-defroute').checked;
  2962. const disabled = document.getElementById('pptp-modal-disabled').checked;
  2963. try {
  2964. const res = await fetch(`${API_BASE}/vpn/pptp/clients`, {
  2965. method: 'POST',
  2966. headers: { 'Content-Type': 'application/json' },
  2967. body: JSON.stringify({
  2968. name,
  2969. connect_to: server,
  2970. username: user,
  2971. password: pass,
  2972. profile: profile,
  2973. require_mppe: mppe,
  2974. default_route: defRoute,
  2975. auto_reconnect: true,
  2976. disabled
  2977. })
  2978. });
  2979. if (res.ok) {
  2980. showToast('PPTP Saved', `Client ${name} configuration saved`, 'success');
  2981. closePPTPModal();
  2982. loadPPTP(false);
  2983. fetchData(false);
  2984. }
  2985. } catch (err) {
  2986. showToast('Error', err.message, 'error');
  2987. }
  2988. }
  2989. async function connectPPTPInstance(name) {
  2990. try {
  2991. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  2992. if (res.ok) {
  2993. showToast('Connecting', `Dialing PPTP ${name}...`, 'info');
  2994. setTimeout(() => loadPPTP(false), 2000);
  2995. }
  2996. } catch (err) {
  2997. showToast('Error', err.message, 'error');
  2998. }
  2999. }
  3000. async function disconnectPPTPInstance(name) {
  3001. try {
  3002. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  3003. if (res.ok) {
  3004. showToast('Disconnected', `PPTP tunnel ${name} terminated`, 'info');
  3005. loadPPTP(false);
  3006. }
  3007. } catch (err) {
  3008. showToast('Error', err.message, 'error');
  3009. }
  3010. }
  3011. async function togglePPTPState(name, enable) {
  3012. try {
  3013. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/state`, {
  3014. method: 'POST',
  3015. headers: { 'Content-Type': 'application/json' },
  3016. body: JSON.stringify({ enabled: enable })
  3017. });
  3018. if (res.ok) {
  3019. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  3020. loadPPTP(false);
  3021. }
  3022. } catch (err) {
  3023. showToast('Error', err.message, 'error');
  3024. }
  3025. }
  3026. async function deletePPTPInstance(name) {
  3027. if (!confirm(`Are you sure you want to delete PPTP client ${name}?`)) return;
  3028. try {
  3029. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  3030. if (res.ok) {
  3031. showToast('Deleted', `PPTP client ${name} removed`, 'success');
  3032. loadPPTP(false);
  3033. fetchData(false);
  3034. }
  3035. } catch (err) {
  3036. showToast('Error', err.message, 'error');
  3037. }
  3038. }
  3039. // ---------------- Modal & Helper Functions ----------------
  3040. function openVlanModal(defaultParent = '') {
  3041. const select = document.getElementById('vlan-parent');
  3042. select.innerHTML = '';
  3043. const allIfaces = state.interfaces || [];
  3044. const eligible = allIfaces.filter(i => supportsVLAN(i));
  3045. if (eligible.length === 0) {
  3046. const opt = document.createElement('option');
  3047. opt.value = '';
  3048. opt.innerText = 'No VLAN-capable interfaces available';
  3049. select.appendChild(opt);
  3050. } else {
  3051. eligible.forEach(i => {
  3052. const opt = document.createElement('option');
  3053. opt.value = i.name;
  3054. opt.innerText = `${i.name} (${i.role || i.type || 'Ethernet'} - ${i.state})`;
  3055. if (i.name === defaultParent) opt.selected = true;
  3056. select.appendChild(opt);
  3057. });
  3058. }
  3059. document.getElementById('vlan-id').value = '';
  3060. document.getElementById('vlan-name').value = '';
  3061. document.getElementById('vlan-ip').value = '';
  3062. document.getElementById('vlan-desc').value = '';
  3063. populateRoleSelects('LAN');
  3064. autoSuggestVlanName();
  3065. document.getElementById('vlan-modal').classList.remove('hidden');
  3066. }
  3067. function closeVlanModal() {
  3068. document.getElementById('vlan-modal').classList.add('hidden');
  3069. }
  3070. function autoSuggestVlanName() {
  3071. const parent = document.getElementById('vlan-parent').value;
  3072. if (!parent) return;
  3073. const id = document.getElementById('vlan-id').value;
  3074. const nameInput = document.getElementById('vlan-name');
  3075. if (parent && id) nameInput.placeholder = `${parent}.${id}`;
  3076. }
  3077. function setSubnetPreset(cidr) {
  3078. const ipInput = document.getElementById('vlan-ip');
  3079. const id = document.getElementById('vlan-id').value || '10';
  3080. ipInput.value = `192.168.${id}.1${cidr}`;
  3081. }
  3082. async function submitCreateVlan(e) {
  3083. e.preventDefault();
  3084. const btn = document.getElementById('vlan-submit-btn');
  3085. btn.disabled = true;
  3086. btn.innerText = 'Creating...';
  3087. const parent = document.getElementById('vlan-parent').value;
  3088. if (!parent) {
  3089. showToast('Error', 'Please select a valid VLAN-capable parent interface', 'error');
  3090. btn.disabled = false;
  3091. btn.innerText = 'Create VLAN';
  3092. return;
  3093. }
  3094. const id = parseInt(document.getElementById('vlan-id').value, 10);
  3095. const name = document.getElementById('vlan-name').value.trim();
  3096. const ip = document.getElementById('vlan-ip').value.trim();
  3097. const role = document.getElementById('vlan-role').value;
  3098. const desc = document.getElementById('vlan-desc').value.trim();
  3099. try {
  3100. const res = await fetch(`${API_BASE}/vlans`, {
  3101. method: 'POST',
  3102. headers: { 'Content-Type': 'application/json' },
  3103. body: JSON.stringify({
  3104. parent_name: parent,
  3105. vlan_id: id,
  3106. name: name,
  3107. ip_address: ip,
  3108. role: role,
  3109. description: desc,
  3110. mtu: 1500,
  3111. auto_up: true
  3112. })
  3113. });
  3114. const data = await res.json();
  3115. if (res.ok) {
  3116. showToast('VLAN Created', `Created ${data.name} (VLAN ${data.vlan_id})`, 'success');
  3117. state.expandedParents.add(parent);
  3118. closeVlanModal();
  3119. await fetchData(true);
  3120. if (state.activeTab !== 'interfaces') navigate('interfaces');
  3121. } else {
  3122. showToast('Creation Failed', data.message || 'Failed to create VLAN', 'error');
  3123. }
  3124. } catch (err) {
  3125. showToast('Error', err.message, 'error');
  3126. } finally {
  3127. btn.disabled = false;
  3128. btn.innerText = 'Create VLAN';
  3129. }
  3130. }
  3131. async function confirmDeleteVlan(name) {
  3132. if (!confirm(`Delete VLAN interface ${name}?`)) return;
  3133. try {
  3134. const res = await fetch(`${API_BASE}/vlans/${encodeURIComponent(name)}`, { method: 'DELETE' });
  3135. if (res.ok) {
  3136. showToast('VLAN Deleted', `Interface ${name} removed`, 'success');
  3137. closeIfaceModal();
  3138. fetchData(true);
  3139. }
  3140. } catch (err) {
  3141. showToast('Error', err.message, 'error');
  3142. }
  3143. }
  3144. function openIfaceModal(name) {
  3145. const iface = (state.interfaces || []).find(i => i.name === name);
  3146. if (!iface) return;
  3147. state.currentModalIface = iface.name;
  3148. document.getElementById('modal-iface-name').innerText = iface.name;
  3149. document.getElementById('modal-iface-badge').innerText = iface.is_vlan ? `VLAN ${iface.vlan_id}` : iface.type;
  3150. document.getElementById('modal-iface-mtu').value = iface.mtu;
  3151. populateRoleSelects(iface.role || 'LAN');
  3152. document.getElementById('modal-iface-desc').value = iface.description || '';
  3153. const nameInput = document.getElementById('modal-iface-new-name');
  3154. const renameBtn = document.getElementById('modal-btn-rename');
  3155. const renameHelp = document.getElementById('modal-iface-rename-help');
  3156. if (nameInput) {
  3157. nameInput.value = iface.name;
  3158. if (iface.name === 'lo' || iface.type === 'loopback') {
  3159. nameInput.disabled = true;
  3160. if (renameBtn) renameBtn.disabled = true;
  3161. if (renameHelp) renameHelp.innerText = 'Loopback interface cannot be renamed.';
  3162. } else {
  3163. nameInput.disabled = false;
  3164. if (renameBtn) renameBtn.disabled = false;
  3165. if (renameHelp) renameHelp.innerText = 'Device name in Linux (max 15 characters). Automatically preserves operational link state and metadata.';
  3166. }
  3167. }
  3168. const delBtn = document.getElementById('modal-delete-vlan-btn');
  3169. if (iface.is_vlan) {
  3170. delBtn.classList.remove('hidden');
  3171. } else {
  3172. delBtn.classList.add('hidden');
  3173. }
  3174. renderModalIPs(iface);
  3175. document.getElementById('iface-modal').classList.remove('hidden');
  3176. }
  3177. function renderModalIPs(iface) {
  3178. const container = document.getElementById('modal-ip-list');
  3179. container.innerHTML = '';
  3180. const addrs = [...(iface.ipv4 || []), ...(iface.ipv6 || [])];
  3181. if (addrs.length === 0) {
  3182. container.innerHTML = `<span class="text-slate-500 text-xs font-sans">No IP addresses currently bound</span>`;
  3183. return;
  3184. }
  3185. addrs.forEach(addr => {
  3186. const row = document.createElement('div');
  3187. row.className = 'flex items-center justify-between p-2 rounded bg-slate-900 border border-slate-800';
  3188. row.innerHTML = `
  3189. <span class="text-white">${addr}</span>
  3190. <button onclick="removeInterfaceIP('${addr}')" class="text-[11px] text-rose-400 hover:text-rose-300 font-sans">Remove</button>
  3191. `;
  3192. container.appendChild(row);
  3193. });
  3194. }
  3195. function closeIfaceModal() {
  3196. document.getElementById('iface-modal').classList.add('hidden');
  3197. state.currentModalIface = null;
  3198. }
  3199. async function setIfaceState(name, newState) {
  3200. const target = name || state.currentModalIface;
  3201. if (!target) return;
  3202. await toggleInterfaceState(target, newState);
  3203. const updated = (state.interfaces || []).find(i => i.name === target);
  3204. if (updated) openIfaceModal(target);
  3205. }
  3206. async function applyMTU() {
  3207. const mtu = parseInt(document.getElementById('modal-iface-mtu').value, 10);
  3208. try {
  3209. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/mtu`, {
  3210. method: 'POST',
  3211. headers: { 'Content-Type': 'application/json' },
  3212. body: JSON.stringify({ mtu })
  3213. });
  3214. if (res.ok) {
  3215. showToast('MTU Applied', `Set MTU to ${mtu} on ${state.currentModalIface}`, 'success');
  3216. fetchData(false);
  3217. }
  3218. } catch (err) {
  3219. showToast('Error', err.message, 'error');
  3220. }
  3221. }
  3222. async function addInterfaceIP() {
  3223. const ip = document.getElementById('modal-new-ip').value.trim();
  3224. if (!ip) return;
  3225. try {
  3226. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  3227. method: 'POST',
  3228. headers: { 'Content-Type': 'application/json' },
  3229. body: JSON.stringify({ ip })
  3230. });
  3231. if (res.ok) {
  3232. showToast('IP Added', `Bound ${ip} to ${state.currentModalIface}`, 'success');
  3233. document.getElementById('modal-new-ip').value = '';
  3234. await fetchData(false);
  3235. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  3236. if (iface) renderModalIPs(iface);
  3237. } else {
  3238. const err = await res.json();
  3239. showToast('Error', err.error || err.message || 'Failed to add IP address', 'error');
  3240. }
  3241. } catch (err) {
  3242. showToast('Error', err.message, 'error');
  3243. }
  3244. }
  3245. async function removeInterfaceIP(ip) {
  3246. if (!confirm(`Remove IP ${ip}?`)) return;
  3247. try {
  3248. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  3249. method: 'DELETE',
  3250. headers: { 'Content-Type': 'application/json' },
  3251. body: JSON.stringify({ ip })
  3252. });
  3253. if (res.ok) {
  3254. showToast('IP Removed', `Removed ${ip}`, 'success');
  3255. await fetchData(false);
  3256. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  3257. if (iface) renderModalIPs(iface);
  3258. }
  3259. } catch (err) {
  3260. showToast('Error', err.message, 'error');
  3261. }
  3262. }
  3263. async function renameInterface() {
  3264. const oldName = state.currentModalIface;
  3265. const newNameInput = document.getElementById('modal-iface-new-name');
  3266. const newName = (newNameInput?.value || '').trim();
  3267. if (!oldName) return;
  3268. if (!newName) {
  3269. showToast('Warning', 'Interface name cannot be empty', 'warning');
  3270. return;
  3271. }
  3272. if (newName === oldName) {
  3273. showToast('Info', `Interface name is already "${oldName}"`, 'info');
  3274. return;
  3275. }
  3276. if (newName.length > 15) {
  3277. showToast('Validation Error', 'Interface name cannot exceed 15 characters (Linux IFNAMSIZ)', 'error');
  3278. return;
  3279. }
  3280. if (!/^[a-zA-Z0-9_][a-zA-Z0-9_.-]*$/.test(newName)) {
  3281. showToast('Validation Error', 'Name must contain only alphanumeric characters, underscores, hyphens or dots', 'error');
  3282. return;
  3283. }
  3284. const renameBtn = document.getElementById('modal-btn-rename');
  3285. if (renameBtn) {
  3286. renameBtn.disabled = true;
  3287. renameBtn.innerHTML = `<span class="animate-spin inline-block mr-1">⟳</span> Renaming...`;
  3288. }
  3289. try {
  3290. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(oldName)}/rename`, {
  3291. method: 'POST',
  3292. headers: { 'Content-Type': 'application/json' },
  3293. body: JSON.stringify({ new_name: newName })
  3294. });
  3295. const data = await res.json();
  3296. if (!res.ok) {
  3297. showToast('Rename Failed', data.error || data.message || 'Failed to rename interface', 'error');
  3298. return;
  3299. }
  3300. showToast('Interface Renamed', `Successfully renamed ${oldName} → ${newName}`, 'success');
  3301. state.currentModalIface = newName;
  3302. document.getElementById('modal-iface-name').innerText = newName;
  3303. // Refresh application state
  3304. await fetchData(false);
  3305. const updated = (state.interfaces || []).find(i => i.name === newName);
  3306. if (updated) {
  3307. openIfaceModal(newName);
  3308. } else {
  3309. closeIfaceModal();
  3310. }
  3311. } catch (err) {
  3312. showToast('Error', err.message, 'error');
  3313. } finally {
  3314. if (renameBtn) {
  3315. renameBtn.disabled = false;
  3316. renameBtn.innerHTML = `
  3317. <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>
  3318. <span>Rename</span>
  3319. `;
  3320. }
  3321. }
  3322. }
  3323. async function saveInterfaceMetadata() {
  3324. const oldName = state.currentModalIface;
  3325. const newName = (document.getElementById('modal-iface-new-name')?.value || '').trim();
  3326. const role = document.getElementById('modal-iface-role').value;
  3327. const desc = document.getElementById('modal-iface-desc').value.trim();
  3328. let targetName = oldName;
  3329. // If user changed the name before clicking Save Changes, execute rename first
  3330. if (newName && newName !== oldName && oldName !== 'lo') {
  3331. try {
  3332. const renameRes = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(oldName)}/rename`, {
  3333. method: 'POST',
  3334. headers: { 'Content-Type': 'application/json' },
  3335. body: JSON.stringify({ new_name: newName })
  3336. });
  3337. const data = await renameRes.json();
  3338. if (!renameRes.ok) {
  3339. showToast('Rename Failed', data.error || data.message || 'Could not rename interface', 'error');
  3340. return;
  3341. }
  3342. targetName = newName;
  3343. state.currentModalIface = newName;
  3344. showToast('Renamed', `Interface renamed from ${oldName} to ${newName}`, 'success');
  3345. } catch (err) {
  3346. showToast('Error', err.message, 'error');
  3347. return;
  3348. }
  3349. }
  3350. try {
  3351. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(targetName)}/metadata`, {
  3352. method: 'POST',
  3353. headers: { 'Content-Type': 'application/json' },
  3354. body: JSON.stringify({ role, description: desc })
  3355. });
  3356. if (res.ok) {
  3357. showToast('Saved', 'Interface configuration updated', 'success');
  3358. closeIfaceModal();
  3359. fetchData(false);
  3360. } else {
  3361. const err = await res.json();
  3362. showToast('Error', err.error || err.message || 'Failed to save metadata', 'error');
  3363. }
  3364. } catch (err) {
  3365. showToast('Error', err.message, 'error');
  3366. }
  3367. }
  3368. // ======================== MIKROTIK FIREWALL (/ip firewall) ========================
  3369. state.fwSubTab = 'filter';
  3370. state.routesSubTab = 'routes';
  3371. function renderRuleFlag(disabled, hasComment) {
  3372. let flags = '';
  3373. if (disabled) flags += '<span class="text-rose-400 font-bold" title="Disabled">X</span>';
  3374. if (hasComment) flags += '<span class="text-amber-400 font-bold ml-1" title="Has Comment">C</span>';
  3375. return flags || '<span class="text-slate-600">-</span>';
  3376. }
  3377. function renderActionBadge(action) {
  3378. const act = (action || '').toLowerCase();
  3379. let color = 'bg-slate-800 text-slate-300';
  3380. if (act === 'accept') color = 'bg-emerald-500/20 text-emerald-300 border border-emerald-500/30';
  3381. else if (act === 'drop' || act === 'reject') color = 'bg-rose-500/20 text-rose-300 border border-rose-500/30';
  3382. else if (act === 'masquerade' || act === 'src-nat' || act === 'dst-nat') color = 'bg-amber-500/20 text-amber-300 border border-amber-500/30';
  3383. else if (act.startsWith('mark-')) color = 'bg-purple-500/20 text-purple-300 border border-purple-500/30';
  3384. else if (act === 'log') color = 'bg-cyan-500/20 text-cyan-300 border border-cyan-500/30';
  3385. return `<span class="px-2 py-0.5 rounded text-[10px] font-mono font-semibold ${color}">${action}</span>`;
  3386. }
  3387. function switchFWSubTab(tab) {
  3388. state.fwSubTab = tab;
  3389. const tabs = ['filter', 'nat', 'mangle', 'addrlist', 'geo', 'connections'];
  3390. tabs.forEach(t => {
  3391. const panel = document.getElementById(`fw-subtab-${t}`);
  3392. const btn = document.getElementById(`fw-subtab-btn-${t}`);
  3393. if (panel) {
  3394. if (t === tab) panel.classList.remove('hidden');
  3395. else panel.classList.add('hidden');
  3396. }
  3397. if (btn) {
  3398. if (t === tab) {
  3399. 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';
  3400. } else {
  3401. 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';
  3402. }
  3403. }
  3404. });
  3405. const addBtn = document.getElementById('fw-primary-add-btn');
  3406. if (addBtn) {
  3407. if (tab === 'filter') addBtn.innerHTML = '<span>+ Add Filter Rule</span>';
  3408. else if (tab === 'nat') addBtn.innerHTML = '<span>+ Add NAT Rule</span>';
  3409. else if (tab === 'mangle') addBtn.innerHTML = '<span>+ Add Mangle Rule</span>';
  3410. else if (tab === 'addrlist') addBtn.innerHTML = '<span>+ Add Address List</span>';
  3411. else if (tab === 'geo') addBtn.innerHTML = '<span>⚙️ Schedule Settings</span>';
  3412. else if (tab === 'connections') addBtn.innerHTML = '<span>Refresh Flows</span>';
  3413. }
  3414. if (tab === 'filter') renderFilterRules();
  3415. else if (tab === 'nat') renderNATRules();
  3416. else if (tab === 'mangle') renderMangleRules();
  3417. else if (tab === 'addrlist') renderAddressLists();
  3418. else if (tab === 'geo') loadGeoIP();
  3419. else if (tab === 'connections') loadConnections();
  3420. setTimeout(initTableSorting, 50);
  3421. }
  3422. function openCurrentFWModal() {
  3423. if (state.fwSubTab === 'filter') openAddFilterModal();
  3424. else if (state.fwSubTab === 'nat') openAddNATModal();
  3425. else if (state.fwSubTab === 'mangle') openAddMangleModal();
  3426. else if (state.fwSubTab === 'addrlist') openAddAddrListModal();
  3427. else if (state.fwSubTab === 'geo') openGeoIntervalModal();
  3428. else if (state.fwSubTab === 'connections') loadConnections();
  3429. }
  3430. async function loadFirewall(populateDropdowns = true) {
  3431. try {
  3432. const [summaryRes, filterRes, natRes, mangleRes, addrlistRes, geoStatusRes, geoCountriesRes] = await Promise.all([
  3433. fetch(`${API_BASE}/firewall/summary`),
  3434. fetch(`${API_BASE}/firewall/filter`),
  3435. fetch(`${API_BASE}/firewall/nat`),
  3436. fetch(`${API_BASE}/firewall/mangle`),
  3437. fetch(`${API_BASE}/firewall/address-lists`),
  3438. fetch(`${API_BASE}/firewall/geoip/status`),
  3439. fetch(`${API_BASE}/firewall/geoip/countries`)
  3440. ]);
  3441. if (summaryRes.ok) state.fwSummary = await summaryRes.json();
  3442. const applyError = document.getElementById('fw-apply-error');
  3443. if (applyError) {
  3444. applyError.textContent = state.fwSummary?.last_error ? 'Firewall configuration was not applied: ' + state.fwSummary.last_error : '';
  3445. applyError.classList.toggle('hidden', !state.fwSummary?.last_error);
  3446. }
  3447. if (filterRes.ok) state.filterRules = await filterRes.json();
  3448. if (natRes.ok) state.natRules = await natRes.json();
  3449. if (mangleRes.ok) state.mangleRules = await mangleRes.json();
  3450. if (addrlistRes.ok) state.addressLists = await addrlistRes.json();
  3451. if (geoStatusRes.ok) state.geoStatus = await geoStatusRes.json();
  3452. if (geoCountriesRes.ok) state.geoCountries = await geoCountriesRes.json();
  3453. if (applyError) { const messages=[state.fwSummary?.last_error, state.fwSummary?.connections_error, state.geoStatus?.last_error && 'GeoIP: '+state.geoStatus.last_error].filter(Boolean); applyError.textContent=messages.join(' · '); applyError.classList.toggle('hidden', !messages.length); }
  3454. // Badges
  3455. const bFilter = document.getElementById('fw-badge-filter');
  3456. if (bFilter) bFilter.innerText = (state.filterRules || []).length;
  3457. const bNat = document.getElementById('fw-badge-nat');
  3458. if (bNat) bNat.innerText = (state.natRules || []).length;
  3459. const bMangle = document.getElementById('fw-badge-mangle');
  3460. if (bMangle) bMangle.innerText = (state.mangleRules || []).length;
  3461. const bAddr = document.getElementById('fw-badge-addrlist');
  3462. if (bAddr) bAddr.innerText = (state.addressLists || []).length;
  3463. const bGeo = document.getElementById('fw-badge-geo');
  3464. if (bGeo) bGeo.innerText = state.geoStatus?.enabled_count || 0;
  3465. const sigFilter = (state.filterRules || []).map(r => JSON.stringify({...r, packets: 0, bytes: 0})).join(';');
  3466. const sigNat = (state.natRules || []).map(r => JSON.stringify({...r, packets: 0, bytes: 0})).join(';');
  3467. const sigMangle = (state.mangleRules || []).map(r => JSON.stringify({...r, packets: 0, bytes: 0})).join(';');
  3468. const sigAddr = (state.addressLists || []).map(a => JSON.stringify(a)).join(';');
  3469. const tbodyFilter = document.getElementById('filter-table-body');
  3470. if (tbodyFilter) {
  3471. if (populateDropdowns || tbodyFilter.dataset.sig !== sigFilter) {
  3472. tbodyFilter.dataset.sig = sigFilter;
  3473. renderFilterRules();
  3474. } else {
  3475. // In-place live stats update (ZERO flicker)
  3476. (state.filterRules || []).forEach(r => {
  3477. const p = document.getElementById(`filter-pkts-${r.id}`);
  3478. if (p) p.innerText = `${(r.packets || 0).toLocaleString()}p`;
  3479. const b = document.getElementById(`filter-bytes-${r.id}`);
  3480. if (b) b.innerText = formatTraffic(r.bytes || 0).replace('/s', '');
  3481. });
  3482. }
  3483. }
  3484. const tbodyNat = document.getElementById('nat-table-body');
  3485. if (tbodyNat) {
  3486. if (populateDropdowns || tbodyNat.dataset.sig !== sigNat) {
  3487. tbodyNat.dataset.sig = sigNat;
  3488. renderNATRules();
  3489. } else {
  3490. (state.natRules || []).forEach(r => {
  3491. const p = document.getElementById(`nat-pkts-${r.id}`);
  3492. if (p) p.innerText = `${(r.packets || 0).toLocaleString()}p`;
  3493. const b = document.getElementById(`nat-bytes-${r.id}`);
  3494. if (b) b.innerText = formatTraffic(r.bytes || 0).replace('/s', '');
  3495. });
  3496. }
  3497. }
  3498. const tbodyMangle = document.getElementById('mangle-table-body');
  3499. if (tbodyMangle) {
  3500. if (populateDropdowns || tbodyMangle.dataset.sig !== sigMangle) {
  3501. tbodyMangle.dataset.sig = sigMangle;
  3502. renderMangleRules();
  3503. } else {
  3504. (state.mangleRules || []).forEach(r => {
  3505. const p = document.getElementById(`mangle-pkts-${r.id}`);
  3506. if (p) p.innerText = `${(r.packets || 0).toLocaleString()}p`;
  3507. const b = document.getElementById(`mangle-bytes-${r.id}`);
  3508. if (b) b.innerText = formatTraffic(r.bytes || 0).replace('/s', '');
  3509. });
  3510. }
  3511. }
  3512. const tbodyAddr = document.getElementById('addrlist-table-body');
  3513. if (tbodyAddr && (populateDropdowns || tbodyAddr.dataset.sig !== sigAddr)) {
  3514. tbodyAddr.dataset.sig = sigAddr;
  3515. renderAddressLists();
  3516. }
  3517. renderGeoCountries();
  3518. if (state.fwSubTab === 'connections') {
  3519. loadConnections();
  3520. }
  3521. } catch (err) {
  3522. console.error('Failed to load firewall:', err);
  3523. }
  3524. }
  3525. // ----------------- Filter Rules -----------------
  3526. function renderFilterRules() {
  3527. const chainFilter = document.getElementById('filter-filter-chain')?.value || '';
  3528. const tbody = document.getElementById('filter-table-body');
  3529. const empty = document.getElementById('filter-empty');
  3530. if (!tbody) return;
  3531. tbody.innerHTML = '';
  3532. const rules = (state.filterRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  3533. document.getElementById('filter-count-badge').innerText = `${rules.length} Rules`;
  3534. if (rules.length === 0) {
  3535. empty?.classList.remove('hidden');
  3536. return;
  3537. }
  3538. empty?.classList.add('hidden');
  3539. rules.forEach((raw, idx) => {
  3540. const r = safeFirewallRow(raw);
  3541. const tr = document.createElement('tr');
  3542. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  3543. const ports = [r.src_port ? 's:' + r.src_port : '', r.dst_port ? 'd:' + r.dst_port : ''].filter(Boolean).join(' ');
  3544. const ifaces = [r.in_interface ? 'in:' + r.in_interface : '', r.out_interface ? 'out:' + r.out_interface : ''].filter(Boolean).join(' ');
  3545. let actionExtra = '';
  3546. if (r.action === 'reject') {
  3547. actionExtra = `<span class="block text-[10px] text-rose-300 font-mono mt-0.5">(${r.reject_with || 'icmp-net-unreach'})</span>`;
  3548. } else if (r.action === 'jump') {
  3549. actionExtra = `<span class="block text-[10px] text-yellow-300 font-mono mt-0.5">&rarr; ${r.jump_target || '-'}</span>`;
  3550. } else if (r.action.includes('address-list') || r.action.includes('address list')) {
  3551. actionExtra = `<span class="block text-[10px] text-emerald-300 font-mono mt-0.5">&rarr; ${r.address_list || '-'}</span>`;
  3552. } else if (r.action === 'log' && r.log_prefix) {
  3553. actionExtra = `<span class="block text-[10px] text-slate-400 font-mono mt-0.5">${r.log_prefix}</span>`;
  3554. }
  3555. tr.innerHTML = `
  3556. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  3557. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  3558. <td class="py-2.5 px-3 font-bold text-white">${r.chain}</td>
  3559. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  3560. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  3561. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'} <span class="text-[9px] text-slate-500">IPv${r.ip_version || 4}</span></td>
  3562. <td class="py-2.5 px-3 text-amber-400">${ports || '-'}</td>
  3563. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  3564. <td class="py-2.5 px-3">${renderActionBadge(r.action)}${actionExtra}</td>
  3565. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  3566. <span class="text-slate-300" id="filter-pkts-${r.id}">${(r.packets || 0).toLocaleString()}p</span> /
  3567. <span class="text-slate-500" id="filter-bytes-${r.id}">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  3568. </td>
  3569. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  3570. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  3571. <button onclick="moveFilterRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  3572. <button onclick="moveFilterRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  3573. <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>
  3574. <button onclick="openEditFilterModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  3575. <button onclick="deleteFilterRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  3576. </td>
  3577. `;
  3578. tbody.appendChild(tr);
  3579. });
  3580. }
  3581. function formatTarget(addr, list, geo) {
  3582. const parts = [];
  3583. if (addr) parts.push(`<span>${addr}</span>`);
  3584. if (list) {
  3585. const inv = list.startsWith('!') ? '!' : '';
  3586. const clean = list.replace(/^!/, '');
  3587. 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>`);
  3588. }
  3589. if (geo) {
  3590. const inv = geo.startsWith('!') ? '!' : '';
  3591. const clean = geo.replace(/^!/, '').replace(/^geo:/, '');
  3592. 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>`);
  3593. }
  3594. if (parts.length === 0) return '<span class="text-slate-600">0.0.0.0/0</span>';
  3595. return parts.join(' ');
  3596. }
  3597. function populateInterfaceSelect(selectId, currentVal = '') {
  3598. const sel = document.getElementById(selectId);
  3599. if (!sel) return;
  3600. sel.innerHTML = '<option value="">(Any Interface)</option>';
  3601. (state.interfaces || []).forEach(i => {
  3602. const opt = document.createElement('option');
  3603. opt.value = i.name;
  3604. opt.innerText = `${i.name} (${i.role || i.type})`;
  3605. if (i.name === currentVal) opt.selected = true;
  3606. sel.appendChild(opt);
  3607. });
  3608. }
  3609. function populateAddressListSelect(selectId, currentVal = '') {
  3610. const sel = document.getElementById(selectId);
  3611. if (!sel) return;
  3612. sel.innerHTML = '<option value="">(None)</option>';
  3613. const cleanVal = (currentVal || '').replace(/^!/, '');
  3614. const ruleLists = [...(state.filterRules||[]), ...(state.natRules||[]), ...(state.mangleRules||[])].flatMap(r => [r.src_address_list,r.dst_address_list,r.address_list]).filter(Boolean).map(n => n.replace(/^!/, '')).filter(n => !n.startsWith('geo:') && !n.startsWith('geo_'));
  3615. const customNames = Array.from(new Set([...(state.addressLists || []).map(a => a.name), ...ruleLists])).sort();
  3616. customNames.forEach(name => {
  3617. const count = (state.addressLists || []).filter(a => a.name === name).length;
  3618. const opt = document.createElement('option');
  3619. opt.value = name;
  3620. opt.innerText = `${name} (${count} entries)`;
  3621. if (name === cleanVal) opt.selected = true;
  3622. sel.appendChild(opt);
  3623. });
  3624. if (cleanVal && !Array.from(sel.options).some(option => option.value === cleanVal)) {
  3625. const opt = document.createElement('option');
  3626. opt.value = cleanVal;
  3627. opt.innerText = cleanVal;
  3628. opt.selected = true;
  3629. sel.appendChild(opt);
  3630. }
  3631. populateCommonAddrListDatalist();
  3632. }
  3633. function populateCommonAddrListDatalist() {
  3634. const dl = document.getElementById('fw-addrlist-datalist');
  3635. if (!dl) return;
  3636. dl.innerHTML = '';
  3637. const names = Array.from(new Set((state.addressLists || []).map(a => a.name).filter(Boolean))).sort();
  3638. names.forEach(name => {
  3639. const opt = document.createElement('option');
  3640. opt.value = name;
  3641. dl.appendChild(opt);
  3642. });
  3643. }
  3644. function populateGeoIPSelect(selectId, currentVal = '') {
  3645. const sel = document.getElementById(selectId);
  3646. if (!sel) return;
  3647. sel.innerHTML = '<option value="">(None)</option>';
  3648. const cleanVal = (currentVal || '').replace(/^!/, '').replace(/^geo:/, '').toUpperCase();
  3649. // Presets optgroup
  3650. const grpPresets = document.createElement('optgroup');
  3651. grpPresets.label = '⚡ Regional Presets';
  3652. const presets = [
  3653. { code: 'EU', label: '🇪🇺 European Union (EU - 27 countries)' },
  3654. { code: 'BALKANS', label: '🏛️ Balkans (GR, CY, BG, RO, AL, etc.)' },
  3655. { code: 'BLOCKLIST', label: '🛡️ High-Risk Blocklist (CN, RU, IR, KP, BY)' }
  3656. ];
  3657. presets.forEach(p => {
  3658. const opt = document.createElement('option');
  3659. opt.value = p.code;
  3660. opt.innerText = p.label;
  3661. if (p.code === cleanVal) opt.selected = true;
  3662. grpPresets.appendChild(opt);
  3663. });
  3664. sel.appendChild(grpPresets);
  3665. // All Countries optgroup
  3666. const grpCountries = document.createElement('optgroup');
  3667. grpCountries.label = '🌍 All Countries';
  3668. const countries = (state.geoCountries || []).slice().sort((a, b) => a.name.localeCompare(b.name));
  3669. countries.forEach(c => {
  3670. const opt = document.createElement('option');
  3671. opt.value = c.code;
  3672. const subnetsInfo = c.subnet_count ? ` [${c.subnet_count.toLocaleString()} subnets]` : '';
  3673. opt.innerText = `${c.name} (${c.code})${subnetsInfo}`;
  3674. if (c.code === cleanVal) opt.selected = true;
  3675. grpCountries.appendChild(opt);
  3676. });
  3677. sel.appendChild(grpCountries);
  3678. }
  3679. // ==================== FIREWALL FILTER MODAL (DEBTIK WEBFIG / WINBOX V4) ====================
  3680. function switchFwRuleTab(tab) {
  3681. state.activeFwRuleTab = tab;
  3682. document.querySelectorAll('.fw-rule-tab-btn').forEach(btn => {
  3683. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  3684. btn.classList.add('text-slate-400', 'border-transparent');
  3685. });
  3686. const activeBtn = document.getElementById(`fw-tab-btn-${tab}`);
  3687. if (activeBtn) {
  3688. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  3689. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  3690. }
  3691. document.querySelectorAll('.fw-rule-pane').forEach(p => p.classList.add('hidden'));
  3692. const activePane = document.getElementById(`fw-pane-${tab}`);
  3693. if (activePane) activePane.classList.remove('hidden');
  3694. if (tab === 'statistics') {
  3695. startFwStatPolling();
  3696. } else {
  3697. stopFwStatPolling();
  3698. }
  3699. }
  3700. function toggleFwField(fieldKey, expand) {
  3701. const plusBtn = document.getElementById(`fw-plus-${fieldKey}`);
  3702. const fieldBox = document.getElementById(`fw-field-${fieldKey}`);
  3703. if (!plusBtn || !fieldBox) return;
  3704. if (expand) {
  3705. plusBtn.classList.add('hidden');
  3706. fieldBox.classList.remove('hidden');
  3707. const valInput = document.getElementById(`fw-val-${fieldKey}`);
  3708. if (valInput) valInput.focus();
  3709. } else {
  3710. fieldBox.classList.add('hidden');
  3711. plusBtn.classList.remove('hidden');
  3712. const valInput = document.getElementById(`fw-val-${fieldKey}`);
  3713. if (valInput) {
  3714. if (valInput.tagName === 'SELECT') {
  3715. valInput.selectedIndex = 0;
  3716. } else {
  3717. valInput.value = '';
  3718. }
  3719. }
  3720. const invInput = document.getElementById(`fw-inv-${fieldKey}`);
  3721. if (invInput) invInput.checked = false;
  3722. if (fieldKey === 'cs') {
  3723. ['filter-modal-cs-established', 'filter-modal-cs-related', 'filter-modal-cs-new', 'filter-modal-cs-invalid', 'filter-modal-cs-untracked'].forEach(id => {
  3724. const el = document.getElementById(id);
  3725. if (el) el.checked = false;
  3726. });
  3727. }
  3728. if (fieldKey === 'natstate') {
  3729. ['filter-modal-nat-srcnat', 'filter-modal-nat-dstnat'].forEach(id => {
  3730. const el = document.getElementById(id);
  3731. if (el) el.checked = false;
  3732. });
  3733. }
  3734. if (fieldKey === 'days') {
  3735. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3736. const el = document.getElementById(`fw-day-${d}`);
  3737. if (el) el.checked = true;
  3738. });
  3739. }
  3740. }
  3741. }
  3742. function setFwFieldVal(fieldKey, value, hasInvert = false) {
  3743. if (fieldKey === 'ipsec' && typeof value === 'string') value = value.replace(':', ',');
  3744. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  3745. toggleFwField(fieldKey, true);
  3746. let strVal = String(value);
  3747. if (hasInvert) {
  3748. const inv = strVal.startsWith('!');
  3749. if (inv) strVal = strVal.slice(1);
  3750. const invEl = document.getElementById(`fw-inv-${fieldKey}`);
  3751. if (invEl) invEl.checked = inv;
  3752. else if (inv) strVal = '!'+strVal;
  3753. }
  3754. const valEl = document.getElementById(`fw-val-${fieldKey}`);
  3755. if (valEl) { if (valEl.tagName === 'SELECT' && !Array.from(valEl.options).some(o => o.value === strVal)) { const option=document.createElement('option'); option.value=strVal; option.textContent=strVal+' (saved)'; valEl.appendChild(option); } valEl.value = strVal; }
  3756. } else {
  3757. toggleFwField(fieldKey, false);
  3758. }
  3759. }
  3760. function getFwFieldVal(fieldKey, hasInvert = false) {
  3761. const fieldBox = document.getElementById(`fw-field-${fieldKey}`);
  3762. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  3763. const valEl = document.getElementById(`fw-val-${fieldKey}`);
  3764. let v = valEl ? valEl.value.trim() : '';
  3765. if (!v) return '';
  3766. if (hasInvert) {
  3767. const invEl = document.getElementById(`fw-inv-${fieldKey}`);
  3768. if (invEl && invEl.checked) {
  3769. v = '!' + v.replace(/^!/, '');
  3770. }
  3771. }
  3772. return v;
  3773. }
  3774. function toggleMaximizeFilterModal() {
  3775. const win = document.getElementById('filter-modal-window');
  3776. if (!win) return;
  3777. if (win.classList.contains('max-w-[720px]')) {
  3778. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  3779. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  3780. } else {
  3781. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  3782. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  3783. }
  3784. }
  3785. function openAddFilterModal() {
  3786. const tos = document.getElementById('fw-val-tos'); if (tos) tos.value = '';
  3787. switchFwRuleTab('general');
  3788. setFirewallDays('fw', '');
  3789. const badge = document.getElementById('fw-modal-badge');
  3790. if (badge) badge.innerText = 'New...';
  3791. document.getElementById('filter-modal-id').value = '';
  3792. document.getElementById('filter-modal-family').value = '4';
  3793. document.getElementById('filter-modal-enabled').checked = true;
  3794. document.getElementById('filter-modal-comment').value = '';
  3795. document.getElementById('filter-modal-chain').value = 'forward';
  3796. document.getElementById('filter-modal-action').value = 'accept';
  3797. document.getElementById('filter-modal-log').checked = false;
  3798. populateInterfaceSelect('fw-val-iniface');
  3799. populateInterfaceSelect('fw-val-outiface');
  3800. populateAddressListSelect('fw-val-srclist');
  3801. populateAddressListSelect('fw-val-dstlist');
  3802. populateGeoIPSelect('fw-val-srcgeo');
  3803. populateGeoIPSelect('fw-val-dstgeo');
  3804. const allFieldKeys = [
  3805. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  3806. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  3807. 'routingmark', 'conntype', 'cs', 'natstate',
  3808. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  3809. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  3810. 'ipsec', 'tlshost', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  3811. 'pktsize', 'random', 'tcpflags', 'icmpoptions', 'ipv4options', 'ttl',
  3812. 'time', 'days', 'limit', 'dstlimit', 'psd', 'logprefix'
  3813. ];
  3814. allFieldKeys.forEach(k => toggleFwField(k, false));
  3815. resetRuleCounterDisplay();
  3816. toggleFilterActionFields();
  3817. refreshFirewallRejectTypes();
  3818. document.getElementById('filter-modal').classList.remove('hidden');
  3819. }
  3820. function openEditFilterModal(id) {
  3821. id = decodeURIComponent(id);
  3822. const r = (state.filterRules || []).find(rule => rule.id === id);
  3823. if (!r) return;
  3824. switchFwRuleTab('general');
  3825. const badge = document.getElementById('fw-modal-badge');
  3826. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  3827. document.getElementById('filter-modal-id').value = r.id;
  3828. document.getElementById('filter-modal-family').value = String(r.ip_version || 4);
  3829. document.getElementById('filter-modal-enabled').checked = !r.disabled;
  3830. document.getElementById('filter-modal-comment').value = r.comment || '';
  3831. document.getElementById('filter-modal-chain').value = r.chain || 'forward';
  3832. setFirewallActionSelection('filter', r.action || 'accept');
  3833. document.getElementById('filter-modal-log').checked = !!r.log;
  3834. populateInterfaceSelect('fw-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  3835. populateInterfaceSelect('fw-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  3836. populateAddressListSelect('fw-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  3837. populateAddressListSelect('fw-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  3838. populateGeoIPSelect('fw-val-srcgeo', r.src_geoip || '');
  3839. populateGeoIPSelect('fw-val-dstgeo', r.dst_geoip || '');
  3840. setFwFieldVal('src', r.src_address, true);
  3841. setFwFieldVal('dst', r.dst_address, true);
  3842. setFwFieldVal('srclist', r.src_address_list, true);
  3843. setFwFieldVal('dstlist', r.dst_address_list, true);
  3844. setFwFieldVal('srcgeo', r.src_geoip, true);
  3845. setFwFieldVal('dstgeo', r.dst_geoip, true);
  3846. if (r.protocol && r.protocol !== 'all') {
  3847. setFwFieldVal('proto', r.protocol, true);
  3848. } else {
  3849. toggleFwField('proto', false);
  3850. }
  3851. setFwFieldVal('sport', r.src_port, true);
  3852. setFwFieldVal('dport', r.dst_port, true);
  3853. setFwFieldVal('anyport', r.any_port, true);
  3854. setFwFieldVal('iniface', r.in_interface, true);
  3855. setFwFieldVal('outiface', r.out_interface, true);
  3856. setFwFieldVal('inifacelist', r.in_interface_list, true);
  3857. setFwFieldVal('outifacelist', r.out_interface_list, true);
  3858. setFwFieldVal('pktmark', r.packet_mark, true);
  3859. setFwFieldVal('connmark', r.connection_mark, true);
  3860. setFwFieldVal('routingmark', r.routing_mark, true);
  3861. setFwFieldVal('conntype', r.connection_type, false);
  3862. const states = r.connection_state || [];
  3863. if (states.length > 0) {
  3864. toggleFwField('cs', true);
  3865. document.getElementById('filter-modal-cs-established').checked = states.includes('established');
  3866. document.getElementById('filter-modal-cs-related').checked = states.includes('related');
  3867. document.getElementById('filter-modal-cs-new').checked = states.includes('new');
  3868. document.getElementById('filter-modal-cs-invalid').checked = states.includes('invalid');
  3869. document.getElementById('filter-modal-cs-untracked').checked = states.includes('untracked');
  3870. } else {
  3871. toggleFwField('cs', false);
  3872. }
  3873. const natStates = r.connection_nat_state || [];
  3874. if (natStates.length > 0) {
  3875. toggleFwField('natstate', true);
  3876. document.getElementById('filter-modal-nat-srcnat').checked = natStates.includes('srcnat');
  3877. document.getElementById('filter-modal-nat-dstnat').checked = natStates.includes('dstnat');
  3878. } else {
  3879. toggleFwField('natstate', false);
  3880. }
  3881. // Advanced tab fields
  3882. setFwFieldVal('layer7', r.layer7_protocol, false);
  3883. setFwFieldVal('content', r.content, false);
  3884. setFwFieldVal('connbytes', r.connection_bytes, false);
  3885. setFwFieldVal('connrate', r.connection_rate, false);
  3886. setFwFieldVal('pcc', r.pcc, false);
  3887. setFwFieldVal('srcmac', r.src_mac_address, true);
  3888. setFwFieldVal('outbridgeport', r.out_bridge_port, false);
  3889. setFwFieldVal('inbridgeport', r.in_bridge_port, false);
  3890. setFwFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  3891. setFwFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  3892. setFwFieldVal('ipsec', r.ipsec_policy, false);
  3893. setFwFieldVal('tlshost', r.tls_host, false);
  3894. setFwFieldVal('ingresspriority', r.ingress_priority, false);
  3895. setFwFieldVal('priority', r.priority, false);
  3896. setFwFieldVal('dscp', r.dscp, false);
  3897. setFwFieldVal('tcpmss', r.tcp_mss, false);
  3898. { const tosEl = document.getElementById('fw-val-tos'); if (tosEl) tosEl.value = r.tos || ''; }
  3899. setFwFieldVal('pktsize', r.packet_size, false);
  3900. setFwFieldVal('random', r.random, false);
  3901. setFwFieldVal('tcpflags', r.tcp_flags, false);
  3902. setFwFieldVal('icmpoptions', r.icmp_options, false);
  3903. setFwFieldVal('ipv4options', r.ipv4_options, false);
  3904. setFwFieldVal('ttl', r.ttl, false);
  3905. // Extra tab fields
  3906. setFwFieldVal('time', r.time, false);
  3907. if (r.days) {
  3908. toggleFwField('days', true);
  3909. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3910. const chk = document.getElementById(`fw-day-${d}`);
  3911. if (chk) chk.checked = r.days.toLowerCase().includes(d);
  3912. });
  3913. } else {
  3914. toggleFwField('days', false);
  3915. }
  3916. setFwFieldVal('limit', r.limit, false);
  3917. setFwFieldVal('dstlimit', r.dst_limit, false);
  3918. setFwFieldVal('psd', r.psd, false);
  3919. // Action fields
  3920. if (r.reject_with) {
  3921. const rwEl = document.getElementById('filter-modal-rejectwith');
  3922. if (rwEl) rwEl.value = r.reject_with;
  3923. }
  3924. if (r.jump_target) {
  3925. const jtEl = document.getElementById('filter-modal-jumptarget');
  3926. if (jtEl) jtEl.value = r.jump_target;
  3927. }
  3928. if (r.address_list) {
  3929. const alEl = document.getElementById('filter-modal-action-addrlist');
  3930. if (alEl) alEl.value = r.address_list;
  3931. }
  3932. if (r.address_list_timeout) {
  3933. const toEl = document.getElementById('filter-modal-action-timeout');
  3934. if (toEl) toEl.value = r.address_list_timeout;
  3935. }
  3936. setFwFieldVal('logprefix', r.log_prefix, false);
  3937. // Statistics
  3938. const bEl = document.getElementById('fw-stat-bytes');
  3939. const pEl = document.getElementById('fw-stat-packets');
  3940. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  3941. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  3942. state.fwLastBytes = r.bytes || 0;
  3943. state.fwLastPackets = r.packets || 0;
  3944. state.fwLastTimestamp = Date.now();
  3945. state.fwStatRateHistory = new Array(30).fill(0);
  3946. state.fwStatPktHistory = new Array(30).fill(0);
  3947. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  3948. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  3949. toggleFilterActionFields();
  3950. refreshFirewallRejectTypes();
  3951. document.getElementById('filter-modal').classList.remove('hidden');
  3952. }
  3953. function closeFilterModal() {
  3954. stopFwStatPolling();
  3955. document.getElementById('filter-modal').classList.add('hidden');
  3956. }
  3957. function toggleFilterActionFields() {
  3958. const act = document.getElementById('filter-modal-action')?.value || 'accept';
  3959. const rejectBox = document.getElementById('filter-action-reject-box');
  3960. const jumpBox = document.getElementById('filter-action-jump-box');
  3961. const addrBox = document.getElementById('filter-action-addrlist-box');
  3962. if (rejectBox) {
  3963. if (act === 'reject') rejectBox.classList.remove('hidden');
  3964. else rejectBox.classList.add('hidden');
  3965. }
  3966. if (jumpBox) {
  3967. if (act === 'jump') jumpBox.classList.remove('hidden');
  3968. else jumpBox.classList.add('hidden');
  3969. }
  3970. if (addrBox) {
  3971. if (act === 'add-dst-to-address-list' || act === 'add-src-to-address-list' || act.includes('address-list') || act.includes('address list')) {
  3972. addrBox.classList.remove('hidden');
  3973. } else {
  3974. addrBox.classList.add('hidden');
  3975. }
  3976. }
  3977. if (act === 'log') {
  3978. const logEl = document.getElementById('filter-modal-log');
  3979. if (logEl) logEl.checked = true;
  3980. toggleFwField('logprefix', true);
  3981. }
  3982. }
  3983. function toggleFwLogPrefix() {
  3984. const isLog = document.getElementById('filter-modal-log')?.checked;
  3985. toggleFwField('logprefix', !!isLog);
  3986. }
  3987. function copyFilterRule() {
  3988. document.getElementById('filter-modal-id').value = '';
  3989. const badge = document.getElementById('fw-modal-badge');
  3990. if (badge) badge.innerText = 'New...';
  3991. showToast('Rule Cloned', 'Ready to save as a new rule copy', 'info');
  3992. }
  3993. function resetRuleCounterDisplay() {
  3994. state.fwStatRateHistory = new Array(30).fill(0);
  3995. state.fwStatPktHistory = new Array(30).fill(0);
  3996. state.fwLastBytes = 0;
  3997. state.fwLastPackets = 0;
  3998. state.fwLastTimestamp = Date.now();
  3999. const bEl = document.getElementById('fw-stat-bytes');
  4000. const pEl = document.getElementById('fw-stat-packets');
  4001. const rEl = document.getElementById('fw-stat-rate');
  4002. const prEl = document.getElementById('fw-stat-pktrate');
  4003. if (bEl) bEl.value = '0 B';
  4004. if (pEl) pEl.value = '0';
  4005. if (rEl) rEl.value = '0 bps';
  4006. if (prEl) prEl.value = '0 p/s';
  4007. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  4008. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  4009. showToast('Counters Reset', 'Rule counter display reset to 0', 'info');
  4010. }
  4011. async function resetAllFwCounters() {
  4012. try {
  4013. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  4014. if (res.ok) {
  4015. resetRuleCounterDisplay();
  4016. showToast('All Counters Reset', 'All firewall counters zeroed', 'success');
  4017. loadFirewall(false);
  4018. }
  4019. } catch (err) {
  4020. showToast('Error', err.message, 'error');
  4021. }
  4022. }
  4023. async function applyFilterRule(closeAfter = false) {
  4024. const id = document.getElementById('filter-modal-id').value;
  4025. if (!reviewLegacyFirewallSettings('filter', id)) return;
  4026. let selectedDays; try { selectedDays = getFirewallDays('fw'); } catch(error) { showToast('Error', error.message, 'error'); return; }
  4027. const chain = document.getElementById('filter-modal-chain').value;
  4028. const action = document.getElementById('filter-modal-action').value;
  4029. const comment = document.getElementById('filter-modal-comment').value.trim();
  4030. const enabled = document.getElementById('filter-modal-enabled').checked;
  4031. const src = getFwFieldVal('src', true);
  4032. const dst = getFwFieldVal('dst', true);
  4033. const srclist = getFwFieldVal('srclist', true);
  4034. const dstlist = getFwFieldVal('dstlist', true);
  4035. const srcgeo = getFwFieldVal('srcgeo', true);
  4036. const dstgeo = getFwFieldVal('dstgeo', true);
  4037. const proto = getFwFieldVal('proto', true);
  4038. const sport = getFwFieldVal('sport', true);
  4039. const dport = getFwFieldVal('dport', true);
  4040. const anyport = getFwFieldVal('anyport', true);
  4041. const iniface = getFwFieldVal('iniface', true);
  4042. const outiface = getFwFieldVal('outiface', true);
  4043. const inifacelist = getFwFieldVal('inifacelist', true);
  4044. const outifacelist = getFwFieldVal('outifacelist', true);
  4045. const pktmark = getFwFieldVal('pktmark', true);
  4046. const connmark = getFwFieldVal('connmark', true);
  4047. const routingmark = getFwFieldVal('routingmark', true);
  4048. const conntype = getFwFieldVal('conntype', false);
  4049. const states = [];
  4050. const csBox = document.getElementById('fw-field-cs');
  4051. if (csBox && !csBox.classList.contains('hidden')) {
  4052. if (document.getElementById('filter-modal-cs-established')?.checked) states.push('established');
  4053. if (document.getElementById('filter-modal-cs-related')?.checked) states.push('related');
  4054. if (document.getElementById('filter-modal-cs-new')?.checked) states.push('new');
  4055. if (document.getElementById('filter-modal-cs-invalid')?.checked) states.push('invalid');
  4056. if (document.getElementById('filter-modal-cs-untracked')?.checked) states.push('untracked');
  4057. }
  4058. const natStates = [];
  4059. const natBox = document.getElementById('fw-field-natstate');
  4060. if (natBox && !natBox.classList.contains('hidden')) {
  4061. if (document.getElementById('filter-modal-nat-srcnat')?.checked) natStates.push('srcnat');
  4062. if (document.getElementById('filter-modal-nat-dstnat')?.checked) natStates.push('dstnat');
  4063. }
  4064. const payload = {
  4065. ip_version: Number(document.getElementById('filter-modal-family').value),
  4066. id,
  4067. chain,
  4068. action,
  4069. protocol: proto || 'all',
  4070. src_address: src,
  4071. dst_address: dst,
  4072. src_port: sport,
  4073. dst_port: dport,
  4074. any_port: anyport,
  4075. in_interface: iniface,
  4076. out_interface: outiface,
  4077. in_interface_list: inifacelist,
  4078. out_interface_list: outifacelist,
  4079. packet_mark: pktmark,
  4080. connection_mark: connmark,
  4081. routing_mark: routingmark,
  4082. connection_type: conntype,
  4083. connection_state: states,
  4084. connection_nat_state: natStates,
  4085. src_address_list: srclist,
  4086. dst_address_list: dstlist,
  4087. src_geoip: srcgeo,
  4088. dst_geoip: dstgeo,
  4089. comment,
  4090. disabled: !enabled,
  4091. // Advanced tab
  4092. content: getFwFieldVal('content', false),
  4093. src_mac_address: getFwFieldVal('srcmac', true),
  4094. out_bridge_port: getFwFieldVal('outbridgeport', false),
  4095. in_bridge_port: getFwFieldVal('inbridgeport', false),
  4096. ipsec_policy: getFwFieldVal('ipsec', false),
  4097. dscp: getFwFieldVal('dscp', false),
  4098. tcp_mss: getFwFieldVal('tcpmss', false),
  4099. tos: document.getElementById('fw-val-tos')?.value || '',
  4100. packet_size: getFwFieldVal('pktsize', false),
  4101. random: getFwFieldVal('random', false),
  4102. tcp_flags: getFwFieldVal('tcpflags', false),
  4103. icmp_options: getFwFieldVal('icmpoptions', false),
  4104. ttl: getFwFieldVal('ttl', false),
  4105. days: selectedDays,
  4106. // Extra tab
  4107. time: getFwFieldVal('time', false),
  4108. limit: getFwFieldVal('limit', false),
  4109. // Action tab
  4110. reject_with: action === 'reject' ? (document.getElementById('filter-modal-rejectwith')?.value || '') : '',
  4111. jump_target: action === 'jump' ? (document.getElementById('filter-modal-jumptarget')?.value || '') : '',
  4112. address_list: action.startsWith('add-') ? (document.getElementById('filter-modal-action-addrlist')?.value || '') : '',
  4113. address_list_timeout: action.startsWith('add-') ? (document.getElementById('filter-modal-action-timeout')?.value || '') : '',
  4114. log: document.getElementById('filter-modal-log')?.checked || false,
  4115. log_prefix: getFwFieldVal('logprefix', false)
  4116. };
  4117. try {
  4118. const res = await fetch(`${API_BASE}/firewall/filter`, {
  4119. method: 'POST',
  4120. headers: { 'Content-Type': 'application/json' },
  4121. body: JSON.stringify(payload)
  4122. });
  4123. if (res.ok) {
  4124. const data = await res.json();
  4125. showToast('Filter Rule Saved', 'Rule applied successfully to firewall', 'success');
  4126. loadFirewall(false);
  4127. if (closeAfter) {
  4128. closeFilterModal();
  4129. } else {
  4130. if (data.id) {
  4131. document.getElementById('filter-modal-id').value = data.id;
  4132. const badge = document.getElementById('fw-modal-badge');
  4133. if (badge) badge.innerText = `#${data.id}`;
  4134. }
  4135. }
  4136. } else {
  4137. const err = await res.json();
  4138. showToast('Error', err.message || 'Failed to save rule', 'error');
  4139. }
  4140. } catch (err) {
  4141. showToast('Error', err.message, 'error');
  4142. }
  4143. }
  4144. function submitSaveFilterRule(e) {
  4145. if (e && e.preventDefault) e.preventDefault();
  4146. return applyFilterRule(true);
  4147. }
  4148. function startFwStatPolling() {
  4149. stopFwStatPolling();
  4150. pollRuleStats();
  4151. state.fwStatInterval = setInterval(pollRuleStats, 1000);
  4152. }
  4153. function stopFwStatPolling() {
  4154. if (state.fwStatInterval) {
  4155. clearInterval(state.fwStatInterval);
  4156. state.fwStatInterval = null;
  4157. }
  4158. }
  4159. async function pollRuleStats() {
  4160. const id = document.getElementById('filter-modal-id')?.value;
  4161. if (!id) {
  4162. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory || new Array(30).fill(0), 'bps', 'fw-stat-legend-rate');
  4163. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory || new Array(30).fill(0), 'p/s', 'fw-stat-legend-pktrate');
  4164. return;
  4165. }
  4166. try {
  4167. const res = await fetch(`${API_BASE}/firewall/filter`);
  4168. if (!res.ok) return;
  4169. const rules = await res.json();
  4170. const r = rules.find(x => x.id === id);
  4171. if (!r) return;
  4172. const now = Date.now();
  4173. const dt = Math.max(0.2, (now - (state.fwLastTimestamp || now)) / 1000);
  4174. state.fwLastTimestamp = now;
  4175. const curBytes = r.bytes || 0;
  4176. const curPackets = r.packets || 0;
  4177. const deltaBytes = Math.max(0, curBytes - (state.fwLastBytes ?? curBytes));
  4178. const deltaPkts = Math.max(0, curPackets - (state.fwLastPackets ?? curPackets));
  4179. state.fwLastBytes = curBytes;
  4180. state.fwLastPackets = curPackets;
  4181. const rateBps = Math.round((deltaBytes * 8) / dt);
  4182. const ratePkt = Math.round(deltaPkts / dt);
  4183. if (!state.fwStatRateHistory) state.fwStatRateHistory = new Array(30).fill(0);
  4184. if (!state.fwStatPktHistory) state.fwStatPktHistory = new Array(30).fill(0);
  4185. state.fwStatRateHistory.push(rateBps);
  4186. if (state.fwStatRateHistory.length > 30) state.fwStatRateHistory.shift();
  4187. state.fwStatPktHistory.push(ratePkt);
  4188. if (state.fwStatPktHistory.length > 30) state.fwStatPktHistory.shift();
  4189. const bEl = document.getElementById('fw-stat-bytes');
  4190. const pEl = document.getElementById('fw-stat-packets');
  4191. const rEl = document.getElementById('fw-stat-rate');
  4192. const prEl = document.getElementById('fw-stat-pktrate');
  4193. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  4194. if (pEl) pEl.value = curPackets.toLocaleString();
  4195. if (rEl) rEl.value = formatBps(rateBps);
  4196. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  4197. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  4198. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  4199. } catch (e) {
  4200. console.error('Error polling rule stats', e);
  4201. }
  4202. }
  4203. function formatBps(bps) {
  4204. if (bps >= 1000000000) return (bps / 1000000000).toFixed(1) + ' Gbps';
  4205. if (bps >= 1000000) return (bps / 1000000).toFixed(1) + ' Mbps';
  4206. if (bps >= 1000) return (bps / 1000).toFixed(1) + ' kbps';
  4207. return bps + ' bps';
  4208. }
  4209. function renderFwSparkline(svgId, dataArray, unit, legendId) {
  4210. const svg = document.getElementById(svgId);
  4211. if (!svg) return;
  4212. const w = 500;
  4213. const h = 100;
  4214. const paddingRight = 45;
  4215. const graphWidth = w - paddingRight;
  4216. const maxVal = Math.max(5, ...dataArray);
  4217. const currentVal = dataArray[dataArray.length - 1] || 0;
  4218. const leg = document.getElementById(legendId);
  4219. if (leg) {
  4220. leg.innerText = unit === 'bps' ? formatBps(currentVal) : `${currentVal.toLocaleString()} p/s`;
  4221. }
  4222. let gridLines = '';
  4223. for (let i = 0; i <= 5; i++) {
  4224. const y = 8 + (i * (h - 18) / 5);
  4225. const valAtLevel = Math.round(maxVal * (5 - i) / 5);
  4226. const label = unit === 'bps' ? formatBps(valAtLevel) : `${valAtLevel} p/s`;
  4227. gridLines += `
  4228. <line x1="0" y1="${y.toFixed(1)}" x2="${graphWidth}" y2="${y.toFixed(1)}" stroke="#1e2c3e" stroke-width="1" />
  4229. <text x="${w - 2}" y="${(y + 3).toFixed(1)}" fill="#64748b" font-size="9" font-family="monospace" text-anchor="end">${label}</text>
  4230. `;
  4231. }
  4232. const step = graphWidth / (dataArray.length - 1);
  4233. const points = dataArray.map((val, idx) => {
  4234. const x = idx * step;
  4235. const y = (h - 10) - (val / maxVal) * (h - 20);
  4236. return `${x.toFixed(1)},${y.toFixed(1)}`;
  4237. });
  4238. const polylineStr = points.join(' ');
  4239. const areaPath = `M 0,${h - 10} L ${polylineStr} L ${graphWidth},${h - 10} Z`;
  4240. svg.innerHTML = `
  4241. ${gridLines}
  4242. <path d="${areaPath}" fill="rgba(14, 165, 233, 0.12)" />
  4243. <polyline fill="none" stroke="#38bdf8" stroke-width="1.8" stroke-linejoin="round" points="${polylineStr}" />
  4244. <circle cx="${graphWidth}" cy="${points[points.length - 1].split(',')[1]}" r="3" fill="#38bdf8" />
  4245. `;
  4246. }
  4247. async function moveFilterRule(id, dir) {
  4248. id = decodeURIComponent(id);
  4249. try {
  4250. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/move`, {
  4251. method: 'POST',
  4252. headers: { 'Content-Type': 'application/json' },
  4253. body: JSON.stringify({ direction: dir })
  4254. });
  4255. if (res.ok) loadFirewall(false);
  4256. } catch (err) {
  4257. showToast('Error', err.message, 'error');
  4258. }
  4259. }
  4260. async function toggleFilterRuleState(id, disabled) {
  4261. id = decodeURIComponent(id);
  4262. try {
  4263. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/state`, {
  4264. method: 'POST',
  4265. headers: { 'Content-Type': 'application/json' },
  4266. body: JSON.stringify({ disabled })
  4267. });
  4268. if (res.ok) loadFirewall(false);
  4269. } catch (err) {
  4270. showToast('Error', err.message, 'error');
  4271. }
  4272. }
  4273. async function deleteFilterRule(id) {
  4274. id = decodeURIComponent(id);
  4275. if (!confirm('Are you sure you want to delete this filter rule?')) return;
  4276. try {
  4277. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4278. if (res.ok) {
  4279. showToast('Deleted', 'Filter rule removed', 'success');
  4280. loadFirewall(false);
  4281. }
  4282. } catch (err) {
  4283. showToast('Error', err.message, 'error');
  4284. }
  4285. }
  4286. // ----------------- NAT Rules -----------------
  4287. function renderNATRules() {
  4288. const chainFilter = document.getElementById('nat-filter-chain')?.value || '';
  4289. const tbody = document.getElementById('nat-table-body');
  4290. const empty = document.getElementById('nat-empty');
  4291. if (!tbody) return;
  4292. tbody.innerHTML = '';
  4293. const rules = (state.natRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  4294. document.getElementById('nat-count-badge').innerText = `${rules.length} Rules`;
  4295. if (rules.length === 0) {
  4296. empty?.classList.remove('hidden');
  4297. return;
  4298. }
  4299. empty?.classList.add('hidden');
  4300. rules.forEach((raw, idx) => {
  4301. const r = safeFirewallRow(raw);
  4302. const tr = document.createElement('tr');
  4303. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  4304. let toTarget = '-';
  4305. if (r.action === 'jump') {
  4306. toTarget = `<span class="text-yellow-300 font-mono font-bold">&rarr; ${r.jump_target || '-'}</span>`;
  4307. } else if (r.action.includes('address-list') || r.action.includes('address list')) {
  4308. toTarget = `<span class="text-emerald-300 font-mono font-bold">&rarr; ${r.address_list || '-'}</span>`;
  4309. } else if (r.action === 'redirect') {
  4310. toTarget = `<span class="text-amber-300 font-mono font-bold">ports:${r.to_ports || 'all'}</span>`;
  4311. } else if (r.action === 'masquerade') {
  4312. 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>`;
  4313. } else if (r.action === 'log') {
  4314. toTarget = `<span class="text-slate-400 font-mono font-bold">${r.log_prefix || 'log'}</span>`;
  4315. } else {
  4316. const parts = [r.to_addresses, r.to_ports].filter(Boolean);
  4317. toTarget = parts.length ? `<span class="text-amber-300 font-mono font-bold">${parts.join(':')}</span>` : '-';
  4318. }
  4319. const ifaces = [r.out_interface ? 'out:' + r.out_interface : '', r.in_interface ? 'in:' + r.in_interface : ''].filter(Boolean).join(' ');
  4320. tr.innerHTML = `
  4321. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  4322. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  4323. <td class="py-2.5 px-3 font-bold text-amber-400">${r.chain}</td>
  4324. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  4325. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  4326. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}${r.dst_port ? ':' + r.dst_port : ''} <span class="text-[9px] text-slate-500">IPv${r.ip_version || 4}</span></td>
  4327. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  4328. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  4329. <td class="py-2.5 px-3 font-mono text-xs">${toTarget}</td>
  4330. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  4331. <span class="text-slate-300" id="nat-pkts-${r.id}">${(r.packets || 0).toLocaleString()}p</span> /
  4332. <span class="text-slate-500" id="nat-bytes-${r.id}">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  4333. </td>
  4334. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  4335. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  4336. <button onclick="moveNATRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  4337. <button onclick="moveNATRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  4338. <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>
  4339. <button onclick="openEditNATModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  4340. <button onclick="deleteNATRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  4341. </td>
  4342. `;
  4343. tbody.appendChild(tr);
  4344. });
  4345. }
  4346. // ==================== FIREWALL NAT MODAL (DEBTIK WEBFIG / WINBOX V4) ====================
  4347. function switchNATRuleTab(tab) {
  4348. if (!document.getElementById(`nat-pane-${tab}`)) tab = 'general';
  4349. state.activeNATRuleTab = tab;
  4350. document.querySelectorAll('.nat-rule-tab-btn').forEach(btn => {
  4351. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  4352. btn.classList.add('text-slate-400', 'border-transparent');
  4353. });
  4354. const activeBtn = document.getElementById(`nat-tab-btn-${tab}`);
  4355. if (activeBtn) {
  4356. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  4357. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  4358. }
  4359. document.querySelectorAll('.nat-rule-pane').forEach(p => p.classList.add('hidden'));
  4360. const activePane = document.getElementById(`nat-pane-${tab}`);
  4361. if (activePane) activePane.classList.remove('hidden');
  4362. if (tab === 'statistics') {
  4363. startNATStatPolling();
  4364. } else {
  4365. stopNATStatPolling();
  4366. }
  4367. }
  4368. function toggleNATField(fieldKey, expand) {
  4369. const plusBtn = document.getElementById(`nat-plus-${fieldKey}`);
  4370. const fieldBox = document.getElementById(`nat-field-${fieldKey}`);
  4371. if (!plusBtn || !fieldBox) return;
  4372. if (expand) {
  4373. plusBtn.classList.add('hidden');
  4374. fieldBox.classList.remove('hidden');
  4375. const valInput = document.getElementById(`nat-val-${fieldKey}`);
  4376. if (valInput) valInput.focus();
  4377. } else {
  4378. fieldBox.classList.add('hidden');
  4379. plusBtn.classList.remove('hidden');
  4380. const valInput = document.getElementById(`nat-val-${fieldKey}`);
  4381. if (valInput) {
  4382. if (valInput.tagName === 'SELECT') {
  4383. valInput.selectedIndex = 0;
  4384. } else {
  4385. valInput.value = '';
  4386. }
  4387. }
  4388. const invInput = document.getElementById(`nat-inv-${fieldKey}`);
  4389. if (invInput) invInput.checked = false;
  4390. if (fieldKey === 'days') {
  4391. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  4392. const el = document.getElementById(`nat-day-${d}`);
  4393. if (el) el.checked = true;
  4394. });
  4395. }
  4396. }
  4397. }
  4398. function setNATFieldVal(fieldKey, value, hasInvert = false) {
  4399. if (fieldKey === 'ipsec' && typeof value === 'string') value = value.replace(':', ',');
  4400. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  4401. toggleNATField(fieldKey, true);
  4402. let strVal = String(value);
  4403. if (hasInvert) {
  4404. const inv = strVal.startsWith('!');
  4405. if (inv) strVal = strVal.slice(1);
  4406. const invEl = document.getElementById(`nat-inv-${fieldKey}`);
  4407. if (invEl) invEl.checked = inv;
  4408. else if (inv) strVal = '!'+strVal;
  4409. }
  4410. const valEl = document.getElementById(`nat-val-${fieldKey}`);
  4411. if (valEl) { if (valEl.tagName === 'SELECT' && !Array.from(valEl.options).some(o => o.value === strVal)) { const option=document.createElement('option'); option.value=strVal; option.textContent=strVal+' (saved)'; valEl.appendChild(option); } valEl.value = strVal; }
  4412. } else {
  4413. toggleNATField(fieldKey, false);
  4414. }
  4415. }
  4416. function getNATFieldVal(fieldKey, hasInvert = false) {
  4417. const fieldBox = document.getElementById(`nat-field-${fieldKey}`);
  4418. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  4419. const valEl = document.getElementById(`nat-val-${fieldKey}`);
  4420. let v = valEl ? valEl.value.trim() : '';
  4421. if (!v) return '';
  4422. if (hasInvert) {
  4423. const invEl = document.getElementById(`nat-inv-${fieldKey}`);
  4424. if (invEl && invEl.checked) {
  4425. v = '!' + v.replace(/^!/, '');
  4426. }
  4427. }
  4428. return v;
  4429. }
  4430. function toggleMaximizeNATModal() {
  4431. const win = document.getElementById('nat-modal-window');
  4432. if (!win) return;
  4433. if (win.classList.contains('max-w-[720px]')) {
  4434. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  4435. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  4436. } else {
  4437. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  4438. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  4439. }
  4440. }
  4441. function handleNATChainChange() {
  4442. const ch = document.getElementById('nat-modal-chain')?.value || 'srcnat';
  4443. const actSel = document.getElementById('nat-modal-action');
  4444. if (actSel) {
  4445. if (ch === 'srcnat' && (actSel.value === 'dst-nat' || actSel.value === 'redirect')) {
  4446. actSel.value = 'masquerade';
  4447. } else if (ch === 'dstnat' && (actSel.value === 'masquerade' || actSel.value === 'src-nat')) {
  4448. actSel.value = 'dst-nat';
  4449. }
  4450. }
  4451. toggleNATActionFields();
  4452. }
  4453. function toggleNATActionFields() {
  4454. const act = document.getElementById('nat-modal-action')?.value || 'masquerade';
  4455. const rowAddr = document.getElementById('nat-row-toaddr');
  4456. const rowPort = document.getElementById('nat-row-toport');
  4457. const jumpBox = document.getElementById('nat-action-jump-box');
  4458. const addrBox = document.getElementById('nat-action-addrlist-box');
  4459. // Hide all dynamic rows first
  4460. if (rowAddr) rowAddr.classList.add('hidden');
  4461. if (rowPort) rowPort.classList.add('hidden');
  4462. if (jumpBox) jumpBox.classList.add('hidden');
  4463. if (addrBox) addrBox.classList.add('hidden');
  4464. if (['src-nat', 'dst-nat', 'netmap'].includes(act)) {
  4465. if (rowAddr) rowAddr.classList.remove('hidden');
  4466. if (rowPort && act !== 'netmap') rowPort.classList.remove('hidden');
  4467. } else if (act === 'redirect' || act === 'masquerade') {
  4468. if (rowPort) rowPort.classList.remove('hidden');
  4469. } else if (act === 'jump') {
  4470. if (jumpBox) jumpBox.classList.remove('hidden');
  4471. } else if (act.includes('address-list') || act.includes('address list')) {
  4472. if (addrBox) addrBox.classList.remove('hidden');
  4473. }
  4474. if (act === 'log') {
  4475. const logEl = document.getElementById('nat-modal-log');
  4476. if (logEl) logEl.checked = true;
  4477. toggleNATField('logprefix', true);
  4478. }
  4479. }
  4480. function handleNATActionChange() {
  4481. const action = document.getElementById('nat-modal-action')?.value;
  4482. const chain = document.getElementById('nat-modal-chain');
  4483. if (action === 'dst-nat' && chain && ['srcnat', 'postrouting', 'input'].includes(chain.value.toLowerCase())) chain.value = 'dstnat';
  4484. toggleNATActionFields();
  4485. }
  4486. function toggleNATLogPrefix() {
  4487. const isLog = document.getElementById('nat-modal-log')?.checked;
  4488. toggleNATField('logprefix', !!isLog);
  4489. }
  4490. function openAddNATModal() {
  4491. const tos = document.getElementById('nat-val-tos'); if (tos) tos.value = '';
  4492. switchNATRuleTab('general');
  4493. setFirewallDays('nat', '');
  4494. const badge = document.getElementById('nat-modal-badge');
  4495. if (badge) badge.innerText = 'New...';
  4496. document.getElementById('nat-modal-id').value = '';
  4497. document.getElementById('nat-modal-family').value = '4';
  4498. document.getElementById('nat-modal-enabled').checked = true;
  4499. document.getElementById('nat-modal-comment').value = '';
  4500. document.getElementById('nat-modal-chain').value = 'srcnat';
  4501. document.getElementById('nat-modal-action').value = 'masquerade';
  4502. document.getElementById('nat-modal-toaddr').value = '';
  4503. document.getElementById('nat-modal-toport').value = '';
  4504. document.getElementById('nat-modal-log').checked = false;
  4505. populateInterfaceSelect('nat-val-iniface');
  4506. populateInterfaceSelect('nat-val-outiface');
  4507. populateAddressListSelect('nat-val-srclist');
  4508. populateAddressListSelect('nat-val-dstlist');
  4509. populateGeoIPSelect('nat-val-srcgeo');
  4510. populateGeoIPSelect('nat-val-dstgeo');
  4511. const allFieldKeys = [
  4512. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  4513. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  4514. 'routingmark', 'conntype',
  4515. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  4516. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  4517. 'ipsec', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  4518. 'pktsize', 'random', 'icmpoptions', 'ipv4options', 'ttl',
  4519. 'time', 'days', 'limit', 'dstlimit', 'psd', 'logprefix'
  4520. ];
  4521. allFieldKeys.forEach(k => toggleNATField(k, false));
  4522. resetNATCounterDisplay();
  4523. toggleNATActionFields();
  4524. document.getElementById('nat-modal').classList.remove('hidden');
  4525. }
  4526. function openEditNATModal(id) {
  4527. id = decodeURIComponent(id);
  4528. const r = (state.natRules || []).find(rule => rule.id === id);
  4529. if (!r) return;
  4530. setFirewallDays('nat', r.days || '');
  4531. switchNATRuleTab('general');
  4532. const badge = document.getElementById('nat-modal-badge');
  4533. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  4534. document.getElementById('nat-modal-id').value = r.id;
  4535. document.getElementById('nat-modal-family').value = String(r.ip_version || 4);
  4536. document.getElementById('nat-modal-enabled').checked = !r.disabled;
  4537. document.getElementById('nat-modal-comment').value = r.comment || '';
  4538. document.getElementById('nat-modal-chain').value = r.chain || 'srcnat';
  4539. setFirewallActionSelection('nat', r.action || 'accept');
  4540. document.getElementById('nat-modal-toaddr').value = r.to_addresses || '';
  4541. document.getElementById('nat-modal-toport').value = r.to_ports || '';
  4542. document.getElementById('nat-modal-log').checked = !!r.log;
  4543. populateInterfaceSelect('nat-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  4544. populateInterfaceSelect('nat-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  4545. populateAddressListSelect('nat-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  4546. populateAddressListSelect('nat-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  4547. populateGeoIPSelect('nat-val-srcgeo', r.src_geoip || '');
  4548. populateGeoIPSelect('nat-val-dstgeo', r.dst_geoip || '');
  4549. setNATFieldVal('src', r.src_address, true);
  4550. setNATFieldVal('dst', r.dst_address, true);
  4551. setNATFieldVal('srclist', r.src_address_list, true);
  4552. setNATFieldVal('dstlist', r.dst_address_list, true);
  4553. setNATFieldVal('srcgeo', r.src_geoip, true);
  4554. setNATFieldVal('dstgeo', r.dst_geoip, true);
  4555. if (r.protocol && r.protocol !== 'all') {
  4556. setNATFieldVal('proto', r.protocol, true);
  4557. } else {
  4558. toggleNATField('proto', false);
  4559. }
  4560. setNATFieldVal('sport', r.src_port, true);
  4561. setNATFieldVal('dport', r.dst_port, true);
  4562. setNATFieldVal('anyport', r.any_port, true);
  4563. setNATFieldVal('iniface', r.in_interface, true);
  4564. setNATFieldVal('outiface', r.out_interface, true);
  4565. setNATFieldVal('inifacelist', r.in_interface_list, true);
  4566. setNATFieldVal('outifacelist', r.out_interface_list, true);
  4567. setNATFieldVal('pktmark', r.packet_mark, true);
  4568. setNATFieldVal('connmark', r.connection_mark, true);
  4569. setNATFieldVal('routingmark', r.routing_mark, true);
  4570. setNATFieldVal('conntype', r.connection_type, false);
  4571. // Advanced tab fields
  4572. setNATFieldVal('layer7', r.layer7_protocol, false);
  4573. setNATFieldVal('content', r.content, false);
  4574. setNATFieldVal('connbytes', r.connection_bytes, false);
  4575. setNATFieldVal('connrate', r.connection_rate, false);
  4576. setNATFieldVal('pcc', r.pcc, false);
  4577. setNATFieldVal('srcmac', r.src_mac_address, true);
  4578. setNATFieldVal('outbridgeport', r.out_bridge_port, false);
  4579. setNATFieldVal('inbridgeport', r.in_bridge_port, false);
  4580. setNATFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  4581. setNATFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  4582. setNATFieldVal('ipsec', r.ipsec_policy, false);
  4583. setNATFieldVal('ingresspriority', r.ingress_priority, false);
  4584. setNATFieldVal('priority', r.priority, false);
  4585. setNATFieldVal('dscp', r.dscp, false);
  4586. setNATFieldVal('tcpmss', r.tcp_mss, false);
  4587. { const tosEl = document.getElementById('nat-val-tos'); if (tosEl) tosEl.value = r.tos || ''; }
  4588. setNATFieldVal('pktsize', r.packet_size, false);
  4589. setNATFieldVal('random', r.random, false);
  4590. setNATFieldVal('icmpoptions', r.icmp_options, false);
  4591. setNATFieldVal('ipv4options', r.ipv4_options, false);
  4592. setNATFieldVal('ttl', r.ttl, false);
  4593. // Extra tab fields
  4594. setNATFieldVal('time', r.time, false);
  4595. if (r.days) {
  4596. toggleNATField('days', true);
  4597. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  4598. const chk = document.getElementById(`nat-day-${d}`);
  4599. if (chk) chk.checked = r.days.toLowerCase().includes(d);
  4600. });
  4601. } else {
  4602. toggleNATField('days', false);
  4603. }
  4604. setNATFieldVal('limit', r.limit, false);
  4605. setNATFieldVal('dstlimit', r.dst_limit, false);
  4606. setNATFieldVal('psd', r.psd, false);
  4607. // Action fields
  4608. if (r.jump_target) {
  4609. const jtEl = document.getElementById('nat-modal-jumptarget');
  4610. if (jtEl) jtEl.value = r.jump_target;
  4611. }
  4612. if (r.address_list) {
  4613. const alEl = document.getElementById('nat-modal-action-addrlist');
  4614. if (alEl) alEl.value = r.address_list;
  4615. }
  4616. if (r.address_list_timeout) {
  4617. const toEl = document.getElementById('nat-modal-action-timeout');
  4618. if (toEl) toEl.value = r.address_list_timeout;
  4619. }
  4620. setNATFieldVal('logprefix', r.log_prefix, false);
  4621. // Statistics
  4622. const bEl = document.getElementById('nat-stat-bytes');
  4623. const pEl = document.getElementById('nat-stat-packets');
  4624. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  4625. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  4626. state.natLastBytes = r.bytes || 0;
  4627. state.natLastPackets = r.packets || 0;
  4628. state.natLastTimestamp = Date.now();
  4629. state.natStatRateHistory = new Array(30).fill(0);
  4630. state.natStatPktHistory = new Array(30).fill(0);
  4631. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  4632. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  4633. toggleNATActionFields();
  4634. document.getElementById('nat-modal').classList.remove('hidden');
  4635. }
  4636. function closeNATModal() {
  4637. stopNATStatPolling();
  4638. document.getElementById('nat-modal').classList.add('hidden');
  4639. }
  4640. function copyNATRule() {
  4641. document.getElementById('nat-modal-id').value = '';
  4642. const badge = document.getElementById('nat-modal-badge');
  4643. if (badge) badge.innerText = 'New...';
  4644. showToast('Rule Cloned', 'Ready to save as a new NAT rule copy', 'info');
  4645. }
  4646. function resetNATCounterDisplay() {
  4647. state.natStatRateHistory = new Array(30).fill(0);
  4648. state.natStatPktHistory = new Array(30).fill(0);
  4649. state.natLastBytes = 0;
  4650. state.natLastPackets = 0;
  4651. state.natLastTimestamp = Date.now();
  4652. const bEl = document.getElementById('nat-stat-bytes');
  4653. const pEl = document.getElementById('nat-stat-packets');
  4654. const rEl = document.getElementById('nat-stat-rate');
  4655. const prEl = document.getElementById('nat-stat-pktrate');
  4656. if (bEl) bEl.value = '0 B';
  4657. if (pEl) pEl.value = '0';
  4658. if (rEl) rEl.value = '0 bps';
  4659. if (prEl) prEl.value = '0 p/s';
  4660. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  4661. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  4662. showToast('Counters Reset', 'NAT rule counter display reset to 0', 'info');
  4663. }
  4664. async function applyNATRule(closeAfter = false) {
  4665. const id = document.getElementById('nat-modal-id').value;
  4666. if (!reviewLegacyFirewallSettings('nat', id)) return;
  4667. let selectedDays; try { selectedDays = getFirewallDays('nat'); } catch(error) { showToast('Error', error.message, 'error'); return; }
  4668. const chain = document.getElementById('nat-modal-chain').value;
  4669. const action = document.getElementById('nat-modal-action').value;
  4670. const comment = document.getElementById('nat-modal-comment').value.trim();
  4671. const enabled = document.getElementById('nat-modal-enabled').checked;
  4672. const src = getNATFieldVal('src', true);
  4673. const dst = getNATFieldVal('dst', true);
  4674. const srclist = getNATFieldVal('srclist', true);
  4675. const dstlist = getNATFieldVal('dstlist', true);
  4676. const srcgeo = getNATFieldVal('srcgeo', true);
  4677. const dstgeo = getNATFieldVal('dstgeo', true);
  4678. const proto = getNATFieldVal('proto', true);
  4679. const sport = getNATFieldVal('sport', true);
  4680. const dport = getNATFieldVal('dport', true);
  4681. const anyport = getNATFieldVal('anyport', true);
  4682. const iniface = getNATFieldVal('iniface', true);
  4683. const outiface = getNATFieldVal('outiface', true);
  4684. const inifacelist = getNATFieldVal('inifacelist', true);
  4685. const outifacelist = getNATFieldVal('outifacelist', true);
  4686. const pktmark = getNATFieldVal('pktmark', true);
  4687. const connmark = getNATFieldVal('connmark', true);
  4688. const routingmark = getNATFieldVal('routingmark', true);
  4689. const conntype = getNATFieldVal('conntype', false);
  4690. const usesAddr = ['src-nat', 'dst-nat', 'netmap'].includes(action);
  4691. const usesPort = ['src-nat', 'dst-nat', 'redirect', 'masquerade'].includes(action);
  4692. if (!chain.trim()) { switchNATRuleTab('general'); showToast('NAT rule', 'Enter a chain.', 'error'); document.getElementById('nat-modal-chain').focus(); return; }
  4693. if (usesAddr && !document.getElementById('nat-modal-toaddr').value.trim()) { switchNATRuleTab('general'); showToast('NAT rule', 'Enter the destination IP / address for this action.', 'error'); document.getElementById('nat-modal-toaddr').focus(); return; }
  4694. if ((sport || dport || anyport || (usesPort && document.getElementById('nat-modal-toport').value.trim())) && !['tcp', 'udp'].includes(proto)) {
  4695. switchNATRuleTab('general'); toggleNATField('proto', true); document.getElementById('nat-val-proto').value = proto || 'all';
  4696. showToast('Select protocol', 'Port rules require TCP or UDP. For DNS, create one UDP and one TCP rule.', 'error'); document.getElementById('nat-val-proto').focus(); return;
  4697. }
  4698. const payload = {
  4699. ip_version: Number(document.getElementById('nat-modal-family').value),
  4700. id,
  4701. chain,
  4702. action,
  4703. to_addresses: usesAddr ? (document.getElementById('nat-modal-toaddr')?.value.trim() || '') : '',
  4704. to_ports: usesPort ? (document.getElementById('nat-modal-toport')?.value.trim() || '') : '',
  4705. protocol: proto || 'all',
  4706. src_address: src,
  4707. dst_address: dst,
  4708. src_port: sport,
  4709. dst_port: dport,
  4710. any_port: anyport,
  4711. in_interface: iniface,
  4712. out_interface: outiface,
  4713. in_interface_list: inifacelist,
  4714. out_interface_list: outifacelist,
  4715. packet_mark: pktmark,
  4716. connection_mark: connmark,
  4717. routing_mark: routingmark,
  4718. connection_type: conntype,
  4719. src_address_list: srclist,
  4720. dst_address_list: dstlist,
  4721. src_geoip: srcgeo,
  4722. dst_geoip: dstgeo,
  4723. comment,
  4724. disabled: !enabled,
  4725. // Advanced tab
  4726. content: getNATFieldVal('content', false),
  4727. src_mac_address: getNATFieldVal('srcmac', true),
  4728. out_bridge_port: getNATFieldVal('outbridgeport', false),
  4729. in_bridge_port: getNATFieldVal('inbridgeport', false),
  4730. ipsec_policy: getNATFieldVal('ipsec', false),
  4731. dscp: getNATFieldVal('dscp', false),
  4732. tcp_mss: getNATFieldVal('tcpmss', false),
  4733. tos: document.getElementById('nat-val-tos')?.value || '',
  4734. packet_size: getNATFieldVal('pktsize', false),
  4735. random: getNATFieldVal('random', false),
  4736. icmp_options: getNATFieldVal('icmpoptions', false),
  4737. ttl: getNATFieldVal('ttl', false),
  4738. days: selectedDays,
  4739. // Extra tab
  4740. time: getNATFieldVal('time', false),
  4741. limit: getNATFieldVal('limit', false),
  4742. // Action tab
  4743. jump_target: action === 'jump' ? (document.getElementById('nat-modal-jumptarget')?.value || '') : '',
  4744. address_list: action.includes('address') ? (document.getElementById('nat-modal-action-addrlist')?.value || '') : '',
  4745. address_list_timeout: action.includes('address') ? (document.getElementById('nat-modal-action-timeout')?.value || '') : '',
  4746. log: document.getElementById('nat-modal-log')?.checked || false,
  4747. log_prefix: getNATFieldVal('logprefix', false)
  4748. };
  4749. try {
  4750. const res = await fetch(`${API_BASE}/firewall/nat`, {
  4751. method: 'POST',
  4752. headers: { 'Content-Type': 'application/json' },
  4753. body: JSON.stringify(payload)
  4754. });
  4755. if (res.ok) {
  4756. const data = await res.json();
  4757. showToast('NAT Rule Saved', 'NAT mapping updated', 'success');
  4758. loadFirewall(false);
  4759. if (closeAfter) {
  4760. closeNATModal();
  4761. } else {
  4762. if (data.id) {
  4763. document.getElementById('nat-modal-id').value = data.id;
  4764. const badge = document.getElementById('nat-modal-badge');
  4765. if (badge) badge.innerText = `#${data.id}`;
  4766. }
  4767. }
  4768. } else {
  4769. const err = await res.json();
  4770. showToast('Error', err.message || 'Failed to save rule', 'error');
  4771. }
  4772. } catch (err) {
  4773. showToast('Error', err.message, 'error');
  4774. }
  4775. }
  4776. function submitSaveNATRule(e) {
  4777. if (e && e.preventDefault) e.preventDefault();
  4778. return applyNATRule(true);
  4779. }
  4780. function startNATStatPolling() {
  4781. stopNATStatPolling();
  4782. pollNATRuleStats();
  4783. state.natStatInterval = setInterval(pollNATRuleStats, 1000);
  4784. }
  4785. function stopNATStatPolling() {
  4786. if (state.natStatInterval) {
  4787. clearInterval(state.natStatInterval);
  4788. state.natStatInterval = null;
  4789. }
  4790. }
  4791. async function pollNATRuleStats() {
  4792. const id = document.getElementById('nat-modal-id')?.value;
  4793. if (!id) {
  4794. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory || new Array(30).fill(0), 'bps', 'nat-stat-legend-rate');
  4795. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory || new Array(30).fill(0), 'p/s', 'nat-stat-legend-pktrate');
  4796. return;
  4797. }
  4798. try {
  4799. const res = await fetch(`${API_BASE}/firewall/nat`);
  4800. if (!res.ok) return;
  4801. const rules = await res.json();
  4802. const r = rules.find(x => x.id === id);
  4803. if (!r) return;
  4804. const now = Date.now();
  4805. const dt = Math.max(0.2, (now - (state.natLastTimestamp || now)) / 1000);
  4806. state.natLastTimestamp = now;
  4807. const curBytes = r.bytes || 0;
  4808. const curPackets = r.packets || 0;
  4809. const deltaBytes = Math.max(0, curBytes - (state.natLastBytes ?? curBytes));
  4810. const deltaPkts = Math.max(0, curPackets - (state.natLastPackets ?? curPackets));
  4811. state.natLastBytes = curBytes;
  4812. state.natLastPackets = curPackets;
  4813. const rateBps = Math.round((deltaBytes * 8) / dt);
  4814. const ratePkt = Math.round(deltaPkts / dt);
  4815. if (!state.natStatRateHistory) state.natStatRateHistory = new Array(30).fill(0);
  4816. if (!state.natStatPktHistory) state.natStatPktHistory = new Array(30).fill(0);
  4817. state.natStatRateHistory.push(rateBps);
  4818. if (state.natStatRateHistory.length > 30) state.natStatRateHistory.shift();
  4819. state.natStatPktHistory.push(ratePkt);
  4820. if (state.natStatPktHistory.length > 30) state.natStatPktHistory.shift();
  4821. const bEl = document.getElementById('nat-stat-bytes');
  4822. const pEl = document.getElementById('nat-stat-packets');
  4823. const rEl = document.getElementById('nat-stat-rate');
  4824. const prEl = document.getElementById('nat-stat-pktrate');
  4825. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  4826. if (pEl) pEl.value = curPackets.toLocaleString();
  4827. if (rEl) rEl.value = formatBps(rateBps);
  4828. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  4829. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  4830. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  4831. } catch (e) {
  4832. console.error('Error polling NAT rule stats', e);
  4833. }
  4834. }
  4835. async function moveNATRule(id, dir) {
  4836. id = decodeURIComponent(id);
  4837. try {
  4838. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/move`, {
  4839. method: 'POST',
  4840. headers: { 'Content-Type': 'application/json' },
  4841. body: JSON.stringify({ direction: dir })
  4842. });
  4843. if (res.ok) loadFirewall(false);
  4844. } catch (err) {
  4845. showToast('Error', err.message, 'error');
  4846. }
  4847. }
  4848. async function toggleNATRuleState(id, disabled) {
  4849. id = decodeURIComponent(id);
  4850. try {
  4851. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/state`, {
  4852. method: 'POST',
  4853. headers: { 'Content-Type': 'application/json' },
  4854. body: JSON.stringify({ disabled })
  4855. });
  4856. if (res.ok) loadFirewall(false);
  4857. } catch (err) {
  4858. showToast('Error', err.message, 'error');
  4859. }
  4860. }
  4861. async function deleteNATRule(id) {
  4862. id = decodeURIComponent(id);
  4863. if (!confirm('Are you sure you want to delete this NAT rule?')) return;
  4864. try {
  4865. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4866. if (res.ok) {
  4867. showToast('Deleted', 'NAT rule removed', 'success');
  4868. loadFirewall(false);
  4869. }
  4870. } catch (err) {
  4871. showToast('Error', err.message, 'error');
  4872. }
  4873. }
  4874. // ----------------- Mangle Rules -----------------
  4875. function renderMangleRules() {
  4876. const chainFilter = document.getElementById('mangle-filter-chain')?.value || '';
  4877. const tbody = document.getElementById('mangle-table-body');
  4878. const empty = document.getElementById('mangle-empty');
  4879. if (!tbody) return;
  4880. tbody.innerHTML = '';
  4881. const rules = (state.mangleRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  4882. document.getElementById('mangle-count-badge').innerText = `${rules.length} Rules`;
  4883. if (rules.length === 0) {
  4884. empty?.classList.remove('hidden');
  4885. return;
  4886. }
  4887. empty?.classList.add('hidden');
  4888. rules.forEach((raw, idx) => {
  4889. const r = safeFirewallRow(raw);
  4890. const tr = document.createElement('tr');
  4891. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  4892. let markVal = '<span class="text-slate-500">-</span>';
  4893. if (r.new_connection_mark) markVal = `<span class="text-cyan-300 font-mono font-bold">${r.new_connection_mark}</span>`;
  4894. else if (r.new_routing_mark) markVal = `<span class="text-amber-300 font-mono font-bold">${r.new_routing_mark}</span>`;
  4895. else if (r.new_packet_mark) markVal = `<span class="text-emerald-300 font-mono font-bold">${r.new_packet_mark}</span>`;
  4896. else if (r.new_mss) markVal = `<span class="text-sky-300 font-mono font-bold">mss:${r.new_mss}</span>`;
  4897. else if (r.action === 'change-dscp') markVal = `<span class="text-purple-300 font-mono font-bold">dscp:${r.new_dscp}</span>`;
  4898. else if (r.new_ttl) markVal = `<span class="text-blue-300 font-mono font-bold">ttl:${r.new_ttl}</span>`;
  4899. else if (r.new_priority) markVal = `<span class="text-indigo-300 font-mono font-bold">prio:${r.new_priority}</span>`;
  4900. else if (r.route) markVal = `<span class="text-orange-300 font-mono font-bold">route:${r.route}</span>`;
  4901. else if (r.sniff_target) markVal = `<span class="text-pink-300 font-mono font-bold">sniff:${r.sniff_target}</span>`;
  4902. else if (r.action === 'jump') markVal = `<span class="text-yellow-300 font-mono font-bold">&rarr; ${r.jump_target || '-'}</span>`;
  4903. 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>`;
  4904. else if (r.action === 'log') markVal = `<span class="text-slate-400 font-mono font-bold">${r.log_prefix || 'log'}</span>`;
  4905. tr.innerHTML = `
  4906. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  4907. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  4908. <td class="py-2.5 px-3 font-bold text-purple-400">${r.chain}</td>
  4909. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  4910. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  4911. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  4912. <td class="py-2.5 px-3 font-mono text-xs">${markVal}</td>
  4913. <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>
  4914. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  4915. <span class="text-slate-300" id="mangle-pkts-${r.id}">${(r.packets || 0).toLocaleString()}p</span> /
  4916. <span class="text-slate-500" id="mangle-bytes-${r.id}">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  4917. </td>
  4918. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  4919. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  4920. <button onclick="moveMangleRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  4921. <button onclick="moveMangleRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  4922. <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>
  4923. <button onclick="openEditMangleModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  4924. <button onclick="deleteMangleRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  4925. </td>
  4926. `;
  4927. tbody.appendChild(tr);
  4928. });
  4929. }
  4930. // ==================== FIREWALL MANGLE MODAL (DEBTIK WEBFIG / WINBOX V4) ====================
  4931. function switchMangleRuleTab(tab) {
  4932. state.activeMangleRuleTab = tab;
  4933. document.querySelectorAll('.mangle-rule-tab-btn').forEach(btn => {
  4934. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  4935. btn.classList.add('text-slate-400', 'border-transparent');
  4936. });
  4937. const activeBtn = document.getElementById(`mangle-tab-btn-${tab}`);
  4938. if (activeBtn) {
  4939. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  4940. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  4941. }
  4942. document.querySelectorAll('.mangle-rule-pane').forEach(p => p.classList.add('hidden'));
  4943. const activePane = document.getElementById(`mangle-pane-${tab}`);
  4944. if (activePane) activePane.classList.remove('hidden');
  4945. if (tab === 'statistics') {
  4946. startMangleStatPolling();
  4947. } else {
  4948. stopMangleStatPolling();
  4949. }
  4950. }
  4951. function toggleMangleField(fieldKey, expand) {
  4952. const plusBtn = document.getElementById(`mangle-plus-${fieldKey}`);
  4953. const fieldBox = document.getElementById(`mangle-field-${fieldKey}`);
  4954. if (!plusBtn || !fieldBox) return;
  4955. if (expand) {
  4956. plusBtn.classList.add('hidden');
  4957. fieldBox.classList.remove('hidden');
  4958. const valInput = document.getElementById(`mangle-val-${fieldKey}`);
  4959. if (valInput) valInput.focus();
  4960. } else {
  4961. fieldBox.classList.add('hidden');
  4962. plusBtn.classList.remove('hidden');
  4963. const valInput = document.getElementById(`mangle-val-${fieldKey}`);
  4964. if (valInput) {
  4965. if (valInput.tagName === 'SELECT') {
  4966. valInput.selectedIndex = 0;
  4967. } else {
  4968. valInput.value = '';
  4969. }
  4970. }
  4971. const invInput = document.getElementById(`mangle-inv-${fieldKey}`);
  4972. if (invInput) invInput.checked = false;
  4973. if (fieldKey === 'cs') {
  4974. ['mangle-modal-cs-established', 'mangle-modal-cs-related', 'mangle-modal-cs-new', 'mangle-modal-cs-invalid', 'mangle-modal-cs-untracked'].forEach(id => {
  4975. const el = document.getElementById(id);
  4976. if (el) el.checked = false;
  4977. });
  4978. }
  4979. if (fieldKey === 'natstate') {
  4980. ['mangle-modal-nat-srcnat', 'mangle-modal-nat-dstnat'].forEach(id => {
  4981. const el = document.getElementById(id);
  4982. if (el) el.checked = false;
  4983. });
  4984. }
  4985. }
  4986. }
  4987. function setMangleFieldVal(fieldKey, value, hasInvert = false) {
  4988. if (fieldKey === 'ipsec' && typeof value === 'string') value = value.replace(':', ',');
  4989. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  4990. toggleMangleField(fieldKey, true);
  4991. let strVal = String(value);
  4992. if (hasInvert) {
  4993. const inv = strVal.startsWith('!');
  4994. if (inv) strVal = strVal.slice(1);
  4995. const invEl = document.getElementById(`mangle-inv-${fieldKey}`);
  4996. if (invEl) invEl.checked = inv;
  4997. else if (inv) strVal = '!'+strVal;
  4998. }
  4999. const valEl = document.getElementById(`mangle-val-${fieldKey}`);
  5000. if (valEl) { if (valEl.tagName === 'SELECT' && !Array.from(valEl.options).some(o => o.value === strVal)) { const option=document.createElement('option'); option.value=strVal; option.textContent=strVal+' (saved)'; valEl.appendChild(option); } valEl.value = strVal; }
  5001. } else {
  5002. toggleMangleField(fieldKey, false);
  5003. }
  5004. }
  5005. function getMangleFieldVal(fieldKey, hasInvert = false) {
  5006. const fieldBox = document.getElementById(`mangle-field-${fieldKey}`);
  5007. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  5008. const valEl = document.getElementById(`mangle-val-${fieldKey}`);
  5009. let v = valEl ? valEl.value.trim() : '';
  5010. if (!v) return '';
  5011. if (hasInvert) {
  5012. const invEl = document.getElementById(`mangle-inv-${fieldKey}`);
  5013. if (invEl && invEl.checked) {
  5014. v = '!' + v.replace(/^!/, '');
  5015. }
  5016. }
  5017. return v;
  5018. }
  5019. function toggleMaximizeMangleModal() {
  5020. const win = document.getElementById('mangle-modal-window');
  5021. if (!win) return;
  5022. if (win.classList.contains('max-w-[720px]')) {
  5023. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  5024. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  5025. } else {
  5026. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  5027. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  5028. }
  5029. }
  5030. function toggleMangleActionFields() {
  5031. const act = document.getElementById('mangle-modal-action')?.value || 'mark-connection';
  5032. // Hide all dynamic rows first
  5033. ['newconnmark', 'newroutingmark', 'newpktmark', 'newmss', 'newdscp', 'newttl', 'newpriority', 'route', 'sniff', 'passthrough'].forEach(id => {
  5034. const el = document.getElementById(`mangle-row-${id}`);
  5035. if (el) el.classList.add('hidden');
  5036. });
  5037. const jumpBox = document.getElementById('mangle-action-jump-box');
  5038. const addrBox = document.getElementById('mangle-action-addrlist-box');
  5039. if (jumpBox) jumpBox.classList.add('hidden');
  5040. if (addrBox) addrBox.classList.add('hidden');
  5041. // Activate matching rows
  5042. if (act === 'mark-connection') {
  5043. document.getElementById('mangle-row-newconnmark')?.classList.remove('hidden');
  5044. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5045. } else if (act === 'mark-routing') {
  5046. document.getElementById('mangle-row-newroutingmark')?.classList.remove('hidden');
  5047. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5048. } else if (act === 'mark-packet') {
  5049. document.getElementById('mangle-row-newpktmark')?.classList.remove('hidden');
  5050. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5051. } else if (act === 'change-mss') {
  5052. document.getElementById('mangle-row-newmss')?.classList.remove('hidden');
  5053. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5054. } else if (act === 'change-dscp') {
  5055. document.getElementById('mangle-row-newdscp')?.classList.remove('hidden');
  5056. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5057. } else if (act === 'change-ttl') {
  5058. document.getElementById('mangle-row-newttl')?.classList.remove('hidden');
  5059. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5060. } else if (act === 'set-priority') {
  5061. document.getElementById('mangle-row-newpriority')?.classList.remove('hidden');
  5062. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5063. } else if (act === 'route') {
  5064. document.getElementById('mangle-row-route')?.classList.remove('hidden');
  5065. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5066. } else if (act === 'sniff-pc' || act === 'sniff-tzsp') {
  5067. document.getElementById('mangle-row-sniff')?.classList.remove('hidden');
  5068. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5069. } else if (act === 'clear-df' || act === 'strip-ipv4-options') {
  5070. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5071. } else if (act === 'jump') {
  5072. if (jumpBox) jumpBox.classList.remove('hidden');
  5073. } else if (act.includes('address-list') || act.includes('address list')) {
  5074. if (addrBox) addrBox.classList.remove('hidden');
  5075. }
  5076. if (act === 'log') {
  5077. const logEl = document.getElementById('mangle-modal-log');
  5078. if (logEl) logEl.checked = true;
  5079. toggleMangleField('logprefix', true);
  5080. }
  5081. }
  5082. function toggleMangleLogPrefix() {
  5083. const isLog = document.getElementById('mangle-modal-log')?.checked;
  5084. toggleMangleField('logprefix', !!isLog);
  5085. }
  5086. const allMangleFieldKeys = [
  5087. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  5088. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  5089. 'routingmark', 'conntype', 'cs', 'natstate',
  5090. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  5091. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  5092. 'ipsec', 'tlshost', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  5093. 'pktsize', 'random', 'tcpflags', 'icmpoptions', 'ipv4options', 'ttl',
  5094. 'nth', 'connlimit', 'srcaddrtype', 'dstaddrtype', 'hotspot', 'ipfragment',
  5095. 'limit', 'dstlimit', 'time', 'psd', 'logprefix'
  5096. ];
  5097. function openAddMangleModal() {
  5098. const tos = document.getElementById('mangle-val-tos'); if (tos) tos.value = '';
  5099. switchMangleRuleTab('general');
  5100. const badge = document.getElementById('mangle-modal-badge');
  5101. if (badge) badge.innerText = 'New...';
  5102. document.getElementById('mangle-modal-id').value = '';
  5103. document.getElementById('mangle-modal-family').value = '4';
  5104. document.getElementById('mangle-modal-enabled').checked = true;
  5105. document.getElementById('mangle-modal-comment').value = '';
  5106. document.getElementById('mangle-modal-chain').value = 'prerouting';
  5107. document.getElementById('mangle-modal-action').value = 'mark-connection';
  5108. if (document.getElementById('mangle-modal-newconnmark')) document.getElementById('mangle-modal-newconnmark').value = '';
  5109. if (document.getElementById('mangle-modal-newroutingmark')) document.getElementById('mangle-modal-newroutingmark').value = '';
  5110. if (document.getElementById('mangle-modal-newpktmark')) document.getElementById('mangle-modal-newpktmark').value = '';
  5111. if (document.getElementById('mangle-modal-newmss')) document.getElementById('mangle-modal-newmss').value = '';
  5112. if (document.getElementById('mangle-modal-newdscp')) document.getElementById('mangle-modal-newdscp').value = '';
  5113. if (document.getElementById('mangle-modal-newttl')) document.getElementById('mangle-modal-newttl').value = '';
  5114. if (document.getElementById('mangle-modal-newpriority')) document.getElementById('mangle-modal-newpriority').value = '';
  5115. if (document.getElementById('mangle-modal-route')) document.getElementById('mangle-modal-route').value = '';
  5116. if (document.getElementById('mangle-modal-sniff')) document.getElementById('mangle-modal-sniff').value = '';
  5117. if (document.getElementById('mangle-modal-jumptarget')) document.getElementById('mangle-modal-jumptarget').value = '';
  5118. if (document.getElementById('mangle-modal-action-addrlist')) document.getElementById('mangle-modal-action-addrlist').value = '';
  5119. if (document.getElementById('mangle-modal-action-timeout')) document.getElementById('mangle-modal-action-timeout').value = '';
  5120. if (document.getElementById('mangle-modal-passthrough')) document.getElementById('mangle-modal-passthrough').checked = true;
  5121. if (document.getElementById('mangle-modal-log')) document.getElementById('mangle-modal-log').checked = false;
  5122. populateInterfaceSelect('mangle-val-iniface');
  5123. populateInterfaceSelect('mangle-val-outiface');
  5124. populateAddressListSelect('mangle-val-srclist');
  5125. populateAddressListSelect('mangle-val-dstlist');
  5126. populateGeoIPSelect('mangle-val-srcgeo');
  5127. populateGeoIPSelect('mangle-val-dstgeo');
  5128. allMangleFieldKeys.forEach(k => toggleMangleField(k, false));
  5129. resetMangleCounterDisplay();
  5130. toggleMangleActionFields();
  5131. document.getElementById('mangle-modal').classList.remove('hidden');
  5132. }
  5133. function openEditMangleModal(id) {
  5134. id = decodeURIComponent(id);
  5135. const r = (state.mangleRules || []).find(rule => rule.id === id);
  5136. if (!r) return;
  5137. switchMangleRuleTab('general');
  5138. const badge = document.getElementById('mangle-modal-badge');
  5139. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  5140. document.getElementById('mangle-modal-id').value = r.id;
  5141. document.getElementById('mangle-modal-family').value = String(r.ip_version || 4);
  5142. document.getElementById('mangle-modal-enabled').checked = !r.disabled;
  5143. document.getElementById('mangle-modal-comment').value = r.comment || '';
  5144. document.getElementById('mangle-modal-chain').value = r.chain || 'prerouting';
  5145. setFirewallActionSelection('mangle', r.action || 'accept');
  5146. if (document.getElementById('mangle-modal-newconnmark')) document.getElementById('mangle-modal-newconnmark').value = r.new_connection_mark || '';
  5147. if (document.getElementById('mangle-modal-newroutingmark')) document.getElementById('mangle-modal-newroutingmark').value = r.new_routing_mark || '';
  5148. if (document.getElementById('mangle-modal-newpktmark')) document.getElementById('mangle-modal-newpktmark').value = r.new_packet_mark || '';
  5149. if (document.getElementById('mangle-modal-newmss')) document.getElementById('mangle-modal-newmss').value = r.new_mss || '';
  5150. if (document.getElementById('mangle-modal-newdscp')) document.getElementById('mangle-modal-newdscp').value = r.new_dscp != null ? r.new_dscp : '';
  5151. if (document.getElementById('mangle-modal-newttl')) document.getElementById('mangle-modal-newttl').value = r.new_ttl || '';
  5152. if (document.getElementById('mangle-modal-newpriority')) document.getElementById('mangle-modal-newpriority').value = r.new_priority || '';
  5153. if (document.getElementById('mangle-modal-route')) document.getElementById('mangle-modal-route').value = r.route || '';
  5154. if (document.getElementById('mangle-modal-sniff')) document.getElementById('mangle-modal-sniff').value = r.sniff_target || '';
  5155. if (document.getElementById('mangle-modal-jumptarget')) document.getElementById('mangle-modal-jumptarget').value = r.jump_target || '';
  5156. if (document.getElementById('mangle-modal-action-addrlist')) document.getElementById('mangle-modal-action-addrlist').value = r.address_list || '';
  5157. if (document.getElementById('mangle-modal-action-timeout')) document.getElementById('mangle-modal-action-timeout').value = r.address_list_timeout || '';
  5158. if (document.getElementById('mangle-modal-passthrough')) document.getElementById('mangle-modal-passthrough').checked = r.passthrough ?? true;
  5159. if (document.getElementById('mangle-modal-log')) document.getElementById('mangle-modal-log').checked = !!r.log;
  5160. populateInterfaceSelect('mangle-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  5161. populateInterfaceSelect('mangle-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  5162. populateAddressListSelect('mangle-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  5163. populateAddressListSelect('mangle-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  5164. populateGeoIPSelect('mangle-val-srcgeo', r.src_geoip || '');
  5165. populateGeoIPSelect('mangle-val-dstgeo', r.dst_geoip || '');
  5166. setMangleFieldVal('src', r.src_address, true);
  5167. setMangleFieldVal('dst', r.dst_address, true);
  5168. setMangleFieldVal('srclist', r.src_address_list, true);
  5169. setMangleFieldVal('dstlist', r.dst_address_list, true);
  5170. setMangleFieldVal('srcgeo', r.src_geoip, true);
  5171. setMangleFieldVal('dstgeo', r.dst_geoip, true);
  5172. if (r.protocol && r.protocol !== 'all') {
  5173. setMangleFieldVal('proto', r.protocol, true);
  5174. } else {
  5175. toggleMangleField('proto', false);
  5176. }
  5177. setMangleFieldVal('sport', r.src_port, true);
  5178. setMangleFieldVal('dport', r.dst_port, true);
  5179. setMangleFieldVal('anyport', r.any_port, true);
  5180. setMangleFieldVal('iniface', r.in_interface, true);
  5181. setMangleFieldVal('outiface', r.out_interface, true);
  5182. setMangleFieldVal('inifacelist', r.in_interface_list, true);
  5183. setMangleFieldVal('outifacelist', r.out_interface_list, true);
  5184. setMangleFieldVal('pktmark', r.packet_mark, true);
  5185. setMangleFieldVal('connmark', r.connection_mark, true);
  5186. setMangleFieldVal('routingmark', r.routing_mark, true);
  5187. setMangleFieldVal('conntype', r.connection_type, false);
  5188. // Connection State
  5189. const states = r.connection_state || [];
  5190. if (states.length > 0) {
  5191. toggleMangleField('cs', true);
  5192. ['established', 'related', 'new', 'invalid', 'untracked'].forEach(s => {
  5193. const el = document.getElementById(`mangle-modal-cs-${s}`);
  5194. if (el) el.checked = states.includes(s);
  5195. });
  5196. } else {
  5197. toggleMangleField('cs', false);
  5198. }
  5199. // Connection NAT State
  5200. const natStates = r.connection_nat_state || [];
  5201. if (natStates.length > 0) {
  5202. toggleMangleField('natstate', true);
  5203. ['srcnat', 'dstnat'].forEach(s => {
  5204. const el = document.getElementById(`mangle-modal-nat-${s}`);
  5205. if (el) el.checked = natStates.includes(s);
  5206. });
  5207. } else {
  5208. toggleMangleField('natstate', false);
  5209. }
  5210. // Advanced tab fields
  5211. setMangleFieldVal('layer7', r.layer7_protocol, false);
  5212. setMangleFieldVal('content', r.content, false);
  5213. setMangleFieldVal('connbytes', r.connection_bytes, false);
  5214. setMangleFieldVal('connrate', r.connection_rate, false);
  5215. setMangleFieldVal('pcc', r.pcc, false);
  5216. setMangleFieldVal('srcmac', r.src_mac_address, true);
  5217. setMangleFieldVal('outbridgeport', r.out_bridge_port, false);
  5218. setMangleFieldVal('inbridgeport', r.in_bridge_port, false);
  5219. setMangleFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  5220. setMangleFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  5221. setMangleFieldVal('ipsec', r.ipsec_policy, false);
  5222. setMangleFieldVal('tlshost', r.tls_host, false);
  5223. setMangleFieldVal('ingresspriority', r.ingress_priority, false);
  5224. setMangleFieldVal('priority', r.priority, false);
  5225. setMangleFieldVal('dscp', r.dscp, false);
  5226. setMangleFieldVal('tcpmss', r.tcp_mss, false);
  5227. { const tosEl = document.getElementById('mangle-val-tos'); if (tosEl) tosEl.value = r.tos || ''; }
  5228. setMangleFieldVal('pktsize', r.packet_size, false);
  5229. setMangleFieldVal('random', r.random, false);
  5230. setMangleFieldVal('tcpflags', r.tcp_flags, false);
  5231. setMangleFieldVal('icmpoptions', r.icmp_options, false);
  5232. setMangleFieldVal('ipv4options', r.ipv4_options, false);
  5233. setMangleFieldVal('ttl', r.ttl, false);
  5234. // Extra tab fields
  5235. setMangleFieldVal('nth', r.nth, false);
  5236. setMangleFieldVal('connlimit', r.connection_limit, false);
  5237. setMangleFieldVal('srcaddrtype', r.src_address_type, false);
  5238. setMangleFieldVal('dstaddrtype', r.dst_address_type, false);
  5239. setMangleFieldVal('hotspot', r.hotspot, false);
  5240. setMangleFieldVal('ipfragment', r.ip_fragment, false);
  5241. setMangleFieldVal('limit', r.limit, false);
  5242. setMangleFieldVal('dstlimit', r.dst_limit, false);
  5243. setMangleFieldVal('time', r.time, false);
  5244. setMangleFieldVal('psd', r.psd, false);
  5245. // Action fields
  5246. if (r.jump_target) {
  5247. const jtEl = document.getElementById('mangle-modal-jumptarget');
  5248. if (jtEl) jtEl.value = r.jump_target;
  5249. }
  5250. if (r.address_list) {
  5251. const alEl = document.getElementById('mangle-modal-action-addrlist');
  5252. if (alEl) alEl.value = r.address_list;
  5253. }
  5254. if (r.address_list_timeout) {
  5255. const toEl = document.getElementById('mangle-modal-action-timeout');
  5256. if (toEl) toEl.value = r.address_list_timeout;
  5257. }
  5258. setMangleFieldVal('logprefix', r.log_prefix, false);
  5259. // Statistics
  5260. const bEl = document.getElementById('mangle-stat-bytes');
  5261. const pEl = document.getElementById('mangle-stat-packets');
  5262. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  5263. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  5264. state.mangleLastBytes = r.bytes || 0;
  5265. state.mangleLastPackets = r.packets || 0;
  5266. state.mangleLastTimestamp = Date.now();
  5267. state.mangleStatRateHistory = new Array(30).fill(0);
  5268. state.mangleStatPktHistory = new Array(30).fill(0);
  5269. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  5270. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  5271. toggleMangleActionFields();
  5272. document.getElementById('mangle-modal').classList.remove('hidden');
  5273. }
  5274. function closeMangleModal() {
  5275. stopMangleStatPolling();
  5276. document.getElementById('mangle-modal').classList.add('hidden');
  5277. }
  5278. function copyMangleRule() {
  5279. document.getElementById('mangle-modal-id').value = '';
  5280. const badge = document.getElementById('mangle-modal-badge');
  5281. if (badge) badge.innerText = 'New...';
  5282. showToast('Rule Cloned', 'Ready to save as a new Mangle rule copy', 'info');
  5283. }
  5284. function resetMangleCounterDisplay() {
  5285. state.mangleStatRateHistory = new Array(30).fill(0);
  5286. state.mangleStatPktHistory = new Array(30).fill(0);
  5287. state.mangleLastBytes = 0;
  5288. state.mangleLastPackets = 0;
  5289. state.mangleLastTimestamp = Date.now();
  5290. const bEl = document.getElementById('mangle-stat-bytes');
  5291. const pEl = document.getElementById('mangle-stat-packets');
  5292. const rEl = document.getElementById('mangle-stat-rate');
  5293. const prEl = document.getElementById('mangle-stat-pktrate');
  5294. if (bEl) bEl.value = '0 B';
  5295. if (pEl) pEl.value = '0';
  5296. if (rEl) rEl.value = '0 bps';
  5297. if (prEl) prEl.value = '0 p/s';
  5298. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  5299. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  5300. showToast('Counters Reset', 'Mangle rule counter display reset to 0', 'info');
  5301. }
  5302. async function applyMangleRule(closeAfter = false) {
  5303. const id = document.getElementById('mangle-modal-id').value;
  5304. if (!reviewLegacyFirewallSettings('mangle', id)) return;
  5305. const chain = document.getElementById('mangle-modal-chain').value;
  5306. const action = document.getElementById('mangle-modal-action').value;
  5307. const comment = document.getElementById('mangle-modal-comment').value.trim();
  5308. const enabled = document.getElementById('mangle-modal-enabled').checked;
  5309. const src = getMangleFieldVal('src', true);
  5310. const dst = getMangleFieldVal('dst', true);
  5311. const srclist = getMangleFieldVal('srclist', true);
  5312. const dstlist = getMangleFieldVal('dstlist', true);
  5313. const srcgeo = getMangleFieldVal('srcgeo', true);
  5314. const dstgeo = getMangleFieldVal('dstgeo', true);
  5315. const proto = getMangleFieldVal('proto', true);
  5316. const sport = getMangleFieldVal('sport', true);
  5317. const dport = getMangleFieldVal('dport', true);
  5318. const anyport = getMangleFieldVal('anyport', true);
  5319. const iniface = getMangleFieldVal('iniface', true);
  5320. const outiface = getMangleFieldVal('outiface', true);
  5321. const inifacelist = getMangleFieldVal('inifacelist', true);
  5322. const outifacelist = getMangleFieldVal('outifacelist', true);
  5323. const pktmark = getMangleFieldVal('pktmark', true);
  5324. const connmark = getMangleFieldVal('connmark', true);
  5325. const routingmark = getMangleFieldVal('routingmark', true);
  5326. const conntype = getMangleFieldVal('conntype', false);
  5327. const states = [];
  5328. const csBox = document.getElementById('mangle-field-cs');
  5329. if (csBox && !csBox.classList.contains('hidden')) {
  5330. ['established', 'related', 'new', 'invalid', 'untracked'].forEach(s => {
  5331. if (document.getElementById(`mangle-modal-cs-${s}`)?.checked) states.push(s);
  5332. });
  5333. }
  5334. const natStates = [];
  5335. const natBox = document.getElementById('mangle-field-natstate');
  5336. if (natBox && !natBox.classList.contains('hidden')) {
  5337. ['srcnat', 'dstnat'].forEach(s => {
  5338. if (document.getElementById(`mangle-modal-nat-${s}`)?.checked) natStates.push(s);
  5339. });
  5340. }
  5341. const payload = {
  5342. ip_version: Number(document.getElementById('mangle-modal-family').value),
  5343. id,
  5344. chain,
  5345. action,
  5346. protocol: proto || 'all',
  5347. src_address: src,
  5348. dst_address: dst,
  5349. src_port: sport,
  5350. dst_port: dport,
  5351. any_port: anyport,
  5352. in_interface: iniface,
  5353. out_interface: outiface,
  5354. in_interface_list: inifacelist,
  5355. out_interface_list: outifacelist,
  5356. packet_mark: pktmark,
  5357. connection_mark: connmark,
  5358. routing_mark: routingmark,
  5359. connection_type: conntype,
  5360. connection_state: states,
  5361. connection_nat_state: natStates,
  5362. src_address_list: srclist,
  5363. dst_address_list: dstlist,
  5364. src_geoip: srcgeo,
  5365. dst_geoip: dstgeo,
  5366. comment,
  5367. disabled: !enabled,
  5368. // Advanced tab
  5369. content: getMangleFieldVal('content', false),
  5370. src_mac_address: getMangleFieldVal('srcmac', true),
  5371. out_bridge_port: getMangleFieldVal('outbridgeport', false),
  5372. in_bridge_port: getMangleFieldVal('inbridgeport', false),
  5373. ipsec_policy: getMangleFieldVal('ipsec', false),
  5374. dscp: getMangleFieldVal('dscp', false),
  5375. tcp_mss: getMangleFieldVal('tcpmss', false),
  5376. tos: document.getElementById('mangle-val-tos')?.value || '',
  5377. packet_size: getMangleFieldVal('pktsize', false),
  5378. random: getMangleFieldVal('random', false),
  5379. tcp_flags: getMangleFieldVal('tcpflags', false),
  5380. icmp_options: getMangleFieldVal('icmpoptions', false),
  5381. ttl: getMangleFieldVal('ttl', false),
  5382. // Extra tab
  5383. nth: getMangleFieldVal('nth', false),
  5384. connection_limit: getMangleFieldVal('connlimit', false),
  5385. src_address_type: getMangleFieldVal('srcaddrtype', false),
  5386. dst_address_type: getMangleFieldVal('dstaddrtype', false),
  5387. ip_fragment: getMangleFieldVal('ipfragment', false),
  5388. limit: getMangleFieldVal('limit', false),
  5389. time: getMangleFieldVal('time', false),
  5390. // Action tab
  5391. new_connection_mark: action === 'mark-connection' ? (document.getElementById('mangle-modal-newconnmark')?.value.trim() || '') : '',
  5392. new_routing_mark: action === 'mark-routing' ? (document.getElementById('mangle-modal-newroutingmark')?.value.trim() || '') : '',
  5393. new_packet_mark: action === 'mark-packet' ? (document.getElementById('mangle-modal-newpktmark')?.value.trim() || '') : '',
  5394. new_mss: action === 'change-mss' ? (document.getElementById('mangle-modal-newmss')?.value.trim() || '') : '',
  5395. new_dscp: action === 'change-dscp' ? parseInt(document.getElementById('mangle-modal-newdscp')?.value || '0', 10) : 0,
  5396. new_ttl: action === 'change-ttl' ? (document.getElementById('mangle-modal-newttl')?.value.trim() || '') : '',
  5397. new_priority: action === 'set-priority' ? (document.getElementById('mangle-modal-newpriority')?.value.trim() || '') : '',
  5398. passthrough: document.getElementById('mangle-modal-passthrough')?.checked ?? true,
  5399. jump_target: action === 'jump' ? (document.getElementById('mangle-modal-jumptarget')?.value || '') : '',
  5400. address_list: action.includes('address') ? (document.getElementById('mangle-modal-action-addrlist')?.value || '') : '',
  5401. address_list_timeout: action.includes('address') ? (document.getElementById('mangle-modal-action-timeout')?.value || '') : '',
  5402. log: document.getElementById('mangle-modal-log')?.checked || false,
  5403. log_prefix: getMangleFieldVal('logprefix', false)
  5404. };
  5405. try {
  5406. const res = await fetch(`${API_BASE}/firewall/mangle`, {
  5407. method: 'POST',
  5408. headers: { 'Content-Type': 'application/json' },
  5409. body: JSON.stringify(payload)
  5410. });
  5411. if (res.ok) {
  5412. const data = await res.json();
  5413. showToast('Mangle Rule Saved', 'Marking rule updated', 'success');
  5414. loadFirewall(false);
  5415. if (closeAfter) {
  5416. closeMangleModal();
  5417. } else {
  5418. if (data.id) {
  5419. document.getElementById('mangle-modal-id').value = data.id;
  5420. const badge = document.getElementById('mangle-modal-badge');
  5421. if (badge) badge.innerText = `#${data.id}`;
  5422. }
  5423. }
  5424. } else {
  5425. const err = await res.json();
  5426. showToast('Error', err.message || 'Failed to save mangle rule', 'error');
  5427. }
  5428. } catch (err) {
  5429. showToast('Error', err.message, 'error');
  5430. }
  5431. }
  5432. function submitSaveMangleRule(e) {
  5433. if (e && e.preventDefault) e.preventDefault();
  5434. return applyMangleRule(true);
  5435. }
  5436. function startMangleStatPolling() {
  5437. stopMangleStatPolling();
  5438. pollMangleRuleStats();
  5439. state.mangleStatInterval = setInterval(pollMangleRuleStats, 1000);
  5440. }
  5441. function stopMangleStatPolling() {
  5442. if (state.mangleStatInterval) {
  5443. clearInterval(state.mangleStatInterval);
  5444. state.mangleStatInterval = null;
  5445. }
  5446. }
  5447. async function pollMangleRuleStats() {
  5448. const id = document.getElementById('mangle-modal-id')?.value;
  5449. if (!id) {
  5450. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory || new Array(30).fill(0), 'bps', 'mangle-stat-legend-rate');
  5451. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory || new Array(30).fill(0), 'p/s', 'mangle-stat-legend-pktrate');
  5452. return;
  5453. }
  5454. try {
  5455. const res = await fetch(`${API_BASE}/firewall/mangle`);
  5456. if (!res.ok) return;
  5457. const rules = await res.json();
  5458. const r = rules.find(x => x.id === id);
  5459. if (!r) return;
  5460. const now = Date.now();
  5461. const dt = Math.max(0.2, (now - (state.mangleLastTimestamp || now)) / 1000);
  5462. state.mangleLastTimestamp = now;
  5463. const curBytes = r.bytes || 0;
  5464. const curPackets = r.packets || 0;
  5465. const deltaBytes = Math.max(0, curBytes - (state.mangleLastBytes ?? curBytes));
  5466. const deltaPkts = Math.max(0, curPackets - (state.mangleLastPackets ?? curPackets));
  5467. state.mangleLastBytes = curBytes;
  5468. state.mangleLastPackets = curPackets;
  5469. const rateBps = Math.round((deltaBytes * 8) / dt);
  5470. const ratePkt = Math.round(deltaPkts / dt);
  5471. if (!state.mangleStatRateHistory) state.mangleStatRateHistory = new Array(30).fill(0);
  5472. if (!state.mangleStatPktHistory) state.mangleStatPktHistory = new Array(30).fill(0);
  5473. state.mangleStatRateHistory.push(rateBps);
  5474. if (state.mangleStatRateHistory.length > 30) state.mangleStatRateHistory.shift();
  5475. state.mangleStatPktHistory.push(ratePkt);
  5476. if (state.mangleStatPktHistory.length > 30) state.mangleStatPktHistory.shift();
  5477. const bEl = document.getElementById('mangle-stat-bytes');
  5478. const pEl = document.getElementById('mangle-stat-packets');
  5479. const rEl = document.getElementById('mangle-stat-rate');
  5480. const prEl = document.getElementById('mangle-stat-pktrate');
  5481. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  5482. if (pEl) pEl.value = curPackets.toLocaleString();
  5483. if (rEl) rEl.value = formatBps(rateBps);
  5484. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  5485. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  5486. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  5487. } catch (e) {
  5488. console.error('Error polling Mangle rule stats', e);
  5489. }
  5490. }
  5491. async function moveMangleRule(id, dir) {
  5492. id = decodeURIComponent(id);
  5493. try {
  5494. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/move`, {
  5495. method: 'POST',
  5496. headers: { 'Content-Type': 'application/json' },
  5497. body: JSON.stringify({ direction: dir })
  5498. });
  5499. if (res.ok) loadFirewall(false);
  5500. } catch (err) {
  5501. showToast('Error', err.message, 'error');
  5502. }
  5503. }
  5504. async function toggleMangleRuleState(id, disabled) {
  5505. id = decodeURIComponent(id);
  5506. try {
  5507. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/state`, {
  5508. method: 'POST',
  5509. headers: { 'Content-Type': 'application/json' },
  5510. body: JSON.stringify({ disabled })
  5511. });
  5512. if (res.ok) loadFirewall(false);
  5513. } catch (err) {
  5514. showToast('Error', err.message, 'error');
  5515. }
  5516. }
  5517. async function deleteMangleRule(id) {
  5518. id = decodeURIComponent(id);
  5519. if (!confirm('Are you sure you want to delete this mangle rule?')) return;
  5520. try {
  5521. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5522. if (res.ok) {
  5523. showToast('Deleted', 'Mangle rule removed', 'success');
  5524. loadFirewall(false);
  5525. }
  5526. } catch (err) {
  5527. showToast('Error', err.message, 'error');
  5528. }
  5529. }
  5530. // ----------------- Address Lists -----------------
  5531. function renderAddressLists() {
  5532. const filterList = document.getElementById('addrlist-filter-name')?.value || '';
  5533. const tbody = document.getElementById('addrlist-table-body');
  5534. const empty = document.getElementById('addrlist-empty');
  5535. if (!tbody) return;
  5536. tbody.innerHTML = '';
  5537. const entries = (state.addressLists || []).filter(e => !filterList || e.name === filterList);
  5538. document.getElementById('addrlist-count-badge').innerText = `${entries.length} Entries${entries.filter(e => e.dynamic).length >= 2000 ? ' (dynamic results capped at 2000)' : ''}`;
  5539. // Update filter select
  5540. const sel = document.getElementById('addrlist-filter-name');
  5541. if (sel) {
  5542. const cur = sel.value;
  5543. sel.innerHTML = '<option value="">All Lists</option>';
  5544. const set = new Set((state.addressLists || []).map(a => a.name));
  5545. set.forEach(n => {
  5546. const opt = document.createElement('option');
  5547. opt.value = n;
  5548. opt.innerText = n;
  5549. if (n === cur) opt.selected = true;
  5550. sel.appendChild(opt);
  5551. });
  5552. }
  5553. if (entries.length === 0) {
  5554. empty?.classList.remove('hidden');
  5555. return;
  5556. }
  5557. empty?.classList.add('hidden');
  5558. entries.forEach((raw, idx) => {
  5559. const e = safeFirewallRow(raw);
  5560. const tr = document.createElement('tr');
  5561. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${e.disabled ? 'opacity-50' : ''}`;
  5562. if (!e.dynamic) tr.setAttribute('ondblclick', `openEditAddrListModal('${e.id}')`);
  5563. tr.innerHTML = `
  5564. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  5565. <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>
  5566. <td class="py-2.5 px-3 font-bold text-white font-mono">${e.name}</td>
  5567. <td class="py-2.5 px-3 font-mono font-bold text-emerald-400">${e.address}</td>
  5568. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[150px]">${e.dynamic ? 'Dynamic · '+(e.timeout ? e.timeout+'s remaining' : 'no expiry') : e.comment || '-'}</td>
  5569. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  5570. ${e.dynamic ? '' : ` <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>
  5571. <button onclick="openEditAddrListModal('${e.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-medium">Edit</button>
  5572. `}
  5573. <button onclick="deleteAddrList('${e.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  5574. </td>
  5575. `;
  5576. tbody.appendChild(tr);
  5577. });
  5578. populateCommonAddrListDatalist();
  5579. }
  5580. function openAddAddrListModal() {
  5581. document.getElementById('addrlist-modal-title').innerText = 'Add Address List Entry';
  5582. document.getElementById('addrlist-modal-id').value = '';
  5583. document.getElementById('addrlist-modal-name').value = '';
  5584. document.getElementById('addrlist-modal-addr').value = '';
  5585. document.getElementById('addrlist-modal-comment').value = '';
  5586. document.getElementById('addrlist-modal-disabled').checked = false;
  5587. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  5588. if (submitBtn) submitBtn.innerText = 'Add to List';
  5589. document.getElementById('addrlist-modal').classList.remove('hidden');
  5590. }
  5591. function openEditAddrListModal(id) {
  5592. id = decodeURIComponent(id);
  5593. const e = (state.addressLists || []).find(item => item.id === id);
  5594. if (!e) return;
  5595. document.getElementById('addrlist-modal-title').innerText = `Edit Address List Entry: ${e.name}`;
  5596. document.getElementById('addrlist-modal-id').value = e.id;
  5597. document.getElementById('addrlist-modal-name').value = e.name;
  5598. document.getElementById('addrlist-modal-addr').value = e.address;
  5599. document.getElementById('addrlist-modal-comment').value = e.comment || '';
  5600. document.getElementById('addrlist-modal-disabled').checked = !!e.disabled;
  5601. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  5602. if (submitBtn) submitBtn.innerText = 'Save Changes';
  5603. document.getElementById('addrlist-modal').classList.remove('hidden');
  5604. }
  5605. function closeAddrListModal() {
  5606. document.getElementById('addrlist-modal').classList.add('hidden');
  5607. }
  5608. async function submitSaveAddrList(e) {
  5609. e.preventDefault();
  5610. const id = document.getElementById('addrlist-modal-id').value;
  5611. const name = document.getElementById('addrlist-modal-name').value.trim();
  5612. const addr = document.getElementById('addrlist-modal-addr').value.trim();
  5613. const comment = document.getElementById('addrlist-modal-comment').value.trim();
  5614. const disabled = document.getElementById('addrlist-modal-disabled').checked;
  5615. try {
  5616. const res = await fetch(`${API_BASE}/firewall/address-lists`, {
  5617. method: 'POST',
  5618. headers: { 'Content-Type': 'application/json' },
  5619. body: JSON.stringify({ id, name, address: addr, comment, disabled })
  5620. });
  5621. if (res.ok) {
  5622. showToast('Address List Item Saved', `Saved ${addr} in ${name}`, 'success');
  5623. closeAddrListModal();
  5624. loadFirewall(false);
  5625. } else {
  5626. const err = await res.json();
  5627. showToast('Error', err.message || 'Failed to save address list', 'error');
  5628. }
  5629. } catch (err) {
  5630. showToast('Error', err.message, 'error');
  5631. }
  5632. }
  5633. async function toggleAddrListState(id, disabled) {
  5634. id = decodeURIComponent(id);
  5635. try {
  5636. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}/state`, {
  5637. method: 'POST',
  5638. headers: { 'Content-Type': 'application/json' },
  5639. body: JSON.stringify({ disabled })
  5640. });
  5641. if (res.ok) {
  5642. loadFirewall(false);
  5643. }
  5644. } catch (err) {
  5645. showToast('Error', err.message, 'error');
  5646. }
  5647. }
  5648. async function deleteAddrList(id) {
  5649. id = decodeURIComponent(id);
  5650. if (!confirm('Are you sure you want to delete this address list item?')) return;
  5651. try {
  5652. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5653. if (res.ok) {
  5654. showToast('Deleted', 'Address list item removed', 'info');
  5655. loadFirewall(false);
  5656. }
  5657. } catch (err) {
  5658. showToast('Error', err.message, 'error');
  5659. }
  5660. }
  5661. // ----------------- Geo-Location IP Management -----------------
  5662. async function loadGeoIP() {
  5663. try {
  5664. const [statusRes, countriesRes] = await Promise.all([
  5665. fetch(`${API_BASE}/firewall/geoip/status`),
  5666. fetch(`${API_BASE}/firewall/geoip/countries`)
  5667. ]);
  5668. if (statusRes.ok) state.geoStatus = await statusRes.json();
  5669. if (countriesRes.ok) state.geoCountries = await countriesRes.json();
  5670. updateGeoHeader();
  5671. renderGeoCountries();
  5672. } catch (err) {
  5673. console.error('Failed to load GeoIP:', err);
  5674. }
  5675. }
  5676. function getGeoUsageMap() {
  5677. const usage = {};
  5678. const checkRule = (r, type) => {
  5679. ['src_geoip', 'dst_geoip'].forEach(field => {
  5680. let val = (r && r[field]) || '';
  5681. let code = val.replace(/^!/, '').replace(/^geo:/, '').replace(/^geo_/, '').toUpperCase().trim();
  5682. if (code) {
  5683. if (!usage[code]) usage[code] = [];
  5684. const label = `${type} #${r.priority !== undefined ? r.priority : (r.id || '')}`;
  5685. if (!usage[code].includes(label)) usage[code].push(label);
  5686. }
  5687. });
  5688. };
  5689. (state.filterRules || []).forEach(r => checkRule(r, 'Filter'));
  5690. (state.natRules || []).forEach(r => checkRule(r, 'NAT'));
  5691. (state.mangleRules || []).forEach(r => checkRule(r, 'Mangle'));
  5692. return usage;
  5693. }
  5694. function updateGeoHeader() {
  5695. const s = state.geoStatus || {};
  5696. const statusBadge = document.getElementById('geo-status-badge');
  5697. if (statusBadge) {
  5698. statusBadge.innerText = s.auto_update ? 'Auto-Update ON' : 'Auto-Update OFF';
  5699. statusBadge.className = s.auto_update
  5700. ? 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-emerald-500/20 text-emerald-300 border border-emerald-500/30'
  5701. : 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 text-slate-400';
  5702. }
  5703. const intervalLabel = document.getElementById('geo-interval-label');
  5704. if (intervalLabel) {
  5705. intervalLabel.innerText = `Every ${s.interval_hours || 24}h`;
  5706. }
  5707. const usageMap = getGeoUsageMap();
  5708. const inUseCount = Object.keys(usageMap).length;
  5709. const activeCountEl = document.getElementById('geo-stat-active-countries');
  5710. if (activeCountEl) activeCountEl.innerText = inUseCount.toLocaleString();
  5711. const totalSubnetsEl = document.getElementById('geo-stat-total-subnets');
  5712. if (totalSubnetsEl) totalSubnetsEl.innerText = (s.total_subnets || 0).toLocaleString();
  5713. const lastSyncEl = document.getElementById('geo-stat-last-sync');
  5714. if (lastSyncEl) {
  5715. if (s.last_updated && !s.last_updated.startsWith('0001')) {
  5716. const d = new Date(s.last_updated);
  5717. lastSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  5718. } else {
  5719. lastSyncEl.innerText = 'Never (Sync Pending)';
  5720. }
  5721. }
  5722. const nextSyncEl = document.getElementById('geo-stat-next-sync');
  5723. if (nextSyncEl) {
  5724. if (s.next_update && !s.next_update.startsWith('0001')) {
  5725. const d = new Date(s.next_update);
  5726. nextSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  5727. } else {
  5728. nextSyncEl.innerText = '-';
  5729. }
  5730. }
  5731. const badge = document.getElementById('fw-badge-geo');
  5732. if (badge) badge.innerText = inUseCount || (state.geoCountries || []).filter(c => c.subnet_count > 0).length || 0;
  5733. }
  5734. function renderGeoCountries() {
  5735. const tbody = document.getElementById('geo-table-body');
  5736. const empty = document.getElementById('geo-empty');
  5737. if (!tbody) return;
  5738. tbody.innerHTML = '';
  5739. const q = (document.getElementById('geo-search-input')?.value || '').trim().toLowerCase();
  5740. const continent = document.getElementById('geo-continent-filter')?.value || '';
  5741. const inUseOnly = document.getElementById('geo-filter-inuse-only')?.checked;
  5742. const cachedOnly = document.getElementById('geo-filter-cached-only')?.checked;
  5743. const usageMap = getGeoUsageMap();
  5744. const countries = (state.geoCountries || []).filter(c => {
  5745. const isUsed = !!usageMap[c.code];
  5746. if (inUseOnly && !isUsed) return false;
  5747. if (cachedOnly && (!c.subnet_count || c.subnet_count === 0)) return false;
  5748. if (continent && c.continent !== continent) return false;
  5749. if (q) {
  5750. const matchCode = c.code.toLowerCase().includes(q);
  5751. const matchName = c.name.toLowerCase().includes(q);
  5752. if (!matchCode && !matchName) return false;
  5753. }
  5754. return true;
  5755. });
  5756. if (countries.length === 0) {
  5757. empty?.classList.remove('hidden');
  5758. return;
  5759. }
  5760. empty?.classList.add('hidden');
  5761. countries.forEach(c => {
  5762. const tr = document.createElement('tr');
  5763. const isUsed = !!usageMap[c.code];
  5764. const rulesUsing = usageMap[c.code] || [];
  5765. tr.className = `hover:bg-slate-800/40 transition text-xs ${isUsed ? 'bg-emerald-950/20' : ''}`;
  5766. let statusHtml = '';
  5767. if (isUsed) {
  5768. 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>`;
  5769. } else if (c.subnet_count > 0) {
  5770. 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>';
  5771. } else {
  5772. statusHtml = '<span class="px-2 py-0.5 rounded text-[10px] font-mono text-slate-500 bg-slate-800/60">READY</span>';
  5773. }
  5774. tr.innerHTML = `
  5775. <td class="py-2.5 px-3 text-center">
  5776. <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'}">
  5777. ${c.code}
  5778. </span>
  5779. </td>
  5780. <td class="py-2.5 px-3 font-bold text-white">${c.name}</td>
  5781. <td class="py-2.5 px-3 text-slate-400">${c.continent}</td>
  5782. <td class="py-2.5 px-3 font-mono ${c.subnet_count > 0 ? 'text-emerald-400 font-bold' : 'text-slate-500'}">
  5783. ${c.subnet_count > 0 ? c.subnet_count.toLocaleString() + ' CIDRs' : 'Not Cached'}
  5784. </td>
  5785. <td class="py-2.5 px-3 font-mono text-purple-300">${c.ipset_name}</td>
  5786. <td class="py-2.5 px-3">
  5787. ${statusHtml}
  5788. </td>
  5789. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  5790. <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>
  5791. <button onclick="viewGeoSubnets('${c.code}')" class="text-xs text-slate-400 hover:text-white" title="Preview Subnet Ranges">View</button>
  5792. </td>
  5793. `;
  5794. tbody.appendChild(tr);
  5795. });
  5796. }
  5797. function quickFilterGeo(preset) {
  5798. const searchInput = document.getElementById('geo-search-input');
  5799. const continentSel = document.getElementById('geo-continent-filter');
  5800. const inUseCheck = document.getElementById('geo-filter-inuse-only');
  5801. const cachedCheck = document.getElementById('geo-filter-cached-only');
  5802. if (searchInput) searchInput.value = '';
  5803. if (continentSel) continentSel.value = '';
  5804. if (inUseCheck) inUseCheck.checked = false;
  5805. if (cachedCheck) cachedCheck.checked = false;
  5806. if (preset === 'GR') {
  5807. if (searchInput) searchInput.value = 'Greece';
  5808. } else if (preset === 'Europe') {
  5809. if (continentSel) continentSel.value = 'Europe';
  5810. } else if (preset === 'HIGHRISK') {
  5811. if (searchInput) searchInput.value = 'China';
  5812. }
  5813. renderGeoCountries();
  5814. }
  5815. async function toggleGeoCountry(code, enabled) {
  5816. try {
  5817. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/toggle`, {
  5818. method: 'POST',
  5819. headers: { 'Content-Type': 'application/json' },
  5820. body: JSON.stringify({ enabled })
  5821. });
  5822. if (res.ok) {
  5823. showToast(enabled ? 'Country Enabled' : 'Country Disabled', `${code} ${enabled ? 'active in firewall' : 'removed from firewall'}`, 'success');
  5824. loadGeoIP();
  5825. } else {
  5826. const err = await res.json();
  5827. showToast('Error', err.message || 'Failed to toggle country', 'error');
  5828. }
  5829. } catch (err) {
  5830. showToast('Error', err.message, 'error');
  5831. }
  5832. }
  5833. async function updateGeoCountry(code) {
  5834. try {
  5835. showToast('Syncing Country', `Downloading latest IP blocks for ${code}...`, 'info');
  5836. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/update`, { method: 'POST' });
  5837. if (res.ok) {
  5838. const data = await res.json();
  5839. showToast('Synced', `Loaded ${data.subnets} CIDR blocks for ${code}`, 'success');
  5840. loadGeoIP();
  5841. } else {
  5842. const err = await res.json();
  5843. showToast('Sync Error', err.message || 'Failed to sync country', 'error');
  5844. }
  5845. } catch (err) {
  5846. showToast('Error', err.message, 'error');
  5847. }
  5848. }
  5849. async function triggerGeoUpdateNow() {
  5850. const spinner = document.getElementById('geo-update-spinner');
  5851. if (spinner) spinner.classList.remove('hidden');
  5852. try {
  5853. const res = await fetch(`${API_BASE}/firewall/geoip/update-now`, { method: 'POST' });
  5854. if (res.ok) {
  5855. showToast('Update Started', 'Updating all active GeoIP country zones in background...', 'info');
  5856. setTimeout(() => {
  5857. loadGeoIP();
  5858. if (spinner) spinner.classList.add('hidden');
  5859. }, 2500);
  5860. } else {
  5861. const err = await res.json();
  5862. showToast('Notice', err.message || 'Update in progress', 'info');
  5863. if (spinner) spinner.classList.add('hidden');
  5864. }
  5865. } catch (err) {
  5866. showToast('Error', err.message, 'error');
  5867. if (spinner) spinner.classList.add('hidden');
  5868. }
  5869. }
  5870. async function applyGeoPreset(preset) {
  5871. try {
  5872. const res = await fetch(`${API_BASE}/firewall/geoip/batch-toggle`, {
  5873. method: 'POST',
  5874. headers: { 'Content-Type': 'application/json' },
  5875. body: JSON.stringify({ preset, enabled: preset !== 'NONE' })
  5876. });
  5877. if (res.ok) {
  5878. showToast('Preset Applied', `Preset ${preset} updated in firewall`, 'success');
  5879. loadGeoIP();
  5880. }
  5881. } catch (err) {
  5882. showToast('Error', err.message, 'error');
  5883. }
  5884. }
  5885. function openGeoIntervalModal() {
  5886. const s = state.geoStatus || {};
  5887. document.getElementById('geo-cfg-autoupdate').checked = s.auto_update !== false;
  5888. const sel = document.getElementById('geo-cfg-interval');
  5889. const customBox = document.getElementById('geo-cfg-custom-box');
  5890. const customHoursInput = document.getElementById('geo-cfg-custom-hours');
  5891. const curHours = s.interval_hours || 24;
  5892. const matchOption = Array.from(sel.options).find(o => parseInt(o.value, 10) === curHours);
  5893. if (matchOption) {
  5894. sel.value = String(curHours);
  5895. customBox.classList.add('hidden');
  5896. } else {
  5897. sel.value = 'custom';
  5898. customHoursInput.value = curHours;
  5899. customBox.classList.remove('hidden');
  5900. }
  5901. document.getElementById('geo-interval-modal').classList.remove('hidden');
  5902. }
  5903. function closeGeoIntervalModal() {
  5904. document.getElementById('geo-interval-modal').classList.add('hidden');
  5905. }
  5906. function toggleCustomGeoInterval() {
  5907. const val = document.getElementById('geo-cfg-interval').value;
  5908. const customBox = document.getElementById('geo-cfg-custom-box');
  5909. if (val === 'custom') {
  5910. customBox.classList.remove('hidden');
  5911. } else {
  5912. customBox.classList.add('hidden');
  5913. }
  5914. }
  5915. async function submitGeoIntervalSettings(e) {
  5916. e.preventDefault();
  5917. const autoUpdate = document.getElementById('geo-cfg-autoupdate').checked;
  5918. const intervalVal = document.getElementById('geo-cfg-interval').value;
  5919. let hours = 24;
  5920. if (intervalVal === 'custom') {
  5921. hours = parseInt(document.getElementById('geo-cfg-custom-hours').value, 10) || 24;
  5922. } else {
  5923. hours = parseInt(intervalVal, 10) || 24;
  5924. }
  5925. try {
  5926. const res = await fetch(`${API_BASE}/firewall/geoip/config`, {
  5927. method: 'POST',
  5928. headers: { 'Content-Type': 'application/json' },
  5929. body: JSON.stringify({ auto_update: autoUpdate, interval_hours: hours })
  5930. });
  5931. if (res.ok) {
  5932. showToast('Schedule Saved', `Auto-update set to every ${hours} hours`, 'success');
  5933. closeGeoIntervalModal();
  5934. loadGeoIP();
  5935. } else {
  5936. const err = await res.json();
  5937. showToast('Error', err.message || 'Failed to save schedule', 'error');
  5938. }
  5939. } catch (err) {
  5940. showToast('Error', err.message, 'error');
  5941. }
  5942. }
  5943. async function viewGeoSubnets(code, name) {
  5944. if (!name) {
  5945. const found = (state.geoCountries || []).find(x => x.code === code);
  5946. name = found ? found.name : code;
  5947. }
  5948. document.getElementById('geo-subnets-title').innerText = `${name} (${code}) Subnets`;
  5949. document.getElementById('geo-subnets-subtitle').innerText = `Kernel IPSet: mk_geo_${code}`;
  5950. const listEl = document.getElementById('geo-subnets-list');
  5951. listEl.innerHTML = '<span class="text-slate-500">Loading subnets...</span>';
  5952. document.getElementById('geo-subnets-modal').classList.remove('hidden');
  5953. try {
  5954. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/subnets`);
  5955. if (res.ok) {
  5956. const data = await res.json();
  5957. const subnets = data.subnets || [];
  5958. if (subnets.length === 0) {
  5959. listEl.innerHTML = '<span class="text-slate-500">No cached subnets found. Click Sync to download this zone.</span>';
  5960. } else {
  5961. listEl.innerHTML = subnets.map(s => `<div>${s}</div>`).join('');
  5962. }
  5963. } else {
  5964. listEl.innerHTML = '<span class="text-rose-400">Failed to load subnets.</span>';
  5965. }
  5966. } catch (err) {
  5967. listEl.innerHTML = `<span class="text-rose-400">Error: ${err.message}</span>`;
  5968. }
  5969. }
  5970. function closeGeoSubnetsModal() {
  5971. document.getElementById('geo-subnets-modal').classList.add('hidden');
  5972. }
  5973. // ----------------- Active Connections Tracking -----------------
  5974. async function loadConnections() {
  5975. try {
  5976. const res = await fetch(`${API_BASE}/firewall/connections`);
  5977. const data = await res.json();
  5978. if (!res.ok) throw new Error(data.message || 'Connection tracking unavailable');
  5979. state.connections = Array.isArray(data) ? data : [];
  5980. document.getElementById('fw-badge-connections').innerText = state.connections.length;
  5981. document.getElementById('conns-count-badge').innerText = `${state.connections.length} Flows`;
  5982. renderConnections();
  5983. } catch (err) {
  5984. console.error('Failed to load connections:', err);
  5985. const badge=document.getElementById('conns-count-badge'); if(badge) badge.textContent='Unavailable: '+err.message;
  5986. }
  5987. }
  5988. function renderConnections() {
  5989. const search = (document.getElementById('conns-search-input')?.value || '').toLowerCase();
  5990. const protoFilter = document.getElementById('conns-filter-proto')?.value || '';
  5991. const tbody = document.getElementById('conns-table-body');
  5992. const empty = document.getElementById('conns-empty');
  5993. if (!tbody) return;
  5994. tbody.innerHTML = '';
  5995. const conns = (state.connections || []).filter(c => {
  5996. if (protoFilter && c.protocol !== protoFilter) return false;
  5997. if (search) {
  5998. const line = `${c.protocol} ${c.src_address} ${c.dst_address} ${c.src_port} ${c.dst_port} ${c.tcp_state} ${c.connection_mark}`.toLowerCase();
  5999. if (!line.includes(search)) return false;
  6000. }
  6001. return true;
  6002. });
  6003. if (conns.length === 0) {
  6004. empty?.classList.remove('hidden');
  6005. return;
  6006. }
  6007. empty?.classList.add('hidden');
  6008. conns.slice(0, 150).forEach(c => {
  6009. const tr = document.createElement('tr');
  6010. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  6011. let stateColor = 'text-slate-400';
  6012. if (c.tcp_state === 'ESTABLISHED') stateColor = 'text-emerald-400 font-bold';
  6013. else if (c.tcp_state === 'TIME_WAIT' || c.tcp_state === 'SYN_SENT') stateColor = 'text-amber-400';
  6014. tr.innerHTML = `
  6015. <td class="py-2.5 px-3 font-bold text-cyan-400">${c.protocol}</td>
  6016. <td class="py-2.5 px-3 font-mono text-white">${c.src_address}:${c.src_port}</td>
  6017. <td class="py-2.5 px-3 font-mono text-white">${c.dst_address}:${c.dst_port}</td>
  6018. <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>
  6019. <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>
  6020. <td class="py-2.5 px-3 font-mono ${stateColor}">${c.tcp_state}</td>
  6021. <td class="py-2.5 px-3 font-mono text-purple-300">${c.connection_mark || '-'}</td>
  6022. <td class="py-2.5 px-3 text-slate-500">${c.timeout ? c.timeout + 's' : '-'}</td>
  6023. <td class="py-2.5 px-3 text-right font-sans">
  6024. ${['TCP','UDP','SCTP','DCCP','ICMP','ICMPV6'].includes(c.protocol) ? ` <button onclick="killConnection('${c.protocol}', '${c.src_address}', ${c.src_port}, '${c.dst_address}', ${c.dst_port}, ${c.ip_version || 4}, ${c.zone || 0}, ${c.icmp_id ?? 'null'}, ${c.icmp_type ?? 'null'}, ${c.icmp_code ?? 'null'})" class="text-xs text-rose-400 hover:text-rose-300">Kill</button>` : ''}
  6025. </td>
  6026. `;
  6027. tbody.appendChild(tr);
  6028. });
  6029. }
  6030. async function killConnection(protocol, src, sport, dst, dport, ip_version, zone, icmp_id, icmp_type, icmp_code) {
  6031. try {
  6032. const res = await fetch(`${API_BASE}/firewall/connections/kill`, {
  6033. method: 'POST',
  6034. headers: { 'Content-Type': 'application/json' },
  6035. body: JSON.stringify({ protocol, src, sport, dst, dport, ip_version, zone, icmp_id, icmp_type, icmp_code })
  6036. });
  6037. if (res.ok) {
  6038. showToast('Terminated', `Killed flow ${src}:${sport} -> ${dst}:${dport}`, 'info');
  6039. loadConnections();
  6040. } else { const error = await res.json(); showToast('Error', error.message || 'Unable to terminate this flow', 'error'); }
  6041. } catch (err) {
  6042. showToast('Error', err.message, 'error');
  6043. }
  6044. }
  6045. async function resetFirewallCounters() {
  6046. if (!confirm('Reset all firewall packet and byte counters to zero?')) return;
  6047. try {
  6048. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  6049. if (res.ok) {
  6050. showToast('Counters Reset', 'All rules counters reset to 0', 'success');
  6051. loadFirewall(false);
  6052. }
  6053. } catch (err) {
  6054. showToast('Error', err.message, 'error');
  6055. }
  6056. }
  6057. // ======================== MIKROTIK ROUTING & POLICY (/ip route) ========================
  6058. function switchRoutesSubTab(tab) {
  6059. state.routesSubTab = tab;
  6060. const tabs = ['routes', 'rules', 'tables'];
  6061. tabs.forEach(t => {
  6062. const panel = document.getElementById(`routes-subtab-${t}`);
  6063. const btn = document.getElementById(`routes-subtab-btn-${t}`);
  6064. if (panel) {
  6065. if (t === tab) panel.classList.remove('hidden');
  6066. else panel.classList.add('hidden');
  6067. }
  6068. if (btn) {
  6069. if (t === tab) {
  6070. 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';
  6071. } else {
  6072. 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';
  6073. }
  6074. }
  6075. });
  6076. setTimeout(initTableSorting, 50);
  6077. }
  6078. async function loadRoutes() {
  6079. try {
  6080. const [routesRes, rulesRes, tablesRes] = await Promise.all([
  6081. fetch(`${API_BASE}/routes`),
  6082. fetch(`${API_BASE}/routing/rules`),
  6083. fetch(`${API_BASE}/routing/tables`)
  6084. ]);
  6085. if (routesRes.ok) state.routes = await routesRes.json();
  6086. if (rulesRes.ok) state.policyRules = await rulesRes.json();
  6087. if (tablesRes.ok) state.routingTables = await tablesRes.json();
  6088. const bRoutes = document.getElementById('routes-badge-routes');
  6089. if (bRoutes) bRoutes.innerText = (state.routes || []).length;
  6090. const showSystem = document.getElementById('prule-show-system')?.checked;
  6091. const userRules = (state.policyRules || []).filter(pr => showSystem || (!pr.is_default && !pr.is_system));
  6092. const bRules = document.getElementById('routes-badge-rules');
  6093. if (bRules) bRules.innerText = userRules.length;
  6094. const bTables = document.getElementById('routes-badge-tables');
  6095. if (bTables) bTables.innerText = (state.routingTables || []).length;
  6096. const bRoutesCount = document.getElementById('badge-routes-count');
  6097. if (bRoutesCount) bRoutesCount.innerText = (state.routes || []).length;
  6098. renderRoutesList();
  6099. renderPolicyRules();
  6100. renderRoutingTables();
  6101. } catch (err) {
  6102. console.error('Failed to load routing:', err);
  6103. }
  6104. }
  6105. function getRouteProtocolBadge(proto) {
  6106. const p = (proto || 'static').toLowerCase();
  6107. switch (p) {
  6108. case 'bgp':
  6109. 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>`;
  6110. case 'ibgp':
  6111. 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>`;
  6112. case 'ospf':
  6113. 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>`;
  6114. case 'rip':
  6115. 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>`;
  6116. case 'static':
  6117. 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>`;
  6118. case 'connected':
  6119. 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>`;
  6120. case 'dhcp':
  6121. 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>`;
  6122. case 'multicast':
  6123. 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>`;
  6124. default:
  6125. 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>`;
  6126. }
  6127. }
  6128. function renderRoutesList() {
  6129. const tableFilter = document.getElementById('routes-filter-table')?.value || '';
  6130. const typeFilter = document.getElementById('routes-filter-type')?.value || '';
  6131. const tbody = document.getElementById('routes-table-body');
  6132. const empty = document.getElementById('routes-empty');
  6133. if (!tbody) return;
  6134. // Update table filter select
  6135. const sel = document.getElementById('routes-filter-table');
  6136. if (sel) {
  6137. const cur = sel.value;
  6138. sel.innerHTML = '<option value="">All Tables</option>';
  6139. (state.routingTables || []).forEach(t => {
  6140. const opt = document.createElement('option');
  6141. opt.value = t.name;
  6142. opt.innerText = t.name;
  6143. if (t.name === cur) opt.selected = true;
  6144. sel.appendChild(opt);
  6145. });
  6146. }
  6147. const routes = (state.routes || []).filter(r => {
  6148. if (tableFilter && r.routing_table !== tableFilter) return false;
  6149. if (typeFilter === 'ecmp' && !r.ecmp) return false;
  6150. if (typeFilter === 'multicast' && !r.multicast) return false;
  6151. if (typeFilter === 'static' && !r.static) return false;
  6152. if (typeFilter === 'dynamic' && !r.dynamic) return false;
  6153. if (typeFilter === 'connected' && !r.connect) return false;
  6154. if (typeFilter === 'bgp' && (r.protocol || '').toLowerCase() !== 'bgp' && (r.protocol || '').toLowerCase() !== 'ibgp') return false;
  6155. if (typeFilter === 'ospf' && (r.protocol || '').toLowerCase() !== 'ospf') return false;
  6156. if (typeFilter === 'dhcp' && (r.protocol || '').toLowerCase() !== 'dhcp') return false;
  6157. return true;
  6158. });
  6159. const ecmpCount = (state.routes || []).filter(r => r.ecmp).length;
  6160. const mcCount = (state.routes || []).filter(r => r.multicast).length;
  6161. let summaryText = `${routes.length} Routes`;
  6162. if (ecmpCount > 0) summaryText += ` • ${ecmpCount} ECMP`;
  6163. if (mcCount > 0) summaryText += ` • ${mcCount} Multicast/IGMP`;
  6164. const badgeEl = document.getElementById('routes-count-badge');
  6165. if (badgeEl) badgeEl.innerText = summaryText;
  6166. if (routes.length === 0) {
  6167. empty?.classList.remove('hidden');
  6168. tbody.innerHTML = '';
  6169. return;
  6170. }
  6171. empty?.classList.add('hidden');
  6172. 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(';');
  6173. if (tbody.dataset.sig === sig) {
  6174. return; // Routes table unchanged! Do not wipe DOM or flicker!
  6175. }
  6176. tbody.dataset.sig = sig;
  6177. tbody.innerHTML = '';
  6178. routes.forEach(r => {
  6179. const tr = document.createElement('tr');
  6180. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${r.disabled ? 'opacity-50' : ''}`;
  6181. tr.setAttribute('ondblclick', `openEditRouteModal('${r.id}')`);
  6182. // Routing Flags string: D=Dynamic, A=Active, C=Connect, S=Static, E=ECMP, M=Multicast, X=Disabled
  6183. let flags = '';
  6184. if (r.dynamic) flags += 'D';
  6185. if (r.active) flags += 'A';
  6186. if (r.connect) flags += 'C';
  6187. if (r.static) flags += 'S';
  6188. if (r.ecmp) flags += 'E';
  6189. if (r.multicast) flags += 'M';
  6190. if (r.disabled) flags += 'X';
  6191. const isDefault = r.dst_address === 'default' || r.dst_address === '0.0.0.0/0';
  6192. let healthCell = `<span class="text-slate-600 font-mono text-[11px]">-</span>`;
  6193. if (r.check_gateway === 'internet') {
  6194. if (r.health_status === 'online') {
  6195. const ms = (r.health_rtt_ms || 0).toFixed(0);
  6196. healthCell = `
  6197. <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)">
  6198. <span class="w-1.5 h-1.5 rounded-full bg-emerald-400 animate-pulse"></span>
  6199. <span>Internet OK (${ms}ms)</span>
  6200. </span>
  6201. `;
  6202. } else if (r.health_status === 'offline') {
  6203. healthCell = `
  6204. <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.">
  6205. <span class="w-1.5 h-1.5 rounded-full bg-rose-400"></span>
  6206. <span>Internet Down</span>
  6207. </span>
  6208. `;
  6209. } else {
  6210. healthCell = `
  6211. <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">
  6212. <span class="w-1.5 h-1.5 rounded-full bg-amber-400 animate-ping"></span>
  6213. <span>Checking...</span>
  6214. </span>
  6215. `;
  6216. }
  6217. } else if (r.check_gateway === 'ping') {
  6218. if (r.health_status === 'online') {
  6219. healthCell = `
  6220. <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">
  6221. <span class="w-1.5 h-1.5 rounded-full bg-cyan-400"></span>
  6222. <span>Gateway OK (${(r.health_rtt_ms || 0).toFixed(0)}ms)</span>
  6223. </span>
  6224. `;
  6225. } else if (r.health_status === 'offline') {
  6226. healthCell = `
  6227. <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">
  6228. <span class="w-1.5 h-1.5 rounded-full bg-rose-400"></span>
  6229. <span>Gateway Dead</span>
  6230. </span>
  6231. `;
  6232. }
  6233. }
  6234. const flagDescriptions = [];
  6235. if (r.dynamic) flagDescriptions.push('Dynamic (D)');
  6236. if (r.active) flagDescriptions.push('Active (A)');
  6237. if (r.connect) flagDescriptions.push('Connected (C)');
  6238. if (r.static) flagDescriptions.push('Static (S)');
  6239. if (r.ecmp) flagDescriptions.push('ECMP - Equal-Cost Multi-Path (E)');
  6240. if (r.multicast) flagDescriptions.push('Multicast / IGMP Group (M)');
  6241. if (r.disabled) flagDescriptions.push('Disabled (X)');
  6242. tr.innerHTML = `
  6243. <td class="py-2.5 px-3 text-center">
  6244. <span class="px-1.5 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 ${
  6245. 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')
  6246. }" title="Flags: ${flagDescriptions.join(', ')}">
  6247. ${flags || '-'}
  6248. </span>
  6249. </td>
  6250. <td class="py-2.5 px-3">
  6251. <div class="flex items-center gap-1.5 flex-wrap">
  6252. <span class="font-bold ${isDefault ? 'text-cyan-300' : 'text-white'}">${escapeHtml(r.dst_address)}</span>
  6253. ${r.ecmp ? `
  6254. <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)">
  6255. <span>⚡ ECMP</span>
  6256. </span>
  6257. ` : ''}
  6258. ${r.multicast ? `
  6259. <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">
  6260. <span>IGMP</span>
  6261. </span>
  6262. ` : ''}
  6263. </div>
  6264. </td>
  6265. <td class="py-2.5 px-3">${getRouteProtocolBadge(r.protocol)}</td>
  6266. <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>
  6267. <td class="py-2.5 px-3 text-slate-400 font-mono">${(r.distance !== undefined && r.distance !== null) ? r.distance : 0}</td>
  6268. <td class="py-2.5 px-3 font-mono font-semibold text-purple-300">${r.routing_table || 'main'}</td>
  6269. <td class="py-2.5 px-3 text-emerald-400 font-mono">${r.interface || '-'}</td>
  6270. <td class="py-2.5 px-3">${healthCell}</td>
  6271. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]">${r.comment || '-'}</td>
  6272. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  6273. ${r.static ? `
  6274. <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>
  6275. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold">Edit</button>
  6276. <button onclick="deleteRoute('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  6277. ` : `
  6278. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">View</button>
  6279. `}
  6280. </td>
  6281. `;
  6282. tbody.appendChild(tr);
  6283. });
  6284. }
  6285. function openAddRouteModal() {
  6286. document.getElementById('route-modal-title').innerText = 'Add Static Route';
  6287. document.getElementById('route-modal-id').value = '';
  6288. document.getElementById('route-modal-old-dst').value = '';
  6289. document.getElementById('route-modal-old-gw').value = '';
  6290. document.getElementById('route-modal-old-distance').value = '';
  6291. document.getElementById('route-modal-old-table').value = '';
  6292. document.getElementById('route-modal-old-iface').value = '';
  6293. const dstInput = document.getElementById('route-modal-dst');
  6294. const gwInput = document.getElementById('route-modal-gw');
  6295. const distInput = document.getElementById('route-modal-distance');
  6296. const ifaceSelect = document.getElementById('route-modal-iface');
  6297. const tableSelect = document.getElementById('route-modal-table');
  6298. const commentInput = document.getElementById('route-modal-comment');
  6299. const disCheck = document.getElementById('route-modal-disabled');
  6300. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  6301. dstInput.disabled = false;
  6302. dstInput.value = '0.0.0.0/0';
  6303. gwInput.disabled = false;
  6304. gwInput.value = '';
  6305. distInput.disabled = false;
  6306. distInput.value = '1';
  6307. ifaceSelect.disabled = false;
  6308. tableSelect.disabled = false;
  6309. commentInput.disabled = false;
  6310. commentInput.value = '';
  6311. disCheck.disabled = false;
  6312. disCheck.checked = false;
  6313. if (saveBtn) saveBtn.classList.remove('hidden');
  6314. const checkGw = document.getElementById('route-modal-check-gw');
  6315. if (checkGw) checkGw.value = 'internet';
  6316. const checkTarget = document.getElementById('route-modal-check-target');
  6317. if (checkTarget) checkTarget.value = '1.1.1.1';
  6318. const checkInterval = document.getElementById('route-modal-check-interval');
  6319. if (checkInterval) checkInterval.value = '5';
  6320. const checkThresh = document.getElementById('route-modal-check-threshold');
  6321. if (checkThresh) checkThresh.value = '3';
  6322. toggleRouteCheckModeUI();
  6323. populateInterfaceSelect('route-modal-iface');
  6324. // Populate tables
  6325. tableSelect.innerHTML = '';
  6326. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  6327. const opt = document.createElement('option');
  6328. opt.value = t.name;
  6329. opt.innerText = t.name;
  6330. if (t.name === 'main') opt.selected = true;
  6331. tableSelect.appendChild(opt);
  6332. });
  6333. document.getElementById('route-modal').classList.remove('hidden');
  6334. }
  6335. function openEditRouteModal(id) {
  6336. const r = (state.routes || []).find(route => route.id === id);
  6337. if (!r) return;
  6338. const isStatic = !!r.static;
  6339. document.getElementById('route-modal-title').innerText = isStatic
  6340. ? `Edit Route: ${r.dst_address}`
  6341. : `Route Properties (Read Only): ${r.dst_address}`;
  6342. document.getElementById('route-modal-id').value = r.id;
  6343. document.getElementById('route-modal-old-dst').value = r.dst_address || '';
  6344. document.getElementById('route-modal-old-gw').value = r.gateway || '';
  6345. document.getElementById('route-modal-old-distance').value = (r.distance !== undefined && r.distance !== null) ? r.distance : '';
  6346. document.getElementById('route-modal-old-table').value = r.routing_table || 'main';
  6347. document.getElementById('route-modal-old-iface').value = r.interface || '';
  6348. const dstInput = document.getElementById('route-modal-dst');
  6349. const gwInput = document.getElementById('route-modal-gw');
  6350. const distInput = document.getElementById('route-modal-distance');
  6351. const ifaceSelect = document.getElementById('route-modal-iface');
  6352. const tableSelect = document.getElementById('route-modal-table');
  6353. const commentInput = document.getElementById('route-modal-comment');
  6354. const disCheck = document.getElementById('route-modal-disabled');
  6355. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  6356. dstInput.value = r.dst_address;
  6357. gwInput.value = r.gateway || '';
  6358. distInput.value = (r.distance !== undefined && r.distance !== null) ? r.distance : 1;
  6359. commentInput.value = r.comment || '';
  6360. disCheck.checked = !!r.disabled;
  6361. const checkGw = document.getElementById('route-modal-check-gw');
  6362. if (checkGw) checkGw.value = r.check_gateway || 'none';
  6363. const checkTarget = document.getElementById('route-modal-check-target');
  6364. if (checkTarget) checkTarget.value = r.check_target || '1.1.1.1';
  6365. const checkInterval = document.getElementById('route-modal-check-interval');
  6366. if (checkInterval) checkInterval.value = r.check_interval || 5;
  6367. const checkThresh = document.getElementById('route-modal-check-threshold');
  6368. if (checkThresh) checkThresh.value = r.check_threshold || 3;
  6369. toggleRouteCheckModeUI();
  6370. dstInput.disabled = !isStatic;
  6371. gwInput.disabled = !isStatic;
  6372. distInput.disabled = !isStatic;
  6373. ifaceSelect.disabled = !isStatic;
  6374. tableSelect.disabled = !isStatic;
  6375. commentInput.disabled = !isStatic;
  6376. disCheck.disabled = !isStatic;
  6377. if (checkGw) checkGw.disabled = !isStatic;
  6378. if (checkTarget) checkTarget.disabled = !isStatic;
  6379. if (checkInterval) checkInterval.disabled = !isStatic;
  6380. if (checkThresh) checkThresh.disabled = !isStatic;
  6381. if (saveBtn) {
  6382. if (isStatic) {
  6383. saveBtn.classList.remove('hidden');
  6384. } else {
  6385. saveBtn.classList.add('hidden');
  6386. }
  6387. }
  6388. populateInterfaceSelect('route-modal-iface', r.interface);
  6389. tableSelect.innerHTML = '';
  6390. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  6391. const opt = document.createElement('option');
  6392. opt.value = t.name;
  6393. opt.innerText = t.name;
  6394. if (t.name === (r.routing_table || 'main')) opt.selected = true;
  6395. tableSelect.appendChild(opt);
  6396. });
  6397. document.getElementById('route-modal').classList.remove('hidden');
  6398. }
  6399. function closeRouteModal() {
  6400. document.getElementById('route-modal').classList.add('hidden');
  6401. }
  6402. function setRouteCheckTarget(ip) {
  6403. const inp = document.getElementById('route-modal-check-target');
  6404. if (inp) inp.value = ip;
  6405. }
  6406. function toggleRouteCheckModeUI() {
  6407. const mode = document.getElementById('route-modal-check-gw')?.value || 'none';
  6408. const targetRow = document.getElementById('route-row-check-target');
  6409. const paramsRow = document.getElementById('route-row-check-params');
  6410. if (mode === 'none') {
  6411. if (targetRow) targetRow.classList.add('opacity-40', 'pointer-events-none');
  6412. if (paramsRow) paramsRow.classList.add('opacity-40', 'pointer-events-none');
  6413. } else if (mode === 'ping') {
  6414. if (targetRow) targetRow.classList.add('opacity-40', 'pointer-events-none');
  6415. if (paramsRow) paramsRow.classList.remove('opacity-40', 'pointer-events-none');
  6416. } else { // internet
  6417. if (targetRow) targetRow.classList.remove('opacity-40', 'pointer-events-none');
  6418. if (paramsRow) paramsRow.classList.remove('opacity-40', 'pointer-events-none');
  6419. }
  6420. }
  6421. async function submitSaveRoute(e) {
  6422. e.preventDefault();
  6423. const id = document.getElementById('route-modal-id').value;
  6424. const oldDst = document.getElementById('route-modal-old-dst')?.value || '';
  6425. const oldGw = document.getElementById('route-modal-old-gw')?.value || '';
  6426. const oldDistStr = document.getElementById('route-modal-old-distance')?.value;
  6427. const oldTable = document.getElementById('route-modal-old-table')?.value || '';
  6428. const oldIface = document.getElementById('route-modal-old-iface')?.value || '';
  6429. const dst = document.getElementById('route-modal-dst').value.trim();
  6430. const gw = document.getElementById('route-modal-gw').value.trim();
  6431. const table = document.getElementById('route-modal-table').value;
  6432. const distance = parseInt(document.getElementById('route-modal-distance').value, 10) || 0;
  6433. const iface = document.getElementById('route-modal-iface').value;
  6434. const comment = document.getElementById('route-modal-comment').value.trim();
  6435. const disabled = document.getElementById('route-modal-disabled').checked;
  6436. const check_gateway = document.getElementById('route-modal-check-gw')?.value || 'none';
  6437. const check_target = document.getElementById('route-modal-check-target')?.value.trim() || '1.1.1.1';
  6438. const check_interval = parseInt(document.getElementById('route-modal-check-interval')?.value, 10) || 5;
  6439. const check_threshold = parseInt(document.getElementById('route-modal-check-threshold')?.value, 10) || 3;
  6440. if (!dst) {
  6441. showToast('Error', 'Destination address is required', 'error');
  6442. return;
  6443. }
  6444. if (!gw && !iface) {
  6445. showToast('Error', 'Either Gateway IP or Interface must be specified', 'error');
  6446. return;
  6447. }
  6448. const payload = {
  6449. id,
  6450. old_dst_address: oldDst,
  6451. old_gateway: oldGw,
  6452. old_routing_table: oldTable,
  6453. old_interface: oldIface,
  6454. dst_address: dst,
  6455. gateway: gw || iface,
  6456. routing_table: table,
  6457. distance,
  6458. interface: iface,
  6459. comment,
  6460. disabled,
  6461. check_gateway,
  6462. check_target,
  6463. check_interval,
  6464. check_threshold
  6465. };
  6466. if (oldDistStr !== undefined && oldDistStr !== '') {
  6467. payload.old_distance = parseInt(oldDistStr, 10);
  6468. }
  6469. try {
  6470. const res = await fetch(`${API_BASE}/routes`, {
  6471. method: 'POST',
  6472. headers: { 'Content-Type': 'application/json' },
  6473. body: JSON.stringify(payload)
  6474. });
  6475. if (res.ok) {
  6476. showToast('Route Saved', `Route to ${dst} installed`, 'success');
  6477. closeRouteModal();
  6478. loadRoutes();
  6479. } else {
  6480. const err = await res.json();
  6481. showToast('Error', err.message || 'Failed to save route', 'error');
  6482. }
  6483. } catch (err) {
  6484. showToast('Error', err.message, 'error');
  6485. }
  6486. }
  6487. async function toggleRouteState(id, disabled) {
  6488. try {
  6489. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}/state`, {
  6490. method: 'POST',
  6491. headers: { 'Content-Type': 'application/json' },
  6492. body: JSON.stringify({ disabled })
  6493. });
  6494. if (res.ok) loadRoutes();
  6495. } catch (err) {
  6496. showToast('Error', err.message, 'error');
  6497. }
  6498. }
  6499. async function deleteRoute(id) {
  6500. if (!confirm('Are you sure you want to delete this route?')) return;
  6501. try {
  6502. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6503. if (res.ok) {
  6504. showToast('Deleted', 'Route removed', 'success');
  6505. loadRoutes();
  6506. }
  6507. } catch (err) {
  6508. showToast('Error', err.message, 'error');
  6509. }
  6510. }
  6511. // ----------------- Policy Rules (/ip route rule) -----------------
  6512. function renderPolicyRules() {
  6513. const tbody = document.getElementById('rules-table-body');
  6514. const empty = document.getElementById('rules-empty');
  6515. if (!tbody) return;
  6516. const showSystem = document.getElementById('prule-show-system')?.checked;
  6517. const filtered = (state.policyRules || []).filter(pr => showSystem || (!pr.is_default && !pr.is_system));
  6518. const countBadge = document.getElementById('rules-count-badge');
  6519. if (countBadge) countBadge.innerText = `${filtered.length} Rules`;
  6520. const bRules = document.getElementById('routes-badge-rules');
  6521. if (bRules) bRules.innerText = filtered.length;
  6522. if (filtered.length === 0) {
  6523. empty?.classList.remove('hidden');
  6524. tbody.innerHTML = '';
  6525. return;
  6526. }
  6527. empty?.classList.add('hidden');
  6528. const sig = `${showSystem}|` + filtered.map(pr => `${pr.id}:${pr.priority}:${pr.src_address}:${pr.dst_address}:${pr.table}:${pr.routing_mark}`).join(';');
  6529. if (tbody.dataset.sig === sig) return;
  6530. tbody.dataset.sig = sig;
  6531. tbody.innerHTML = '';
  6532. filtered.forEach(pr => {
  6533. const isSys = pr.is_default || pr.is_system;
  6534. const tr = document.createElement('tr');
  6535. tr.className = `hover:bg-slate-800/40 transition text-xs ${isSys ? 'opacity-70 bg-slate-950/20' : ''}`;
  6536. tr.innerHTML = `
  6537. <td class="py-2.5 px-3 font-mono text-cyan-400 font-bold">${pr.priority}</td>
  6538. <td class="py-2.5 px-3 font-mono text-white">${pr.src_address || '<span class="text-slate-600">all</span>'}</td>
  6539. <td class="py-2.5 px-3 font-mono text-white">${pr.dst_address || '<span class="text-slate-600">all</span>'}</td>
  6540. <td class="py-2.5 px-3 font-mono font-bold text-purple-300">${pr.routing_mark || '<span class="text-slate-600">-</span>'}</td>
  6541. <td class="py-2.5 px-3 font-mono font-bold text-amber-300">${pr.table}</td>
  6542. <td class="py-2.5 px-3 font-mono text-slate-300">${pr.action}</td>
  6543. <td class="py-2.5 px-3 text-right font-sans">
  6544. ${!pr.is_default ? `
  6545. <button onclick="deletePolicyRule('${pr.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  6546. ` : `<span class="text-slate-600 text-[10px]">Default</span>`}
  6547. </td>
  6548. `;
  6549. tbody.appendChild(tr);
  6550. });
  6551. }
  6552. function openAddPolicyRuleModal() {
  6553. const userRules = (state.policyRules || []).filter(pr => !pr.is_default && !pr.is_system);
  6554. document.getElementById('prule-modal-pref').value = userRules.length * 10 + 1000;
  6555. document.getElementById('prule-modal-mark').value = '';
  6556. document.getElementById('prule-modal-src').value = '';
  6557. document.getElementById('prule-modal-dst').value = '';
  6558. const sel = document.getElementById('prule-modal-table');
  6559. sel.innerHTML = '';
  6560. (state.routingTables || []).forEach(t => {
  6561. const opt = document.createElement('option');
  6562. opt.value = t.name;
  6563. opt.innerText = t.name;
  6564. sel.appendChild(opt);
  6565. });
  6566. document.getElementById('prule-modal').classList.remove('hidden');
  6567. }
  6568. function closePolicyRuleModal() {
  6569. document.getElementById('prule-modal').classList.add('hidden');
  6570. }
  6571. async function submitSavePolicyRule(e) {
  6572. e.preventDefault();
  6573. const pref = parseInt(document.getElementById('prule-modal-pref').value, 10) || 1000;
  6574. const mark = document.getElementById('prule-modal-mark').value.trim();
  6575. const src = document.getElementById('prule-modal-src').value.trim();
  6576. const dst = document.getElementById('prule-modal-dst').value.trim();
  6577. const table = document.getElementById('prule-modal-table').value;
  6578. const action = document.getElementById('prule-modal-action').value;
  6579. try {
  6580. const res = await fetch(`${API_BASE}/routing/rules`, {
  6581. method: 'POST',
  6582. headers: { 'Content-Type': 'application/json' },
  6583. body: JSON.stringify({ priority: pref, routing_mark: mark, src_address: src, dst_address: dst, table, action })
  6584. });
  6585. if (res.ok) {
  6586. showToast('Rule Added', `Policy rule installed for table ${table}`, 'success');
  6587. closePolicyRuleModal();
  6588. loadRoutes();
  6589. } else {
  6590. const err = await res.json();
  6591. showToast('Error', err.message, 'error');
  6592. }
  6593. } catch (err) {
  6594. showToast('Error', err.message, 'error');
  6595. }
  6596. }
  6597. async function deletePolicyRule(id) {
  6598. if (!confirm('Are you sure you want to remove this policy rule?')) return;
  6599. try {
  6600. const res = await fetch(`${API_BASE}/routing/rules/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6601. if (res.ok) {
  6602. showToast('Rule Removed', 'Policy rule deleted', 'success');
  6603. loadRoutes();
  6604. }
  6605. } catch (err) {
  6606. showToast('Error', err.message, 'error');
  6607. }
  6608. }
  6609. // ----------------- Routing Tables -----------------
  6610. function renderRoutingTables() {
  6611. const tbody = document.getElementById('tables-table-body');
  6612. if (!tbody) return;
  6613. const tables = state.routingTables || [];
  6614. const sig = tables.map(t => `${t.table_id}:${t.name}:${t.comment}`).join(';');
  6615. if (tbody.dataset.sig === sig) return;
  6616. tbody.dataset.sig = sig;
  6617. tbody.innerHTML = '';
  6618. (state.routingTables || []).forEach(t => {
  6619. const tr = document.createElement('tr');
  6620. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  6621. tr.innerHTML = `
  6622. <td class="py-2.5 px-3 text-cyan-400 font-bold">${t.table_id}</td>
  6623. <td class="py-2.5 px-3 font-bold text-white">${t.name}</td>
  6624. <td class="py-2.5 px-3 text-slate-400 italic">${t.comment || '-'}</td>
  6625. `;
  6626. tbody.appendChild(tr);
  6627. });
  6628. }
  6629. function openAddTableModal() {
  6630. document.getElementById('table-modal-name').value = '';
  6631. document.getElementById('table-modal-id').value = '';
  6632. document.getElementById('table-modal-comment').value = '';
  6633. document.getElementById('table-modal').classList.remove('hidden');
  6634. }
  6635. function closeTableModal() {
  6636. document.getElementById('table-modal').classList.add('hidden');
  6637. }
  6638. async function submitSaveTable(e) {
  6639. e.preventDefault();
  6640. const name = document.getElementById('table-modal-name').value.trim();
  6641. const id = parseInt(document.getElementById('table-modal-id').value, 10) || 0;
  6642. const comment = document.getElementById('table-modal-comment').value.trim();
  6643. try {
  6644. const res = await fetch(`${API_BASE}/routing/tables`, {
  6645. method: 'POST',
  6646. headers: { 'Content-Type': 'application/json' },
  6647. body: JSON.stringify({ name, table_id: id, comment })
  6648. });
  6649. if (res.ok) {
  6650. showToast('Table Created', `Routing table ${name} registered`, 'success');
  6651. closeTableModal();
  6652. loadRoutes();
  6653. } else {
  6654. const err = await res.json();
  6655. showToast('Error', err.message, 'error');
  6656. }
  6657. } catch (err) {
  6658. showToast('Error', err.message, 'error');
  6659. }
  6660. }
  6661. async function loadDebianConfig() {
  6662. const view = document.getElementById('debian-config-view');
  6663. view.innerText = 'Generating live configuration...';
  6664. try {
  6665. const res = await fetch(`${API_BASE}/debian/config`);
  6666. const data = await res.json();
  6667. view.innerText = data.content || '# Empty config';
  6668. } catch (err) {
  6669. view.innerText = 'Failed to generate Debian network config.';
  6670. }
  6671. }
  6672. async function saveDebianConfig() {
  6673. try {
  6674. const res = await fetch(`${API_BASE}/debian/apply`, { method: 'POST' });
  6675. const data = await res.json();
  6676. if (res.ok) {
  6677. showToast('Configuration Saved', data.message || 'Saved to /etc/network/interfaces.d/vlans.cfg', 'success');
  6678. loadDebianConfig();
  6679. }
  6680. } catch (err) {
  6681. showToast('Error', err.message, 'error');
  6682. }
  6683. }
  6684. function showToast(title, message, type = 'info') {
  6685. const container = document.getElementById('toast-container');
  6686. const toast = document.createElement('div');
  6687. const borderColors = {
  6688. success: 'border-emerald-500/40 bg-slate-900/95 text-emerald-400',
  6689. error: 'border-rose-500/40 bg-slate-900/95 text-rose-400',
  6690. info: 'border-cyan-500/40 bg-slate-900/95 text-cyan-400'
  6691. };
  6692. 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}`;
  6693. toast.innerHTML = `
  6694. <div class="flex-1">
  6695. <div class="font-bold text-xs text-white">${escapeHtml(title)}</div>
  6696. <div class="text-[11px] text-slate-300 mt-0.5 leading-relaxed font-sans">${escapeHtml(message)}</div>
  6697. </div>
  6698. `;
  6699. container.appendChild(toast);
  6700. requestAnimationFrame(() => toast.classList.remove('translate-y-2', 'opacity-0'));
  6701. setTimeout(() => {
  6702. toast.classList.add('opacity-0', 'translate-y-2');
  6703. setTimeout(() => toast.remove(), 300);
  6704. }, 4000);
  6705. }
  6706. function formatTraffic(bytesPerSec) {
  6707. if (bytesPerSec < 1024) return `${Math.round(bytesPerSec)} B/s`;
  6708. const kb = bytesPerSec / 1024;
  6709. if (kb < 1024) return `${kb.toFixed(1)} KB/s`;
  6710. const mb = kb / 1024;
  6711. return `${mb.toFixed(2)} MB/s`;
  6712. }
  6713. function toggleSidebar() {
  6714. const sb = document.getElementById('sidebar');
  6715. sb.classList.toggle('-translate-x-full');
  6716. }
  6717. // ======================== EoIP (Ethernet over IP) ========================
  6718. async function loadEoIP(populate = true) {
  6719. try {
  6720. const res = await fetch(`${API_BASE}/vpn/eoip`);
  6721. const data = await res.json();
  6722. state.eoipTunnels = Array.isArray(data) ? data : [];
  6723. const badge = document.getElementById('eoip-count-badge');
  6724. if (badge) badge.innerText = `${state.eoipTunnels.length} Tunnels`;
  6725. const sideBadge = document.getElementById('badge-eoip-count');
  6726. if (sideBadge) sideBadge.innerText = state.eoipTunnels.length;
  6727. renderEoIPTunnels();
  6728. } catch (err) {
  6729. console.error('Failed to load EoIP:', err);
  6730. }
  6731. }
  6732. function renderEoIPTunnels() {
  6733. const tbody = document.getElementById('eoip-table-body');
  6734. const empty = document.getElementById('eoip-empty');
  6735. if (!tbody) return;
  6736. tbody.innerHTML = '';
  6737. const tunnels = state.eoipTunnels || [];
  6738. if (tunnels.length === 0) {
  6739. empty?.classList.remove('hidden');
  6740. return;
  6741. }
  6742. empty?.classList.add('hidden');
  6743. tunnels.forEach(t => {
  6744. const tr = document.createElement('tr');
  6745. tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
  6746. tr.innerHTML = `
  6747. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.running, t.disabled)}</td>
  6748. <td class="py-2.5 px-3 font-bold text-white font-mono">${t.name}</td>
  6749. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${t.tunnel_id}</td>
  6750. <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>
  6751. <td class="py-2.5 px-3 text-cyan-300 font-mono">${t.remote_address}</td>
  6752. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.local_address || '(any)'}</td>
  6753. <td class="py-2.5 px-3 text-slate-300 font-mono text-[11px]">${t.mac_address || '-'}</td>
  6754. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.mtu || 1500}</td>
  6755. <td class="py-2.5 px-3 font-mono text-[11px]">
  6756. <span class="text-emerald-400">↓ ${t.rx_human || '0 B'}</span>
  6757. <span class="text-cyan-400 ml-1">↑ ${t.tx_human || '0 B'}</span>
  6758. </td>
  6759. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${t.comment || ''}">${t.comment || '-'}</td>
  6760. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  6761. <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>
  6762. <button onclick="openEditEoIPModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  6763. <button onclick="deleteEoIP('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  6764. </td>
  6765. `;
  6766. tbody.appendChild(tr);
  6767. });
  6768. }
  6769. function openAddEoIPModal() {
  6770. document.getElementById('eoip-modal-title').innerText = 'Add EoIP Tunnel';
  6771. document.getElementById('eoip-modal-id').value = '';
  6772. document.getElementById('eoip-modal-name').value = `eoip-tunnel${(state.eoipTunnels || []).length + 1}`;
  6773. document.getElementById('eoip-modal-tunnelid').value = (state.eoipTunnels || []).length + 10;
  6774. document.getElementById('eoip-modal-remote').value = '';
  6775. document.getElementById('eoip-modal-ip').value = '';
  6776. document.getElementById('eoip-modal-local').value = '';
  6777. document.getElementById('eoip-modal-mac').value = '';
  6778. document.getElementById('eoip-modal-mtu').value = '1500';
  6779. document.getElementById('eoip-modal-comment').value = '';
  6780. document.getElementById('eoip-modal-clampmss').checked = true;
  6781. document.getElementById('eoip-modal-disabled').checked = false;
  6782. document.getElementById('eoip-modal').classList.remove('hidden');
  6783. }
  6784. function openEditEoIPModal(id) {
  6785. const t = (state.eoipTunnels || []).find(tun => tun.id === id);
  6786. if (!t) return;
  6787. document.getElementById('eoip-modal-title').innerText = `Edit EoIP Tunnel (${t.name})`;
  6788. document.getElementById('eoip-modal-id').value = t.id;
  6789. document.getElementById('eoip-modal-name').value = t.name;
  6790. document.getElementById('eoip-modal-tunnelid').value = t.tunnel_id;
  6791. document.getElementById('eoip-modal-remote').value = t.remote_address;
  6792. document.getElementById('eoip-modal-ip').value = t.ip_address || '';
  6793. document.getElementById('eoip-modal-local').value = t.local_address || '';
  6794. document.getElementById('eoip-modal-mac').value = t.mac_address || '';
  6795. document.getElementById('eoip-modal-mtu').value = t.mtu || 1500;
  6796. document.getElementById('eoip-modal-comment').value = t.comment || '';
  6797. document.getElementById('eoip-modal-clampmss').checked = !!t.clamp_mss;
  6798. document.getElementById('eoip-modal-disabled').checked = !!t.disabled;
  6799. document.getElementById('eoip-modal').classList.remove('hidden');
  6800. }
  6801. function closeEoIPModal() {
  6802. document.getElementById('eoip-modal').classList.add('hidden');
  6803. }
  6804. async function submitSaveEoIP(e) {
  6805. e.preventDefault();
  6806. const id = document.getElementById('eoip-modal-id').value;
  6807. const name = document.getElementById('eoip-modal-name').value.trim();
  6808. const tunnelId = parseInt(document.getElementById('eoip-modal-tunnelid').value);
  6809. const remote = document.getElementById('eoip-modal-remote').value.trim();
  6810. const ipAddress = document.getElementById('eoip-modal-ip').value.trim();
  6811. const local = document.getElementById('eoip-modal-local').value.trim();
  6812. const mac = document.getElementById('eoip-modal-mac').value.trim();
  6813. const mtu = parseInt(document.getElementById('eoip-modal-mtu').value) || 1500;
  6814. const comment = document.getElementById('eoip-modal-comment').value.trim();
  6815. const clampMss = document.getElementById('eoip-modal-clampmss').checked;
  6816. const disabled = document.getElementById('eoip-modal-disabled').checked;
  6817. try {
  6818. const res = await fetch(`${API_BASE}/vpn/eoip`, {
  6819. method: 'POST',
  6820. headers: { 'Content-Type': 'application/json' },
  6821. body: JSON.stringify({
  6822. id,
  6823. name,
  6824. tunnel_id: tunnelId,
  6825. remote_address: remote,
  6826. ip_address: ipAddress,
  6827. local_address: local,
  6828. mac_address: mac,
  6829. mtu,
  6830. clamp_mss: clampMss,
  6831. comment,
  6832. disabled
  6833. })
  6834. });
  6835. if (res.ok) {
  6836. showToast('EoIP Saved', `Tunnel ${name} configured successfully`, 'success');
  6837. closeEoIPModal();
  6838. loadEoIP(false);
  6839. fetchData(false);
  6840. } else {
  6841. const err = await res.json();
  6842. showToast('Error', err.message, 'error');
  6843. }
  6844. } catch (err) {
  6845. showToast('Error', err.message, 'error');
  6846. }
  6847. }
  6848. async function toggleEoIPState(id, disabled) {
  6849. try {
  6850. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}/state`, {
  6851. method: 'POST',
  6852. headers: { 'Content-Type': 'application/json' },
  6853. body: JSON.stringify({ disabled })
  6854. });
  6855. if (res.ok) {
  6856. showToast(disabled ? 'Disabled' : 'Enabled', 'EoIP tunnel state updated', 'info');
  6857. loadEoIP(false);
  6858. fetchData(false);
  6859. }
  6860. } catch (err) {
  6861. showToast('Error', err.message, 'error');
  6862. }
  6863. }
  6864. async function deleteEoIP(id) {
  6865. if (!confirm('Are you sure you want to delete this EoIP tunnel?')) return;
  6866. try {
  6867. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6868. if (res.ok) {
  6869. showToast('Deleted', 'EoIP tunnel removed', 'success');
  6870. loadEoIP(false);
  6871. fetchData(false);
  6872. }
  6873. } catch (err) {
  6874. showToast('Error', err.message, 'error');
  6875. }
  6876. }
  6877. // ======================== AeroTUN (Custom Encrypted VPN with Adaptive LZ4) ========================
  6878. async function loadAeroTUN(populate = true) {
  6879. try {
  6880. const [tunnelsRes, statsRes] = await Promise.all([
  6881. fetch(`${API_BASE}/vpn/aerotun/tunnels`),
  6882. fetch(`${API_BASE}/vpn/aerotun/stats`)
  6883. ]);
  6884. if (tunnelsRes.ok) {
  6885. const data = await tunnelsRes.json();
  6886. state.aerotunTunnels = Array.isArray(data) ? data : [];
  6887. }
  6888. if (statsRes.ok) {
  6889. state.aerotunStats = await statsRes.json();
  6890. }
  6891. const countBadge = document.getElementById('aerotun-count-badge');
  6892. if (countBadge) countBadge.innerText = `${(state.aerotunTunnels || []).length} Tunnels`;
  6893. const sideBadge = document.getElementById('badge-aerotun-count');
  6894. if (sideBadge) sideBadge.innerText = (state.aerotunTunnels || []).length;
  6895. renderAeroTUN();
  6896. } catch (err) {
  6897. console.error('Failed to load AeroTUN:', err);
  6898. }
  6899. }
  6900. function renderAeroTUN() {
  6901. const tbody = document.getElementById('aerotun-table-body');
  6902. const empty = document.getElementById('aerotun-empty');
  6903. // Update summary cards
  6904. const stats = state.aerotunStats || {};
  6905. const tunnels = state.aerotunTunnels || [];
  6906. const statActive = document.getElementById('aerotun-stat-active');
  6907. if (statActive) {
  6908. const activeCount = tunnels.filter(t => t.connected).length;
  6909. statActive.innerText = `${activeCount} / ${tunnels.length}`;
  6910. }
  6911. const statSaved = document.getElementById('aerotun-stat-saved');
  6912. if (statSaved) {
  6913. statSaved.innerText = formatBytes(stats.total_saved_bytes || 0);
  6914. }
  6915. const statRatio = document.getElementById('aerotun-stat-ratio');
  6916. if (statRatio) {
  6917. statRatio.innerText = stats.average_ratio || '1.00x (0% saved)';
  6918. }
  6919. const statTraffic = document.getElementById('aerotun-stat-traffic');
  6920. if (statTraffic) {
  6921. statTraffic.innerText = `↓ ${formatBytes(stats.total_rx_bytes || 0)} / ↑ ${formatBytes(stats.total_tx_bytes || 0)}`;
  6922. }
  6923. if (!tbody) return;
  6924. tbody.innerHTML = '';
  6925. if (tunnels.length === 0) {
  6926. empty?.classList.remove('hidden');
  6927. return;
  6928. }
  6929. empty?.classList.add('hidden');
  6930. tunnels.forEach(t => {
  6931. const tr = document.createElement('tr');
  6932. tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
  6933. const modeBadge = t.mode === 'server'
  6934. ? `<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>`
  6935. : `<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>`;
  6936. const endpointInfo = t.mode === 'server'
  6937. ? `<span class="text-sky-300 font-mono">Port :${t.listen_port || 51830}</span>`
  6938. : `<span class="text-indigo-300 font-mono">${escapeHtml(t.remote_endpoint || '(not set)')}</span>`;
  6939. const compBadge = t.compression
  6940. ? `<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>`
  6941. : `<span class="text-slate-500 text-[10px]">Off</span>`;
  6942. const activePeer = t.connected && t.active_peer_endpoint
  6943. ? `<span class="text-emerald-400 font-mono text-[11px]" title="Last authenticated packet: ${escapeHtml(t.last_handshake || 'just now')}; dropped: ${t.dropped_packets || 0}; auth failures: ${t.auth_failures || 0}; replay drops: ${t.replay_drops || 0}${t.last_error ? '; last error: ' + escapeHtml(t.last_error) : ''}">● ${escapeHtml(t.active_peer_endpoint)}</span>`
  6944. : `<span class="text-slate-500 text-[11px]">${t.last_error ? 'Failed: ' + escapeHtml(t.last_error) : (!t.running ? (t.disabled ? 'Saved / disabled' : 'Stopped') : (t.mode === 'server' ? 'Waiting for peer...' : 'Connecting...'))}</span>`;
  6945. const rawRx = formatBytes(t.rx_bytes || 0);
  6946. const rawTx = formatBytes(t.tx_bytes || 0);
  6947. const wireRx = formatBytes(t.wire_bytes_in || 0);
  6948. const wireTx = formatBytes(t.wire_bytes_out || 0);
  6949. tr.innerHTML = `
  6950. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.connected, t.disabled)}</td>
  6951. <td class="py-2.5 px-3 font-bold text-white font-mono flex items-center gap-1.5">
  6952. <span>${escapeHtml(t.name)}</span>
  6953. ${t.default_route ? '<span class="text-[9px] px-1 rounded bg-amber-500/20 text-amber-300 border border-amber-500/30">DEF</span>' : ''}
  6954. <span class="text-slate-400 text-[10px]">v${t.protocol_version || 2}</span>
  6955. </td>
  6956. <td class="py-2.5 px-3">${modeBadge}</td>
  6957. <td class="py-2.5 px-3 text-xs font-mono">${endpointInfo}</td>
  6958. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${escapeHtml(t.local_address || '-')}</td>
  6959. <td class="py-2.5 px-3">${compBadge}</td>
  6960. <td class="py-2.5 px-3">${activePeer}</td>
  6961. <td class="py-2.5 px-3 font-mono text-[11px]">
  6962. <span class="text-emerald-400">↓ ${rawRx}</span>
  6963. <span class="text-cyan-400 ml-1">↑ ${rawTx}</span>
  6964. </td>
  6965. <td class="py-2.5 px-3 font-mono text-[11px]">
  6966. <span class="text-slate-400">↓ ${wireRx}</span>
  6967. <span class="text-slate-400 ml-1">↑ ${wireTx}</span>
  6968. </td>
  6969. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(t.comment || '')}">${escapeHtml(t.comment || '-')}</td>
  6970. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  6971. ${t.running
  6972. ? `<button onclick="stopAeroTUNTunnel('${t.id}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Stop</button>`
  6973. : `<button onclick="startAeroTUNTunnel('${t.id}')" class="text-xs text-emerald-400 hover:text-emerald-300 font-medium">Start</button>`
  6974. }
  6975. <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>
  6976. <button onclick="openEditAeroTUNModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  6977. <button onclick="deleteAeroTUN('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  6978. </td>
  6979. `;
  6980. tbody.appendChild(tr);
  6981. });
  6982. }
  6983. let aeroModalGeneration = 0;
  6984. let aeroIdentityDraft = '';
  6985. let aeroSaving = false;
  6986. let aeroPSKRequest = 0;
  6987. function discardAeroIdentityDraft(id) {
  6988. if (id) fetch(`${API_BASE}/vpn/aerotun/identity-drafts/${encodeURIComponent(id)}`, {method:'DELETE'}).catch(() => {});
  6989. }
  6990. async function generateAeroTUNIdentity() {
  6991. const generation = aeroModalGeneration;
  6992. const retry = document.getElementById('aerotun-retry-identity');
  6993. if (aeroIdentityDraft) { discardAeroIdentityDraft(aeroIdentityDraft); aeroIdentityDraft = ''; }
  6994. retry.classList.add('hidden');
  6995. document.getElementById('aerotun-modal-public').value = '';
  6996. try {
  6997. const res = await fetch(`${API_BASE}/vpn/aerotun/identity-drafts`, {method:'POST'});
  6998. if (!res.ok) throw new Error(await responseError(res));
  6999. const draft = await res.json();
  7000. if (generation !== aeroModalGeneration) { discardAeroIdentityDraft(draft.draft_id); return; }
  7001. aeroIdentityDraft = draft.draft_id;
  7002. document.getElementById('aerotun-modal-public').value = draft.public_key;
  7003. updateAeroTUNSetupHint();
  7004. } catch (err) {
  7005. if (generation !== aeroModalGeneration) return;
  7006. retry.classList.remove('hidden');
  7007. updateAeroTUNSetupHint();
  7008. showToast('Identity Generation Failed', err.message, 'error');
  7009. }
  7010. }
  7011. function onAeroTUNModeChange() {
  7012. const mode = document.getElementById('aerotun-modal-mode').value;
  7013. const endpointInput = document.getElementById('aerotun-modal-endpoint');
  7014. const portInput = document.getElementById('aerotun-modal-port');
  7015. if (mode === 'server') {
  7016. if (!portInput.value) portInput.value = '51830';
  7017. endpointInput.placeholder = 'Optional / learned roaming peer';
  7018. } else {
  7019. endpointInput.placeholder = 'vpn.example.com:51830 (required)';
  7020. if (!portInput.value) portInput.value = '';
  7021. }
  7022. }
  7023. function onAeroTUNPeerChange() {
  7024. const peer = document.getElementById('aerotun-modal-peer');
  7025. const allowed = document.getElementById('aerotun-modal-allowed');
  7026. const previous = peer.dataset.allowedDefault || '';
  7027. const host = peer.value.trim().split('/')[0];
  7028. const next = host ? `${host}/${host.includes(':') ? 128 : 32}` : '';
  7029. if (allowed.value.trim() === previous) allowed.value = next;
  7030. peer.dataset.allowedDefault = next;
  7031. }
  7032. async function generateAeroTUNKey(automatic = false) {
  7033. const generation = aeroModalGeneration, request = ++aeroPSKRequest;
  7034. const input = document.getElementById('aerotun-modal-psk'), previous = input.value;
  7035. try {
  7036. const res = await fetch(`${API_BASE}/vpn/aerotun/genkey`);
  7037. if (!res.ok) throw new Error(await responseError(res));
  7038. const data = await res.json();
  7039. if (generation !== aeroModalGeneration || request !== aeroPSKRequest || (automatic && input.value !== previous)) return;
  7040. input.value = data.key;
  7041. if (!automatic) showToast('Key Generated', 'Share this PSK securely with the peer before enabling', 'success');
  7042. } catch (err) {
  7043. if (generation === aeroModalGeneration && request === aeroPSKRequest) showToast('Key Generation Failed', err.message, 'error');
  7044. }
  7045. }
  7046. function updateAeroTUNSetupHint() {
  7047. const version = document.getElementById('aerotun-modal-protocol').value;
  7048. const key = document.getElementById('aerotun-modal-public').value;
  7049. const peer = document.getElementById('aerotun-modal-peerkey').value.trim();
  7050. const hint = document.getElementById('aerotun-setup-hint');
  7051. document.getElementById('aerotun-v3-fields').classList.toggle('hidden', version !== '3');
  7052. if (!hint) return;
  7053. hint.innerText = version !== '3' ? 'Legacy v2 uses a shared PSK. Both endpoints must use the same protocol.' : !key ? (document.getElementById('aerotun-modal-id').value ? 'Save this existing tunnel disabled to create its v3 identity, then exchange public keys.' : 'Generating the local identity. You can fill in the other settings while you wait.') : !peer ? 'Copy the local public key to the peer and paste its public key here. Use the same PSK on both endpoints; save disabled if the peer key is not ready.' : 'Check reciprocal addresses, allowed peer source prefixes and the shared PSK before enabling. Allowed prefixes do not create LAN routes.';
  7054. }
  7055. async function copyAeroTUNPublicKey() {
  7056. const input = document.getElementById('aerotun-modal-public');
  7057. if (!input.value) { showToast('Key Not Ready', 'Wait for the local identity or retry key generation.', 'info'); return; }
  7058. try {
  7059. await navigator.clipboard.writeText(input.value);
  7060. showToast('Public Key Copied', 'Paste it into the other endpoint’s pinned peer key', 'success');
  7061. } catch {
  7062. input.focus(); input.select();
  7063. showToast('Copy Public Key', 'Key selected; press Ctrl+C to copy', 'info');
  7064. }
  7065. }
  7066. async function copyAeroTUNPSK() {
  7067. const input = document.getElementById('aerotun-modal-psk');
  7068. if (!input.value) { showToast('PSK Not Available', 'Generate or enter a PSK to copy it. Existing keys are not displayed.', 'info'); return; }
  7069. try { await navigator.clipboard.writeText(input.value); showToast('PSK Copied', 'Share it securely with the peer.', 'success'); }
  7070. catch { input.type = 'text'; input.focus(); input.select(); showToast('Copy PSK', 'Key selected; press Ctrl+C to copy.', 'info'); }
  7071. }
  7072. function openAddAeroTUNModal() {
  7073. if (aeroSaving) return;
  7074. aeroModalGeneration++; discardAeroIdentityDraft(aeroIdentityDraft); aeroIdentityDraft = '';
  7075. const tunnels = state.aerotunTunnels || [];
  7076. const usedNames = new Set(tunnels.map(t => t.name));
  7077. const usedPorts = new Set(tunnels.map(t => Number(t.listen_port)));
  7078. let index = 0; while (index < 256 && (usedNames.has(`aerotun${index}`) || usedPorts.has(51830 + index) || tunnels.some(t => (t.local_address || '').startsWith(`10.99.${index}.`)))) index++;
  7079. if (index >= 256) index = 0;
  7080. document.getElementById('aerotun-modal-title').innerText = 'Add AeroTUN Interface';
  7081. document.getElementById('aerotun-modal-id').value = '';
  7082. document.getElementById('aerotun-modal-protocol').value='3';
  7083. document.getElementById('aerotun-modal-public').value='';
  7084. document.getElementById('aerotun-modal-peerkey').value='';
  7085. document.getElementById('aerotun-modal-allowed').value=`10.99.${index}.2/32`;
  7086. document.getElementById('aerotun-modal-name').value = `aerotun${index}`;
  7087. document.getElementById('aerotun-modal-mode').value = 'server';
  7088. document.getElementById('aerotun-modal-port').value = 51830 + index;
  7089. document.getElementById('aerotun-modal-endpoint').value = '';
  7090. document.getElementById('aerotun-modal-local').value = `10.99.${index}.1/24`;
  7091. document.getElementById('aerotun-modal-peer').value = `10.99.${index}.2/24`;
  7092. document.getElementById('aerotun-modal-peer').dataset.allowedDefault = `10.99.${index}.2/32`;
  7093. document.getElementById('aerotun-modal-psk').value = '';
  7094. document.getElementById('aerotun-modal-mtu').value = '1420';
  7095. document.getElementById('aerotun-modal-comment').value = '';
  7096. document.getElementById('aerotun-modal-compression').checked = false;
  7097. document.getElementById('aerotun-modal-defroute').checked = false;
  7098. document.getElementById('aerotun-modal-disabled').checked = true;
  7099. document.getElementById('aerotun-modal-psk').type = 'password';
  7100. document.getElementById('aerotun-modal-psk').placeholder = 'Generate or enter the shared key';
  7101. onAeroTUNModeChange();
  7102. updateAeroTUNSetupHint();
  7103. document.getElementById('aerotun-modal').classList.remove('hidden');
  7104. generateAeroTUNKey(true);
  7105. generateAeroTUNIdentity();
  7106. }
  7107. function openEditAeroTUNModal(id) {
  7108. if (aeroSaving) return;
  7109. const t = (state.aerotunTunnels || []).find(tun => tun.id === id);
  7110. if (!t) return;
  7111. aeroModalGeneration++; discardAeroIdentityDraft(aeroIdentityDraft); aeroIdentityDraft = '';
  7112. document.getElementById('aerotun-retry-identity').classList.add('hidden');
  7113. document.getElementById('aerotun-modal-title').innerText = `Edit AeroTUN Interface (${t.name})`;
  7114. document.getElementById('aerotun-modal-id').value = t.id;
  7115. document.getElementById('aerotun-modal-protocol').value=String(t.protocol_version || 2);
  7116. document.getElementById('aerotun-modal-public').value=t.public_key || '';
  7117. document.getElementById('aerotun-modal-peerkey').value=t.peer_public_key || '';
  7118. document.getElementById('aerotun-modal-allowed').value=(t.allowed_ips || []).join(', ');
  7119. document.getElementById('aerotun-modal-name').value = t.name;
  7120. document.getElementById('aerotun-modal-mode').value = t.mode || 'server';
  7121. document.getElementById('aerotun-modal-port').value = t.listen_port || '';
  7122. document.getElementById('aerotun-modal-endpoint').value = t.remote_endpoint || '';
  7123. document.getElementById('aerotun-modal-local').value = t.local_address || '';
  7124. document.getElementById('aerotun-modal-peer').value = t.peer_address || '';
  7125. const peerHost = (t.peer_address || '').split('/')[0];
  7126. document.getElementById('aerotun-modal-peer').dataset.allowedDefault = peerHost ? `${peerHost}/${peerHost.includes(':') ? 128 : 32}` : '';
  7127. document.getElementById('aerotun-modal-psk').value = '';
  7128. document.getElementById('aerotun-modal-psk').type = 'password';
  7129. document.getElementById('aerotun-modal-psk').placeholder = t.has_psk ? 'Leave blank to keep the existing key' : 'New random 256-bit PSK';
  7130. document.getElementById('aerotun-modal-mtu').value = t.mtu || 1420;
  7131. document.getElementById('aerotun-modal-comment').value = t.comment || '';
  7132. document.getElementById('aerotun-modal-compression').checked = !!t.compression;
  7133. document.getElementById('aerotun-modal-defroute').checked = !!t.default_route;
  7134. document.getElementById('aerotun-modal-disabled').checked = !!t.disabled;
  7135. onAeroTUNModeChange();
  7136. updateAeroTUNSetupHint();
  7137. document.getElementById('aerotun-modal').classList.remove('hidden');
  7138. }
  7139. function closeAeroTUNModal() {
  7140. if (aeroSaving) return;
  7141. aeroModalGeneration++; discardAeroIdentityDraft(aeroIdentityDraft); aeroIdentityDraft = '';
  7142. document.getElementById('aerotun-modal-psk').value = '';
  7143. document.getElementById('aerotun-modal').classList.add('hidden');
  7144. }
  7145. async function submitSaveAeroTUN(e) {
  7146. e.preventDefault();
  7147. if (aeroSaving) return;
  7148. const id = document.getElementById('aerotun-modal-id').value;
  7149. const name = document.getElementById('aerotun-modal-name').value.trim();
  7150. const mode = document.getElementById('aerotun-modal-mode').value;
  7151. const port = parseInt(document.getElementById('aerotun-modal-port').value) || 0;
  7152. const endpoint = document.getElementById('aerotun-modal-endpoint').value.trim();
  7153. const local = document.getElementById('aerotun-modal-local').value.trim();
  7154. const peer = document.getElementById('aerotun-modal-peer').value.trim();
  7155. const psk = document.getElementById('aerotun-modal-psk').value.trim();
  7156. const mtuValue = document.getElementById('aerotun-modal-mtu').value;
  7157. const mtu = mtuValue === '' ? 1420 : Number(mtuValue);
  7158. const comment = document.getElementById('aerotun-modal-comment').value.trim();
  7159. const compression = document.getElementById('aerotun-modal-compression').checked;
  7160. const defaultRoute = document.getElementById('aerotun-modal-defroute').checked;
  7161. const disabled = document.getElementById('aerotun-modal-disabled').checked;
  7162. if (mode === 'client' && !endpoint) {
  7163. showToast('Validation Error', 'Remote endpoint (host:port) is required in client mode', 'error');
  7164. return;
  7165. }
  7166. if (defaultRoute && (mode !== 'client' || !endpoint)) {
  7167. showToast('Validation Error', 'Default route requires client mode and a fixed remote endpoint.', 'error');
  7168. return;
  7169. }
  7170. if (!Number.isInteger(mtu) || mtu < 576 || mtu > 9000) {
  7171. showToast('Validation Error', 'MTU must be between 576 and 9000.', 'error');
  7172. return;
  7173. }
  7174. const version = parseInt(document.getElementById('aerotun-modal-protocol').value, 10);
  7175. if (version === 3 && !id && !aeroIdentityDraft) {
  7176. showToast('Local Key Not Ready', 'Wait for the local identity or retry key generation before saving.', 'error');
  7177. return;
  7178. }
  7179. if (version === 3 && !document.getElementById('aerotun-modal-allowed').value.trim()) {
  7180. showToast('Allowed Prefix Required', 'Enter at least one allowed peer source prefix, such as the peer tunnel IP /32.', 'error');
  7181. document.getElementById('aerotun-modal-allowed').focus();
  7182. return;
  7183. }
  7184. if (version === 3 && !disabled && !document.getElementById('aerotun-modal-peerkey').value.trim()) {
  7185. showToast('Peer Key Required', 'Enter the peer public key, or save this tunnel disabled until it is available.', 'error');
  7186. return;
  7187. }
  7188. if (!psk && !id) {
  7189. showToast('Validation Error', 'Pre-shared key (PSK) is required', 'error');
  7190. return;
  7191. }
  7192. aeroSaving = true;
  7193. const submit = document.querySelector('#aerotun-modal button[type="submit"]');
  7194. if (submit) submit.disabled = true;
  7195. try {
  7196. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels`, {
  7197. method: 'POST',
  7198. headers: { 'Content-Type': 'application/json' },
  7199. body: JSON.stringify({
  7200. protocol_version:parseInt(document.getElementById('aerotun-modal-protocol').value,10),
  7201. identity_draft_id: version === 3 && !id ? aeroIdentityDraft : '',
  7202. peer_public_key:document.getElementById('aerotun-modal-peerkey').value.trim(),
  7203. allowed_ips:document.getElementById('aerotun-modal-allowed').value.split(',').map(s=>s.trim()).filter(Boolean),
  7204. id,
  7205. name,
  7206. mode,
  7207. listen_port: port,
  7208. remote_endpoint: endpoint,
  7209. local_address: local,
  7210. peer_address: peer,
  7211. psk,
  7212. mtu,
  7213. compression,
  7214. default_route: defaultRoute,
  7215. comment,
  7216. disabled
  7217. })
  7218. });
  7219. if (res.ok) {
  7220. await res.json();
  7221. if (version !== 3) discardAeroIdentityDraft(aeroIdentityDraft);
  7222. aeroIdentityDraft = '';
  7223. aeroSaving = false;
  7224. closeAeroTUNModal();
  7225. await loadAeroTUN(false);
  7226. showToast('AeroTUN Saved', disabled ? 'Configuration saved; tunnel is disabled' : 'Configuration saved; waiting for authenticated peer traffic', 'success');
  7227. fetchData(false);
  7228. } else {
  7229. const err = await responseError(res);
  7230. if (err.includes('configuration saved but tunnel failed to start')) {
  7231. aeroIdentityDraft = '';
  7232. aeroSaving = false;
  7233. closeAeroTUNModal();
  7234. await loadAeroTUN(false);
  7235. showToast('Saved, but not started', err, 'error');
  7236. } else showToast('Error Saving Tunnel', err, 'error');
  7237. }
  7238. } catch (err) {
  7239. showToast('Network Error', err.message, 'error');
  7240. } finally {
  7241. aeroSaving = false;
  7242. if (submit) submit.disabled = false;
  7243. }
  7244. }
  7245. async function startAeroTUNTunnel(id) {
  7246. try {
  7247. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/start`, { method: 'POST' });
  7248. if (res.ok) {
  7249. showToast('AeroTUN Started', 'Interface started; connection is confirmed by authenticated peer traffic', 'info');
  7250. loadAeroTUN(false);
  7251. fetchData(false);
  7252. } else {
  7253. const err = await res.text();
  7254. showToast('Failed to Start', err, 'error');
  7255. }
  7256. } catch (err) {
  7257. showToast('Error', err.message, 'error');
  7258. }
  7259. }
  7260. async function stopAeroTUNTunnel(id) {
  7261. try {
  7262. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/stop`, { method: 'POST' });
  7263. if (res.ok) {
  7264. showToast('AeroTUN Stopped', 'Tunnel stopped', 'info');
  7265. loadAeroTUN(false);
  7266. fetchData(false);
  7267. } else {
  7268. const err = await res.text();
  7269. showToast('Failed to Stop', err, 'error');
  7270. }
  7271. } catch (err) {
  7272. showToast('Error', err.message, 'error');
  7273. }
  7274. }
  7275. async function toggleAeroTUNState(id, disabled) {
  7276. try {
  7277. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/state`, {
  7278. method: 'POST',
  7279. headers: { 'Content-Type': 'application/json' },
  7280. body: JSON.stringify({ disabled })
  7281. });
  7282. if (res.ok) {
  7283. showToast('State Updated', disabled ? 'Tunnel disabled' : 'Tunnel enabled', 'info');
  7284. loadAeroTUN(false);
  7285. fetchData(false);
  7286. }
  7287. } catch (err) {
  7288. showToast('Error', err.message, 'error');
  7289. }
  7290. }
  7291. async function deleteAeroTUN(id) {
  7292. if (!confirm('Are you sure you want to delete this AeroTUN tunnel?')) return;
  7293. try {
  7294. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7295. if (res.ok) {
  7296. showToast('Deleted', 'AeroTUN tunnel removed', 'success');
  7297. loadAeroTUN(false);
  7298. fetchData(false);
  7299. }
  7300. } catch (err) {
  7301. showToast('Error', err.message, 'error');
  7302. }
  7303. }
  7304. // ======================== PPP Central Hub & Servers ========================
  7305. function switchPPPSubTab(tab) {
  7306. state.pppSubTab = tab;
  7307. const tabs = ['secrets', 'profiles', 'pppoe', 'pptp', 'l2tp', 'active'];
  7308. tabs.forEach(t => {
  7309. const panel = document.getElementById(`ppp-subtab-${t}`);
  7310. const btn = document.getElementById(`ppp-subtab-btn-${t}`);
  7311. if (panel) {
  7312. if (t === tab) panel.classList.remove('hidden');
  7313. else panel.classList.add('hidden');
  7314. }
  7315. if (btn) {
  7316. if (t === tab) {
  7317. 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';
  7318. } else {
  7319. 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';
  7320. }
  7321. }
  7322. });
  7323. const addBtn = document.getElementById('ppp-primary-add-btn');
  7324. if (addBtn) {
  7325. if (tab === 'secrets') addBtn.innerHTML = '<span>+ Add User (Secret)</span>';
  7326. else if (tab === 'profiles') addBtn.innerHTML = '<span>+ Add Profile</span>';
  7327. else if (tab === 'active') addBtn.innerHTML = '<span>Refresh Sessions</span>';
  7328. else addBtn.innerHTML = '<span>Save Config</span>';
  7329. }
  7330. if (tab === 'active') loadPPPSessions();
  7331. }
  7332. function openCurrentPPPModal() {
  7333. if (state.pppSubTab === 'secrets') openAddPPPSecretModal();
  7334. else if (state.pppSubTab === 'profiles') openAddPPPProfileModal();
  7335. else if (state.pppSubTab === 'active') loadPPPSessions();
  7336. else if (state.pppSubTab === 'pppoe') document.querySelector('#ppp-subtab-pppoe form')?.requestSubmit();
  7337. else if (state.pppSubTab === 'pptp') document.querySelector('#ppp-subtab-pptp form')?.requestSubmit();
  7338. else if (state.pppSubTab === 'l2tp') document.querySelector('#ppp-subtab-l2tp form')?.requestSubmit();
  7339. }
  7340. async function loadPPP(populateDropdowns = true) {
  7341. await Promise.all([
  7342. loadPPPSecrets(),
  7343. loadPPPProfiles(),
  7344. loadPPPServers(),
  7345. loadPPPSessions()
  7346. ]);
  7347. }
  7348. async function loadPPPSecrets() {
  7349. try {
  7350. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`);
  7351. const data = await res.json();
  7352. state.pppSecrets = Array.isArray(data) ? data : [];
  7353. const b = document.getElementById('ppp-badge-secrets');
  7354. if (b) b.innerText = state.pppSecrets.length;
  7355. const b2 = document.getElementById('secrets-count-badge');
  7356. if (b2) b2.innerText = `${state.pppSecrets.length} Users`;
  7357. renderPPPSecrets();
  7358. } catch (err) {
  7359. console.error('Failed to load PPP secrets:', err);
  7360. }
  7361. }
  7362. function renderPPPSecrets() {
  7363. const tbody = document.getElementById('secrets-table-body');
  7364. const empty = document.getElementById('secrets-empty');
  7365. if (!tbody) return;
  7366. tbody.innerHTML = '';
  7367. const secrets = state.pppSecrets || [];
  7368. if (secrets.length === 0) {
  7369. empty?.classList.remove('hidden');
  7370. return;
  7371. }
  7372. empty?.classList.add('hidden');
  7373. secrets.forEach(s => {
  7374. const tr = document.createElement('tr');
  7375. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  7376. tr.innerHTML = `
  7377. <td class="py-2.5 px-3 text-center">${renderRuleFlag(s.disabled, !!s.comment)}</td>
  7378. <td class="py-2.5 px-3 font-bold text-white font-mono">${s.name}</td>
  7379. <td class="py-2.5 px-3 text-purple-300 font-mono font-semibold">${s.service}</td>
  7380. <td class="py-2.5 px-3 text-amber-300 font-mono">${s.profile}</td>
  7381. <td class="py-2.5 px-3 text-slate-400 font-mono">${s.local_address || '(profile)'}</td>
  7382. <td class="py-2.5 px-3 text-cyan-400 font-mono font-bold">${s.remote_address || '(profile)'}</td>
  7383. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]">${s.comment || '-'}</td>
  7384. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  7385. <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>
  7386. <button onclick="openEditPPPSecretModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  7387. <button onclick="deletePPPSecret('${s.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  7388. </td>
  7389. `;
  7390. tbody.appendChild(tr);
  7391. });
  7392. }
  7393. async function loadPPPProfiles() {
  7394. try {
  7395. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`);
  7396. const data = await res.json();
  7397. state.pppProfiles = Array.isArray(data) ? data : [];
  7398. const b = document.getElementById('ppp-badge-profiles');
  7399. if (b) b.innerText = state.pppProfiles.length;
  7400. const b2 = document.getElementById('profiles-count-badge');
  7401. if (b2) b2.innerText = `${state.pppProfiles.length} Profiles`;
  7402. // Populate profile selects across modals
  7403. const selects = ['secret-modal-profile', 'pppoe-server-profile', 'pptp-server-profile', 'l2tp-server-profile'];
  7404. selects.forEach(sid => {
  7405. const el = document.getElementById(sid);
  7406. if (!el) return;
  7407. const cur = el.value;
  7408. el.innerHTML = '';
  7409. state.pppProfiles.forEach(p => {
  7410. const opt = document.createElement('option');
  7411. opt.value = p.name;
  7412. opt.innerText = `${p.name} (${p.remote_address})`;
  7413. if (p.name === cur) opt.selected = true;
  7414. el.appendChild(opt);
  7415. });
  7416. });
  7417. renderPPPProfiles();
  7418. } catch (err) {
  7419. console.error('Failed to load PPP profiles:', err);
  7420. }
  7421. }
  7422. function renderPPPProfiles() {
  7423. const tbody = document.getElementById('profiles-table-body');
  7424. if (!tbody) return;
  7425. tbody.innerHTML = '';
  7426. (state.pppProfiles || []).forEach(p => {
  7427. const isDefault = p.name.startsWith('default');
  7428. const tr = document.createElement('tr');
  7429. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  7430. tr.innerHTML = `
  7431. <td class="py-2.5 px-3 font-bold text-white">${p.name}</td>
  7432. <td class="py-2.5 px-3 text-slate-300">${p.local_address}</td>
  7433. <td class="py-2.5 px-3 text-cyan-400 font-bold">${p.remote_address}</td>
  7434. <td class="py-2.5 px-3 text-slate-400">${p.dns_servers || '-'}</td>
  7435. <td class="py-2.5 px-3 text-purple-300 font-semibold">${p.use_encryption}</td>
  7436. <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>
  7437. <td class="py-2.5 px-3 text-slate-400 italic">${p.comment || '-'}</td>
  7438. <td class="py-2.5 px-3 text-right font-sans whitespace-nowrap">
  7439. ${!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>`}
  7440. </td>
  7441. `;
  7442. tbody.appendChild(tr);
  7443. });
  7444. }
  7445. async function loadPPPServers() {
  7446. try {
  7447. const [pppoeRes, pptpRes, l2tpRes, ipsecRes] = await Promise.all([
  7448. fetch(`${API_BASE}/vpn/servers/pppoe`),
  7449. fetch(`${API_BASE}/vpn/servers/pptp`),
  7450. fetch(`${API_BASE}/vpn/servers/l2tp`),
  7451. fetch(`${API_BASE}/vpn/servers/ipsec`)
  7452. ]);
  7453. if (pppoeRes.ok) {
  7454. state.pppoeServer = await pppoeRes.json();
  7455. const s = state.pppoeServer;
  7456. document.getElementById('pppoe-server-enabled').checked = !!s.enabled;
  7457. document.getElementById('pppoe-server-name').value = s.service_name || 'proxmox-pppoe';
  7458. populateInterfaceSelect('pppoe-server-iface', s.interface || 'eth0');
  7459. document.getElementById('pppoe-server-profile').value = s.default_profile || 'default';
  7460. document.getElementById('pppoe-server-mtu').value = s.max_mtu || 1480;
  7461. document.getElementById('pppoe-server-onesession').checked = !!s.one_session_per_host;
  7462. const pill = document.getElementById('pppoe-server-status-pill');
  7463. if (pill) {
  7464. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  7465. 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';
  7466. }
  7467. setDotBadge('ppp-badge-pppoe-state', s.running);
  7468. }
  7469. if (pptpRes.ok) {
  7470. state.pptpServer = await pptpRes.json();
  7471. const s = state.pptpServer;
  7472. document.getElementById('pptp-server-enabled').checked = !!s.enabled;
  7473. document.getElementById('pptp-server-port').value = s.port || 1723;
  7474. document.getElementById('pptp-server-profile').value = s.default_profile || 'default-encryption';
  7475. document.getElementById('pptp-server-mppe').checked = s.require_mppe !== false;
  7476. const pill = document.getElementById('pptp-server-status-pill');
  7477. if (pill) {
  7478. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  7479. 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';
  7480. }
  7481. setDotBadge('ppp-badge-pptp-state', s.running);
  7482. }
  7483. if (l2tpRes.ok) {
  7484. state.l2tpServer = await l2tpRes.json();
  7485. const s = state.l2tpServer;
  7486. document.getElementById('l2tp-server-enabled').checked = !!s.enabled;
  7487. document.getElementById('l2tp-server-port').value = s.port || 1701;
  7488. document.getElementById('l2tp-server-profile').value = s.default_profile || 'default';
  7489. document.getElementById('l2tp-server-useipsec').value = s.use_ipsec || 'no';
  7490. document.getElementById('l2tp-server-ipsecsecret').value = s.ipsec_secret || '';
  7491. const pill = document.getElementById('l2tp-server-status-pill');
  7492. if (pill) {
  7493. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  7494. 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';
  7495. }
  7496. setDotBadge('ppp-badge-l2tp-state', s.running);
  7497. }
  7498. if (ipsecRes.ok) {
  7499. state.ipsecServer = await ipsecRes.json();
  7500. const s = state.ipsecServer;
  7501. const modalEn = document.getElementById('modal-ipsec-server-enabled');
  7502. if (modalEn) modalEn.checked = !!s.enabled;
  7503. const modalPsk = document.getElementById('modal-ipsec-server-psk');
  7504. if (modalPsk) modalPsk.value = s.preshared_key || '';
  7505. const modalPool = document.getElementById('modal-ipsec-server-pool');
  7506. if (modalPool) modalPool.value = s.pool_address || '10.10.30.0/24';
  7507. const modalDns = document.getElementById('modal-ipsec-server-dns');
  7508. if (modalDns) modalDns.value = s.dns_servers || '1.1.1.1,8.8.8.8';
  7509. const modalSubnet = document.getElementById('modal-ipsec-server-subnet');
  7510. if (modalSubnet) modalSubnet.value = s.local_subnet || '0.0.0.0/0';
  7511. const pill = document.getElementById('modal-ipsec-server-status');
  7512. if (pill) {
  7513. pill.innerText = s.running ? 'ACTIVE RESPONDER' : 'STOPPED';
  7514. 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';
  7515. }
  7516. }
  7517. } catch (err) {
  7518. console.error('Failed to load VPN servers:', err);
  7519. }
  7520. }
  7521. async function loadPPPSessions() {
  7522. try {
  7523. const res = await fetch(`${API_BASE}/vpn/ppp/active`);
  7524. const data = await res.json();
  7525. state.pppActiveSessions = Array.isArray(data) ? data : [];
  7526. const b = document.getElementById('ppp-badge-active');
  7527. if (b) b.innerText = state.pppActiveSessions.length;
  7528. const sideB = document.getElementById('badge-ppp-sessions');
  7529. if (sideB) sideB.innerText = state.pppActiveSessions.length;
  7530. renderPPPSessions();
  7531. } catch (err) {
  7532. console.error('Failed to load active PPP sessions:', err);
  7533. }
  7534. }
  7535. function renderPPPSessions() {
  7536. const tbody = document.getElementById('active-ppp-table-body');
  7537. const empty = document.getElementById('active-ppp-empty');
  7538. if (!tbody) return;
  7539. tbody.innerHTML = '';
  7540. const list = state.pppActiveSessions || [];
  7541. if (list.length === 0) {
  7542. empty?.classList.remove('hidden');
  7543. return;
  7544. }
  7545. empty?.classList.add('hidden');
  7546. list.forEach(s => {
  7547. const tr = document.createElement('tr');
  7548. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  7549. tr.innerHTML = `
  7550. <td class="py-2.5 px-3 font-bold text-white">${s.interface}</td>
  7551. <td class="py-2.5 px-3 font-semibold text-violet-300">${s.username}</td>
  7552. <td class="py-2.5 px-3 text-cyan-400 uppercase">${s.service}</td>
  7553. <td class="py-2.5 px-3 text-emerald-400 font-bold">${s.address || '-'}</td>
  7554. <td class="py-2.5 px-3 text-slate-400">${s.uptime}</td>
  7555. <td class="py-2.5 px-3 text-[11px]">
  7556. <span class="text-emerald-400">↓ ${s.rx_human || '0 B'}</span>
  7557. <span class="text-cyan-400 ml-1">↑ ${s.tx_human || '0 B'}</span>
  7558. </td>
  7559. <td class="py-2.5 px-3 text-right font-sans">
  7560. <button onclick="disconnectPPPSession('${s.interface}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  7561. </td>
  7562. `;
  7563. tbody.appendChild(tr);
  7564. });
  7565. }
  7566. async function disconnectPPPSession(iface) {
  7567. if (!confirm(`Disconnect session ${iface}?`)) return;
  7568. try {
  7569. const res = await fetch(`${API_BASE}/vpn/ppp/active/${encodeURIComponent(iface)}`, { method: 'DELETE' });
  7570. if (res.ok) {
  7571. showToast('Disconnected', `Session ${iface} terminated`, 'info');
  7572. loadPPPSessions();
  7573. }
  7574. } catch (err) {
  7575. showToast('Error', err.message, 'error');
  7576. }
  7577. }
  7578. // PPP Secret Modal handlers
  7579. function openAddPPPSecretModal() {
  7580. document.getElementById('secret-modal-title').innerText = 'Add PPP Secret';
  7581. document.getElementById('secret-modal-id').value = '';
  7582. document.getElementById('secret-modal-name').value = '';
  7583. document.getElementById('secret-modal-password').value = '';
  7584. document.getElementById('secret-modal-service').value = 'any';
  7585. document.getElementById('secret-modal-profile').value = 'default';
  7586. document.getElementById('secret-modal-local').value = '';
  7587. document.getElementById('secret-modal-remote').value = '';
  7588. document.getElementById('secret-modal-comment').value = '';
  7589. document.getElementById('secret-modal-disabled').checked = false;
  7590. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  7591. }
  7592. function openEditPPPSecretModal(id) {
  7593. const s = (state.pppSecrets || []).find(sec => sec.id === id);
  7594. if (!s) return;
  7595. document.getElementById('secret-modal-title').innerText = `Edit PPP Secret (${s.name})`;
  7596. document.getElementById('secret-modal-id').value = s.id;
  7597. document.getElementById('secret-modal-name').value = s.name;
  7598. document.getElementById('secret-modal-password').value = s.password;
  7599. document.getElementById('secret-modal-service').value = s.service || 'any';
  7600. document.getElementById('secret-modal-profile').value = s.profile || 'default';
  7601. document.getElementById('secret-modal-local').value = s.local_address || '';
  7602. document.getElementById('secret-modal-remote').value = s.remote_address || '';
  7603. document.getElementById('secret-modal-comment').value = s.comment || '';
  7604. document.getElementById('secret-modal-disabled').checked = !!s.disabled;
  7605. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  7606. }
  7607. function closePPPSecretModal() {
  7608. document.getElementById('ppp-secret-modal').classList.add('hidden');
  7609. }
  7610. async function submitSavePPPSecret(e) {
  7611. e.preventDefault();
  7612. const id = document.getElementById('secret-modal-id').value;
  7613. const name = document.getElementById('secret-modal-name').value.trim();
  7614. const password = document.getElementById('secret-modal-password').value.trim();
  7615. const service = document.getElementById('secret-modal-service').value;
  7616. const profile = document.getElementById('secret-modal-profile').value;
  7617. const local = document.getElementById('secret-modal-local').value.trim();
  7618. const remote = document.getElementById('secret-modal-remote').value.trim();
  7619. const comment = document.getElementById('secret-modal-comment').value.trim();
  7620. const disabled = document.getElementById('secret-modal-disabled').checked;
  7621. try {
  7622. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`, {
  7623. method: 'POST',
  7624. headers: { 'Content-Type': 'application/json' },
  7625. body: JSON.stringify({
  7626. id,
  7627. name,
  7628. password,
  7629. service,
  7630. profile,
  7631. local_address: local,
  7632. remote_address: remote,
  7633. comment,
  7634. disabled
  7635. })
  7636. });
  7637. if (res.ok) {
  7638. showToast('Secret Saved', `User ${name} saved to PPP database`, 'success');
  7639. closePPPSecretModal();
  7640. loadPPPSecrets();
  7641. } else {
  7642. const err = await res.json();
  7643. showToast('Error', err.message, 'error');
  7644. }
  7645. } catch (err) {
  7646. showToast('Error', err.message, 'error');
  7647. }
  7648. }
  7649. async function togglePPPSecretState(id, disabled) {
  7650. try {
  7651. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}/state`, {
  7652. method: 'POST',
  7653. headers: { 'Content-Type': 'application/json' },
  7654. body: JSON.stringify({ disabled })
  7655. });
  7656. if (res.ok) {
  7657. showToast(disabled ? 'Disabled' : 'Enabled', 'Secret user state updated', 'info');
  7658. loadPPPSecrets();
  7659. }
  7660. } catch (err) {
  7661. showToast('Error', err.message, 'error');
  7662. }
  7663. }
  7664. async function deletePPPSecret(id) {
  7665. if (!confirm('Are you sure you want to delete this secret account?')) return;
  7666. try {
  7667. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7668. if (res.ok) {
  7669. showToast('Deleted', 'Secret account removed', 'success');
  7670. loadPPPSecrets();
  7671. }
  7672. } catch (err) {
  7673. showToast('Error', err.message, 'error');
  7674. }
  7675. }
  7676. // PPP Profile Modal handlers
  7677. function openAddPPPProfileModal() {
  7678. document.getElementById('profile-modal-name').value = '';
  7679. document.getElementById('profile-modal-local').value = '10.10.10.1';
  7680. document.getElementById('profile-modal-remote').value = '10.10.10.10-10.10.10.50';
  7681. document.getElementById('profile-modal-dns').value = '1.1.1.1,8.8.8.8';
  7682. document.getElementById('profile-modal-encryption').value = 'required';
  7683. document.getElementById('profile-modal-onlyone').checked = true;
  7684. document.getElementById('profile-modal-comment').value = '';
  7685. document.getElementById('ppp-profile-modal').classList.remove('hidden');
  7686. }
  7687. function closePPPProfileModal() {
  7688. document.getElementById('ppp-profile-modal').classList.add('hidden');
  7689. }
  7690. async function submitSavePPPProfile(e) {
  7691. e.preventDefault();
  7692. const name = document.getElementById('profile-modal-name').value.trim();
  7693. const local = document.getElementById('profile-modal-local').value.trim();
  7694. const remote = document.getElementById('profile-modal-remote').value.trim();
  7695. const dns = document.getElementById('profile-modal-dns').value.trim();
  7696. const enc = document.getElementById('profile-modal-encryption').value;
  7697. const onlyone = document.getElementById('profile-modal-onlyone').checked;
  7698. const comment = document.getElementById('profile-modal-comment').value.trim();
  7699. try {
  7700. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`, {
  7701. method: 'POST',
  7702. headers: { 'Content-Type': 'application/json' },
  7703. body: JSON.stringify({
  7704. id: name,
  7705. name,
  7706. local_address: local,
  7707. remote_address: remote,
  7708. dns_servers: dns,
  7709. use_encryption: enc,
  7710. only_one: onlyone,
  7711. comment
  7712. })
  7713. });
  7714. if (res.ok) {
  7715. showToast('Profile Saved', `PPP profile ${name} created`, 'success');
  7716. closePPPProfileModal();
  7717. loadPPPProfiles();
  7718. } else {
  7719. const err = await res.json();
  7720. showToast('Error', err.message, 'error');
  7721. }
  7722. } catch (err) {
  7723. showToast('Error', err.message, 'error');
  7724. }
  7725. }
  7726. async function deletePPPProfile(name) {
  7727. if (!confirm(`Delete PPP profile ${name}?`)) return;
  7728. try {
  7729. const res = await fetch(`${API_BASE}/vpn/ppp/profiles/${encodeURIComponent(name)}`, { method: 'DELETE' });
  7730. if (res.ok) {
  7731. showToast('Deleted', 'Profile removed', 'success');
  7732. loadPPPProfiles();
  7733. } else {
  7734. const err = await res.json();
  7735. showToast('Error', err.message, 'error');
  7736. }
  7737. } catch (err) {
  7738. showToast('Error', err.message, 'error');
  7739. }
  7740. }
  7741. // Server Config submissions
  7742. async function savePPPoEServerConfig(e) {
  7743. e.preventDefault();
  7744. const enabled = document.getElementById('pppoe-server-enabled').checked;
  7745. const name = document.getElementById('pppoe-server-name').value.trim();
  7746. const iface = document.getElementById('pppoe-server-iface').value;
  7747. const profile = document.getElementById('pppoe-server-profile').value;
  7748. const mtu = parseInt(document.getElementById('pppoe-server-mtu').value) || 1480;
  7749. const onesession = document.getElementById('pppoe-server-onesession').checked;
  7750. try {
  7751. const res = await fetch(`${API_BASE}/vpn/servers/pppoe`, {
  7752. method: 'POST',
  7753. headers: { 'Content-Type': 'application/json' },
  7754. body: JSON.stringify({
  7755. enabled,
  7756. service_name: name,
  7757. interface: iface,
  7758. default_profile: profile,
  7759. max_mtu: mtu,
  7760. max_mru: mtu,
  7761. one_session_per_host: onesession
  7762. })
  7763. });
  7764. if (res.ok) {
  7765. showToast('PPPoE Server', enabled ? 'PPPoE Server started' : 'PPPoE Server stopped', 'success');
  7766. loadPPPServers();
  7767. fetchData(false);
  7768. } else {
  7769. const err = await res.json();
  7770. showToast('Error', err.message, 'error');
  7771. }
  7772. } catch (err) {
  7773. showToast('Error', err.message, 'error');
  7774. }
  7775. }
  7776. async function savePPTPServerConfig(e) {
  7777. e.preventDefault();
  7778. const enabled = document.getElementById('pptp-server-enabled').checked;
  7779. const port = parseInt(document.getElementById('pptp-server-port').value) || 1723;
  7780. const profile = document.getElementById('pptp-server-profile').value;
  7781. const mppe = document.getElementById('pptp-server-mppe').checked;
  7782. try {
  7783. const res = await fetch(`${API_BASE}/vpn/servers/pptp`, {
  7784. method: 'POST',
  7785. headers: { 'Content-Type': 'application/json' },
  7786. body: JSON.stringify({
  7787. enabled,
  7788. port,
  7789. default_profile: profile,
  7790. require_mppe: mppe
  7791. })
  7792. });
  7793. if (res.ok) {
  7794. showToast('PPTP Server', enabled ? 'PPTP Server started' : 'PPTP Server stopped', 'success');
  7795. loadPPPServers();
  7796. fetchData(false);
  7797. } else {
  7798. const err = await res.json();
  7799. showToast('Error', err.message, 'error');
  7800. }
  7801. } catch (err) {
  7802. showToast('Error', err.message, 'error');
  7803. }
  7804. }
  7805. async function saveL2TPServerConfig(e) {
  7806. e.preventDefault();
  7807. const enabled = document.getElementById('l2tp-server-enabled').checked;
  7808. const port = parseInt(document.getElementById('l2tp-server-port').value) || 1701;
  7809. const profile = document.getElementById('l2tp-server-profile').value;
  7810. const useipsec = document.getElementById('l2tp-server-useipsec').value;
  7811. const psk = document.getElementById('l2tp-server-ipsecsecret').value.trim();
  7812. try {
  7813. const res = await fetch(`${API_BASE}/vpn/servers/l2tp`, {
  7814. method: 'POST',
  7815. headers: { 'Content-Type': 'application/json' },
  7816. body: JSON.stringify({
  7817. enabled,
  7818. port,
  7819. default_profile: profile,
  7820. use_ipsec: useipsec,
  7821. ipsec_secret: psk
  7822. })
  7823. });
  7824. if (res.ok) {
  7825. showToast('L2TP Server', enabled ? 'L2TP Server started' : 'L2TP Server stopped', 'success');
  7826. loadPPPServers();
  7827. fetchData(false);
  7828. } else {
  7829. const err = await res.json();
  7830. showToast('Error', err.message, 'error');
  7831. }
  7832. } catch (err) {
  7833. showToast('Error', err.message, 'error');
  7834. }
  7835. }
  7836. // IPSec Server Modal
  7837. function openIPSecServerModal() {
  7838. loadPPPServers();
  7839. document.getElementById('ipsec-server-modal').classList.remove('hidden');
  7840. }
  7841. function closeIPSecServerModal() {
  7842. document.getElementById('ipsec-server-modal').classList.add('hidden');
  7843. }
  7844. async function submitSaveIPSecServer(e) {
  7845. e.preventDefault();
  7846. const enabled = document.getElementById('modal-ipsec-server-enabled').checked;
  7847. const psk = document.getElementById('modal-ipsec-server-psk').value.trim();
  7848. const pool = document.getElementById('modal-ipsec-server-pool').value.trim();
  7849. const dns = document.getElementById('modal-ipsec-server-dns').value.trim();
  7850. const subnet = document.getElementById('modal-ipsec-server-subnet').value.trim();
  7851. try {
  7852. const res = await fetch(`${API_BASE}/vpn/servers/ipsec`, {
  7853. method: 'POST',
  7854. headers: { 'Content-Type': 'application/json' },
  7855. body: JSON.stringify({
  7856. enabled,
  7857. preshared_key: psk,
  7858. pool_address: pool,
  7859. dns_servers: dns,
  7860. local_subnet: subnet
  7861. })
  7862. });
  7863. if (res.ok) {
  7864. showToast('IPSec Server', enabled ? 'IKEv2 Roadwarrior responder active' : 'IPSec Server stopped', 'success');
  7865. closeIPSecServerModal();
  7866. loadPPPServers();
  7867. fetchData(false);
  7868. } else {
  7869. const err = await res.json();
  7870. showToast('Error', err.message, 'error');
  7871. }
  7872. } catch (err) {
  7873. showToast('Error', err.message, 'error');
  7874. }
  7875. }
  7876. // WireGuard Client Config Viewer
  7877. let currentWGClientConf = '';
  7878. async function openWGClientConfModal(iface, clientIP) {
  7879. try {
  7880. const res = await fetch(`${API_BASE}/vpn/wireguard/client-config`, {
  7881. method: 'POST',
  7882. headers: { 'Content-Type': 'application/json' },
  7883. body: JSON.stringify({
  7884. interface: iface,
  7885. address: clientIP || '10.10.0.2/32',
  7886. dns: '1.1.1.1, 8.8.8.8'
  7887. })
  7888. });
  7889. if (res.ok) {
  7890. const data = await res.json();
  7891. currentWGClientConf = data.config;
  7892. document.getElementById('wg-client-conf-text').value = currentWGClientConf;
  7893. document.getElementById('wg-client-conf-modal').classList.remove('hidden');
  7894. } else {
  7895. const err = await res.json();
  7896. showToast('Error', err.message, 'error');
  7897. }
  7898. } catch (err) {
  7899. showToast('Error', err.message, 'error');
  7900. }
  7901. }
  7902. function closeWGClientConfModal() {
  7903. document.getElementById('wg-client-conf-modal').classList.add('hidden');
  7904. }
  7905. function copyWGClientConf() {
  7906. if (!currentWGClientConf) return;
  7907. copyToClipboard(currentWGClientConf, 'WireGuard Client Profile');
  7908. }
  7909. function downloadWGClientConf() {
  7910. if (!currentWGClientConf) return;
  7911. const blob = new Blob([currentWGClientConf], { type: 'text/plain;charset=utf-8' });
  7912. const a = document.createElement('a');
  7913. a.href = URL.createObjectURL(blob);
  7914. a.download = 'wireguard-client.conf';
  7915. document.body.appendChild(a);
  7916. a.click();
  7917. document.body.removeChild(a);
  7918. showToast('Downloaded', 'wireguard-client.conf saved', 'success');
  7919. }
  7920. // =========================================================================
  7921. // DYNAMIC ROUTING (FRRouting BGP & OSPFv2)
  7922. // =========================================================================
  7923. state.activeDynSubTab = 'bgp-peers';
  7924. state.activeBgpSubTab = 'bgp-peers';
  7925. state.activeOspfTab = 'instances';
  7926. state.bgpInstance = null;
  7927. state.bgpPeers = [];
  7928. state.bgpNets = [];
  7929. state.bgpRoutes = [];
  7930. state.ospfInstance = null;
  7931. state.ospfInstances = [];
  7932. state.ospfAreas = [];
  7933. state.ospfAreaRanges = [];
  7934. state.ospfTemplates = [];
  7935. state.ospfLiveInterfaces = [];
  7936. state.ospfStaticNbrs = [];
  7937. state.ospfNeighbors = [];
  7938. state.ospfLSA = [];
  7939. state.ospfRoutes = [];
  7940. state.selectedOspfRow = {
  7941. instances: null,
  7942. areas: null,
  7943. 'area-ranges': null,
  7944. templates: null,
  7945. interfaces: null,
  7946. 'static-nbrs': null,
  7947. neighbors: null,
  7948. lsa: null,
  7949. };
  7950. state.ospfSort = {
  7951. instances: { col: 'name', asc: true },
  7952. areas: { col: 'name', asc: true },
  7953. ranges: { col: 'area', asc: true },
  7954. templates: { col: 'interfaces', asc: true },
  7955. live_ifaces: { col: 'interface', asc: true },
  7956. snbrs: { col: 'address', asc: true },
  7957. neighbors: { col: 'address', asc: true },
  7958. lsa: { col: 'instance', asc: true },
  7959. };
  7960. function switchBgpSubTab(subTab) {
  7961. state.activeBgpSubTab = subTab;
  7962. const tabs = ['bgp-peers', 'bgp-nets', 'bgp-routes'];
  7963. tabs.forEach(t => {
  7964. const el = document.getElementById(`dyn-subtab-${t}`);
  7965. const btn = document.getElementById(`bgp-subtab-btn-${t}`);
  7966. if (el) el.classList.toggle('hidden', t !== subTab);
  7967. if (btn) {
  7968. if (t === subTab) {
  7969. 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';
  7970. } else {
  7971. 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';
  7972. }
  7973. }
  7974. });
  7975. }
  7976. function switchOspfTab(tabName) {
  7977. state.activeOspfTab = tabName;
  7978. const tabs = ['instances', 'areas', 'area-ranges', 'templates', 'interfaces', 'static-nbrs', 'neighbors', 'lsa'];
  7979. tabs.forEach(t => {
  7980. const pane = document.getElementById(`ospf-pane-${t}`);
  7981. const btn = document.getElementById(`ospf-tab-btn-${t}`);
  7982. if (pane) pane.classList.toggle('hidden', t !== tabName);
  7983. if (btn) {
  7984. if (t === tabName) {
  7985. 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';
  7986. } else {
  7987. 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';
  7988. }
  7989. }
  7990. });
  7991. }
  7992. function switchOspfSubTab(tab) {
  7993. // Legacy alias
  7994. if (tab === 'ospf-ifaces') switchOspfTab('templates');
  7995. else if (tab === 'ospf-areas') switchOspfTab('areas');
  7996. else if (tab === 'ospf-nbrs') switchOspfTab('neighbors');
  7997. else switchOspfTab('instances');
  7998. }
  7999. function switchDynSubTab(subTab) {
  8000. if (subTab.startsWith('bgp')) {
  8001. if (state.activeTab !== 'bgp') navigate('bgp');
  8002. switchBgpSubTab(subTab);
  8003. } else if (subTab.startsWith('ospf')) {
  8004. if (state.activeTab !== 'ospf') navigate('ospf');
  8005. switchOspfTab('instances');
  8006. }
  8007. }
  8008. async function loadDynamicRouting(showToastMsg = false) {
  8009. try {
  8010. const fetchSafeJson = async (url) => {
  8011. try {
  8012. const r = await fetch(url);
  8013. return r.ok ? await r.json() : null;
  8014. } catch (e) {
  8015. return null;
  8016. }
  8017. };
  8018. const [
  8019. sum, bgpInst, bgpPeers, bgpNets, bgpRoutes,
  8020. ospfInsts, ospfAreas, ospfRanges, ospfTemplates, ospfLiveIfaces, ospfStaticNbrs, ospfNbrs, ospfLsa, filters,
  8021. selectRules, commLists, asLists
  8022. ] = await Promise.all([
  8023. fetchSafeJson(`${API_BASE}/routing/dynamic/summary`),
  8024. fetchSafeJson(`${API_BASE}/routing/bgp/instance`),
  8025. fetchSafeJson(`${API_BASE}/routing/bgp/peers`),
  8026. fetchSafeJson(`${API_BASE}/routing/bgp/networks`),
  8027. fetchSafeJson(`${API_BASE}/routing/bgp/routes`),
  8028. fetchSafeJson(`${API_BASE}/routing/ospf/instances`),
  8029. fetchSafeJson(`${API_BASE}/routing/ospf/areas`),
  8030. fetchSafeJson(`${API_BASE}/routing/ospf/area-ranges`),
  8031. fetchSafeJson(`${API_BASE}/routing/ospf/templates`),
  8032. fetchSafeJson(`${API_BASE}/routing/ospf/interfaces-live`),
  8033. fetchSafeJson(`${API_BASE}/routing/ospf/static-neighbors`),
  8034. fetchSafeJson(`${API_BASE}/routing/ospf/neighbors`),
  8035. fetchSafeJson(`${API_BASE}/routing/ospf/lsa`),
  8036. fetchSafeJson(`${API_BASE}/routing/filters`),
  8037. fetchSafeJson(`${API_BASE}/routing/filters/select-rules`),
  8038. fetchSafeJson(`${API_BASE}/routing/filters/community-lists`),
  8039. fetchSafeJson(`${API_BASE}/routing/filters/as-lists`)
  8040. ]);
  8041. if (sum) state.dynSummary = sum;
  8042. if (bgpInst) state.bgpInstance = bgpInst;
  8043. if (bgpPeers) state.bgpPeers = bgpPeers;
  8044. if (bgpNets) state.bgpNets = bgpNets;
  8045. if (bgpRoutes) state.bgpRoutes = bgpRoutes;
  8046. if (ospfInsts) state.ospfInstances = ospfInsts;
  8047. if (ospfAreas) state.ospfAreas = ospfAreas;
  8048. if (ospfRanges) state.ospfAreaRanges = ospfRanges;
  8049. if (ospfTemplates) state.ospfTemplates = ospfTemplates;
  8050. if (ospfLiveIfaces) state.ospfLiveInterfaces = ospfLiveIfaces;
  8051. if (ospfStaticNbrs) state.ospfStaticNbrs = ospfStaticNbrs;
  8052. if (ospfNbrs) state.ospfNeighbors = ospfNbrs;
  8053. if (ospfLsa) state.ospfLSA = ospfLsa;
  8054. if (filters) state.routingFilters = filters;
  8055. if (selectRules) state.routingSelectRules = selectRules;
  8056. if (commLists) state.routingCommunityLists = commLists;
  8057. if (asLists) state.routingASLists = asLists;
  8058. try { renderBgpStatusPill(); } catch(e) { console.error('renderBgpStatusPill error:', e); }
  8059. try { renderBgpPeers(); } catch(e) { console.error('renderBgpPeers error:', e); }
  8060. try { renderBgpNetworks(); } catch(e) { console.error('renderBgpNetworks error:', e); }
  8061. try { renderBgpRoutes(); } catch(e) { console.error('renderBgpRoutes error:', e); }
  8062. try { renderOspfInstances(); } catch(e) { console.error('renderOspfInstances error:', e); }
  8063. try { renderOspfAreas(); } catch(e) { console.error('renderOspfAreas error:', e); }
  8064. try { renderOspfAreaRanges(); } catch(e) { console.error('renderOspfAreaRanges error:', e); }
  8065. try { renderOspfTemplates(); } catch(e) { console.error('renderOspfTemplates error:', e); }
  8066. try { renderOspfLiveInterfaces(); } catch(e) { console.error('renderOspfLiveInterfaces error:', e); }
  8067. try { renderOspfStaticNbrs(); } catch(e) { console.error('renderOspfStaticNbrs error:', e); }
  8068. try { renderOspfNeighbors(); } catch(e) { console.error('renderOspfNeighbors error:', e); }
  8069. try { renderOspfLSA(); } catch(e) { console.error('renderOspfLSA error:', e); }
  8070. try { renderRoutingFilters(); } catch(e) { console.error('renderRoutingFilters error:', e); }
  8071. try { updateBadges(); } catch(e) { console.error('updateBadges error:', e); }
  8072. if (showToastMsg) showToast('Refreshed', 'Dynamic routing telemetry updated', 'info');
  8073. } catch (err) {
  8074. console.error('Failed to load dynamic routing:', err);
  8075. if (showToastMsg) showToast('Notice', 'Unable to refresh dynamic routing telemetry', 'warning');
  8076. }
  8077. }
  8078. async function loadOspfAll() {
  8079. await loadDynamicRouting(true);
  8080. }
  8081. function renderBgpStatusPill() {
  8082. const pills = document.querySelectorAll('.bgp-live-status-pill');
  8083. pills.forEach(pill => {
  8084. const inst = state.bgpInstance;
  8085. if (!inst || !inst.enabled) {
  8086. pill.className = 'bgp-live-status-pill text-[10px] px-2 py-0.5 rounded font-mono bg-slate-800 text-slate-400 border border-slate-700';
  8087. pill.innerText = 'BGP DISABLED';
  8088. } else if (inst.running) {
  8089. pill.className = 'bgp-live-status-pill text-[10px] px-2 py-0.5 rounded font-mono bg-purple-950 text-purple-300 border border-purple-800/60 font-semibold';
  8090. pill.innerText = `BGP ACTIVE (AS ${inst.as})`;
  8091. } else {
  8092. pill.className = 'bgp-live-status-pill text-[10px] px-2 py-0.5 rounded font-mono bg-amber-950 text-amber-300 border border-amber-800/60 font-semibold';
  8093. pill.innerText = 'BGP STARTING...';
  8094. }
  8095. });
  8096. }
  8097. function renderBgpPeers() {
  8098. const tbody = document.getElementById('bgp-peers-table-body');
  8099. if (!tbody) return;
  8100. const empty = document.getElementById('bgp-peers-empty');
  8101. const countBadge = document.getElementById('bgp-peers-count-badge');
  8102. const navBadge = document.getElementById('dyn-badge-bgp-peers');
  8103. const peers = state.bgpPeers || [];
  8104. if (countBadge) countBadge.innerText = `${peers.length} Peers`;
  8105. if (navBadge) navBadge.innerText = peers.length;
  8106. if (peers.length === 0) {
  8107. tbody.innerHTML = '';
  8108. if (empty) empty.classList.remove('hidden');
  8109. return;
  8110. }
  8111. if (empty) empty.classList.add('hidden');
  8112. const sig = peers.map(p => `${p.name}:${p.state}:${p.uptime}:${p.prefix_received}:${p.prefix_sent}:${p.disabled}`).join(';');
  8113. if (tbody.dataset.sig === sig) return;
  8114. tbody.dataset.sig = sig;
  8115. tbody.innerHTML = peers.map(p => {
  8116. let flagA = !p.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  8117. let flagE = p.state === 'Established' ? '<span class="text-emerald-400 font-bold ml-1" title="Established">E</span>' : '';
  8118. let flagX = p.disabled ? '<span class="text-rose-400 font-bold ml-1" title="Disabled">X</span>' : '';
  8119. let stateBadge = '';
  8120. if (p.disabled) {
  8121. 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>';
  8122. } else if (p.state === 'Established') {
  8123. 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>';
  8124. } else if (p.state === 'Connect' || p.state === 'Active') {
  8125. 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>`;
  8126. } else {
  8127. 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>`;
  8128. }
  8129. return `
  8130. <tr class="hover:bg-slate-800/40 transition">
  8131. <td class="py-2.5 px-3 text-center tracking-wider">${flagA}${flagE}${flagX}</td>
  8132. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(p.name)}</td>
  8133. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(p.remote_address)}</td>
  8134. <td class="py-2.5 px-3">
  8135. <div class="font-bold text-slate-200">AS ${p.remote_as}</div>
  8136. ${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>`}
  8137. </td>
  8138. <td class="py-2.5 px-3">${stateBadge}</td>
  8139. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(p.uptime || '-')}</td>
  8140. <td class="py-2.5 px-3 text-slate-300">
  8141. <span class="text-emerald-400 font-bold">↓ ${p.prefix_received || 0}</span> /
  8142. <span class="text-blue-400 font-bold">↑ ${p.prefix_sent || 0}</span>
  8143. </td>
  8144. <td class="py-2.5 px-3 font-mono text-[11px] whitespace-nowrap">
  8145. ${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> ` : ''}
  8146. ${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>` : ''}
  8147. ${!p.in_filter && !p.out_filter ? '<span class="text-slate-600">-</span>' : ''}
  8148. </td>
  8149. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(p.comment || '')}</td>
  8150. <td class="py-2.5 px-3 text-right space-x-1.5 whitespace-nowrap font-sans">
  8151. <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'}">
  8152. ${p.disabled ? 'Enable' : 'Disable'}
  8153. </button>
  8154. <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">
  8155. Edit
  8156. </button>
  8157. <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">
  8158. Delete
  8159. </button>
  8160. </td>
  8161. </tr>
  8162. `;
  8163. }).join('');
  8164. }
  8165. function renderBgpNetworks() {
  8166. const tbody = document.getElementById('bgp-nets-table-body');
  8167. if (!tbody) return;
  8168. const empty = document.getElementById('bgp-nets-empty');
  8169. const countBadge = document.getElementById('bgp-nets-count-badge');
  8170. const navBadge = document.getElementById('dyn-badge-bgp-nets');
  8171. const nets = state.bgpNets || [];
  8172. if (countBadge) countBadge.innerText = `${nets.length} Networks`;
  8173. if (navBadge) navBadge.innerText = nets.length;
  8174. if (nets.length === 0) {
  8175. tbody.innerHTML = '';
  8176. if (empty) empty.classList.remove('hidden');
  8177. return;
  8178. }
  8179. if (empty) empty.classList.add('hidden');
  8180. const sig = nets.map(n => `${n.network}:${n.disabled}:${n.comment}`).join(';');
  8181. if (tbody.dataset.sig === sig) return;
  8182. tbody.dataset.sig = sig;
  8183. tbody.innerHTML = nets.map(n => `
  8184. <tr class="hover:bg-slate-800/40 transition">
  8185. <td class="py-2.5 px-3 font-semibold text-purple-300 font-mono">${escapeHtml(n.network)}</td>
  8186. <td class="py-2.5 px-3">
  8187. ${n.disabled
  8188. ? '<span class="px-2 py-0.5 rounded-full text-[10px] bg-slate-800 text-slate-400 border border-slate-700">Disabled</span>'
  8189. : '<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>'}
  8190. </td>
  8191. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(n.comment || '')}</td>
  8192. <td class="py-2.5 px-3 text-right space-x-1 font-sans">
  8193. <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">
  8194. Delete
  8195. </button>
  8196. </td>
  8197. </tr>
  8198. `).join('');
  8199. }
  8200. function renderBgpRoutes() {
  8201. const tbody = document.getElementById('bgp-routes-table-body');
  8202. if (!tbody) return;
  8203. const empty = document.getElementById('bgp-routes-empty');
  8204. const countBadge = document.getElementById('bgp-routes-count-badge');
  8205. const navBadge = document.getElementById('dyn-badge-bgp-routes');
  8206. const routes = state.bgpRoutes || [];
  8207. if (countBadge) countBadge.innerText = `${routes.length} Routes`;
  8208. if (navBadge) navBadge.innerText = routes.length;
  8209. if (routes.length === 0) {
  8210. tbody.innerHTML = '';
  8211. if (empty) empty.classList.remove('hidden');
  8212. return;
  8213. }
  8214. if (empty) empty.classList.add('hidden');
  8215. const sig = routes.map(r => `${r.prefix}:${r.next_hop}:${r.metric}:${r.path}`).join(';');
  8216. if (tbody.dataset.sig === sig) return;
  8217. tbody.dataset.sig = sig;
  8218. tbody.innerHTML = routes.map(r => `
  8219. <tr class="hover:bg-slate-800/40 transition">
  8220. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.prefix)}</td>
  8221. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(r.next_hop || '-')}</td>
  8222. <td class="py-2.5 px-3 text-slate-300">${r.metric}</td>
  8223. <td class="py-2.5 px-3 text-slate-300">${r.weight}</td>
  8224. <td class="py-2.5 px-3 text-amber-300">${escapeHtml(r.path || 'i')}</td>
  8225. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.origin || 'IGP')}</td>
  8226. </tr>
  8227. `).join('');
  8228. }
  8229. // =========================================================================
  8230. // DEBTIK v7 OSPF TABLE RENDERING & SORTING
  8231. // =========================================================================
  8232. function sortOspfTable(tab, col) {
  8233. if (!state.ospfSort) state.ospfSort = {};
  8234. if (!state.ospfSort[tab]) state.ospfSort[tab] = { col: col, asc: true };
  8235. if (state.ospfSort[tab].col === col) {
  8236. state.ospfSort[tab].asc = !state.ospfSort[tab].asc;
  8237. } else {
  8238. state.ospfSort[tab].col = col;
  8239. state.ospfSort[tab].asc = true;
  8240. }
  8241. const asc = state.ospfSort[tab].asc;
  8242. let list = [];
  8243. if (tab === 'instances') list = state.ospfInstances || [];
  8244. else if (tab === 'areas') list = state.ospfAreas || [];
  8245. else if (tab === 'ranges') list = state.ospfAreaRanges || [];
  8246. else if (tab === 'templates') list = state.ospfTemplates || [];
  8247. else if (tab === 'live_ifaces') list = state.ospfLiveInterfaces || [];
  8248. else if (tab === 'snbrs') list = state.ospfStaticNbrs || [];
  8249. else if (tab === 'neighbors') list = state.ospfNeighbors || [];
  8250. else if (tab === 'lsa') list = state.ospfLSA || [];
  8251. list.sort((a, b) => {
  8252. let valA = a[col] ?? '';
  8253. let valB = b[col] ?? '';
  8254. if (typeof valA === 'number' && typeof valB === 'number') {
  8255. return asc ? valA - valB : valB - valA;
  8256. }
  8257. return asc ? String(valA).localeCompare(String(valB)) : String(valB).localeCompare(String(valA));
  8258. });
  8259. if (tab === 'instances') renderOspfInstances();
  8260. else if (tab === 'areas') renderOspfAreas();
  8261. else if (tab === 'ranges') renderOspfAreaRanges();
  8262. else if (tab === 'templates') renderOspfTemplates();
  8263. else if (tab === 'live_ifaces') renderOspfLiveInterfaces();
  8264. else if (tab === 'snbrs') renderOspfStaticNbrs();
  8265. else if (tab === 'neighbors') renderOspfNeighbors();
  8266. else if (tab === 'lsa') renderOspfLSA();
  8267. }
  8268. function selectOspfRow(tab, id) {
  8269. if (!state.selectedOspfRow) state.selectedOspfRow = {};
  8270. state.selectedOspfRow[tab] = id;
  8271. if (tab === 'instances') {
  8272. renderOspfInstances();
  8273. const btnEn = document.getElementById('btn-ospf-inst-enable');
  8274. const btnDis = document.getElementById('btn-ospf-inst-disable');
  8275. const btnRem = document.getElementById('btn-ospf-inst-remove');
  8276. const btnCom = document.getElementById('btn-ospf-inst-comment');
  8277. if (btnEn) btnEn.disabled = false;
  8278. if (btnDis) btnDis.disabled = false;
  8279. if (btnRem) btnRem.disabled = false;
  8280. if (btnCom) btnCom.disabled = false;
  8281. } else if (tab === 'areas') {
  8282. renderOspfAreas();
  8283. const btnEn = document.getElementById('btn-ospf-area-enable');
  8284. const btnDis = document.getElementById('btn-ospf-area-disable');
  8285. const btnRem = document.getElementById('btn-ospf-area-remove');
  8286. const btnCom = document.getElementById('btn-ospf-area-comment');
  8287. if (btnEn) btnEn.disabled = false;
  8288. if (btnDis) btnDis.disabled = false;
  8289. if (btnRem) btnRem.disabled = false;
  8290. if (btnCom) btnCom.disabled = false;
  8291. } else if (tab === 'ranges') {
  8292. renderOspfAreaRanges();
  8293. const btnEn = document.getElementById('btn-ospf-range-enable');
  8294. const btnDis = document.getElementById('btn-ospf-range-disable');
  8295. const btnRem = document.getElementById('btn-ospf-range-remove');
  8296. const btnCom = document.getElementById('btn-ospf-range-comment');
  8297. if (btnEn) btnEn.disabled = false;
  8298. if (btnDis) btnDis.disabled = false;
  8299. if (btnRem) btnRem.disabled = false;
  8300. if (btnCom) btnCom.disabled = false;
  8301. } else if (tab === 'templates') {
  8302. renderOspfTemplates();
  8303. const btnEn = document.getElementById('btn-ospf-tmpl-enable');
  8304. const btnDis = document.getElementById('btn-ospf-tmpl-disable');
  8305. const btnRem = document.getElementById('btn-ospf-tmpl-remove');
  8306. const btnCom = document.getElementById('btn-ospf-tmpl-comment');
  8307. if (btnEn) btnEn.disabled = false;
  8308. if (btnDis) btnDis.disabled = false;
  8309. if (btnRem) btnRem.disabled = false;
  8310. if (btnCom) btnCom.disabled = false;
  8311. } else if (tab === 'snbrs') {
  8312. renderOspfStaticNbrs();
  8313. const btnEn = document.getElementById('btn-ospf-snbr-enable');
  8314. const btnDis = document.getElementById('btn-ospf-snbr-disable');
  8315. const btnRem = document.getElementById('btn-ospf-snbr-remove');
  8316. const btnCom = document.getElementById('btn-ospf-snbr-comment');
  8317. if (btnEn) btnEn.disabled = false;
  8318. if (btnDis) btnDis.disabled = false;
  8319. if (btnRem) btnRem.disabled = false;
  8320. if (btnCom) btnCom.disabled = false;
  8321. }
  8322. }
  8323. // TAB 1: INSTANCES
  8324. function renderOspfInstances() {
  8325. const tbody = document.getElementById('ospf-instances-table-body');
  8326. if (!tbody) return;
  8327. const countEl = document.getElementById('ospf-instances-footer-count');
  8328. const filter = (document.getElementById('filter-ospf-instances')?.value || '').toLowerCase();
  8329. let list = state.ospfInstances || [];
  8330. if (filter) {
  8331. list = list.filter(i => (i.name || '').toLowerCase().includes(filter) || (i.router_id || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  8332. }
  8333. if (countEl) countEl.innerText = list.length;
  8334. const selId = state.selectedOspfRow?.instances;
  8335. tbody.innerHTML = list.map((inst, idx) => {
  8336. const isSel = inst.id === selId;
  8337. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  8338. const flagD = inst.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  8339. return `
  8340. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('instances', '${inst.id}')" ondblclick="openEditOspfInstanceModal('${inst.id}')">
  8341. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  8342. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🔀'}</td>
  8343. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(inst.comment || '')}</td>
  8344. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  8345. <span class="text-sky-400">↳</span> <span>${escapeHtml(inst.name || 'Default')}</span>
  8346. </td>
  8347. <td class="py-1.5 px-3">${inst.version || 2}</td>
  8348. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(inst.vrf || 'main')}</td>
  8349. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(inst.router_id || '192.168.131.56')}</td>
  8350. </tr>
  8351. `;
  8352. }).join('');
  8353. }
  8354. // TAB 2: AREAS
  8355. function renderOspfAreas() {
  8356. const tbody = document.getElementById('ospf-areas-table-body');
  8357. if (!tbody) return;
  8358. const countEl = document.getElementById('ospf-areas-footer-count');
  8359. const filter = (document.getElementById('filter-ospf-areas')?.value || '').toLowerCase();
  8360. let list = state.ospfAreas || [];
  8361. if (filter) {
  8362. list = list.filter(a => (a.name || '').toLowerCase().includes(filter) || (a.area_id || '').toLowerCase().includes(filter) || (a.comment || '').toLowerCase().includes(filter));
  8363. }
  8364. if (countEl) countEl.innerText = list.length;
  8365. const selId = state.selectedOspfRow?.areas;
  8366. tbody.innerHTML = list.map((a, idx) => {
  8367. const isSel = a.id === selId;
  8368. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  8369. const flagD = a.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  8370. return `
  8371. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('areas', '${a.id}')" ondblclick="openEditOspfAreaModal('${a.id}')">
  8372. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  8373. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🌐'}</td>
  8374. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(a.comment || '')}</td>
  8375. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  8376. <span class="text-sky-400">↳</span> <span>${escapeHtml(a.name || 'Default')}</span>
  8377. </td>
  8378. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(a.instance || 'Default')}</td>
  8379. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(a.area_id || '0.0.0.0')}</td>
  8380. <td class="py-1.5 px-3 font-mono text-slate-400">${escapeHtml(a.area_type || 'default')}</td>
  8381. </tr>
  8382. `;
  8383. }).join('');
  8384. }
  8385. // TAB 3: AREA RANGES
  8386. function renderOspfAreaRanges() {
  8387. const tbody = document.getElementById('ospf-ranges-table-body');
  8388. if (!tbody) return;
  8389. const countEl = document.getElementById('ospf-ranges-footer-count');
  8390. const filter = (document.getElementById('filter-ospf-area-ranges')?.value || '').toLowerCase();
  8391. let list = state.ospfAreaRanges || [];
  8392. if (filter) {
  8393. list = list.filter(r => (r.prefix || '').toLowerCase().includes(filter) || (r.area || '').toLowerCase().includes(filter) || (r.comment || '').toLowerCase().includes(filter));
  8394. }
  8395. if (countEl) countEl.innerText = list.length;
  8396. const selId = state.selectedOspfRow?.['area-ranges'];
  8397. tbody.innerHTML = list.map((r, idx) => {
  8398. const isSel = r.id === selId;
  8399. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  8400. const flagD = r.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  8401. return `
  8402. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('ranges', '${r.id}')" ondblclick="openEditOspfAreaRangeModal('${r.id}')">
  8403. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  8404. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🏷'}</td>
  8405. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(r.comment || '')}</td>
  8406. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(r.area || 'Default')}</td>
  8407. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(r.prefix || '')}</td>
  8408. <td class="py-1.5 px-3">${r.cost || 1}</td>
  8409. <td class="py-1.5 px-3">${r.advertise !== false ? 'yes' : 'no'}</td>
  8410. </tr>
  8411. `;
  8412. }).join('');
  8413. }
  8414. // TAB 4: INTERFACE TEMPLATES
  8415. function renderOspfTemplates() {
  8416. const tbody = document.getElementById('ospf-templates-table-body');
  8417. if (!tbody) return;
  8418. const countEl = document.getElementById('ospf-templates-footer-count');
  8419. const filter = (document.getElementById('filter-ospf-templates')?.value || '').toLowerCase();
  8420. let list = state.ospfTemplates || [];
  8421. if (filter) {
  8422. list = list.filter(t => (t.interfaces || t.interface || '').toLowerCase().includes(filter) || (t.networks || t.network || '').toLowerCase().includes(filter) || (t.comment || '').toLowerCase().includes(filter));
  8423. }
  8424. if (countEl) countEl.innerText = list.length;
  8425. const selId = state.selectedOspfRow?.templates;
  8426. tbody.innerHTML = list.map((t, idx) => {
  8427. const isSel = t.id === selId;
  8428. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  8429. const ifaces = t.interfaces || t.interface || 'all';
  8430. const nets = t.networks || t.network || '';
  8431. const flagD = t.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  8432. return `
  8433. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('templates', '${t.id}')" ondblclick="openEditOspfTemplateModal('${t.id}')">
  8434. <td class="py-1.5 px-3 w-8 text-center text-slate-500 font-bold">${idx}</td>
  8435. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🔀'}</td>
  8436. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(t.comment || '')}</td>
  8437. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  8438. <span class="text-sky-400">↳</span> <span>${escapeHtml(ifaces)}</span>
  8439. </td>
  8440. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(t.area || 'Default')}</td>
  8441. <td class="py-1.5 px-3 font-mono text-sky-300">${escapeHtml(nets)}</td>
  8442. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(t.network_type || 'broadcast')}</td>
  8443. <td class="py-1.5 px-3">${t.cost || 1}</td>
  8444. <td class="py-1.5 px-3">${t.priority || 128}</td>
  8445. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(t.auth || t.auth_type || '')}</td>
  8446. </tr>
  8447. `;
  8448. }).join('');
  8449. }
  8450. // TAB 5: LIVE INTERFACES
  8451. function renderOspfLiveInterfaces() {
  8452. const tbody = document.getElementById('ospf-live-interfaces-table-body');
  8453. if (!tbody) return;
  8454. const countEl = document.getElementById('ospf-live-interfaces-footer-count');
  8455. const filter = (document.getElementById('filter-ospf-interfaces')?.value || '').toLowerCase();
  8456. let list = state.ospfLiveInterfaces || [];
  8457. if (filter) {
  8458. list = list.filter(i => (i.interface || '').toLowerCase().includes(filter) || (i.address || '').toLowerCase().includes(filter) || (i.state || '').toLowerCase().includes(filter));
  8459. }
  8460. if (countEl) countEl.innerText = list.length;
  8461. tbody.innerHTML = list.map(i => `
  8462. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  8463. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(i.flags || 'D')}</td>
  8464. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(i.interface || '')}</td>
  8465. <td class="py-1.5 px-3 font-mono text-sky-300 font-medium">${escapeHtml(i.address || '')}</td>
  8466. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(i.area || 'Default')}</td>
  8467. <td class="py-1.5 px-3 text-center text-slate-400">${i.instance_id || 0}</td>
  8468. <td class="py-1.5 px-3 font-mono text-amber-300 lowercase">${escapeHtml(i.state || 'waiting')}</td>
  8469. <td class="py-1.5 px-3">${i.cost || 1}</td>
  8470. <td class="py-1.5 px-3">${i.priority || 128}</td>
  8471. </tr>
  8472. `).join('');
  8473. }
  8474. // TAB 6: STATIC NEIGHBORS
  8475. function renderOspfStaticNbrs() {
  8476. const tbody = document.getElementById('ospf-snbrs-table-body');
  8477. if (!tbody) return;
  8478. const countEl = document.getElementById('ospf-snbrs-footer-count');
  8479. const filter = (document.getElementById('filter-ospf-static-nbrs')?.value || '').toLowerCase();
  8480. let list = state.ospfStaticNbrs || [];
  8481. if (filter) {
  8482. list = list.filter(n => (n.address || '').toLowerCase().includes(filter) || (n.area || '').toLowerCase().includes(filter) || (n.comment || '').toLowerCase().includes(filter));
  8483. }
  8484. if (countEl) countEl.innerText = list.length;
  8485. const selId = state.selectedOspfRow?.['static-nbrs'];
  8486. tbody.innerHTML = list.map((n, idx) => {
  8487. const isSel = n.id === selId;
  8488. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  8489. const flagD = n.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  8490. return `
  8491. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('snbrs', '${n.id}')" ondblclick="openEditOspfStaticNbrModal('${n.id}')">
  8492. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  8493. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '📡'}</td>
  8494. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(n.comment || '')}</td>
  8495. <td class="py-1.5 px-3 font-semibold font-mono text-sky-300">${escapeHtml(n.address || '')}</td>
  8496. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(n.area || 'Default')}</td>
  8497. <td class="py-1.5 px-3">${n.poll_interval || 120}s</td>
  8498. <td class="py-1.5 px-3">${n.cost || 1}</td>
  8499. </tr>
  8500. `;
  8501. }).join('');
  8502. }
  8503. // TAB 7: LIVE NEIGHBORS
  8504. function renderOspfNeighbors() {
  8505. const tbody = document.getElementById('ospf-neighbors-table-body');
  8506. if (!tbody) return;
  8507. const countEl = document.getElementById('ospf-neighbors-footer-count');
  8508. const filter = (document.getElementById('filter-ospf-neighbors')?.value || '').toLowerCase();
  8509. let list = state.ospfNeighbors || [];
  8510. if (filter) {
  8511. list = list.filter(n => (n.address || '').toLowerCase().includes(filter) || (n.state || '').toLowerCase().includes(filter) || (n.instance || '').toLowerCase().includes(filter));
  8512. }
  8513. if (countEl) countEl.innerText = list.length;
  8514. tbody.innerHTML = list.map(n => `
  8515. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  8516. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(n.flags || 'D')}</td>
  8517. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(n.comment || '')}</td>
  8518. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  8519. <span class="text-sky-400">↳</span> <span>${escapeHtml(n.instance || 'Default')}</span>
  8520. </td>
  8521. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(n.area || 'Default')}</td>
  8522. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(n.address || '')}</td>
  8523. <td class="py-1.5 px-3 font-mono font-bold text-emerald-400">${escapeHtml(n.state || 'Full')}</td>
  8524. <td class="py-1.5 px-3 text-slate-400">${n.state_changes ?? 6}</td>
  8525. </tr>
  8526. `).join('');
  8527. }
  8528. // TAB 8: LINK-STATE DATABASE (LSA)
  8529. function renderOspfLSA() {
  8530. const tbody = document.getElementById('ospf-lsa-table-body');
  8531. if (!tbody) return;
  8532. const countEl = document.getElementById('ospf-lsa-footer-count');
  8533. const filter = (document.getElementById('filter-ospf-lsa')?.value || '').toLowerCase();
  8534. let list = state.ospfLSA || [];
  8535. if (filter) {
  8536. list = list.filter(l => (l.type || '').toLowerCase().includes(filter) || (l.originator || '').toLowerCase().includes(filter) || (l.id || '').toLowerCase().includes(filter));
  8537. }
  8538. if (countEl) countEl.innerText = list.length;
  8539. tbody.innerHTML = list.map(l => `
  8540. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  8541. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(l.flags || 'D')}</td>
  8542. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  8543. <span class="text-sky-400">↳</span> <span>${escapeHtml(l.instance || 'Default')}</span>
  8544. </td>
  8545. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(l.area || 'Default')}</td>
  8546. <td class="py-1.5 px-3 font-mono text-amber-300">${escapeHtml(l.type || 'router')}</td>
  8547. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(l.originator || '')}</td>
  8548. <td class="py-1.5 px-3 font-mono text-sky-300 font-medium">${escapeHtml(l.id || '')}</td>
  8549. <td class="py-1.5 px-3 text-slate-500">${escapeHtml(l.link || '')}</td>
  8550. <td class="py-1.5 px-3 text-slate-500">${l.link_index ?? 0}</td>
  8551. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(l.sequence || '')}</td>
  8552. <td class="py-1.5 px-3 text-slate-400">${l.age ?? 0}</td>
  8553. </tr>
  8554. `).join('');
  8555. }
  8556. function renderOspfStatusPill() {
  8557. // Maintained for backward compatibility
  8558. const pill = document.getElementById('ospf-live-status-pill');
  8559. if (!pill) return;
  8560. 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';
  8561. pill.innerText = 'OSPF ACTIVE';
  8562. }
  8563. function renderOspfInterfaces() {
  8564. renderOspfTemplates();
  8565. }
  8566. function renderOspfRoutes() {
  8567. // Routes retained in background
  8568. }
  8569. // BGP Modals & Actions
  8570. function openBgpInstanceModal() {
  8571. const inst = state.bgpInstance || { enabled: false, as: 65001, router_id: '192.168.131.56', hold_time: 180, keepalive_time: 60 };
  8572. document.getElementById('modal-bgp-enabled').checked = !!inst.enabled;
  8573. document.getElementById('modal-bgp-as').value = inst.as || 65001;
  8574. document.getElementById('modal-bgp-router-id').value = inst.router_id || '';
  8575. document.getElementById('modal-bgp-keepalive').value = inst.keepalive_time || 60;
  8576. document.getElementById('modal-bgp-holdtime').value = inst.hold_time || 180;
  8577. document.getElementById('modal-bgp-redist-conn').checked = !!inst.redistribute_connected;
  8578. document.getElementById('modal-bgp-redist-static').checked = !!inst.redistribute_static;
  8579. document.getElementById('modal-bgp-redist-ospf').checked = !!inst.redistribute_ospf;
  8580. document.getElementById('bgp-instance-modal').classList.remove('hidden');
  8581. }
  8582. function closeBgpInstanceModal() {
  8583. document.getElementById('bgp-instance-modal').classList.add('hidden');
  8584. }
  8585. async function submitBgpInstance(e) {
  8586. e.preventDefault();
  8587. const payload = {
  8588. enabled: document.getElementById('modal-bgp-enabled').checked,
  8589. as: parseInt(document.getElementById('modal-bgp-as').value, 10),
  8590. router_id: document.getElementById('modal-bgp-router-id').value.trim(),
  8591. keepalive_time: parseInt(document.getElementById('modal-bgp-keepalive').value, 10),
  8592. hold_time: parseInt(document.getElementById('modal-bgp-holdtime').value, 10),
  8593. redistribute_connected: document.getElementById('modal-bgp-redist-conn').checked,
  8594. redistribute_static: document.getElementById('modal-bgp-redist-static').checked,
  8595. redistribute_ospf: document.getElementById('modal-bgp-redist-ospf').checked
  8596. };
  8597. try {
  8598. const res = await fetch(`${API_BASE}/routing/bgp/instance`, {
  8599. method: 'POST',
  8600. headers: { 'Content-Type': 'application/json' },
  8601. body: JSON.stringify(payload)
  8602. });
  8603. if (res.ok) {
  8604. closeBgpInstanceModal();
  8605. showToast('Success', 'BGP instance configuration updated', 'success');
  8606. loadDynamicRouting();
  8607. } else {
  8608. const err = await res.json();
  8609. showToast('Error', err.error || 'Failed to update BGP instance', 'error');
  8610. }
  8611. } catch (err) {
  8612. showToast('Error', err.message, 'error');
  8613. }
  8614. }
  8615. // ----------------- BGP Peer Connection Modal (DebTik v7) -----------------
  8616. function switchBgpPeerModalTab(tab) {
  8617. const tabs = ['general', 'extra', 'attributes', 'filter'];
  8618. tabs.forEach(t => {
  8619. const pane = document.getElementById(`bgp-peer-tab-${t}`);
  8620. const btn = document.getElementById(`bgp-peer-tab-btn-${t}`);
  8621. if (t === tab) {
  8622. if (pane) pane.classList.remove('hidden');
  8623. if (btn) btn.className = 'px-4 py-2 text-xs font-bold border-b-2 border-cyan-500 text-white transition';
  8624. } else {
  8625. if (pane) pane.classList.add('hidden');
  8626. 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';
  8627. }
  8628. });
  8629. }
  8630. function addOutputNetworkRow(val = '') {
  8631. const container = document.getElementById('modal-bgp-output-networks-container');
  8632. if (!container) return;
  8633. const row = document.createElement('div');
  8634. row.className = 'flex items-center gap-2 output-net-row';
  8635. row.innerHTML = `
  8636. <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">
  8637. <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>
  8638. `;
  8639. container.appendChild(row);
  8640. }
  8641. function parseBgpTime(val) {
  8642. if (!val) return 0;
  8643. val = String(val).trim();
  8644. if (val.includes(':')) {
  8645. const parts = val.split(':').map(x => parseInt(x, 10) || 0);
  8646. if (parts.length === 3) return parts[0] * 3600 + parts[1] * 60 + parts[2];
  8647. if (parts.length === 2) return parts[0] * 60 + parts[1];
  8648. }
  8649. return parseInt(val, 10) || 0;
  8650. }
  8651. function formatBgpTime(secs) {
  8652. if (!secs || secs <= 0) return '00:00:00';
  8653. const h = Math.floor(secs / 3600);
  8654. const m = Math.floor((secs % 3600) / 60);
  8655. const s = secs % 60;
  8656. return `${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`;
  8657. }
  8658. function populateBgpRoutingTables() {
  8659. const sel = document.getElementById('modal-bgp-peer-routing-table');
  8660. if (!sel) return;
  8661. const cur = sel.value || 'main';
  8662. sel.innerHTML = '<option value="main">main</option>';
  8663. (state.routingTables || []).forEach(t => {
  8664. if (t.name !== 'main') {
  8665. const opt = document.createElement('option');
  8666. opt.value = t.name;
  8667. opt.innerText = t.name;
  8668. sel.appendChild(opt);
  8669. }
  8670. });
  8671. sel.value = cur;
  8672. }
  8673. function openAddBgpPeerModal() {
  8674. document.getElementById('bgp-peer-form').reset();
  8675. document.getElementById('modal-bgp-peer-id').value = '';
  8676. document.getElementById('bgp-peer-modal-title').innerText = 'New...';
  8677. // General Tab
  8678. document.getElementById('modal-bgp-peer-enabled').checked = true;
  8679. document.getElementById('modal-bgp-peer-comment').value = '';
  8680. document.getElementById('modal-bgp-peer-name').value = '';
  8681. if (document.getElementById('modal-bgp-peer-instance')) document.getElementById('modal-bgp-peer-instance').value = 'bgp-instance-1';
  8682. if (document.getElementById('modal-bgp-peer-template')) document.getElementById('modal-bgp-peer-template').value = '';
  8683. document.getElementById('modal-bgp-peer-local-as').value = '';
  8684. document.getElementById('modal-bgp-peer-afi-ip').checked = true;
  8685. document.getElementById('modal-bgp-peer-afi-ipv6').checked = false;
  8686. if (document.getElementById('modal-bgp-peer-afi-l2vpn')) document.getElementById('modal-bgp-peer-afi-l2vpn').checked = false;
  8687. if (document.getElementById('modal-bgp-peer-afi-vpnv4')) document.getElementById('modal-bgp-peer-afi-vpnv4').checked = false;
  8688. if (document.getElementById('modal-bgp-peer-afi-l2vpn-cisco')) document.getElementById('modal-bgp-peer-afi-l2vpn-cisco').checked = false;
  8689. document.getElementById('modal-bgp-peer-router-id').value = '';
  8690. document.getElementById('modal-bgp-peer-remote-addr').value = '';
  8691. document.getElementById('modal-bgp-peer-remote-port').value = '';
  8692. document.getElementById('modal-bgp-peer-remote-as').value = '';
  8693. if (document.getElementById('modal-bgp-peer-remote-allow-as')) document.getElementById('modal-bgp-peer-remote-allow-as').value = '';
  8694. document.getElementById('modal-bgp-peer-local-addr').value = '';
  8695. document.getElementById('modal-bgp-peer-local-port').value = '';
  8696. document.getElementById('modal-bgp-peer-local-role').value = 'ebgp';
  8697. document.getElementById('modal-bgp-peer-password').value = '';
  8698. document.getElementById('modal-bgp-peer-multihop').checked = false;
  8699. if (document.getElementById('modal-bgp-peer-tx-ttl')) document.getElementById('modal-bgp-peer-tx-ttl').value = '';
  8700. if (document.getElementById('modal-bgp-peer-rx-min-ttl')) document.getElementById('modal-bgp-peer-rx-min-ttl').value = '';
  8701. document.getElementById('modal-bgp-peer-connect').checked = true;
  8702. document.getElementById('modal-bgp-peer-listen').checked = true;
  8703. // Extra Tab
  8704. document.getElementById('modal-bgp-peer-holdtime').value = '00:00:30';
  8705. document.getElementById('modal-bgp-peer-keepalive').value = '00:00:10';
  8706. if (document.getElementById('modal-bgp-peer-use-bfd')) document.getElementById('modal-bgp-peer-use-bfd').checked = false;
  8707. if (document.getElementById('modal-bgp-peer-vrf')) document.getElementById('modal-bgp-peer-vrf').value = 'main';
  8708. if (document.getElementById('modal-bgp-peer-no-client-reflect')) document.getElementById('modal-bgp-peer-no-client-reflect').checked = true;
  8709. document.getElementById('modal-bgp-peer-redist-conn').checked = false;
  8710. document.getElementById('modal-bgp-peer-redist-static').checked = true;
  8711. if (document.getElementById('modal-bgp-peer-redist-rip')) document.getElementById('modal-bgp-peer-redist-rip').checked = false;
  8712. document.getElementById('modal-bgp-peer-redist-ospf').checked = false;
  8713. document.getElementById('modal-bgp-peer-redist-bgp').checked = false;
  8714. if (document.getElementById('modal-bgp-peer-redist-vpn')) document.getElementById('modal-bgp-peer-redist-vpn').checked = false;
  8715. if (document.getElementById('modal-bgp-peer-redist-dhcp')) document.getElementById('modal-bgp-peer-redist-dhcp').checked = false;
  8716. if (document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn')) document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn').checked = false;
  8717. if (document.getElementById('modal-bgp-peer-redist-slaac')) document.getElementById('modal-bgp-peer-redist-slaac').checked = false;
  8718. document.getElementById('modal-bgp-peer-default-orig').checked = false;
  8719. if (document.getElementById('modal-bgp-peer-network-blackhole')) document.getElementById('modal-bgp-peer-network-blackhole').checked = false;
  8720. if (document.getElementById('modal-bgp-peer-no-early-cut')) document.getElementById('modal-bgp-peer-no-early-cut').checked = false;
  8721. if (document.getElementById('modal-bgp-peer-keep-sent-attrs')) document.getElementById('modal-bgp-peer-keep-sent-attrs').checked = false;
  8722. if (document.getElementById('modal-bgp-peer-input-affinity')) document.getElementById('modal-bgp-peer-input-affinity').value = '';
  8723. if (document.getElementById('modal-bgp-peer-output-affinity')) document.getElementById('modal-bgp-peer-output-affinity').value = '';
  8724. // Attributes Tab
  8725. document.getElementById('modal-bgp-peer-nexthop-choice').value = 'force-self';
  8726. document.getElementById('modal-bgp-peer-default-prepend').value = 0;
  8727. document.getElementById('modal-bgp-peer-allow-as-in').value = 0;
  8728. if (document.getElementById('modal-bgp-peer-ignore-as-path-len')) document.getElementById('modal-bgp-peer-ignore-as-path-len').checked = false;
  8729. document.getElementById('modal-bgp-peer-remove-priv-as').checked = false;
  8730. document.getElementById('modal-bgp-peer-as-override').checked = false;
  8731. // Filter Tab
  8732. populateFilterChainsDatalist();
  8733. document.getElementById('modal-bgp-peer-in-filter').value = '';
  8734. if (document.getElementById('modal-bgp-peer-in-accept-nlri')) document.getElementById('modal-bgp-peer-in-accept-nlri').value = '';
  8735. if (document.getElementById('modal-bgp-peer-in-accept-comm')) document.getElementById('modal-bgp-peer-in-accept-comm').value = '';
  8736. if (document.getElementById('modal-bgp-peer-in-accept-ext-comm')) document.getElementById('modal-bgp-peer-in-accept-ext-comm').value = '';
  8737. if (document.getElementById('modal-bgp-peer-in-accept-large-comm')) document.getElementById('modal-bgp-peer-in-accept-large-comm').value = '';
  8738. if (document.getElementById('modal-bgp-peer-in-filter-comm')) document.getElementById('modal-bgp-peer-in-filter-comm').value = '';
  8739. if (document.getElementById('modal-bgp-peer-in-filter-ext-comm')) document.getElementById('modal-bgp-peer-in-filter-ext-comm').value = '';
  8740. if (document.getElementById('modal-bgp-peer-in-filter-large-comm')) document.getElementById('modal-bgp-peer-in-filter-large-comm').value = '';
  8741. if (document.getElementById('modal-bgp-peer-in-filter-unknown')) document.getElementById('modal-bgp-peer-in-filter-unknown').checked = false;
  8742. document.getElementById('modal-bgp-peer-out-filter').value = '';
  8743. if (document.getElementById('modal-bgp-peer-out-selection-policy')) document.getElementById('modal-bgp-peer-out-selection-policy').value = 'disabled';
  8744. if (document.getElementById('modal-bgp-peer-out-network-name')) document.getElementById('modal-bgp-peer-out-network-name').value = '';
  8745. populateBgpRoutingTables();
  8746. const container = document.getElementById('modal-bgp-output-networks-container');
  8747. if (container) {
  8748. container.innerHTML = '';
  8749. addOutputNetworkRow('');
  8750. }
  8751. const removeBtn = document.getElementById('modal-btn-remove-peer');
  8752. if (removeBtn) removeBtn.classList.add('hidden');
  8753. switchBgpPeerModalTab('general');
  8754. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  8755. }
  8756. function populateFilterChainsDatalist() {
  8757. const dl = document.getElementById('filter-chains-list');
  8758. if (!dl) return;
  8759. const chains = new Set();
  8760. (state.routingFilters || []).forEach(f => {
  8761. if (f.chain) chains.add(f.chain);
  8762. });
  8763. if (chains.size === 0) {
  8764. chains.add('awmn');
  8765. chains.add('bgp-in');
  8766. chains.add('bgp-out');
  8767. }
  8768. dl.innerHTML = '';
  8769. chains.forEach(c => {
  8770. const opt = document.createElement('option');
  8771. opt.value = c;
  8772. dl.appendChild(opt);
  8773. });
  8774. }
  8775. function openEditBgpPeerModal(id) {
  8776. const p = (state.bgpPeers || []).find(item => item.id === id);
  8777. if (!p) return;
  8778. populateBgpRoutingTables();
  8779. populateFilterChainsDatalist();
  8780. document.getElementById('modal-bgp-peer-id').value = p.id;
  8781. document.getElementById('bgp-peer-modal-title').innerText = p.name || p.id;
  8782. // General Tab
  8783. document.getElementById('modal-bgp-peer-enabled').checked = p.enabled !== false && !p.disabled;
  8784. document.getElementById('modal-bgp-peer-comment').value = p.comment || '';
  8785. document.getElementById('modal-bgp-peer-name').value = p.name || '';
  8786. if (document.getElementById('modal-bgp-peer-instance')) document.getElementById('modal-bgp-peer-instance').value = p.instance || 'bgp-instance-1';
  8787. if (document.getElementById('modal-bgp-peer-template')) document.getElementById('modal-bgp-peer-template').value = p.template || '';
  8788. document.getElementById('modal-bgp-peer-local-as').value = p.local_as || '';
  8789. document.getElementById('modal-bgp-peer-router-id').value = p.router_id || '';
  8790. document.getElementById('modal-bgp-peer-afi-ip').checked = true;
  8791. document.getElementById('modal-bgp-peer-afi-ipv6').checked = p.afi === 'ipv6';
  8792. document.getElementById('modal-bgp-peer-remote-addr').value = p.remote_address || '';
  8793. document.getElementById('modal-bgp-peer-remote-port').value = p.remote_port || '';
  8794. document.getElementById('modal-bgp-peer-remote-as').value = p.remote_as || '';
  8795. if (document.getElementById('modal-bgp-peer-remote-allow-as')) document.getElementById('modal-bgp-peer-remote-allow-as').value = p.remote_allow_as || '';
  8796. document.getElementById('modal-bgp-peer-local-addr').value = p.local_address || '';
  8797. document.getElementById('modal-bgp-peer-local-port').value = p.local_port || '';
  8798. document.getElementById('modal-bgp-peer-local-role').value = p.local_role || 'ebgp';
  8799. document.getElementById('modal-bgp-peer-password').value = p.password || '';
  8800. document.getElementById('modal-bgp-peer-multihop').checked = !!p.multihop;
  8801. if (document.getElementById('modal-bgp-peer-tx-ttl')) document.getElementById('modal-bgp-peer-tx-ttl').value = p.tx_ttl || '';
  8802. if (document.getElementById('modal-bgp-peer-rx-min-ttl')) document.getElementById('modal-bgp-peer-rx-min-ttl').value = p.rx_min_ttl || '';
  8803. document.getElementById('modal-bgp-peer-connect').checked = p.connect !== false;
  8804. document.getElementById('modal-bgp-peer-listen').checked = p.listen !== false;
  8805. // Extra Tab
  8806. document.getElementById('modal-bgp-peer-holdtime').value = p.hold_time ? formatBgpTime(p.hold_time) : '00:00:30';
  8807. document.getElementById('modal-bgp-peer-keepalive').value = p.keepalive_time ? formatBgpTime(p.keepalive_time) : '00:00:10';
  8808. if (document.getElementById('modal-bgp-peer-use-bfd')) document.getElementById('modal-bgp-peer-use-bfd').checked = !!p.use_bfd;
  8809. document.getElementById('modal-bgp-peer-routing-table').value = p.routing_table || 'main';
  8810. if (document.getElementById('modal-bgp-peer-vrf')) document.getElementById('modal-bgp-peer-vrf').value = p.vrf || 'main';
  8811. if (document.getElementById('modal-bgp-peer-no-client-reflect')) document.getElementById('modal-bgp-peer-no-client-reflect').checked = p.no_client_reflect !== false;
  8812. document.getElementById('modal-bgp-peer-redist-conn').checked = !!p.redist_connected;
  8813. document.getElementById('modal-bgp-peer-redist-static').checked = p.redist_static !== false;
  8814. if (document.getElementById('modal-bgp-peer-redist-rip')) document.getElementById('modal-bgp-peer-redist-rip').checked = !!p.redist_rip;
  8815. document.getElementById('modal-bgp-peer-redist-ospf').checked = !!p.redist_ospf;
  8816. document.getElementById('modal-bgp-peer-redist-bgp').checked = !!p.redist_bgp;
  8817. if (document.getElementById('modal-bgp-peer-redist-vpn')) document.getElementById('modal-bgp-peer-redist-vpn').checked = !!p.redist_vpn;
  8818. if (document.getElementById('modal-bgp-peer-redist-dhcp')) document.getElementById('modal-bgp-peer-redist-dhcp').checked = !!p.redist_dhcp;
  8819. 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;
  8820. if (document.getElementById('modal-bgp-peer-redist-slaac')) document.getElementById('modal-bgp-peer-redist-slaac').checked = !!p.redist_slaac;
  8821. document.getElementById('modal-bgp-peer-default-orig').checked = !!p.default_originate;
  8822. if (document.getElementById('modal-bgp-peer-network-blackhole')) document.getElementById('modal-bgp-peer-network-blackhole').checked = !!p.network_blackhole;
  8823. if (document.getElementById('modal-bgp-peer-no-early-cut')) document.getElementById('modal-bgp-peer-no-early-cut').checked = !!p.no_early_cut;
  8824. if (document.getElementById('modal-bgp-peer-keep-sent-attrs')) document.getElementById('modal-bgp-peer-keep-sent-attrs').checked = !!p.keep_sent_attrs;
  8825. if (document.getElementById('modal-bgp-peer-input-affinity')) document.getElementById('modal-bgp-peer-input-affinity').value = p.input_affinity || '';
  8826. if (document.getElementById('modal-bgp-peer-output-affinity')) document.getElementById('modal-bgp-peer-output-affinity').value = p.output_affinity || '';
  8827. // Attributes Tab
  8828. document.getElementById('modal-bgp-peer-nexthop-choice').value = p.nexthop_choice || (p.nexthop_self ? 'force-self' : 'default');
  8829. document.getElementById('modal-bgp-peer-default-prepend').value = p.default_prepend || 0;
  8830. document.getElementById('modal-bgp-peer-allow-as-in').value = p.allow_as_in || 0;
  8831. 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;
  8832. document.getElementById('modal-bgp-peer-remove-priv-as').checked = !!p.remove_private_as;
  8833. document.getElementById('modal-bgp-peer-as-override').checked = !!p.as_override;
  8834. // Filter Tab
  8835. document.getElementById('modal-bgp-peer-in-filter').value = p.in_filter || '';
  8836. if (document.getElementById('modal-bgp-peer-in-accept-nlri')) document.getElementById('modal-bgp-peer-in-accept-nlri').value = p.in_accept_nlri || '';
  8837. if (document.getElementById('modal-bgp-peer-in-accept-comm')) document.getElementById('modal-bgp-peer-in-accept-comm').value = p.in_accept_communities || '';
  8838. 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 || '';
  8839. 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 || '';
  8840. if (document.getElementById('modal-bgp-peer-in-filter-comm')) document.getElementById('modal-bgp-peer-in-filter-comm').value = p.in_filter_communities || '';
  8841. 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 || '';
  8842. 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 || '';
  8843. if (document.getElementById('modal-bgp-peer-in-filter-unknown')) document.getElementById('modal-bgp-peer-in-filter-unknown').checked = !!p.in_filter_unknown;
  8844. document.getElementById('modal-bgp-peer-out-filter').value = p.out_filter || '';
  8845. if (document.getElementById('modal-bgp-peer-out-selection-policy')) document.getElementById('modal-bgp-peer-out-selection-policy').value = p.out_selection_policy || 'disabled';
  8846. if (document.getElementById('modal-bgp-peer-out-network-name')) document.getElementById('modal-bgp-peer-out-network-name').value = p.output_network || '';
  8847. // Output Networks
  8848. const container = document.getElementById('modal-bgp-output-networks-container');
  8849. if (container) {
  8850. container.innerHTML = '';
  8851. if (p.output_networks && p.output_networks.length > 0) {
  8852. p.output_networks.forEach(net => addOutputNetworkRow(net));
  8853. } else {
  8854. addOutputNetworkRow('');
  8855. }
  8856. }
  8857. const removeBtn = document.getElementById('modal-btn-remove-peer');
  8858. if (removeBtn) removeBtn.classList.remove('hidden');
  8859. switchBgpPeerModalTab('general');
  8860. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  8861. }
  8862. function copyCurrentBgpPeer() {
  8863. document.getElementById('modal-bgp-peer-id').value = '';
  8864. const nameEl = document.getElementById('modal-bgp-peer-name');
  8865. if (nameEl) nameEl.value = (nameEl.value || 'peer') + '-copy';
  8866. document.getElementById('bgp-peer-modal-title').innerText = 'New...';
  8867. const removeBtn = document.getElementById('modal-btn-remove-peer');
  8868. if (removeBtn) removeBtn.classList.add('hidden');
  8869. showToast('Cloned', 'BGP connection copied to new draft', 'info');
  8870. }
  8871. function removeCurrentBgpPeer() {
  8872. const id = document.getElementById('modal-bgp-peer-id')?.value;
  8873. if (!id) return;
  8874. deleteBgpPeer(id);
  8875. closeBgpPeerModal();
  8876. }
  8877. function closeBgpPeerModal() {
  8878. document.getElementById('bgp-peer-modal').classList.add('hidden');
  8879. }
  8880. function getBgpPeerFormData() {
  8881. const netInputs = document.querySelectorAll('#modal-bgp-output-networks-container .output-net-row input');
  8882. const outputNetworks = [];
  8883. netInputs.forEach(inp => {
  8884. const v = inp.value.trim();
  8885. if (v) outputNetworks.push(v);
  8886. });
  8887. const enabled = document.getElementById('modal-bgp-peer-enabled').checked;
  8888. return {
  8889. id: document.getElementById('modal-bgp-peer-id').value,
  8890. name: document.getElementById('modal-bgp-peer-name').value.trim(),
  8891. enabled: enabled,
  8892. disabled: !enabled,
  8893. comment: document.getElementById('modal-bgp-peer-comment').value.trim(),
  8894. instance: document.getElementById('modal-bgp-peer-instance')?.value.trim() || 'bgp-instance-1',
  8895. template: document.getElementById('modal-bgp-peer-template')?.value.trim() || '',
  8896. local_as: parseInt(document.getElementById('modal-bgp-peer-local-as')?.value, 10) || 0,
  8897. router_id: document.getElementById('modal-bgp-peer-router-id').value.trim(),
  8898. afi: document.getElementById('modal-bgp-peer-afi-ipv6').checked ? 'ipv6' : 'ip',
  8899. remote_address: document.getElementById('modal-bgp-peer-remote-addr').value.trim(),
  8900. remote_port: parseInt(document.getElementById('modal-bgp-peer-remote-port').value, 10) || 0,
  8901. remote_as: parseInt(document.getElementById('modal-bgp-peer-remote-as').value, 10) || 0,
  8902. remote_allow_as: document.getElementById('modal-bgp-peer-remote-allow-as')?.value.trim() || '',
  8903. local_address: document.getElementById('modal-bgp-peer-local-addr').value.trim(),
  8904. local_port: parseInt(document.getElementById('modal-bgp-peer-local-port').value, 10) || 0,
  8905. local_role: document.getElementById('modal-bgp-peer-local-role').value,
  8906. password: document.getElementById('modal-bgp-peer-password').value,
  8907. multihop: document.getElementById('modal-bgp-peer-multihop').checked,
  8908. tx_ttl: parseInt(document.getElementById('modal-bgp-peer-tx-ttl')?.value, 10) || 0,
  8909. rx_min_ttl: parseInt(document.getElementById('modal-bgp-peer-rx-min-ttl')?.value, 10) || 0,
  8910. connect: document.getElementById('modal-bgp-peer-connect').checked,
  8911. listen: document.getElementById('modal-bgp-peer-listen').checked,
  8912. hold_time: parseBgpTime(document.getElementById('modal-bgp-peer-holdtime').value),
  8913. keepalive_time: parseBgpTime(document.getElementById('modal-bgp-peer-keepalive').value),
  8914. use_bfd: document.getElementById('modal-bgp-peer-use-bfd')?.checked || false,
  8915. routing_table: document.getElementById('modal-bgp-peer-routing-table').value,
  8916. vrf: document.getElementById('modal-bgp-peer-vrf')?.value.trim() || 'main',
  8917. no_client_reflect: document.getElementById('modal-bgp-peer-no-client-reflect')?.checked || false,
  8918. redist_connected: document.getElementById('modal-bgp-peer-redist-conn').checked,
  8919. redist_static: document.getElementById('modal-bgp-peer-redist-static').checked,
  8920. redist_rip: document.getElementById('modal-bgp-peer-redist-rip')?.checked || false,
  8921. redist_ospf: document.getElementById('modal-bgp-peer-redist-ospf').checked,
  8922. redist_bgp: document.getElementById('modal-bgp-peer-redist-bgp').checked,
  8923. redist_vpn: document.getElementById('modal-bgp-peer-redist-vpn')?.checked || false,
  8924. redist_dhcp: document.getElementById('modal-bgp-peer-redist-dhcp')?.checked || false,
  8925. redist_bgp_mpls_vpn: document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn')?.checked || false,
  8926. redist_slaac: document.getElementById('modal-bgp-peer-redist-slaac')?.checked || false,
  8927. default_originate: document.getElementById('modal-bgp-peer-default-orig').checked,
  8928. network_blackhole: document.getElementById('modal-bgp-peer-network-blackhole')?.checked || false,
  8929. no_early_cut: document.getElementById('modal-bgp-peer-no-early-cut')?.checked || false,
  8930. keep_sent_attrs: document.getElementById('modal-bgp-peer-keep-sent-attrs')?.checked || false,
  8931. input_affinity: (document.getElementById('modal-bgp-peer-input-affinity')?.value || '').trim(),
  8932. output_affinity: (document.getElementById('modal-bgp-peer-output-affinity')?.value || '').trim(),
  8933. nexthop_choice: document.getElementById('modal-bgp-peer-nexthop-choice').value,
  8934. nexthop_self: document.getElementById('modal-bgp-peer-nexthop-choice').value === 'force-self',
  8935. default_prepend: parseInt(document.getElementById('modal-bgp-peer-default-prepend').value, 10) || 0,
  8936. allow_as_in: parseInt(document.getElementById('modal-bgp-peer-allow-as-in').value, 10) || 0,
  8937. ignore_as_path_len: document.getElementById('modal-bgp-peer-ignore-as-path-len')?.checked || false,
  8938. remove_private_as: document.getElementById('modal-bgp-peer-remove-priv-as').checked,
  8939. as_override: document.getElementById('modal-bgp-peer-as-override').checked,
  8940. in_filter: (document.getElementById('modal-bgp-peer-in-filter')?.value || '').trim(),
  8941. in_accept_nlri: (document.getElementById('modal-bgp-peer-in-accept-nlri')?.value || '').trim(),
  8942. in_accept_communities: (document.getElementById('modal-bgp-peer-in-accept-comm')?.value || '').trim(),
  8943. in_accept_ext_communities: (document.getElementById('modal-bgp-peer-in-accept-ext-comm')?.value || '').trim(),
  8944. in_accept_large_communities: (document.getElementById('modal-bgp-peer-in-accept-large-comm')?.value || '').trim(),
  8945. in_filter_communities: (document.getElementById('modal-bgp-peer-in-filter-comm')?.value || '').trim(),
  8946. in_filter_ext_communities: (document.getElementById('modal-bgp-peer-in-filter-ext-comm')?.value || '').trim(),
  8947. in_filter_large_communities: (document.getElementById('modal-bgp-peer-in-filter-large-comm')?.value || '').trim(),
  8948. in_filter_unknown: document.getElementById('modal-bgp-peer-in-filter-unknown')?.checked || false,
  8949. out_filter: (document.getElementById('modal-bgp-peer-out-filter')?.value || '').trim(),
  8950. out_selection_policy: document.getElementById('modal-bgp-peer-out-selection-policy')?.value || 'disabled',
  8951. output_network: (document.getElementById('modal-bgp-peer-out-network-name')?.value || '').trim(),
  8952. output_networks: outputNetworks
  8953. };
  8954. }
  8955. async function submitBgpPeer(e) {
  8956. if (e) e.preventDefault();
  8957. const payload = getBgpPeerFormData();
  8958. try {
  8959. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  8960. method: 'POST',
  8961. headers: { 'Content-Type': 'application/json' },
  8962. body: JSON.stringify(payload)
  8963. });
  8964. if (res.ok) {
  8965. closeBgpPeerModal();
  8966. showToast('Success', 'BGP Connection saved', 'success');
  8967. loadDynamicRouting();
  8968. } else {
  8969. const err = await res.json();
  8970. showToast('Error', err.error || 'Failed to save peer', 'error');
  8971. }
  8972. } catch (err) {
  8973. showToast('Error', err.message, 'error');
  8974. }
  8975. }
  8976. async function applyBgpPeerModal(e) {
  8977. if (e) e.preventDefault();
  8978. const payload = getBgpPeerFormData();
  8979. try {
  8980. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  8981. method: 'POST',
  8982. headers: { 'Content-Type': 'application/json' },
  8983. body: JSON.stringify(payload)
  8984. });
  8985. if (res.ok) {
  8986. const data = await res.json();
  8987. if (data.peer && data.peer.id) {
  8988. document.getElementById('modal-bgp-peer-id').value = data.peer.id;
  8989. document.getElementById('bgp-peer-modal-title').innerText = data.peer.name || data.peer.id;
  8990. document.getElementById('modal-btn-remove-peer')?.classList.remove('hidden');
  8991. }
  8992. showToast('Applied', 'BGP Connection applied', 'success');
  8993. loadDynamicRouting();
  8994. } else {
  8995. const err = await res.json();
  8996. showToast('Error', err.error || 'Failed to apply peer', 'error');
  8997. }
  8998. } catch (err) {
  8999. showToast('Error', err.message, 'error');
  9000. }
  9001. }
  9002. async function deleteBgpPeer(id) {
  9003. if (!confirm('Are you sure you want to delete this BGP peer connection?')) return;
  9004. try {
  9005. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9006. if (res.ok) {
  9007. showToast('Deleted', 'BGP peer removed', 'success');
  9008. loadDynamicRouting();
  9009. }
  9010. } catch (err) {
  9011. showToast('Error', err.message, 'error');
  9012. }
  9013. }
  9014. async function toggleBgpPeerState(id, disabled) {
  9015. try {
  9016. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}/state`, {
  9017. method: 'POST',
  9018. headers: { 'Content-Type': 'application/json' },
  9019. body: JSON.stringify({ disabled })
  9020. });
  9021. if (res.ok) {
  9022. showToast('Updated', `Peer ${disabled ? 'disabled' : 'enabled'}`, 'success');
  9023. loadDynamicRouting();
  9024. }
  9025. } catch (err) {
  9026. showToast('Error', err.message, 'error');
  9027. }
  9028. }
  9029. function openAddBgpNetworkModal() {
  9030. document.getElementById('bgp-network-form').reset();
  9031. document.getElementById('modal-bgp-net-id').value = '';
  9032. document.getElementById('bgp-network-modal').classList.remove('hidden');
  9033. }
  9034. function closeBgpNetworkModal() {
  9035. document.getElementById('bgp-network-modal').classList.add('hidden');
  9036. }
  9037. async function submitBgpNetwork(e) {
  9038. e.preventDefault();
  9039. const payload = {
  9040. id: document.getElementById('modal-bgp-net-id').value,
  9041. network: document.getElementById('modal-bgp-net-cidr').value.trim(),
  9042. comment: document.getElementById('modal-bgp-net-comment').value.trim(),
  9043. disabled: document.getElementById('modal-bgp-net-disabled').checked
  9044. };
  9045. try {
  9046. const res = await fetch(`${API_BASE}/routing/bgp/networks`, {
  9047. method: 'POST',
  9048. headers: { 'Content-Type': 'application/json' },
  9049. body: JSON.stringify(payload)
  9050. });
  9051. if (res.ok) {
  9052. closeBgpNetworkModal();
  9053. showToast('Success', 'BGP network advertisement saved', 'success');
  9054. loadDynamicRouting();
  9055. } else {
  9056. const err = await res.json();
  9057. showToast('Error', err.error || 'Failed to save network', 'error');
  9058. }
  9059. } catch (err) {
  9060. showToast('Error', err.message, 'error');
  9061. }
  9062. }
  9063. async function deleteBgpNetwork(id) {
  9064. if (!confirm('Are you sure you want to stop announcing this network?')) return;
  9065. try {
  9066. const res = await fetch(`${API_BASE}/routing/bgp/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9067. if (res.ok) {
  9068. showToast('Deleted', 'Network advertisement removed', 'success');
  9069. loadDynamicRouting();
  9070. }
  9071. } catch (err) {
  9072. showToast('Error', err.message, 'error');
  9073. }
  9074. }
  9075. // =========================================================================
  9076. // DEBTIK v7 OSPF MODALS & ACTIONS
  9077. // =========================================================================
  9078. // --- 1. OSPF INSTANCE ---
  9079. function openOspfInstanceModal(id = null) {
  9080. const isEdit = !!id;
  9081. const inst = (state.ospfInstances || []).find(i => i.id === id) || {
  9082. id: '',
  9083. name: 'Default',
  9084. version: 2,
  9085. vrf: 'main',
  9086. router_id: '192.168.131.56',
  9087. routing_table: 'main',
  9088. enabled: true,
  9089. redistribute_connected: false,
  9090. redistribute_static: true,
  9091. redistribute_bgp: false,
  9092. comment: ''
  9093. };
  9094. document.getElementById('ospf-instance-modal-title').innerText = isEdit ? inst.name : 'New...';
  9095. document.getElementById('modal-ospf-inst-id').value = isEdit ? inst.id : '';
  9096. document.getElementById('modal-ospf-inst-enabled').checked = !inst.disabled;
  9097. document.getElementById('modal-ospf-inst-comment').value = inst.comment || '';
  9098. document.getElementById('modal-ospf-inst-name').value = inst.name || 'Default';
  9099. document.getElementById('modal-ospf-inst-version').value = inst.version || 2;
  9100. document.getElementById('modal-ospf-inst-vrf').value = inst.vrf || 'main';
  9101. document.getElementById('modal-ospf-inst-router-id').value = inst.router_id || '';
  9102. document.getElementById('modal-ospf-inst-routing-table').value = inst.routing_table || 'main';
  9103. document.getElementById('modal-ospf-inst-redist-conn').checked = !!inst.redistribute_connected;
  9104. document.getElementById('modal-ospf-inst-redist-static').checked = inst.redistribute_static !== false;
  9105. document.getElementById('modal-ospf-inst-redist-bgp').checked = !!inst.redistribute_bgp;
  9106. const btnRem = document.getElementById('btn-ospf-inst-modal-remove');
  9107. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  9108. document.getElementById('ospf-instance-modal').classList.remove('hidden');
  9109. }
  9110. function openEditOspfInstanceModal(id) {
  9111. openOspfInstanceModal(id);
  9112. }
  9113. function closeOspfInstanceModal() {
  9114. document.getElementById('ospf-instance-modal').classList.add('hidden');
  9115. }
  9116. async function submitOspfInstance(e) {
  9117. if (e) e.preventDefault();
  9118. const payload = {
  9119. id: document.getElementById('modal-ospf-inst-id').value,
  9120. name: document.getElementById('modal-ospf-inst-name').value.trim() || 'Default',
  9121. version: parseInt(document.getElementById('modal-ospf-inst-version').value, 10) || 2,
  9122. vrf: document.getElementById('modal-ospf-inst-vrf').value.trim() || 'main',
  9123. router_id: document.getElementById('modal-ospf-inst-router-id').value.trim(),
  9124. routing_table: document.getElementById('modal-ospf-inst-routing-table').value.trim() || 'main',
  9125. enabled: document.getElementById('modal-ospf-inst-enabled').checked,
  9126. disabled: !document.getElementById('modal-ospf-inst-enabled').checked,
  9127. comment: document.getElementById('modal-ospf-inst-comment').value.trim(),
  9128. redistribute_connected: document.getElementById('modal-ospf-inst-redist-conn').checked,
  9129. redistribute_static: document.getElementById('modal-ospf-inst-redist-static').checked,
  9130. redistribute_bgp: document.getElementById('modal-ospf-inst-redist-bgp').checked
  9131. };
  9132. try {
  9133. const res = await fetch(`${API_BASE}/routing/ospf/instances`, {
  9134. method: 'POST',
  9135. headers: { 'Content-Type': 'application/json' },
  9136. body: JSON.stringify(payload)
  9137. });
  9138. if (res.ok) {
  9139. closeOspfInstanceModal();
  9140. showToast('Saved', 'OSPF instance updated', 'success');
  9141. loadDynamicRouting();
  9142. } else {
  9143. const err = await res.json();
  9144. showToast('Error', err.error || 'Failed to save OSPF instance', 'error');
  9145. }
  9146. } catch (err) {
  9147. showToast('Error', err.message, 'error');
  9148. }
  9149. }
  9150. function applyOspfInstanceForm() {
  9151. submitOspfInstance(null);
  9152. }
  9153. function copyOspfInstance() {
  9154. document.getElementById('modal-ospf-inst-id').value = '';
  9155. document.getElementById('modal-ospf-inst-name').value += '-copy';
  9156. document.getElementById('ospf-instance-modal-title').innerText = 'New...';
  9157. showToast('Copied', 'Duplicated as new OSPF instance', 'info');
  9158. }
  9159. async function deleteCurrentOspfInstance() {
  9160. const id = document.getElementById('modal-ospf-inst-id').value;
  9161. if (!id) return;
  9162. if (!confirm('Are you sure you want to remove this OSPF instance?')) return;
  9163. try {
  9164. const res = await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9165. if (res.ok) {
  9166. closeOspfInstanceModal();
  9167. showToast('Removed', 'OSPF instance deleted', 'success');
  9168. loadDynamicRouting();
  9169. }
  9170. } catch (err) {
  9171. showToast('Error', err.message, 'error');
  9172. }
  9173. }
  9174. async function enableSelectedOspfInstance() {
  9175. const id = state.selectedOspfRow?.instances;
  9176. if (!id) return;
  9177. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}/state`, {
  9178. method: 'POST',
  9179. headers: { 'Content-Type': 'application/json' },
  9180. body: JSON.stringify({ disabled: false })
  9181. });
  9182. loadDynamicRouting();
  9183. }
  9184. async function disableSelectedOspfInstance() {
  9185. const id = state.selectedOspfRow?.instances;
  9186. if (!id) return;
  9187. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}/state`, {
  9188. method: 'POST',
  9189. headers: { 'Content-Type': 'application/json' },
  9190. body: JSON.stringify({ disabled: true })
  9191. });
  9192. loadDynamicRouting();
  9193. }
  9194. async function removeSelectedOspfInstance() {
  9195. const id = state.selectedOspfRow?.instances;
  9196. if (!id) return;
  9197. if (!confirm('Delete selected OSPF instance?')) return;
  9198. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9199. loadDynamicRouting();
  9200. }
  9201. async function promptCommentOspfInstance() {
  9202. const id = state.selectedOspfRow?.instances;
  9203. if (!id) return;
  9204. const inst = (state.ospfInstances || []).find(i => i.id === id);
  9205. if (!inst) return;
  9206. const comment = prompt('Enter comment for OSPF instance:', inst.comment || '');
  9207. if (comment === null) return;
  9208. inst.comment = comment;
  9209. await fetch(`${API_BASE}/routing/ospf/instances`, {
  9210. method: 'POST',
  9211. headers: { 'Content-Type': 'application/json' },
  9212. body: JSON.stringify(inst)
  9213. });
  9214. loadDynamicRouting();
  9215. }
  9216. // --- 2. OSPF AREA ---
  9217. function populateOspfAreaDropdowns() {
  9218. const instSelect = document.getElementById('modal-ospf-area-instance');
  9219. if (instSelect) {
  9220. const cur = instSelect.value;
  9221. instSelect.innerHTML = (state.ospfInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)}</option>`).join('');
  9222. if (instSelect.innerHTML === '') instSelect.innerHTML = '<option value="Default">Default</option>';
  9223. if (cur) instSelect.value = cur;
  9224. }
  9225. }
  9226. function openOspfAreaModal(id = null) {
  9227. const isEdit = !!id;
  9228. populateOspfAreaDropdowns();
  9229. const area = (state.ospfAreas || []).find(a => a.id === id) || {
  9230. id: '',
  9231. name: 'Default',
  9232. instance: 'Default',
  9233. area_id: '0.0.0.0',
  9234. area_type: 'default',
  9235. default_cost: 1,
  9236. no_summaries: false,
  9237. disabled: false,
  9238. comment: ''
  9239. };
  9240. document.getElementById('ospf-area-modal-title').innerText = isEdit ? area.name : 'New...';
  9241. document.getElementById('modal-ospf-area-id').value = isEdit ? area.id : '';
  9242. document.getElementById('modal-ospf-area-enabled').checked = !area.disabled;
  9243. document.getElementById('modal-ospf-area-comment').value = area.comment || '';
  9244. document.getElementById('modal-ospf-area-name').value = area.name || 'Default';
  9245. document.getElementById('modal-ospf-area-instance').value = area.instance || 'Default';
  9246. document.getElementById('modal-ospf-area-areaid').value = area.area_id || '0.0.0.0';
  9247. document.getElementById('modal-ospf-area-type').value = area.area_type || 'default';
  9248. document.getElementById('modal-ospf-area-default-cost').value = area.default_cost || 1;
  9249. document.getElementById('modal-ospf-area-no-summaries').checked = !!area.no_summaries;
  9250. const btnRem = document.getElementById('btn-ospf-area-modal-remove');
  9251. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  9252. document.getElementById('ospf-area-modal').classList.remove('hidden');
  9253. }
  9254. function openEditOspfAreaModal(id) {
  9255. openOspfAreaModal(id);
  9256. }
  9257. function closeOspfAreaModal() {
  9258. document.getElementById('ospf-area-modal').classList.add('hidden');
  9259. }
  9260. async function submitOspfArea(e) {
  9261. if (e) e.preventDefault();
  9262. const payload = {
  9263. id: document.getElementById('modal-ospf-area-id').value,
  9264. name: document.getElementById('modal-ospf-area-name').value.trim() || 'Default',
  9265. instance: document.getElementById('modal-ospf-area-instance').value.trim() || 'Default',
  9266. area_id: document.getElementById('modal-ospf-area-areaid').value.trim() || '0.0.0.0',
  9267. area_type: document.getElementById('modal-ospf-area-type').value,
  9268. default_cost: parseInt(document.getElementById('modal-ospf-area-default-cost').value, 10) || 1,
  9269. no_summaries: document.getElementById('modal-ospf-area-no-summaries').checked,
  9270. disabled: !document.getElementById('modal-ospf-area-enabled').checked,
  9271. comment: document.getElementById('modal-ospf-area-comment').value.trim()
  9272. };
  9273. try {
  9274. const res = await fetch(`${API_BASE}/routing/ospf/areas`, {
  9275. method: 'POST',
  9276. headers: { 'Content-Type': 'application/json' },
  9277. body: JSON.stringify(payload)
  9278. });
  9279. if (res.ok) {
  9280. closeOspfAreaModal();
  9281. showToast('Saved', 'OSPF area saved', 'success');
  9282. loadDynamicRouting();
  9283. } else {
  9284. const err = await res.json();
  9285. showToast('Error', err.error || 'Failed to save area', 'error');
  9286. }
  9287. } catch (err) {
  9288. showToast('Error', err.message, 'error');
  9289. }
  9290. }
  9291. function applyOspfAreaForm() {
  9292. submitOspfArea(null);
  9293. }
  9294. function copyOspfArea() {
  9295. document.getElementById('modal-ospf-area-id').value = '';
  9296. document.getElementById('modal-ospf-area-name').value += '-copy';
  9297. document.getElementById('ospf-area-modal-title').innerText = 'New...';
  9298. showToast('Copied', 'Duplicated as new OSPF area', 'info');
  9299. }
  9300. async function deleteCurrentOspfArea() {
  9301. const id = document.getElementById('modal-ospf-area-id').value;
  9302. if (!id) return;
  9303. if (!confirm('Are you sure you want to remove this OSPF area?')) return;
  9304. try {
  9305. const res = await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9306. if (res.ok) {
  9307. closeOspfAreaModal();
  9308. showToast('Removed', 'OSPF area deleted', 'success');
  9309. loadDynamicRouting();
  9310. }
  9311. } catch (err) {
  9312. showToast('Error', err.message, 'error');
  9313. }
  9314. }
  9315. async function enableSelectedOspfArea() {
  9316. const id = state.selectedOspfRow?.areas;
  9317. if (!id) return;
  9318. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}/state`, {
  9319. method: 'POST',
  9320. headers: { 'Content-Type': 'application/json' },
  9321. body: JSON.stringify({ disabled: false })
  9322. });
  9323. loadDynamicRouting();
  9324. }
  9325. async function disableSelectedOspfArea() {
  9326. const id = state.selectedOspfRow?.areas;
  9327. if (!id) return;
  9328. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}/state`, {
  9329. method: 'POST',
  9330. headers: { 'Content-Type': 'application/json' },
  9331. body: JSON.stringify({ disabled: true })
  9332. });
  9333. loadDynamicRouting();
  9334. }
  9335. async function removeSelectedOspfArea() {
  9336. const id = state.selectedOspfRow?.areas;
  9337. if (!id) return;
  9338. if (!confirm('Delete selected OSPF area?')) return;
  9339. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9340. loadDynamicRouting();
  9341. }
  9342. async function promptCommentOspfArea() {
  9343. const id = state.selectedOspfRow?.areas;
  9344. if (!id) return;
  9345. const area = (state.ospfAreas || []).find(a => a.id === id);
  9346. if (!area) return;
  9347. const comment = prompt('Enter comment for OSPF area:', area.comment || '');
  9348. if (comment === null) return;
  9349. area.comment = comment;
  9350. await fetch(`${API_BASE}/routing/ospf/areas`, {
  9351. method: 'POST',
  9352. headers: { 'Content-Type': 'application/json' },
  9353. body: JSON.stringify(area)
  9354. });
  9355. loadDynamicRouting();
  9356. }
  9357. // --- 3. OSPF AREA RANGE ---
  9358. function populateAreaRangeDropdowns() {
  9359. const select = document.getElementById('modal-ospf-range-area');
  9360. if (select) {
  9361. const cur = select.value;
  9362. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  9363. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  9364. if (cur) select.value = cur;
  9365. }
  9366. }
  9367. function openOspfAreaRangeModal(id = null) {
  9368. const isEdit = !!id;
  9369. populateAreaRangeDropdowns();
  9370. const r = (state.ospfAreaRanges || []).find(it => it.id === id) || {
  9371. id: '',
  9372. area: 'Default',
  9373. prefix: '',
  9374. cost: 1,
  9375. advertise: true,
  9376. disabled: false,
  9377. comment: ''
  9378. };
  9379. document.getElementById('ospf-area-range-modal-title').innerText = isEdit ? r.prefix : 'New...';
  9380. document.getElementById('modal-ospf-range-id').value = isEdit ? r.id : '';
  9381. document.getElementById('modal-ospf-range-enabled').checked = !r.disabled;
  9382. document.getElementById('modal-ospf-range-comment').value = r.comment || '';
  9383. document.getElementById('modal-ospf-range-area').value = r.area || 'Default';
  9384. document.getElementById('modal-ospf-range-prefix').value = r.prefix || '';
  9385. document.getElementById('modal-ospf-range-cost').value = r.cost || 1;
  9386. document.getElementById('modal-ospf-range-advertise').checked = r.advertise !== false;
  9387. const btnRem = document.getElementById('btn-ospf-range-modal-remove');
  9388. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  9389. document.getElementById('ospf-area-range-modal').classList.remove('hidden');
  9390. }
  9391. function openEditOspfAreaRangeModal(id) {
  9392. openOspfAreaRangeModal(id);
  9393. }
  9394. function closeOspfAreaRangeModal() {
  9395. document.getElementById('ospf-area-range-modal').classList.add('hidden');
  9396. }
  9397. async function submitOspfAreaRange(e) {
  9398. if (e) e.preventDefault();
  9399. const payload = {
  9400. id: document.getElementById('modal-ospf-range-id').value,
  9401. area: document.getElementById('modal-ospf-range-area').value,
  9402. prefix: document.getElementById('modal-ospf-range-prefix').value.trim(),
  9403. cost: parseInt(document.getElementById('modal-ospf-range-cost').value, 10) || 1,
  9404. advertise: document.getElementById('modal-ospf-range-advertise').checked,
  9405. disabled: !document.getElementById('modal-ospf-range-enabled').checked,
  9406. comment: document.getElementById('modal-ospf-range-comment').value.trim()
  9407. };
  9408. try {
  9409. const res = await fetch(`${API_BASE}/routing/ospf/area-ranges`, {
  9410. method: 'POST',
  9411. headers: { 'Content-Type': 'application/json' },
  9412. body: JSON.stringify(payload)
  9413. });
  9414. if (res.ok) {
  9415. closeOspfAreaRangeModal();
  9416. showToast('Saved', 'Area range saved', 'success');
  9417. loadDynamicRouting();
  9418. } else {
  9419. const err = await res.json();
  9420. showToast('Error', err.error || 'Failed to save area range', 'error');
  9421. }
  9422. } catch (err) {
  9423. showToast('Error', err.message, 'error');
  9424. }
  9425. }
  9426. function applyOspfAreaRangeForm() {
  9427. submitOspfAreaRange(null);
  9428. }
  9429. async function deleteCurrentOspfAreaRange() {
  9430. const id = document.getElementById('modal-ospf-range-id').value;
  9431. if (!id) return;
  9432. if (!confirm('Delete this area range?')) return;
  9433. try {
  9434. await fetch(`${API_BASE}/routing/ospf/area-ranges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9435. closeOspfAreaRangeModal();
  9436. showToast('Removed', 'Area range removed', 'success');
  9437. loadDynamicRouting();
  9438. } catch (err) {
  9439. showToast('Error', err.message, 'error');
  9440. }
  9441. }
  9442. async function enableSelectedOspfAreaRange() {
  9443. const id = state.selectedOspfRow?.['area-ranges'];
  9444. if (!id) return;
  9445. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  9446. if (!r) return;
  9447. r.disabled = false;
  9448. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  9449. loadDynamicRouting();
  9450. }
  9451. async function disableSelectedOspfAreaRange() {
  9452. const id = state.selectedOspfRow?.['area-ranges'];
  9453. if (!id) return;
  9454. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  9455. if (!r) return;
  9456. r.disabled = true;
  9457. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  9458. loadDynamicRouting();
  9459. }
  9460. async function removeSelectedOspfAreaRange() {
  9461. const id = state.selectedOspfRow?.['area-ranges'];
  9462. if (!id) return;
  9463. if (!confirm('Delete selected area range?')) return;
  9464. await fetch(`${API_BASE}/routing/ospf/area-ranges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9465. loadDynamicRouting();
  9466. }
  9467. async function promptCommentOspfAreaRange() {
  9468. const id = state.selectedOspfRow?.['area-ranges'];
  9469. if (!id) return;
  9470. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  9471. if (!r) return;
  9472. const comment = prompt('Enter comment for area range:', r.comment || '');
  9473. if (comment === null) return;
  9474. r.comment = comment;
  9475. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  9476. loadDynamicRouting();
  9477. }
  9478. // --- 4. OSPF INTERFACE TEMPLATE ---
  9479. function switchOspfTemplateTab(tab) {
  9480. const tabGen = document.getElementById('ospf-tmpl-tab-general');
  9481. const tabAuth = document.getElementById('ospf-tmpl-tab-auth');
  9482. const btnGen = document.getElementById('ospf-tmpl-tab-btn-general');
  9483. const btnAuth = document.getElementById('ospf-tmpl-tab-btn-auth');
  9484. if (tab === 'general') {
  9485. if (tabGen) tabGen.classList.remove('hidden');
  9486. if (tabAuth) tabAuth.classList.add('hidden');
  9487. if (btnGen) btnGen.className = 'px-4 py-2 text-xs font-bold border-b-2 border-sky-500 text-white transition';
  9488. 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';
  9489. } else {
  9490. if (tabGen) tabGen.classList.add('hidden');
  9491. if (tabAuth) tabAuth.classList.remove('hidden');
  9492. 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';
  9493. if (btnAuth) btnAuth.className = 'px-4 py-2 text-xs font-bold border-b-2 border-sky-500 text-white transition';
  9494. }
  9495. }
  9496. function populateTemplateAreaDropdowns() {
  9497. const select = document.getElementById('modal-ospf-tmpl-area');
  9498. if (select) {
  9499. const cur = select.value;
  9500. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  9501. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  9502. if (cur) select.value = cur;
  9503. }
  9504. }
  9505. function openOspfTemplateModal(id = null) {
  9506. const isEdit = !!id;
  9507. populateTemplateAreaDropdowns();
  9508. switchOspfTemplateTab('general');
  9509. const tmpl = (state.ospfTemplates || []).find(t => t.id === id) || {
  9510. id: '',
  9511. interfaces: '',
  9512. area: 'Default',
  9513. networks: '',
  9514. network_type: 'broadcast',
  9515. cost: 1,
  9516. priority: 128,
  9517. passive: false,
  9518. hello_interval: 10,
  9519. dead_interval: 40,
  9520. auth: 'none',
  9521. auth_key: '',
  9522. disabled: false,
  9523. comment: ''
  9524. };
  9525. document.getElementById('ospf-template-modal-title').innerText = isEdit ? (tmpl.interfaces || tmpl.networks || 'Template') : 'New...';
  9526. document.getElementById('modal-ospf-tmpl-id').value = isEdit ? tmpl.id : '';
  9527. document.getElementById('modal-ospf-tmpl-enabled').checked = !tmpl.disabled;
  9528. document.getElementById('modal-ospf-tmpl-comment').value = tmpl.comment || '';
  9529. document.getElementById('modal-ospf-tmpl-interfaces').value = tmpl.interfaces || tmpl.interface || '';
  9530. document.getElementById('modal-ospf-tmpl-area').value = tmpl.area || 'Default';
  9531. document.getElementById('modal-ospf-tmpl-networks').value = tmpl.networks || tmpl.network || '';
  9532. document.getElementById('modal-ospf-tmpl-net-type').value = tmpl.network_type || 'broadcast';
  9533. document.getElementById('modal-ospf-tmpl-cost').value = tmpl.cost || 1;
  9534. document.getElementById('modal-ospf-tmpl-priority').value = tmpl.priority || 128;
  9535. document.getElementById('modal-ospf-tmpl-passive').checked = !!tmpl.passive;
  9536. document.getElementById('modal-ospf-tmpl-hello').value = tmpl.hello_interval || 10;
  9537. document.getElementById('modal-ospf-tmpl-dead').value = tmpl.dead_interval || 40;
  9538. document.getElementById('modal-ospf-tmpl-auth').value = tmpl.auth || tmpl.auth_type || 'none';
  9539. document.getElementById('modal-ospf-tmpl-auth-key').value = tmpl.auth_key || '';
  9540. const btnRem = document.getElementById('btn-ospf-tmpl-modal-remove');
  9541. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  9542. document.getElementById('ospf-template-modal').classList.remove('hidden');
  9543. }
  9544. function openEditOspfTemplateModal(id) {
  9545. openOspfTemplateModal(id);
  9546. }
  9547. function closeOspfTemplateModal() {
  9548. document.getElementById('ospf-template-modal').classList.add('hidden');
  9549. }
  9550. async function submitOspfTemplate(e) {
  9551. if (e) e.preventDefault();
  9552. const payload = {
  9553. id: document.getElementById('modal-ospf-tmpl-id').value,
  9554. interfaces: document.getElementById('modal-ospf-tmpl-interfaces').value.trim(),
  9555. interface: document.getElementById('modal-ospf-tmpl-interfaces').value.trim(),
  9556. area: document.getElementById('modal-ospf-tmpl-area').value,
  9557. networks: document.getElementById('modal-ospf-tmpl-networks').value.trim(),
  9558. network: document.getElementById('modal-ospf-tmpl-networks').value.trim(),
  9559. network_type: document.getElementById('modal-ospf-tmpl-net-type').value,
  9560. cost: parseInt(document.getElementById('modal-ospf-tmpl-cost').value, 10) || 1,
  9561. priority: parseInt(document.getElementById('modal-ospf-tmpl-priority').value, 10) || 128,
  9562. passive: document.getElementById('modal-ospf-tmpl-passive').checked,
  9563. hello_interval: parseInt(document.getElementById('modal-ospf-tmpl-hello').value, 10) || 10,
  9564. dead_interval: parseInt(document.getElementById('modal-ospf-tmpl-dead').value, 10) || 40,
  9565. auth: document.getElementById('modal-ospf-tmpl-auth').value,
  9566. auth_type: document.getElementById('modal-ospf-tmpl-auth').value,
  9567. auth_key: document.getElementById('modal-ospf-tmpl-auth-key').value,
  9568. disabled: !document.getElementById('modal-ospf-tmpl-enabled').checked,
  9569. comment: document.getElementById('modal-ospf-tmpl-comment').value.trim()
  9570. };
  9571. try {
  9572. const res = await fetch(`${API_BASE}/routing/ospf/templates`, {
  9573. method: 'POST',
  9574. headers: { 'Content-Type': 'application/json' },
  9575. body: JSON.stringify(payload)
  9576. });
  9577. if (res.ok) {
  9578. closeOspfTemplateModal();
  9579. showToast('Saved', 'Interface template saved', 'success');
  9580. loadDynamicRouting();
  9581. } else {
  9582. const err = await res.json();
  9583. showToast('Error', err.error || 'Failed to save interface template', 'error');
  9584. }
  9585. } catch (err) {
  9586. showToast('Error', err.message, 'error');
  9587. }
  9588. }
  9589. function applyOspfTemplateForm() {
  9590. submitOspfTemplate(null);
  9591. }
  9592. function copyOspfTemplate() {
  9593. document.getElementById('modal-ospf-tmpl-id').value = '';
  9594. document.getElementById('ospf-template-modal-title').innerText = 'New...';
  9595. showToast('Copied', 'Duplicated as new template', 'info');
  9596. }
  9597. async function deleteCurrentOspfTemplate() {
  9598. const id = document.getElementById('modal-ospf-tmpl-id').value;
  9599. if (!id) return;
  9600. if (!confirm('Delete this interface template?')) return;
  9601. try {
  9602. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9603. closeOspfTemplateModal();
  9604. showToast('Removed', 'Interface template deleted', 'success');
  9605. loadDynamicRouting();
  9606. } catch (err) {
  9607. showToast('Error', err.message, 'error');
  9608. }
  9609. }
  9610. async function enableSelectedOspfTemplate() {
  9611. const id = state.selectedOspfRow?.templates;
  9612. if (!id) return;
  9613. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  9614. method: 'POST',
  9615. headers: { 'Content-Type': 'application/json' },
  9616. body: JSON.stringify({ disabled: false })
  9617. });
  9618. loadDynamicRouting();
  9619. }
  9620. async function disableSelectedOspfTemplate() {
  9621. const id = state.selectedOspfRow?.templates;
  9622. if (!id) return;
  9623. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  9624. method: 'POST',
  9625. headers: { 'Content-Type': 'application/json' },
  9626. body: JSON.stringify({ disabled: true })
  9627. });
  9628. loadDynamicRouting();
  9629. }
  9630. async function removeSelectedOspfTemplate() {
  9631. const id = state.selectedOspfRow?.templates;
  9632. if (!id) return;
  9633. if (!confirm('Delete selected interface template?')) return;
  9634. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9635. loadDynamicRouting();
  9636. }
  9637. async function promptCommentOspfTemplate() {
  9638. const id = state.selectedOspfRow?.templates;
  9639. if (!id) return;
  9640. const tmpl = (state.ospfTemplates || []).find(t => t.id === id);
  9641. if (!tmpl) return;
  9642. const comment = prompt('Enter comment for template:', tmpl.comment || '');
  9643. if (comment === null) return;
  9644. tmpl.comment = comment;
  9645. await fetch(`${API_BASE}/routing/ospf/templates`, {
  9646. method: 'POST',
  9647. headers: { 'Content-Type': 'application/json' },
  9648. body: JSON.stringify(tmpl)
  9649. });
  9650. loadDynamicRouting();
  9651. }
  9652. // --- 5. OSPF STATIC NEIGHBOR ---
  9653. function populateStaticNbrAreaDropdowns() {
  9654. const select = document.getElementById('modal-ospf-snbr-area');
  9655. if (select) {
  9656. const cur = select.value;
  9657. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  9658. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  9659. if (cur) select.value = cur;
  9660. }
  9661. }
  9662. function openOspfStaticNbrModal(id = null) {
  9663. const isEdit = !!id;
  9664. populateStaticNbrAreaDropdowns();
  9665. const nbr = (state.ospfStaticNbrs || []).find(n => n.id === id) || {
  9666. id: '',
  9667. address: '',
  9668. area: 'Default',
  9669. poll_interval: 120,
  9670. cost: 1,
  9671. disabled: false,
  9672. comment: ''
  9673. };
  9674. document.getElementById('ospf-static-nbr-modal-title').innerText = isEdit ? nbr.address : 'New...';
  9675. document.getElementById('modal-ospf-snbr-id').value = isEdit ? nbr.id : '';
  9676. document.getElementById('modal-ospf-snbr-enabled').checked = !nbr.disabled;
  9677. document.getElementById('modal-ospf-snbr-comment').value = nbr.comment || '';
  9678. document.getElementById('modal-ospf-snbr-address').value = nbr.address || '';
  9679. document.getElementById('modal-ospf-snbr-area').value = nbr.area || 'Default';
  9680. document.getElementById('modal-ospf-snbr-poll').value = nbr.poll_interval || 120;
  9681. document.getElementById('modal-ospf-snbr-cost').value = nbr.cost || 1;
  9682. const btnRem = document.getElementById('btn-ospf-snbr-modal-remove');
  9683. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  9684. document.getElementById('ospf-static-nbr-modal').classList.remove('hidden');
  9685. }
  9686. function openEditOspfStaticNbrModal(id) {
  9687. openOspfStaticNbrModal(id);
  9688. }
  9689. function closeOspfStaticNbrModal() {
  9690. document.getElementById('ospf-static-nbr-modal').classList.add('hidden');
  9691. }
  9692. async function submitOspfStaticNbr(e) {
  9693. if (e) e.preventDefault();
  9694. const payload = {
  9695. id: document.getElementById('modal-ospf-snbr-id').value,
  9696. address: document.getElementById('modal-ospf-snbr-address').value.trim(),
  9697. area: document.getElementById('modal-ospf-snbr-area').value,
  9698. poll_interval: parseInt(document.getElementById('modal-ospf-snbr-poll').value, 10) || 120,
  9699. cost: parseInt(document.getElementById('modal-ospf-snbr-cost').value, 10) || 1,
  9700. disabled: !document.getElementById('modal-ospf-snbr-enabled').checked,
  9701. comment: document.getElementById('modal-ospf-snbr-comment').value.trim()
  9702. };
  9703. try {
  9704. const res = await fetch(`${API_BASE}/routing/ospf/static-neighbors`, {
  9705. method: 'POST',
  9706. headers: { 'Content-Type': 'application/json' },
  9707. body: JSON.stringify(payload)
  9708. });
  9709. if (res.ok) {
  9710. closeOspfStaticNbrModal();
  9711. showToast('Saved', 'Static neighbor saved', 'success');
  9712. loadDynamicRouting();
  9713. } else {
  9714. const err = await res.json();
  9715. showToast('Error', err.error || 'Failed to save static neighbor', 'error');
  9716. }
  9717. } catch (err) {
  9718. showToast('Error', err.message, 'error');
  9719. }
  9720. }
  9721. function applyOspfStaticNbrForm() {
  9722. submitOspfStaticNbr(null);
  9723. }
  9724. async function deleteCurrentOspfStaticNbr() {
  9725. const id = document.getElementById('modal-ospf-snbr-id').value;
  9726. if (!id) return;
  9727. if (!confirm('Delete this static neighbor?')) return;
  9728. try {
  9729. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9730. closeOspfStaticNbrModal();
  9731. showToast('Removed', 'Static neighbor removed', 'success');
  9732. loadDynamicRouting();
  9733. } catch (err) {
  9734. showToast('Error', err.message, 'error');
  9735. }
  9736. }
  9737. async function enableSelectedOspfStaticNbr() {
  9738. const id = state.selectedOspfRow?.['static-nbrs'];
  9739. if (!id) return;
  9740. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  9741. if (!n) return;
  9742. n.disabled = false;
  9743. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  9744. loadDynamicRouting();
  9745. }
  9746. async function disableSelectedOspfStaticNbr() {
  9747. const id = state.selectedOspfRow?.['static-nbrs'];
  9748. if (!id) return;
  9749. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  9750. if (!n) return;
  9751. n.disabled = true;
  9752. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  9753. loadDynamicRouting();
  9754. }
  9755. async function removeSelectedOspfStaticNbr() {
  9756. const id = state.selectedOspfRow?.['static-nbrs'];
  9757. if (!id) return;
  9758. if (!confirm('Delete selected static neighbor?')) return;
  9759. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9760. loadDynamicRouting();
  9761. }
  9762. async function promptCommentOspfStaticNbr() {
  9763. const id = state.selectedOspfRow?.['static-nbrs'];
  9764. if (!id) return;
  9765. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  9766. if (!n) return;
  9767. const comment = prompt('Enter comment for static neighbor:', n.comment || '');
  9768. if (comment === null) return;
  9769. n.comment = comment;
  9770. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  9771. loadDynamicRouting();
  9772. }
  9773. // Backward-compat aliases
  9774. function openAddOspfInterfaceModal() { openOspfTemplateModal(); }
  9775. function openEditOspfInterfaceModal(id) { openEditOspfTemplateModal(id); }
  9776. function closeOspfInterfaceModal() { closeOspfTemplateModal(); }
  9777. function submitOspfInterface(e) { submitOspfTemplate(e); }
  9778. function deleteOspfInterface(id) {
  9779. fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' }).then(() => loadDynamicRouting());
  9780. }
  9781. function toggleOspfInterfaceState(id, disabled) {
  9782. fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  9783. method: 'POST',
  9784. headers: { 'Content-Type': 'application/json' },
  9785. body: JSON.stringify({ disabled })
  9786. }).then(() => loadDynamicRouting());
  9787. }
  9788. function openAddOspfAreaModal() { openOspfAreaModal(); }
  9789. function deleteOspfArea(id) {
  9790. fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' }).then(() => loadDynamicRouting());
  9791. }
  9792. // ============================================================================
  9793. // ==================== MIKROTIK BRIDGE SUBSYSTEM ==============================
  9794. // ============================================================================
  9795. function switchBridgeSubTab(tab) {
  9796. state.bridgeSubTab = tab;
  9797. const tabs = ['bridges', 'ports', 'vlans', 'hosts'];
  9798. tabs.forEach(t => {
  9799. const panel = document.getElementById(`bridge-subtab-${t}`);
  9800. const btn = document.getElementById(`bridge-subtab-btn-${t}`);
  9801. if (panel) {
  9802. if (t === tab) panel.classList.remove('hidden');
  9803. else panel.classList.add('hidden');
  9804. }
  9805. if (btn) {
  9806. if (t === tab) {
  9807. 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';
  9808. } else {
  9809. 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';
  9810. }
  9811. }
  9812. });
  9813. const addBtn = document.getElementById('bridge-top-action-btn');
  9814. if (addBtn) {
  9815. if (tab === 'bridges') addBtn.innerHTML = '<span>+ Add Bridge</span>';
  9816. else if (tab === 'ports') addBtn.innerHTML = '<span>+ Add Port</span>';
  9817. else if (tab === 'vlans') addBtn.innerHTML = '<span>+ Add VLAN Entry</span>';
  9818. else if (tab === 'hosts') addBtn.innerHTML = '<span>🔄 Refresh MACs</span>';
  9819. }
  9820. if (tab === 'hosts') loadBridgeHosts();
  9821. setTimeout(initTableSorting, 50);
  9822. }
  9823. function openCurrentBridgeModal() {
  9824. if (state.bridgeSubTab === 'bridges') openAddBridgeModal();
  9825. else if (state.bridgeSubTab === 'ports') openAddBridgePortModal();
  9826. else if (state.bridgeSubTab === 'vlans') openAddBridgeVLANModal();
  9827. else if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  9828. }
  9829. async function loadBridge() {
  9830. try {
  9831. const [bridgesRes, portsRes, vlansRes, summaryRes, eoipRes, vlanIfacesRes] = await Promise.all([
  9832. fetch(`${API_BASE}/bridge/bridges`),
  9833. fetch(`${API_BASE}/bridge/ports`),
  9834. fetch(`${API_BASE}/bridge/vlans`),
  9835. fetch(`${API_BASE}/bridge/summary`),
  9836. fetch(`${API_BASE}/vpn/eoip`),
  9837. fetch(`${API_BASE}/vlans`)
  9838. ]);
  9839. if (bridgesRes.ok) state.bridges = await bridgesRes.json();
  9840. if (portsRes.ok) state.bridgePorts = await portsRes.json();
  9841. if (vlansRes.ok) state.bridgeVLANs = await vlansRes.json();
  9842. if (summaryRes.ok) state.bridgeSummary = await summaryRes.json();
  9843. if (eoipRes && eoipRes.ok) state.eoipTunnels = await eoipRes.json();
  9844. if (vlanIfacesRes && vlanIfacesRes.ok) state.vlans = await vlanIfacesRes.json();
  9845. // Badges & Stats
  9846. const bBridges = document.getElementById('bridge-badge-bridges');
  9847. if (bBridges) bBridges.innerText = (state.bridges || []).length;
  9848. const bPorts = document.getElementById('bridge-badge-ports');
  9849. if (bPorts) bPorts.innerText = (state.bridgePorts || []).length;
  9850. const bVlans = document.getElementById('bridge-badge-vlans');
  9851. if (bVlans) bVlans.innerText = (state.bridgeVLANs || []).length;
  9852. const bHosts = document.getElementById('bridge-badge-hosts');
  9853. if (bHosts) bHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  9854. const sBr = document.getElementById('bridge-stat-bridges');
  9855. if (sBr) sBr.innerText = (state.bridges || []).length;
  9856. const sPorts = document.getElementById('bridge-stat-ports');
  9857. if (sPorts) sPorts.innerText = (state.bridgePorts || []).length;
  9858. const sHosts = document.getElementById('bridge-stat-hosts');
  9859. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  9860. renderBridges();
  9861. renderBridgePorts();
  9862. renderBridgeVLANs();
  9863. if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  9864. } catch (err) {
  9865. console.error('Failed to load bridge subsystem:', err);
  9866. }
  9867. }
  9868. // ----------------- Bridges -----------------
  9869. function renderBridges() {
  9870. const tbody = document.getElementById('bridge-table-body');
  9871. const empty = document.getElementById('bridge-empty-bridges');
  9872. const countBadge = document.getElementById('bridge-count-badge');
  9873. if (!tbody) return;
  9874. tbody.innerHTML = '';
  9875. const bridges = state.bridges || [];
  9876. if (countBadge) countBadge.innerText = `${bridges.length} Bridges`;
  9877. if (bridges.length === 0) {
  9878. empty?.classList.remove('hidden');
  9879. return;
  9880. }
  9881. empty?.classList.add('hidden');
  9882. bridges.forEach((b, idx) => {
  9883. const tr = document.createElement('tr');
  9884. tr.className = `hover:bg-slate-800/40 transition text-xs ${b.disabled ? 'opacity-50' : ''}`;
  9885. // Format IP addresses pill list
  9886. let ipsHtml = '<span class="text-slate-600 font-sans">None</span>';
  9887. if (b.ip_addresses && b.ip_addresses.length > 0) {
  9888. ipsHtml = b.ip_addresses.map(ip => `
  9889. <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">
  9890. <span>${ip}</span>
  9891. <button onclick="deleteBridgeIP('${b.id}', '${ip}')" class="text-slate-500 hover:text-rose-400 font-bold ml-0.5">×</button>
  9892. </span>
  9893. `).join(' ');
  9894. }
  9895. const runningFlag = b.running ? '<span class="text-emerald-400 font-bold" title="Running (R)">R</span>' : '<span class="text-slate-600">-</span>';
  9896. const disabledFlag = b.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '';
  9897. const flagDisplay = `${runningFlag}${disabledFlag ? ' ' + disabledFlag : ''}`;
  9898. tr.innerHTML = `
  9899. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  9900. <td class="py-2.5 px-3 text-center font-mono">${flagDisplay}</td>
  9901. <td class="py-2.5 px-3 font-bold text-white text-sm">
  9902. <span class="text-sky-400 mr-1.5">🌉</span>${b.name}
  9903. </td>
  9904. <td class="py-2.5 px-3 text-slate-300">${b.mtu}</td>
  9905. <td class="py-2.5 px-3 font-mono text-slate-300 text-[11px]">${b.mac_address || '-'}</td>
  9906. <td class="py-2.5 px-3">
  9907. <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>
  9908. </td>
  9909. <td class="py-2.5 px-3 text-center">
  9910. ${b.vlan_filtering ? '<span class="text-emerald-400 font-bold">yes</span>' : '<span class="text-slate-500">no</span>'}
  9911. </td>
  9912. <td class="py-2.5 px-3 font-mono">${b.pvid || 1}</td>
  9913. <td class="py-2.5 px-3">
  9914. <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>
  9915. </td>
  9916. <td class="py-2.5 px-3">
  9917. <div class="flex items-center gap-1.5 flex-wrap">
  9918. ${ipsHtml}
  9919. <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>
  9920. </div>
  9921. </td>
  9922. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  9923. <span class="text-emerald-400">↓ ${b.rx_human || '0 B'}</span> / <span class="text-cyan-400">↑ ${b.tx_human || '0 B'}</span>
  9924. </td>
  9925. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${b.comment || ''}">${b.comment || '-'}</td>
  9926. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  9927. <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>
  9928. <button onclick="openEditBridgeModal('${b.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  9929. <button onclick="deleteBridge('${b.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  9930. </td>
  9931. `;
  9932. tbody.appendChild(tr);
  9933. });
  9934. }
  9935. function openAddBridgeModal() {
  9936. document.getElementById('bridge-modal-title').innerText = 'Add Bridge Interface';
  9937. document.getElementById('bridge-modal-id').value = '';
  9938. document.getElementById('bridge-modal-name').value = 'bridge1';
  9939. document.getElementById('bridge-modal-name').disabled = false;
  9940. document.getElementById('bridge-modal-mtu').value = '1500';
  9941. document.getElementById('bridge-modal-mac').value = '';
  9942. document.getElementById('bridge-modal-stp').value = 'stp';
  9943. document.getElementById('bridge-modal-priority').value = '32768';
  9944. document.getElementById('bridge-modal-vlanfiltering').checked = false;
  9945. document.getElementById('bridge-modal-pvid').value = '1';
  9946. document.getElementById('bridge-modal-fastforward').checked = true;
  9947. document.getElementById('bridge-modal-comment').value = '';
  9948. document.getElementById('bridge-modal-disabled').checked = false;
  9949. toggleBridgeModalVlanFiltering();
  9950. document.getElementById('bridge-modal').classList.remove('hidden');
  9951. }
  9952. function openEditBridgeModal(id) {
  9953. const b = (state.bridges || []).find(x => x.id === id);
  9954. if (!b) return;
  9955. document.getElementById('bridge-modal-title').innerText = `Edit Bridge (${b.name})`;
  9956. document.getElementById('bridge-modal-id').value = b.id;
  9957. document.getElementById('bridge-modal-name').value = b.name;
  9958. document.getElementById('bridge-modal-name').disabled = true;
  9959. document.getElementById('bridge-modal-mtu').value = b.mtu || 1500;
  9960. document.getElementById('bridge-modal-mac').value = b.mac_address || '';
  9961. document.getElementById('bridge-modal-stp').value = b.stp || 'stp';
  9962. document.getElementById('bridge-modal-priority').value = b.priority || 32768;
  9963. document.getElementById('bridge-modal-vlanfiltering').checked = !!b.vlan_filtering;
  9964. document.getElementById('bridge-modal-pvid').value = b.pvid || 1;
  9965. document.getElementById('bridge-modal-fastforward').checked = b.fast_forward !== false;
  9966. document.getElementById('bridge-modal-comment').value = b.comment || '';
  9967. document.getElementById('bridge-modal-disabled').checked = !!b.disabled;
  9968. toggleBridgeModalVlanFiltering();
  9969. document.getElementById('bridge-modal').classList.remove('hidden');
  9970. }
  9971. function closeBridgeModal() {
  9972. document.getElementById('bridge-modal').classList.add('hidden');
  9973. }
  9974. function toggleBridgeModalVlanFiltering() {
  9975. const chk = document.getElementById('bridge-modal-vlanfiltering').checked;
  9976. const pvidBox = document.getElementById('bridge-modal-pvid-box');
  9977. if (pvidBox) {
  9978. if (chk) pvidBox.classList.remove('opacity-40');
  9979. else pvidBox.classList.add('opacity-40');
  9980. }
  9981. }
  9982. async function submitSaveBridge(e) {
  9983. e.preventDefault();
  9984. const id = document.getElementById('bridge-modal-id').value;
  9985. const name = document.getElementById('bridge-modal-name').value.trim();
  9986. const mtu = parseInt(document.getElementById('bridge-modal-mtu').value, 10) || 1500;
  9987. const mac = document.getElementById('bridge-modal-mac').value.trim();
  9988. const stp = document.getElementById('bridge-modal-stp').value;
  9989. const priority = parseInt(document.getElementById('bridge-modal-priority').value, 10) || 32768;
  9990. const vlanFiltering = document.getElementById('bridge-modal-vlanfiltering').checked;
  9991. const pvid = parseInt(document.getElementById('bridge-modal-pvid').value, 10) || 1;
  9992. const fastForward = document.getElementById('bridge-modal-fastforward').checked;
  9993. const comment = document.getElementById('bridge-modal-comment').value.trim();
  9994. const disabled = document.getElementById('bridge-modal-disabled').checked;
  9995. try {
  9996. const res = await fetch(`${API_BASE}/bridge/bridges`, {
  9997. method: 'POST',
  9998. headers: { 'Content-Type': 'application/json' },
  9999. body: JSON.stringify({
  10000. id,
  10001. name,
  10002. mtu,
  10003. mac_address: mac,
  10004. stp,
  10005. priority,
  10006. vlan_filtering: vlanFiltering,
  10007. pvid,
  10008. fast_forward: fastForward,
  10009. comment,
  10010. disabled
  10011. })
  10012. });
  10013. if (res.ok) {
  10014. showToast('Bridge Saved', `Bridge ${name} configured`, 'success');
  10015. closeBridgeModal();
  10016. loadBridge();
  10017. fetchData(false);
  10018. } else {
  10019. const err = await res.json();
  10020. showToast('Error', err.error || err.message || 'Failed to save bridge', 'error');
  10021. }
  10022. } catch (err) {
  10023. showToast('Error', err.message, 'error');
  10024. }
  10025. }
  10026. async function toggleBridgeState(id, disabled) {
  10027. try {
  10028. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/state`, {
  10029. method: 'POST',
  10030. headers: { 'Content-Type': 'application/json' },
  10031. body: JSON.stringify({ disabled })
  10032. });
  10033. if (res.ok) {
  10034. loadBridge();
  10035. fetchData(false);
  10036. }
  10037. } catch (err) {
  10038. showToast('Error', err.message, 'error');
  10039. }
  10040. }
  10041. async function deleteBridge(id) {
  10042. const b = (state.bridges || []).find(x => x.id === id);
  10043. const name = b ? b.name : id;
  10044. if (!confirm(`Are you sure you want to delete bridge '${name}'? All member ports will be detached.`)) return;
  10045. try {
  10046. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10047. if (res.ok) {
  10048. showToast('Deleted', `Bridge ${name} deleted`, 'success');
  10049. loadBridge();
  10050. fetchData(false);
  10051. } else {
  10052. const err = await res.json();
  10053. showToast('Error', err.error || err.message || 'Failed to delete bridge', 'error');
  10054. }
  10055. } catch (err) {
  10056. showToast('Error', err.message, 'error');
  10057. }
  10058. }
  10059. // ----------------- Bridge IP Assignments -----------------
  10060. function openAddBridgeIPModal(id, name) {
  10061. document.getElementById('bridge-ip-modal-id').value = id;
  10062. document.getElementById('bridge-ip-modal-sub').innerText = name;
  10063. document.getElementById('bridge-ip-modal-cidr').value = '';
  10064. document.getElementById('bridge-ip-modal').classList.remove('hidden');
  10065. }
  10066. function closeBridgeIPModal() {
  10067. document.getElementById('bridge-ip-modal').classList.add('hidden');
  10068. }
  10069. async function submitAddBridgeIP(e) {
  10070. e.preventDefault();
  10071. const id = document.getElementById('bridge-ip-modal-id').value;
  10072. const ip = document.getElementById('bridge-ip-modal-cidr').value.trim();
  10073. try {
  10074. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  10075. method: 'POST',
  10076. headers: { 'Content-Type': 'application/json' },
  10077. body: JSON.stringify({ ip })
  10078. });
  10079. if (res.ok) {
  10080. showToast('IP Assigned', `${ip} assigned to bridge`, 'success');
  10081. closeBridgeIPModal();
  10082. loadBridge();
  10083. fetchData(false);
  10084. } else {
  10085. const err = await res.json();
  10086. showToast('Error', err.error || err.message || 'Failed to add IP', 'error');
  10087. }
  10088. } catch (err) {
  10089. showToast('Error', err.message, 'error');
  10090. }
  10091. }
  10092. async function deleteBridgeIP(id, ip) {
  10093. if (!confirm(`Remove IP address ${ip} from bridge?`)) return;
  10094. try {
  10095. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  10096. method: 'DELETE',
  10097. headers: { 'Content-Type': 'application/json' },
  10098. body: JSON.stringify({ ip })
  10099. });
  10100. if (res.ok) {
  10101. showToast('IP Removed', `${ip} removed from bridge`, 'success');
  10102. loadBridge();
  10103. fetchData(false);
  10104. }
  10105. } catch (err) {
  10106. showToast('Error', err.message, 'error');
  10107. }
  10108. }
  10109. // ----------------- Bridge Ports -----------------
  10110. function renderBridgePorts() {
  10111. const tbody = document.getElementById('bridge-ports-table-body');
  10112. const empty = document.getElementById('bridge-empty-ports');
  10113. const countBadge = document.getElementById('bridge-ports-count-badge');
  10114. const filterBridge = document.getElementById('bridge-ports-filter-bridge')?.value || '';
  10115. if (!tbody) return;
  10116. tbody.innerHTML = '';
  10117. // Update filter select
  10118. populateBridgeSelect('bridge-ports-filter-bridge', filterBridge, true);
  10119. const ports = (state.bridgePorts || []).filter(p => !filterBridge || p.bridge === filterBridge);
  10120. if (countBadge) countBadge.innerText = `${ports.length} Ports`;
  10121. if (ports.length === 0) {
  10122. empty?.classList.remove('hidden');
  10123. return;
  10124. }
  10125. empty?.classList.add('hidden');
  10126. ports.forEach((p, idx) => {
  10127. const tr = document.createElement('tr');
  10128. tr.className = `hover:bg-slate-800/40 transition text-xs ${p.disabled ? 'opacity-50' : ''}`;
  10129. const disabledFlag = p.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  10130. tr.innerHTML = `
  10131. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  10132. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  10133. <td class="py-2.5 px-3 font-bold text-white text-sm">
  10134. <span class="text-emerald-400 mr-1.5">🔌</span>${p.interface}
  10135. </td>
  10136. <td class="py-2.5 px-3 font-semibold text-sky-400">${p.bridge}</td>
  10137. <td class="py-2.5 px-3 font-mono">${p.pvid || 1}</td>
  10138. <td class="py-2.5 px-3 text-slate-300">${p.frame_types}</td>
  10139. <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>
  10140. <td class="py-2.5 px-3">
  10141. ${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>'}
  10142. </td>
  10143. <td class="py-2.5 px-3">
  10144. <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>
  10145. </td>
  10146. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${p.comment || ''}">${p.comment || '-'}</td>
  10147. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  10148. <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>
  10149. <button onclick="openEditBridgePortModal('${p.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  10150. <button onclick="deleteBridgePort('${p.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  10151. </td>
  10152. `;
  10153. tbody.appendChild(tr);
  10154. });
  10155. }
  10156. function openAddBridgePortModal() {
  10157. document.getElementById('bridge-port-modal-title').innerText = 'Add Port to Bridge';
  10158. document.getElementById('bridge-port-modal-id').value = '';
  10159. populateBridgeSelect('bridge-port-modal-bridge');
  10160. populateBridgePortCandidateSelect('bridge-port-modal-interface');
  10161. document.getElementById('bridge-port-modal-pvid').value = '1';
  10162. document.getElementById('bridge-port-modal-frametypes').value = 'admit-all';
  10163. document.getElementById('bridge-port-modal-ingressfiltering').checked = false;
  10164. document.getElementById('bridge-port-modal-horizon').value = '0';
  10165. document.getElementById('bridge-port-modal-pathcost').value = '10';
  10166. document.getElementById('bridge-port-modal-priority').value = '128';
  10167. document.getElementById('bridge-port-modal-learn').checked = true;
  10168. document.getElementById('bridge-port-modal-comment').value = '';
  10169. document.getElementById('bridge-port-modal-disabled').checked = false;
  10170. document.getElementById('bridge-port-modal').classList.remove('hidden');
  10171. }
  10172. function openEditBridgePortModal(id) {
  10173. const p = (state.bridgePorts || []).find(x => x.id === id);
  10174. if (!p) return;
  10175. document.getElementById('bridge-port-modal-title').innerText = `Edit Bridge Port (${p.interface})`;
  10176. document.getElementById('bridge-port-modal-id').value = p.id;
  10177. populateBridgeSelect('bridge-port-modal-bridge', p.bridge);
  10178. populateBridgePortCandidateSelect('bridge-port-modal-interface', p.interface);
  10179. document.getElementById('bridge-port-modal-pvid').value = p.pvid || 1;
  10180. document.getElementById('bridge-port-modal-frametypes').value = p.frame_types || 'admit-all';
  10181. document.getElementById('bridge-port-modal-ingressfiltering').checked = !!p.ingress_filtering;
  10182. document.getElementById('bridge-port-modal-horizon').value = p.horizon || 0;
  10183. document.getElementById('bridge-port-modal-pathcost').value = p.path_cost || 10;
  10184. document.getElementById('bridge-port-modal-priority').value = p.priority || 128;
  10185. document.getElementById('bridge-port-modal-learn').checked = p.learn !== false;
  10186. document.getElementById('bridge-port-modal-comment').value = p.comment || '';
  10187. document.getElementById('bridge-port-modal-disabled').checked = !!p.disabled;
  10188. document.getElementById('bridge-port-modal').classList.remove('hidden');
  10189. }
  10190. function closeBridgePortModal() {
  10191. document.getElementById('bridge-port-modal').classList.add('hidden');
  10192. }
  10193. async function submitSaveBridgePort(e) {
  10194. e.preventDefault();
  10195. const id = document.getElementById('bridge-port-modal-id').value;
  10196. const bridge = document.getElementById('bridge-port-modal-bridge').value;
  10197. const iface = document.getElementById('bridge-port-modal-interface').value;
  10198. const pvid = parseInt(document.getElementById('bridge-port-modal-pvid').value, 10) || 1;
  10199. const frameTypes = document.getElementById('bridge-port-modal-frametypes').value;
  10200. const ingressFiltering = document.getElementById('bridge-port-modal-ingressfiltering').checked;
  10201. const horizon = parseInt(document.getElementById('bridge-port-modal-horizon').value, 10) || 0;
  10202. const pathCost = parseInt(document.getElementById('bridge-port-modal-pathcost').value, 10) || 10;
  10203. const priority = parseInt(document.getElementById('bridge-port-modal-priority').value, 10) || 128;
  10204. const learn = document.getElementById('bridge-port-modal-learn').checked;
  10205. const comment = document.getElementById('bridge-port-modal-comment').value.trim();
  10206. const disabled = document.getElementById('bridge-port-modal-disabled').checked;
  10207. try {
  10208. const res = await fetch(`${API_BASE}/bridge/ports`, {
  10209. method: 'POST',
  10210. headers: { 'Content-Type': 'application/json' },
  10211. body: JSON.stringify({
  10212. id,
  10213. bridge,
  10214. interface: iface,
  10215. pvid,
  10216. frame_types: frameTypes,
  10217. ingress_filtering: ingressFiltering,
  10218. horizon,
  10219. path_cost: pathCost,
  10220. priority,
  10221. learn,
  10222. comment,
  10223. disabled
  10224. })
  10225. });
  10226. if (res.ok) {
  10227. showToast('Port Attached', `${iface} added to ${bridge}`, 'success');
  10228. closeBridgePortModal();
  10229. loadBridge();
  10230. fetchData(false);
  10231. } else {
  10232. const err = await res.json();
  10233. showToast('Error', err.error || err.message || 'Failed to save port', 'error');
  10234. }
  10235. } catch (err) {
  10236. showToast('Error', err.message, 'error');
  10237. }
  10238. }
  10239. async function toggleBridgePortState(id, disabled) {
  10240. try {
  10241. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}/state`, {
  10242. method: 'POST',
  10243. headers: { 'Content-Type': 'application/json' },
  10244. body: JSON.stringify({ disabled })
  10245. });
  10246. if (res.ok) {
  10247. loadBridge();
  10248. fetchData(false);
  10249. }
  10250. } catch (err) {
  10251. showToast('Error', err.message, 'error');
  10252. }
  10253. }
  10254. async function deleteBridgePort(id) {
  10255. const p = (state.bridgePorts || []).find(x => x.id === id);
  10256. const iface = p ? p.interface : id;
  10257. if (!confirm(`Detach interface '${iface}' from bridge?`)) return;
  10258. try {
  10259. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10260. if (res.ok) {
  10261. showToast('Port Detached', `${iface} removed from bridge`, 'success');
  10262. loadBridge();
  10263. fetchData(false);
  10264. }
  10265. } catch (err) {
  10266. showToast('Error', err.message, 'error');
  10267. }
  10268. }
  10269. // ----------------- Bridge VLANs -----------------
  10270. function renderBridgeVLANs() {
  10271. const tbody = document.getElementById('bridge-vlans-table-body');
  10272. const empty = document.getElementById('bridge-empty-vlans');
  10273. const countBadge = document.getElementById('bridge-vlans-count-badge');
  10274. const filterBridge = document.getElementById('bridge-vlans-filter-bridge')?.value || '';
  10275. if (!tbody) return;
  10276. tbody.innerHTML = '';
  10277. populateBridgeSelect('bridge-vlans-filter-bridge', filterBridge, true);
  10278. const vlans = (state.bridgeVLANs || []).filter(v => !filterBridge || v.bridge === filterBridge);
  10279. if (countBadge) countBadge.innerText = `${vlans.length} Entries`;
  10280. if (vlans.length === 0) {
  10281. empty?.classList.remove('hidden');
  10282. return;
  10283. }
  10284. empty?.classList.add('hidden');
  10285. vlans.forEach((v, idx) => {
  10286. const tr = document.createElement('tr');
  10287. tr.className = `hover:bg-slate-800/40 transition text-xs ${v.disabled ? 'opacity-50' : ''}`;
  10288. const taggedHtml = (v.tagged && v.tagged.length > 0)
  10289. ? 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(' ')
  10290. : '<span class="text-slate-600">none</span>';
  10291. const untaggedHtml = (v.untagged && v.untagged.length > 0)
  10292. ? 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(' ')
  10293. : '<span class="text-slate-600">none</span>';
  10294. const disabledFlag = v.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  10295. tr.innerHTML = `
  10296. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  10297. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  10298. <td class="py-2.5 px-3 font-semibold text-sky-400">${v.bridge}</td>
  10299. <td class="py-2.5 px-3 font-bold text-white font-mono text-sm">${v.vlan_ids}</td>
  10300. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${taggedHtml}</div></td>
  10301. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${untaggedHtml}</div></td>
  10302. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${v.comment || ''}">${v.comment || '-'}</td>
  10303. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  10304. <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>
  10305. <button onclick="openEditBridgeVLANModal('${v.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  10306. <button onclick="deleteBridgeVLAN('${v.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  10307. </td>
  10308. `;
  10309. tbody.appendChild(tr);
  10310. });
  10311. }
  10312. function openAddBridgeVLANModal() {
  10313. document.getElementById('bridge-vlan-modal-title').innerText = 'Add Bridge VLAN Entry';
  10314. document.getElementById('bridge-vlan-modal-id').value = '';
  10315. populateBridgeSelect('bridge-vlan-modal-bridge');
  10316. document.getElementById('bridge-vlan-modal-vlanids').value = '';
  10317. document.getElementById('bridge-vlan-modal-comment').value = '';
  10318. document.getElementById('bridge-vlan-modal-disabled').checked = false;
  10319. updateBridgeVlanPortCheckboxes();
  10320. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  10321. }
  10322. function openEditBridgeVLANModal(id) {
  10323. const v = (state.bridgeVLANs || []).find(x => x.id === id);
  10324. if (!v) return;
  10325. document.getElementById('bridge-vlan-modal-title').innerText = `Edit Bridge VLAN (${v.vlan_ids})`;
  10326. document.getElementById('bridge-vlan-modal-id').value = v.id;
  10327. populateBridgeSelect('bridge-vlan-modal-bridge', v.bridge);
  10328. document.getElementById('bridge-vlan-modal-vlanids').value = v.vlan_ids;
  10329. document.getElementById('bridge-vlan-modal-comment').value = v.comment || '';
  10330. document.getElementById('bridge-vlan-modal-disabled').checked = !!v.disabled;
  10331. updateBridgeVlanPortCheckboxes(v.tagged || [], v.untagged || []);
  10332. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  10333. }
  10334. function closeBridgeVlanModal() {
  10335. document.getElementById('bridge-vlan-modal').classList.add('hidden');
  10336. }
  10337. function updateBridgeVlanPortCheckboxes(taggedSelected = [], untaggedSelected = []) {
  10338. const selBridge = document.getElementById('bridge-vlan-modal-bridge')?.value || '';
  10339. const taggedBox = document.getElementById('bridge-vlan-tagged-ports');
  10340. const untaggedBox = document.getElementById('bridge-vlan-untagged-ports');
  10341. if (!taggedBox || !untaggedBox) return;
  10342. // Ports belonging to the selected bridge
  10343. const memberPorts = (state.bridgePorts || []).filter(p => !selBridge || p.bridge === selBridge);
  10344. if (memberPorts.length === 0) {
  10345. taggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  10346. untaggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  10347. return;
  10348. }
  10349. taggedBox.innerHTML = memberPorts.map(p => `
  10350. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  10351. <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">
  10352. <span>${p.interface}</span>
  10353. </label>
  10354. `).join('');
  10355. untaggedBox.innerHTML = memberPorts.map(p => `
  10356. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  10357. <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">
  10358. <span>${p.interface}</span>
  10359. </label>
  10360. `).join('');
  10361. }
  10362. async function submitSaveBridgeVLAN(e) {
  10363. e.preventDefault();
  10364. const id = document.getElementById('bridge-vlan-modal-id').value;
  10365. const bridge = document.getElementById('bridge-vlan-modal-bridge').value;
  10366. const vlanIDs = document.getElementById('bridge-vlan-modal-vlanids').value.trim();
  10367. const comment = document.getElementById('bridge-vlan-modal-comment').value.trim();
  10368. const disabled = document.getElementById('bridge-vlan-modal-disabled').checked;
  10369. const tagged = Array.from(document.querySelectorAll('input[name="bvlan-tagged"]:checked')).map(x => x.value);
  10370. const untagged = Array.from(document.querySelectorAll('input[name="bvlan-untagged"]:checked')).map(x => x.value);
  10371. try {
  10372. const res = await fetch(`${API_BASE}/bridge/vlans`, {
  10373. method: 'POST',
  10374. headers: { 'Content-Type': 'application/json' },
  10375. body: JSON.stringify({
  10376. id,
  10377. bridge,
  10378. vlan_ids: vlanIDs,
  10379. tagged,
  10380. untagged,
  10381. comment,
  10382. disabled
  10383. })
  10384. });
  10385. if (res.ok) {
  10386. showToast('VLAN Entry Saved', `VLAN ${vlanIDs} configured on ${bridge}`, 'success');
  10387. closeBridgeVlanModal();
  10388. loadBridge();
  10389. } else {
  10390. const err = await res.json();
  10391. showToast('Error', err.error || err.message || 'Failed to save VLAN entry', 'error');
  10392. }
  10393. } catch (err) {
  10394. showToast('Error', err.message, 'error');
  10395. }
  10396. }
  10397. async function toggleBridgeVLANState(id, disabled) {
  10398. try {
  10399. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}/state`, {
  10400. method: 'POST',
  10401. headers: { 'Content-Type': 'application/json' },
  10402. body: JSON.stringify({ disabled })
  10403. });
  10404. if (res.ok) loadBridge();
  10405. } catch (err) {
  10406. showToast('Error', err.message, 'error');
  10407. }
  10408. }
  10409. async function deleteBridgeVLAN(id) {
  10410. if (!confirm('Delete this bridge VLAN entry?')) return;
  10411. try {
  10412. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10413. if (res.ok) {
  10414. showToast('Deleted', 'VLAN entry removed from bridge', 'success');
  10415. loadBridge();
  10416. }
  10417. } catch (err) {
  10418. showToast('Error', err.message, 'error');
  10419. }
  10420. }
  10421. // ----------------- Hosts / MAC Table -----------------
  10422. async function loadBridgeHosts() {
  10423. const filterBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || '';
  10424. populateBridgeSelect('bridge-hosts-filter-bridge', filterBridge, true);
  10425. try {
  10426. const url = filterBridge ? `${API_BASE}/bridge/hosts?bridge=${encodeURIComponent(filterBridge)}` : `${API_BASE}/bridge/hosts`;
  10427. const res = await fetch(url);
  10428. if (res.ok) {
  10429. state.bridgeHosts = await res.json();
  10430. renderBridgeHosts();
  10431. }
  10432. } catch (err) {
  10433. console.error('Failed to load bridge hosts:', err);
  10434. }
  10435. }
  10436. function renderBridgeHosts() {
  10437. const tbody = document.getElementById('bridge-hosts-table-body');
  10438. const empty = document.getElementById('bridge-empty-hosts');
  10439. const countBadge = document.getElementById('bridge-hosts-count-badge');
  10440. const search = (document.getElementById('bridge-hosts-search')?.value || '').toLowerCase().trim();
  10441. if (!tbody) return;
  10442. tbody.innerHTML = '';
  10443. const hosts = (state.bridgeHosts || []).filter(h => {
  10444. if (!search) return true;
  10445. return (h.mac || '').toLowerCase().includes(search) || (h.interface || '').toLowerCase().includes(search) || (h.bridge || '').toLowerCase().includes(search);
  10446. });
  10447. if (countBadge) countBadge.innerText = `${hosts.length} Hosts`;
  10448. if (hosts.length === 0) {
  10449. empty?.classList.remove('hidden');
  10450. return;
  10451. }
  10452. empty?.classList.add('hidden');
  10453. hosts.forEach(h => {
  10454. const tr = document.createElement('tr');
  10455. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  10456. let flagBadges = '';
  10457. 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>';
  10458. 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>';
  10459. 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>';
  10460. tr.innerHTML = `
  10461. <td class="py-2.5 px-3 font-mono font-bold text-white text-sm">${h.mac}</td>
  10462. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${h.interface || '-'}</td>
  10463. <td class="py-2.5 px-3 font-mono text-sky-400">${h.bridge || '-'}</td>
  10464. <td class="py-2.5 px-3 font-mono">${h.vlan_id || 1}</td>
  10465. <td class="py-2.5 px-3 font-mono text-slate-400">${h.age ? h.age.toFixed(1) + 's' : '-'}</td>
  10466. <td class="py-2.5 px-3">${flagBadges}</td>
  10467. `;
  10468. tbody.appendChild(tr);
  10469. });
  10470. }
  10471. async function flushBridgeHosts() {
  10472. const selBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || (state.bridges[0] ? state.bridges[0].name : '');
  10473. if (!selBridge) {
  10474. showToast('Notice', 'Please select a bridge to flush dynamic MACs', 'info');
  10475. return;
  10476. }
  10477. if (!confirm(`Flush all dynamic learned MAC addresses on bridge '${selBridge}'?`)) return;
  10478. try {
  10479. const res = await fetch(`${API_BASE}/bridge/hosts/flush`, {
  10480. method: 'POST',
  10481. headers: { 'Content-Type': 'application/json' },
  10482. body: JSON.stringify({ bridge: selBridge })
  10483. });
  10484. if (res.ok) {
  10485. showToast('FDB Flushed', `Dynamic MACs flushed on ${selBridge}`, 'success');
  10486. loadBridgeHosts();
  10487. }
  10488. } catch (err) {
  10489. showToast('Error', err.message, 'error');
  10490. }
  10491. }
  10492. // ----------------- Helpers -----------------
  10493. function populateBridgeSelect(selectId, currentVal = '', includeAll = false) {
  10494. const sel = document.getElementById(selectId);
  10495. if (!sel) return;
  10496. const prevVal = currentVal || sel.value;
  10497. sel.innerHTML = includeAll ? '<option value="">All Bridges</option>' : '';
  10498. (state.bridges || []).forEach(b => {
  10499. const opt = document.createElement('option');
  10500. opt.value = b.name;
  10501. opt.innerText = `${b.name} (${b.ports_count} ports)`;
  10502. if (b.name === prevVal) opt.selected = true;
  10503. sel.appendChild(opt);
  10504. });
  10505. }
  10506. function populateBridgePortCandidateSelect(selectId, currentVal = '') {
  10507. const sel = document.getElementById(selectId);
  10508. if (!sel) return;
  10509. sel.innerHTML = '<option value="">(Select Interface...)</option>';
  10510. // 1. Physical Interfaces
  10511. const grpPhys = document.createElement('optgroup');
  10512. grpPhys.label = 'Physical Interfaces';
  10513. (state.interfaces || []).filter(i => i.type !== 'bridge' && i.type !== 'vlan' && i.type !== 'loopback').forEach(i => {
  10514. const opt = document.createElement('option');
  10515. opt.value = i.name;
  10516. opt.innerText = `${i.name} (${i.role || i.type})`;
  10517. if (i.name === currentVal) opt.selected = true;
  10518. grpPhys.appendChild(opt);
  10519. });
  10520. if (grpPhys.children.length > 0) sel.appendChild(grpPhys);
  10521. // 2. VLAN Sub-interfaces
  10522. const grpVlans = document.createElement('optgroup');
  10523. grpVlans.label = 'VLAN Sub-interfaces (802.1Q)';
  10524. (state.vlans || []).forEach(v => {
  10525. const opt = document.createElement('option');
  10526. opt.value = v.name;
  10527. opt.innerText = `${v.name} (VLAN ${v.vlan_id})`;
  10528. if (v.name === currentVal) opt.selected = true;
  10529. grpVlans.appendChild(opt);
  10530. });
  10531. if (grpVlans.children.length > 0) sel.appendChild(grpVlans);
  10532. // 3. EoIP Tunnels (MikroTik EoIP bridging!)
  10533. const grpEoip = document.createElement('optgroup');
  10534. grpEoip.label = 'EoIP Tunnels (Layer 2 VPN)';
  10535. (state.eoipTunnels || []).forEach(t => {
  10536. const opt = document.createElement('option');
  10537. opt.value = t.name;
  10538. opt.innerText = `${t.name} (Tunnel ID: ${t.tunnel_id} -> ${t.remote_address})`;
  10539. if (t.name === currentVal) opt.selected = true;
  10540. grpEoip.appendChild(opt);
  10541. });
  10542. if (grpEoip.children.length > 0) sel.appendChild(grpEoip);
  10543. }
  10544. // -------------------------------------------------------------
  10545. // DebTik Routing Filters Management (/routing filter)
  10546. // -------------------------------------------------------------
  10547. if (!state.activeRoutingFilterTab) state.activeRoutingFilterTab = 'rules';
  10548. if (!state.selectedFilterRow) state.selectedFilterRow = {};
  10549. if (!state.rfSort) state.rfSort = {};
  10550. function switchRoutingFilterTab(tab) {
  10551. state.activeRoutingFilterTab = tab;
  10552. const tabs = ['rules', 'select-rules', 'community-lists', 'as-lists'];
  10553. tabs.forEach(t => {
  10554. const btn = document.getElementById(`tab-rf-${t}`);
  10555. const content = document.getElementById(`tab-content-rf-${t}`);
  10556. if (btn) {
  10557. if (t === tab) {
  10558. 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';
  10559. } else {
  10560. btn.className = 'px-3 py-1 text-xs font-semibold rounded text-slate-400 hover:text-white hover:bg-slate-800 transition';
  10561. }
  10562. }
  10563. if (content) {
  10564. if (t === tab) content.classList.remove('hidden');
  10565. else content.classList.add('hidden');
  10566. }
  10567. });
  10568. const chainContainer = document.getElementById('rf-chain-filter-container');
  10569. if (chainContainer) {
  10570. if (tab === 'rules' || tab === 'select-rules') chainContainer.classList.remove('hidden');
  10571. else chainContainer.classList.add('hidden');
  10572. }
  10573. renderRoutingFilters();
  10574. }
  10575. function selectFilterRow(tab, id) {
  10576. if (state.selectedFilterRow[tab] === id) {
  10577. delete state.selectedFilterRow[tab];
  10578. } else {
  10579. state.selectedFilterRow[tab] = id;
  10580. }
  10581. if (tab === 'rules') renderRoutingFilterRules();
  10582. else if (tab === 'select-rules') renderRoutingFilterSelectRules();
  10583. else if (tab === 'community-lists') renderRoutingFilterCommunityLists();
  10584. else if (tab === 'as-lists') renderRoutingFilterASLists();
  10585. }
  10586. function openRoutingFilterNewModal() {
  10587. const tab = state.activeRoutingFilterTab || 'rules';
  10588. if (tab === 'rules') openAddRoutingFilterModal();
  10589. else if (tab === 'select-rules') openAddSelectRuleModal();
  10590. else if (tab === 'community-lists') openAddCommunityListModal();
  10591. else if (tab === 'as-lists') openAddASListModal();
  10592. }
  10593. function toggleSelectedRoutingFilter(disabled) {
  10594. const tab = state.activeRoutingFilterTab || 'rules';
  10595. const id = state.selectedFilterRow[tab];
  10596. if (!id) {
  10597. showToast('Select Row', 'Please click on a row to select it first', 'info');
  10598. return;
  10599. }
  10600. if (tab === 'rules') toggleRoutingFilterState(id, disabled);
  10601. else if (tab === 'select-rules') toggleSelectRuleState(id, disabled);
  10602. else if (tab === 'community-lists') toggleCommunityListState(id, disabled);
  10603. else if (tab === 'as-lists') toggleASListState(id, disabled);
  10604. }
  10605. function removeSelectedRoutingFilter() {
  10606. const tab = state.activeRoutingFilterTab || 'rules';
  10607. const id = state.selectedFilterRow[tab];
  10608. if (!id) {
  10609. showToast('Select Row', 'Please click on a row to select it first', 'info');
  10610. return;
  10611. }
  10612. if (tab === 'rules') deleteRoutingFilter(id);
  10613. else if (tab === 'select-rules') deleteSelectRule(id);
  10614. else if (tab === 'community-lists') deleteCommunityList(id);
  10615. else if (tab === 'as-lists') deleteASList(id);
  10616. }
  10617. function searchRoutingFilters(q) {
  10618. state.rfSearchQuery = (q || '').trim().toLowerCase();
  10619. renderRoutingFilters();
  10620. }
  10621. function sortFilterTable(tab, col) {
  10622. if (!state.rfSort) state.rfSort = {};
  10623. if (!state.rfSort[tab]) state.rfSort[tab] = { col: col, asc: true };
  10624. if (state.rfSort[tab].col === col) {
  10625. state.rfSort[tab].asc = !state.rfSort[tab].asc;
  10626. } else {
  10627. state.rfSort[tab].col = col;
  10628. state.rfSort[tab].asc = true;
  10629. }
  10630. const asc = state.rfSort[tab].asc;
  10631. let list = [];
  10632. if (tab === 'rules') list = state.routingFilters || [];
  10633. else if (tab === 'select-rules') list = state.routingSelectRules || [];
  10634. else if (tab === 'community-lists') list = state.routingCommunityLists || [];
  10635. else if (tab === 'as-lists') list = state.routingASLists || [];
  10636. list.sort((a, b) => {
  10637. let valA = a[col] ?? '';
  10638. let valB = b[col] ?? '';
  10639. if (col === 'flags') {
  10640. valA = a.disabled ? 'X' : 'A';
  10641. valB = b.disabled ? 'X' : 'A';
  10642. }
  10643. if (typeof valA === 'number' && typeof valB === 'number') {
  10644. return asc ? valA - valB : valB - valA;
  10645. }
  10646. return asc ? String(valA).localeCompare(String(valB)) : String(valB).localeCompare(String(valA));
  10647. });
  10648. const allCols = ['flags', 'rule_order', 'chain', 'rule', 'name', 'communities', 'range', 'regexp', 'comment'];
  10649. allCols.forEach(c => {
  10650. const el = document.getElementById(`sort-icon-${tab}-${c}`);
  10651. if (el) el.innerText = (c === col) ? (asc ? '▲' : '▼') : '';
  10652. });
  10653. if (tab === 'rules') renderRoutingFilterRules();
  10654. else if (tab === 'select-rules') renderRoutingFilterSelectRules();
  10655. else if (tab === 'community-lists') renderRoutingFilterCommunityLists();
  10656. else if (tab === 'as-lists') renderRoutingFilterASLists();
  10657. }
  10658. function renderRoutingFilters() {
  10659. const navBadge = document.getElementById('badge-filters-count');
  10660. const allRules = state.routingFilters || [];
  10661. if (navBadge) navBadge.innerText = allRules.length;
  10662. // Populate chain filter select options and datalist
  10663. const chainSelect = document.getElementById('routing-filter-chain-select');
  10664. const chainDatalist = document.getElementById('dl-routing-chains');
  10665. const uniqueChains = Array.from(new Set(allRules.map(r => r.chain).filter(Boolean))).sort();
  10666. if (chainSelect) {
  10667. const currentVal = state.filterChainSelected || 'all';
  10668. chainSelect.innerHTML = `<option value="all">All Chains (${allRules.length})</option>` +
  10669. uniqueChains.map(ch => {
  10670. const count = allRules.filter(r => r.chain === ch).length;
  10671. return `<option value="${escapeHtml(ch)}"${currentVal === ch ? ' selected' : ''}>${escapeHtml(ch)} (${count})</option>`;
  10672. }).join('');
  10673. chainSelect.value = currentVal;
  10674. }
  10675. if (chainDatalist) {
  10676. chainDatalist.innerHTML = uniqueChains.map(ch => `<option value="${escapeHtml(ch)}">`).join('');
  10677. }
  10678. renderRoutingFilterRules();
  10679. renderRoutingFilterSelectRules();
  10680. renderRoutingFilterCommunityLists();
  10681. renderRoutingFilterASLists();
  10682. }
  10683. function filterRoutingFiltersByChain(chain) {
  10684. state.filterChainSelected = chain;
  10685. renderRoutingFilters();
  10686. }
  10687. // -------------------------------------------------------------
  10688. // TAB 1: RULES (/routing filter rule)
  10689. // -------------------------------------------------------------
  10690. function renderRoutingFilterRules() {
  10691. const tbody = document.getElementById('routing-filter-rules-tbody');
  10692. if (!tbody) return;
  10693. const empty = document.getElementById('rf-rules-empty');
  10694. const statusCount = document.getElementById('rf-status-count');
  10695. let list = (state.routingFilters || []).slice();
  10696. if (state.filterChainSelected && state.filterChainSelected !== 'all') {
  10697. list = list.filter(r => r.chain === state.filterChainSelected);
  10698. }
  10699. const q = state.rfSearchQuery;
  10700. if (q) {
  10701. list = list.filter(r =>
  10702. (r.chain && r.chain.toLowerCase().includes(q)) ||
  10703. (r.rule && r.rule.toLowerCase().includes(q)) ||
  10704. (r.prefix && r.prefix.toLowerCase().includes(q)) ||
  10705. (r.comment && r.comment.toLowerCase().includes(q))
  10706. );
  10707. }
  10708. if (!state.rfSort?.['rules']) {
  10709. list.sort((a, b) => {
  10710. if (a.chain !== b.chain) return (a.chain || '').localeCompare(b.chain || '');
  10711. return (a.rule_order || 0) - (b.rule_order || 0);
  10712. });
  10713. }
  10714. if (statusCount && (state.activeRoutingFilterTab === 'rules' || !state.activeRoutingFilterTab)) {
  10715. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  10716. }
  10717. if (list.length === 0) {
  10718. tbody.innerHTML = '';
  10719. if (empty) empty.classList.remove('hidden');
  10720. return;
  10721. }
  10722. if (empty) empty.classList.add('hidden');
  10723. tbody.innerHTML = list.map(r => {
  10724. const isSelected = state.selectedFilterRow?.['rules'] === r.id;
  10725. const flagA = !r.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  10726. const flagX = r.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  10727. const flagC = r.comment ? '<span class="text-amber-400 font-bold ml-1" title="Comment">C</span>' : '';
  10728. let ruleDisplay = '';
  10729. if (r.rule && r.rule.trim() !== '') {
  10730. ruleDisplay = `<span class="text-emerald-400 font-mono font-medium">${escapeHtml(r.rule)}</span>`;
  10731. } else {
  10732. let conds = [];
  10733. if (r.prefix) conds.push(`dst in ${escapeHtml(r.prefix)}`);
  10734. if (r.match_protocol && r.match_protocol !== 'any') conds.push(`protocol ${escapeHtml(r.match_protocol)}`);
  10735. let act = r.action || 'accept';
  10736. ruleDisplay = `<span class="text-slate-300 font-mono">if (${conds.length ? conds.join(' && ') : 'true'}) { ${escapeHtml(act)}; }</span>`;
  10737. }
  10738. return `
  10739. <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'}">
  10740. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}${flagC}</td>
  10741. <td class="py-2 px-2 font-mono text-slate-400 font-bold">${r.rule_order || 10}</td>
  10742. <td class="py-2 px-3">
  10743. <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>
  10744. </td>
  10745. <td class="py-2 px-3 break-all max-w-xl">${ruleDisplay}</td>
  10746. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(r.comment || '')}</td>
  10747. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  10748. <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>
  10749. <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>
  10750. <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'}">
  10751. ${r.disabled ? 'Enable' : 'Disable'}
  10752. </button>
  10753. <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">
  10754. Edit
  10755. </button>
  10756. <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">
  10757. ✕
  10758. </button>
  10759. </td>
  10760. </tr>
  10761. `;
  10762. }).join('');
  10763. }
  10764. // -------------------------------------------------------------
  10765. // TAB 2: SELECT RULES (/routing filter select-rule)
  10766. // -------------------------------------------------------------
  10767. function renderRoutingFilterSelectRules() {
  10768. const tbody = document.getElementById('routing-filter-select-rules-tbody');
  10769. if (!tbody) return;
  10770. const empty = document.getElementById('rf-select-rules-empty');
  10771. const statusCount = document.getElementById('rf-status-count');
  10772. let list = (state.routingSelectRules || []).slice();
  10773. if (state.filterChainSelected && state.filterChainSelected !== 'all') {
  10774. list = list.filter(r => r.chain === state.filterChainSelected);
  10775. }
  10776. const q = state.rfSearchQuery;
  10777. if (q) {
  10778. list = list.filter(r =>
  10779. (r.chain && r.chain.toLowerCase().includes(q)) ||
  10780. (r.rule && r.rule.toLowerCase().includes(q)) ||
  10781. (r.comment && r.comment.toLowerCase().includes(q))
  10782. );
  10783. }
  10784. if (statusCount && state.activeRoutingFilterTab === 'select-rules') {
  10785. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  10786. }
  10787. if (list.length === 0) {
  10788. tbody.innerHTML = '';
  10789. if (empty) empty.classList.remove('hidden');
  10790. return;
  10791. }
  10792. if (empty) empty.classList.add('hidden');
  10793. tbody.innerHTML = list.map(r => {
  10794. const isSelected = state.selectedFilterRow?.['select-rules'] === r.id;
  10795. const flagA = !r.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  10796. const flagX = r.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  10797. return `
  10798. <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'}">
  10799. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  10800. <td class="py-2 px-2 font-mono text-slate-400 font-bold">${r.rule_order || 10}</td>
  10801. <td class="py-2 px-3">
  10802. <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>
  10803. </td>
  10804. <td class="py-2 px-3 break-all max-w-xl font-mono text-emerald-400">${escapeHtml(r.rule || '')}</td>
  10805. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(r.comment || '')}</td>
  10806. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  10807. <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'}">
  10808. ${r.disabled ? 'Enable' : 'Disable'}
  10809. </button>
  10810. <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">
  10811. Edit
  10812. </button>
  10813. <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">
  10814. ✕
  10815. </button>
  10816. </td>
  10817. </tr>
  10818. `;
  10819. }).join('');
  10820. }
  10821. // -------------------------------------------------------------
  10822. // TAB 3: COMMUNITY LISTS (/routing filter community-list)
  10823. // -------------------------------------------------------------
  10824. function renderRoutingFilterCommunityLists() {
  10825. const tbody = document.getElementById('routing-filter-comm-lists-tbody');
  10826. if (!tbody) return;
  10827. const empty = document.getElementById('rf-comm-lists-empty');
  10828. const statusCount = document.getElementById('rf-status-count');
  10829. let list = (state.routingCommunityLists || []).slice();
  10830. const q = state.rfSearchQuery;
  10831. if (q) {
  10832. list = list.filter(cl =>
  10833. (cl.name && cl.name.toLowerCase().includes(q)) ||
  10834. (cl.comment && cl.comment.toLowerCase().includes(q)) ||
  10835. (cl.communities && cl.communities.some(c => c.toLowerCase().includes(q)))
  10836. );
  10837. }
  10838. if (statusCount && state.activeRoutingFilterTab === 'community-lists') {
  10839. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  10840. }
  10841. if (list.length === 0) {
  10842. tbody.innerHTML = '';
  10843. if (empty) empty.classList.remove('hidden');
  10844. return;
  10845. }
  10846. if (empty) empty.classList.add('hidden');
  10847. tbody.innerHTML = list.map(cl => {
  10848. const isSelected = state.selectedFilterRow?.['community-lists'] === cl.id;
  10849. const flagA = !cl.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  10850. const flagX = cl.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  10851. const commBadges = (cl.communities || []).map(c =>
  10852. `<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>`
  10853. ).join(' ');
  10854. return `
  10855. <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'}">
  10856. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  10857. <td class="py-2 px-3 font-mono font-bold text-white">${escapeHtml(cl.name)}</td>
  10858. <td class="py-2 px-3 space-x-1">${commBadges || '<span class="text-slate-600">-</span>'}</td>
  10859. <td class="py-2 px-3 font-mono text-slate-400">${escapeHtml(cl.regexp || '-')}</td>
  10860. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(cl.comment || '')}</td>
  10861. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  10862. <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'}">
  10863. ${cl.disabled ? 'Enable' : 'Disable'}
  10864. </button>
  10865. <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">
  10866. Edit
  10867. </button>
  10868. <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">
  10869. ✕
  10870. </button>
  10871. </td>
  10872. </tr>
  10873. `;
  10874. }).join('');
  10875. }
  10876. // -------------------------------------------------------------
  10877. // TAB 4: AS LISTS (/routing filter num-list)
  10878. // -------------------------------------------------------------
  10879. function renderRoutingFilterASLists() {
  10880. const tbody = document.getElementById('routing-filter-as-lists-tbody');
  10881. if (!tbody) return;
  10882. const empty = document.getElementById('rf-as-lists-empty');
  10883. const statusCount = document.getElementById('rf-status-count');
  10884. let list = (state.routingASLists || []).slice();
  10885. const q = state.rfSearchQuery;
  10886. if (q) {
  10887. list = list.filter(al =>
  10888. (al.name && al.name.toLowerCase().includes(q)) ||
  10889. (al.range && al.range.toLowerCase().includes(q)) ||
  10890. (al.comment && al.comment.toLowerCase().includes(q))
  10891. );
  10892. }
  10893. if (statusCount && state.activeRoutingFilterTab === 'as-lists') {
  10894. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  10895. }
  10896. if (list.length === 0) {
  10897. tbody.innerHTML = '';
  10898. if (empty) empty.classList.remove('hidden');
  10899. return;
  10900. }
  10901. if (empty) empty.classList.add('hidden');
  10902. tbody.innerHTML = list.map(al => {
  10903. const isSelected = state.selectedFilterRow?.['as-lists'] === al.id;
  10904. const flagA = !al.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  10905. const flagX = al.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  10906. return `
  10907. <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'}">
  10908. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  10909. <td class="py-2 px-3 font-mono font-bold text-white">${escapeHtml(al.name)}</td>
  10910. <td class="py-2 px-3 font-mono text-purple-300">${escapeHtml(al.range)}</td>
  10911. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(al.comment || '')}</td>
  10912. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  10913. <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'}">
  10914. ${al.disabled ? 'Enable' : 'Disable'}
  10915. </button>
  10916. <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">
  10917. Edit
  10918. </button>
  10919. <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">
  10920. ✕
  10921. </button>
  10922. </td>
  10923. </tr>
  10924. `;
  10925. }).join('');
  10926. }
  10927. // -------------------------------------------------------------
  10928. // SNIPPETS & WIZARD HELPERS
  10929. // -------------------------------------------------------------
  10930. function insertRuleSnippet(type) {
  10931. const textarea = document.getElementById('modal-rf-rule');
  10932. if (!textarea) return;
  10933. let snippet = '';
  10934. switch (type) {
  10935. case 'accept-default':
  10936. snippet = 'if (dst in 0.0.0.0/0) { accept; }';
  10937. break;
  10938. case 'drop-rfc1918':
  10939. snippet = 'if (dst in 10.0.0.0/8 || dst in 172.16.0.0/12 || dst in 192.168.0.0/16) { reject; }';
  10940. break;
  10941. case 'len-24':
  10942. snippet = 'if (dst-len > 24) { reject; }';
  10943. break;
  10944. case 'local-pref-150':
  10945. snippet = 'if (dst in 10.0.0.0/8) { set bgp-local-pref 150; accept; }';
  10946. break;
  10947. case 'as-prepend-2':
  10948. snippet = 'set bgp-path-prepend 2; accept;';
  10949. break;
  10950. case 'set-comm':
  10951. snippet = 'set bgp-communities.add 65000:100; accept;';
  10952. break;
  10953. case 'match-comm':
  10954. snippet = 'if (bgp-communities includes 65000:100) { accept; }';
  10955. break;
  10956. case 'reject-all':
  10957. snippet = 'reject;';
  10958. break;
  10959. }
  10960. if (!snippet) return;
  10961. if (!textarea.value.trim()) {
  10962. textarea.value = snippet;
  10963. } else {
  10964. textarea.value = textarea.value.trim() + '\n' + snippet;
  10965. }
  10966. }
  10967. function generateScriptFromWizard() {
  10968. const pfx = (document.getElementById('modal-rf-prefix')?.value || '').trim();
  10969. const pfxLen = (document.getElementById('modal-rf-prefix-len')?.value || '').trim();
  10970. const proto = document.getElementById('modal-rf-protocol')?.value || 'any';
  10971. const asp = (document.getElementById('modal-rf-as-path')?.value || '').trim();
  10972. const comm = (document.getElementById('modal-rf-community')?.value || '').trim();
  10973. const act = document.getElementById('modal-rf-action')?.value || 'accept';
  10974. const lp = parseInt(document.getElementById('modal-rf-set-local-pref')?.value, 10) || 0;
  10975. const prep = parseInt(document.getElementById('modal-rf-set-as-prepend')?.value, 10) || 0;
  10976. const conds = [];
  10977. if (pfx) {
  10978. if (pfxLen) {
  10979. if (pfxLen.includes('-')) {
  10980. const parts = pfxLen.split('-');
  10981. conds.push(`dst in ${pfx}{${parts[0].trim()},${parts[1].trim()}}`);
  10982. } else {
  10983. conds.push(`dst in ${pfx} && dst-len >= ${pfxLen}`);
  10984. }
  10985. } else {
  10986. conds.push(`dst in ${pfx}`);
  10987. }
  10988. }
  10989. if (proto && proto !== 'any') {
  10990. conds.push(`protocol ${proto}`);
  10991. }
  10992. if (asp) {
  10993. conds.push(`bgp-as-path "${asp}"`);
  10994. }
  10995. if (comm) {
  10996. conds.push(`bgp-communities includes ${comm}`);
  10997. }
  10998. const actions = [];
  10999. if (lp > 0) actions.push(`set bgp-local-pref ${lp};`);
  11000. if (prep > 0) actions.push(`set bgp-path-prepend ${prep};`);
  11001. actions.push(`${act};`);
  11002. let code = '';
  11003. if (conds.length > 0) {
  11004. code = `if (${conds.join(' && ')}) {\n ${actions.join(' ')}\n}`;
  11005. } else {
  11006. code = actions.join(' ');
  11007. }
  11008. const textarea = document.getElementById('modal-rf-rule');
  11009. if (textarea) textarea.value = code;
  11010. }
  11011. // -------------------------------------------------------------
  11012. // MODAL CRUD: RULES (/routing filter rule)
  11013. // -------------------------------------------------------------
  11014. function openAddRoutingFilterModal(defaultChain = '') {
  11015. const form = document.getElementById('routing-filter-form');
  11016. if (form) form.reset();
  11017. const idEl = document.getElementById('modal-rf-id');
  11018. if (idEl) idEl.value = '';
  11019. const titleEl = document.getElementById('modal-rf-title');
  11020. if (titleEl) titleEl.innerText = 'Add Routing Filter Rule';
  11021. const chainEl = document.getElementById('modal-rf-chain');
  11022. if (chainEl) chainEl.value = defaultChain || (state.filterChainSelected && state.filterChainSelected !== 'all' ? state.filterChainSelected : 'bgp-in');
  11023. const orderEl = document.getElementById('modal-rf-order');
  11024. if (orderEl) orderEl.value = ((state.routingFilters || []).length + 1) * 10;
  11025. const ruleEl = document.getElementById('modal-rf-rule');
  11026. if (ruleEl) ruleEl.value = 'if (dst in 10.0.0.0/8) { set bgp-local-pref 150; accept; }';
  11027. const disEl = document.getElementById('modal-rf-disabled');
  11028. if (disEl) disEl.checked = false;
  11029. const modal = document.getElementById('modal-routing-filter');
  11030. if (modal) modal.classList.remove('hidden');
  11031. }
  11032. function openEditRoutingFilterModal(id) {
  11033. const r = (state.routingFilters || []).find(item => item.id === id);
  11034. if (!r) return;
  11035. const idEl = document.getElementById('modal-rf-id');
  11036. if (idEl) idEl.value = r.id;
  11037. const titleEl = document.getElementById('modal-rf-title');
  11038. if (titleEl) titleEl.innerText = 'Edit Routing Filter Rule';
  11039. const chainEl = document.getElementById('modal-rf-chain');
  11040. if (chainEl) chainEl.value = r.chain || '';
  11041. const orderEl = document.getElementById('modal-rf-order');
  11042. if (orderEl) orderEl.value = r.rule_order || 10;
  11043. const ruleEl = document.getElementById('modal-rf-rule');
  11044. if (ruleEl) {
  11045. if (r.rule) {
  11046. ruleEl.value = r.rule;
  11047. } else {
  11048. let conds = [];
  11049. if (r.prefix) conds.push(`dst in ${r.prefix}`);
  11050. if (r.match_protocol && r.match_protocol !== 'any') conds.push(`protocol ${r.match_protocol}`);
  11051. let act = r.action || 'accept';
  11052. ruleEl.value = `if (${conds.length ? conds.join(' && ') : 'true'}) { ${act}; }`;
  11053. }
  11054. }
  11055. const comEl = document.getElementById('modal-rf-comment');
  11056. if (comEl) comEl.value = r.comment || '';
  11057. const disEl = document.getElementById('modal-rf-disabled');
  11058. if (disEl) disEl.checked = !!r.disabled;
  11059. const modal = document.getElementById('modal-routing-filter');
  11060. if (modal) modal.classList.remove('hidden');
  11061. }
  11062. function closeRoutingFilterModal() {
  11063. const modal = document.getElementById('modal-routing-filter');
  11064. if (modal) modal.classList.add('hidden');
  11065. }
  11066. async function submitRoutingFilter(e) {
  11067. if (e) e.preventDefault();
  11068. const payload = {
  11069. id: document.getElementById('modal-rf-id').value,
  11070. chain: document.getElementById('modal-rf-chain').value.trim(),
  11071. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  11072. rule: document.getElementById('modal-rf-rule').value.trim(),
  11073. comment: document.getElementById('modal-rf-comment').value.trim(),
  11074. disabled: document.getElementById('modal-rf-disabled').checked
  11075. };
  11076. try {
  11077. const res = await fetch(`${API_BASE}/routing/filters`, {
  11078. method: 'POST',
  11079. headers: { 'Content-Type': 'application/json' },
  11080. body: JSON.stringify(payload)
  11081. });
  11082. if (res.ok) {
  11083. closeRoutingFilterModal();
  11084. showToast('Success', 'Routing filter rule saved', 'success');
  11085. loadDynamicRouting();
  11086. } else {
  11087. const err = await res.json();
  11088. showToast('Error', err.error || 'Failed to save filter rule', 'error');
  11089. }
  11090. } catch (err) {
  11091. showToast('Error', err.message, 'error');
  11092. }
  11093. }
  11094. async function applyRoutingFilterForm() {
  11095. const payload = {
  11096. id: document.getElementById('modal-rf-id').value,
  11097. chain: document.getElementById('modal-rf-chain').value.trim(),
  11098. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  11099. rule: document.getElementById('modal-rf-rule').value.trim(),
  11100. comment: document.getElementById('modal-rf-comment').value.trim(),
  11101. disabled: document.getElementById('modal-rf-disabled').checked
  11102. };
  11103. try {
  11104. const res = await fetch(`${API_BASE}/routing/filters`, {
  11105. method: 'POST',
  11106. headers: { 'Content-Type': 'application/json' },
  11107. body: JSON.stringify(payload)
  11108. });
  11109. if (res.ok) {
  11110. const data = await res.json();
  11111. if (data.id) document.getElementById('modal-rf-id').value = data.id;
  11112. showToast('Applied', 'Routing filter configuration applied', 'success');
  11113. loadDynamicRouting();
  11114. } else {
  11115. const err = await res.json();
  11116. showToast('Error', err.error || 'Failed to apply filter rule', 'error');
  11117. }
  11118. } catch (err) {
  11119. showToast('Error', err.message, 'error');
  11120. }
  11121. }
  11122. async function moveRoutingFilterOrder(id, delta) {
  11123. const list = state.routingFilters || [];
  11124. const idx = list.findIndex(r => r.id === id);
  11125. if (idx < 0) return;
  11126. const targetIdx = idx + delta;
  11127. if (targetIdx < 0 || targetIdx >= list.length) return;
  11128. const currentOrder = list[idx].rule_order || 10;
  11129. const targetOrder = list[targetIdx].rule_order || 20;
  11130. list[idx].rule_order = targetOrder;
  11131. list[targetIdx].rule_order = currentOrder;
  11132. try {
  11133. await fetch(`${API_BASE}/routing/filters`, {
  11134. method: 'POST',
  11135. headers: { 'Content-Type': 'application/json' },
  11136. body: JSON.stringify(list[idx])
  11137. });
  11138. await fetch(`${API_BASE}/routing/filters`, {
  11139. method: 'POST',
  11140. headers: { 'Content-Type': 'application/json' },
  11141. body: JSON.stringify(list[targetIdx])
  11142. });
  11143. loadDynamicRouting();
  11144. } catch (e) {
  11145. console.error('Reorder error:', e);
  11146. }
  11147. }
  11148. async function deleteRoutingFilter(id) {
  11149. if (!confirm('Are you sure you want to delete this routing filter rule?')) return;
  11150. try {
  11151. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11152. if (res.ok) {
  11153. showToast('Deleted', 'Routing filter rule removed', 'info');
  11154. loadDynamicRouting();
  11155. } else {
  11156. const err = await res.json();
  11157. showToast('Error', err.error || 'Failed to delete rule', 'error');
  11158. }
  11159. } catch (err) {
  11160. showToast('Error', err.message, 'error');
  11161. }
  11162. }
  11163. async function toggleRoutingFilterState(id, disabled) {
  11164. try {
  11165. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}/state`, {
  11166. method: 'POST',
  11167. headers: { 'Content-Type': 'application/json' },
  11168. body: JSON.stringify({ disabled })
  11169. });
  11170. if (res.ok) {
  11171. showToast('Status Updated', `Rule ${disabled ? 'disabled' : 'enabled'}`, 'info');
  11172. loadDynamicRouting();
  11173. } else {
  11174. const err = await res.json();
  11175. showToast('Error', err.error || 'Failed to toggle rule state', 'error');
  11176. }
  11177. } catch (err) {
  11178. showToast('Error', err.message, 'error');
  11179. }
  11180. }
  11181. // -------------------------------------------------------------
  11182. // MODAL CRUD: SELECT RULES (/routing filter select-rule)
  11183. // -------------------------------------------------------------
  11184. function openAddSelectRuleModal() {
  11185. document.getElementById('modal-rf-sr-id').value = '';
  11186. document.getElementById('modal-rf-sr-title').innerText = 'Add Routing Select Rule';
  11187. document.getElementById('modal-rf-sr-chain').value = state.filterChainSelected && state.filterChainSelected !== 'all' ? state.filterChainSelected : 'bgp-out';
  11188. document.getElementById('modal-rf-sr-order').value = ((state.routingSelectRules || []).length + 1) * 10;
  11189. document.getElementById('modal-rf-sr-rule').value = 'if (protocol bgp && dst in 10.0.0.0/8) { accept; }';
  11190. document.getElementById('modal-rf-sr-comment').value = '';
  11191. document.getElementById('modal-rf-sr-disabled').checked = false;
  11192. document.getElementById('modal-rf-select-rule').classList.remove('hidden');
  11193. }
  11194. function openEditSelectRuleModal(id) {
  11195. const r = (state.routingSelectRules || []).find(item => item.id === id);
  11196. if (!r) return;
  11197. document.getElementById('modal-rf-sr-id').value = r.id;
  11198. document.getElementById('modal-rf-sr-title').innerText = 'Edit Routing Select Rule';
  11199. document.getElementById('modal-rf-sr-chain').value = r.chain || '';
  11200. document.getElementById('modal-rf-sr-order').value = r.rule_order || 10;
  11201. document.getElementById('modal-rf-sr-rule').value = r.rule || '';
  11202. document.getElementById('modal-rf-sr-comment').value = r.comment || '';
  11203. document.getElementById('modal-rf-sr-disabled').checked = !!r.disabled;
  11204. document.getElementById('modal-rf-select-rule').classList.remove('hidden');
  11205. }
  11206. function closeSelectRuleModal() {
  11207. document.getElementById('modal-rf-select-rule').classList.add('hidden');
  11208. }
  11209. async function submitSelectRule(e) {
  11210. e.preventDefault();
  11211. const payload = {
  11212. id: document.getElementById('modal-rf-sr-id').value,
  11213. chain: document.getElementById('modal-rf-sr-chain').value.trim(),
  11214. rule_order: parseInt(document.getElementById('modal-rf-sr-order').value, 10) || 10,
  11215. rule: document.getElementById('modal-rf-sr-rule').value.trim(),
  11216. comment: document.getElementById('modal-rf-sr-comment').value.trim(),
  11217. disabled: document.getElementById('modal-rf-sr-disabled').checked
  11218. };
  11219. try {
  11220. const res = await fetch(`${API_BASE}/routing/filters/select-rules`, {
  11221. method: 'POST',
  11222. headers: { 'Content-Type': 'application/json' },
  11223. body: JSON.stringify(payload)
  11224. });
  11225. if (res.ok) {
  11226. closeSelectRuleModal();
  11227. showToast('Success', 'Select rule saved', 'success');
  11228. loadDynamicRouting();
  11229. } else {
  11230. const err = await res.json();
  11231. showToast('Error', err.error || 'Failed to save select rule', 'error');
  11232. }
  11233. } catch (err) {
  11234. showToast('Error', err.message, 'error');
  11235. }
  11236. }
  11237. async function deleteSelectRule(id) {
  11238. if (!confirm('Are you sure you want to delete this select rule?')) return;
  11239. try {
  11240. const res = await fetch(`${API_BASE}/routing/filters/select-rules/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11241. if (res.ok) {
  11242. showToast('Deleted', 'Select rule removed', 'info');
  11243. loadDynamicRouting();
  11244. } else {
  11245. const err = await res.json();
  11246. showToast('Error', err.error || 'Failed to delete select rule', 'error');
  11247. }
  11248. } catch (err) {
  11249. showToast('Error', err.message, 'error');
  11250. }
  11251. }
  11252. async function toggleSelectRuleState(id, disabled) {
  11253. try {
  11254. const res = await fetch(`${API_BASE}/routing/filters/select-rules/${encodeURIComponent(id)}/state`, {
  11255. method: 'POST',
  11256. headers: { 'Content-Type': 'application/json' },
  11257. body: JSON.stringify({ disabled })
  11258. });
  11259. if (res.ok) {
  11260. showToast('Status Updated', `Select rule ${disabled ? 'disabled' : 'enabled'}`, 'info');
  11261. loadDynamicRouting();
  11262. } else {
  11263. const err = await res.json();
  11264. showToast('Error', err.error || 'Failed to update select rule state', 'error');
  11265. }
  11266. } catch (err) {
  11267. showToast('Error', err.message, 'error');
  11268. }
  11269. }
  11270. // -------------------------------------------------------------
  11271. // MODAL CRUD: COMMUNITY LISTS (/routing filter community-list)
  11272. // -------------------------------------------------------------
  11273. function openAddCommunityListModal() {
  11274. document.getElementById('modal-rf-cl-id').value = '';
  11275. document.getElementById('modal-rf-cl-title').innerText = 'Add BGP Community List';
  11276. document.getElementById('modal-rf-cl-name').value = '';
  11277. document.getElementById('modal-rf-cl-communities').value = '';
  11278. document.getElementById('modal-rf-cl-regexp').value = '';
  11279. document.getElementById('modal-rf-cl-comment').value = '';
  11280. document.getElementById('modal-rf-cl-disabled').checked = false;
  11281. document.getElementById('modal-rf-community-list').classList.remove('hidden');
  11282. }
  11283. function openEditCommunityListModal(id) {
  11284. const cl = (state.routingCommunityLists || []).find(item => item.id === id);
  11285. if (!cl) return;
  11286. document.getElementById('modal-rf-cl-id').value = cl.id;
  11287. document.getElementById('modal-rf-cl-title').innerText = 'Edit BGP Community List';
  11288. document.getElementById('modal-rf-cl-name').value = cl.name || '';
  11289. document.getElementById('modal-rf-cl-communities').value = (cl.communities || []).join(', ');
  11290. document.getElementById('modal-rf-cl-regexp').value = cl.regexp || '';
  11291. document.getElementById('modal-rf-cl-comment').value = cl.comment || '';
  11292. document.getElementById('modal-rf-cl-disabled').checked = !!cl.disabled;
  11293. document.getElementById('modal-rf-community-list').classList.remove('hidden');
  11294. }
  11295. function closeCommunityListModal() {
  11296. document.getElementById('modal-rf-community-list').classList.add('hidden');
  11297. }
  11298. async function submitCommunityList(e) {
  11299. e.preventDefault();
  11300. const rawComms = document.getElementById('modal-rf-cl-communities').value;
  11301. const comms = rawComms.split(',').map(c => c.trim()).filter(Boolean);
  11302. const payload = {
  11303. id: document.getElementById('modal-rf-cl-id').value,
  11304. name: document.getElementById('modal-rf-cl-name').value.trim(),
  11305. communities: comms,
  11306. regexp: document.getElementById('modal-rf-cl-regexp').value.trim(),
  11307. comment: document.getElementById('modal-rf-cl-comment').value.trim(),
  11308. disabled: document.getElementById('modal-rf-cl-disabled').checked
  11309. };
  11310. try {
  11311. const res = await fetch(`${API_BASE}/routing/filters/community-lists`, {
  11312. method: 'POST',
  11313. headers: { 'Content-Type': 'application/json' },
  11314. body: JSON.stringify(payload)
  11315. });
  11316. if (res.ok) {
  11317. closeCommunityListModal();
  11318. showToast('Success', 'Community list saved', 'success');
  11319. loadDynamicRouting();
  11320. } else {
  11321. const err = await res.json();
  11322. showToast('Error', err.error || 'Failed to save community list', 'error');
  11323. }
  11324. } catch (err) {
  11325. showToast('Error', err.message, 'error');
  11326. }
  11327. }
  11328. async function deleteCommunityList(id) {
  11329. if (!confirm('Are you sure you want to delete this community list?')) return;
  11330. try {
  11331. const res = await fetch(`${API_BASE}/routing/filters/community-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11332. if (res.ok) {
  11333. showToast('Deleted', 'Community list removed', 'info');
  11334. loadDynamicRouting();
  11335. } else {
  11336. const err = await res.json();
  11337. showToast('Error', err.error || 'Failed to delete community list', 'error');
  11338. }
  11339. } catch (err) {
  11340. showToast('Error', err.message, 'error');
  11341. }
  11342. }
  11343. async function toggleCommunityListState(id, disabled) {
  11344. try {
  11345. const res = await fetch(`${API_BASE}/routing/filters/community-lists/${encodeURIComponent(id)}/state`, {
  11346. method: 'POST',
  11347. headers: { 'Content-Type': 'application/json' },
  11348. body: JSON.stringify({ disabled })
  11349. });
  11350. if (res.ok) {
  11351. showToast('Status Updated', `Community list ${disabled ? 'disabled' : 'enabled'}`, 'info');
  11352. loadDynamicRouting();
  11353. } else {
  11354. const err = await res.json();
  11355. showToast('Error', err.error || 'Failed to update community list state', 'error');
  11356. }
  11357. } catch (err) {
  11358. showToast('Error', err.message, 'error');
  11359. }
  11360. }
  11361. // -------------------------------------------------------------
  11362. // MODAL CRUD: AS LISTS (/routing filter num-list)
  11363. // -------------------------------------------------------------
  11364. function openAddASListModal() {
  11365. document.getElementById('modal-rf-al-id').value = '';
  11366. document.getElementById('modal-rf-al-title').innerText = 'Add AS Number List';
  11367. document.getElementById('modal-rf-al-name').value = '';
  11368. document.getElementById('modal-rf-al-range').value = '';
  11369. document.getElementById('modal-rf-al-comment').value = '';
  11370. document.getElementById('modal-rf-al-disabled').checked = false;
  11371. document.getElementById('modal-rf-as-list').classList.remove('hidden');
  11372. }
  11373. function openEditASListModal(id) {
  11374. const al = (state.routingASLists || []).find(item => item.id === id);
  11375. if (!al) return;
  11376. document.getElementById('modal-rf-al-id').value = al.id;
  11377. document.getElementById('modal-rf-al-title').innerText = 'Edit AS Number List';
  11378. document.getElementById('modal-rf-al-name').value = al.name || '';
  11379. document.getElementById('modal-rf-al-range').value = al.range || '';
  11380. document.getElementById('modal-rf-al-comment').value = al.comment || '';
  11381. document.getElementById('modal-rf-al-disabled').checked = !!al.disabled;
  11382. document.getElementById('modal-rf-as-list').classList.remove('hidden');
  11383. }
  11384. function closeASListModal() {
  11385. document.getElementById('modal-rf-as-list').classList.add('hidden');
  11386. }
  11387. async function submitASList(e) {
  11388. e.preventDefault();
  11389. const payload = {
  11390. id: document.getElementById('modal-rf-al-id').value,
  11391. name: document.getElementById('modal-rf-al-name').value.trim(),
  11392. range: document.getElementById('modal-rf-al-range').value.trim(),
  11393. comment: document.getElementById('modal-rf-al-comment').value.trim(),
  11394. disabled: document.getElementById('modal-rf-al-disabled').checked
  11395. };
  11396. try {
  11397. const res = await fetch(`${API_BASE}/routing/filters/as-lists`, {
  11398. method: 'POST',
  11399. headers: { 'Content-Type': 'application/json' },
  11400. body: JSON.stringify(payload)
  11401. });
  11402. if (res.ok) {
  11403. closeASListModal();
  11404. showToast('Success', 'AS number list saved', 'success');
  11405. loadDynamicRouting();
  11406. } else {
  11407. const err = await res.json();
  11408. showToast('Error', err.error || 'Failed to save AS list', 'error');
  11409. }
  11410. } catch (err) {
  11411. showToast('Error', err.message, 'error');
  11412. }
  11413. }
  11414. async function deleteASList(id) {
  11415. if (!confirm('Are you sure you want to delete this AS list?')) return;
  11416. try {
  11417. const res = await fetch(`${API_BASE}/routing/filters/as-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11418. if (res.ok) {
  11419. showToast('Deleted', 'AS list removed', 'info');
  11420. loadDynamicRouting();
  11421. } else {
  11422. const err = await res.json();
  11423. showToast('Error', err.error || 'Failed to delete AS list', 'error');
  11424. }
  11425. } catch (err) {
  11426. showToast('Error', err.message, 'error');
  11427. }
  11428. }
  11429. async function toggleASListState(id, disabled) {
  11430. try {
  11431. const res = await fetch(`${API_BASE}/routing/filters/as-lists/${encodeURIComponent(id)}/state`, {
  11432. method: 'POST',
  11433. headers: { 'Content-Type': 'application/json' },
  11434. body: JSON.stringify({ disabled })
  11435. });
  11436. if (res.ok) {
  11437. showToast('Status Updated', `AS list ${disabled ? 'disabled' : 'enabled'}`, 'info');
  11438. loadDynamicRouting();
  11439. } else {
  11440. const err = await res.json();
  11441. showToast('Error', err.error || 'Failed to update AS list state', 'error');
  11442. }
  11443. } catch (err) {
  11444. showToast('Error', err.message, 'error');
  11445. }
  11446. }
  11447. // ==========================================
  11448. // TROUBLESHOOT & DIAGNOSTIC TOOLS (/tool)
  11449. // ==========================================
  11450. function loadToolsView() {
  11451. populateToolsInterfaces();
  11452. switchToolsSubTab(state.activeToolsSubTab || 'ping');
  11453. }
  11454. function populateToolsInterfaces() {
  11455. const pingSel = document.getElementById('tools-ping-iface');
  11456. const traceSel = document.getElementById('tools-tr-iface');
  11457. let opts = '<option value="">Auto (Default Route)</option>';
  11458. if (Array.isArray(state.interfaces)) {
  11459. state.interfaces.forEach(iface => {
  11460. if (iface.name) {
  11461. opts += `<option value="${escapeHtml(iface.name)}">${escapeHtml(iface.name)}${iface.ip_address ? ' (' + escapeHtml(iface.ip_address) + ')' : ''}</option>`;
  11462. }
  11463. });
  11464. }
  11465. if (pingSel) {
  11466. const cur = pingSel.value;
  11467. pingSel.innerHTML = opts;
  11468. if (cur) pingSel.value = cur;
  11469. }
  11470. if (traceSel) {
  11471. const cur = traceSel.value;
  11472. traceSel.innerHTML = opts;
  11473. if (cur) traceSel.value = cur;
  11474. }
  11475. }
  11476. function switchToolsSubTab(subTab) {
  11477. state.activeToolsSubTab = subTab;
  11478. const tabs = ['ping', 'traceroute', 'mtr', 'dns', 'port'];
  11479. tabs.forEach(t => {
  11480. const btn = document.getElementById(`tools-subtab-btn-${t}`);
  11481. const view = document.getElementById(`tools-view-${t}`);
  11482. if (btn) {
  11483. if (t === subTab) {
  11484. 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';
  11485. } else {
  11486. 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';
  11487. }
  11488. }
  11489. if (view) {
  11490. if (t === subTab) {
  11491. view.classList.remove('hidden');
  11492. } else {
  11493. view.classList.add('hidden');
  11494. }
  11495. }
  11496. });
  11497. }
  11498. function setPortPreset(port) {
  11499. const input = document.getElementById('tools-port-num');
  11500. if (input) input.value = port;
  11501. }
  11502. let pingAbortController = null;
  11503. let tracerouteAbortController = null;
  11504. function clearPingTable() {
  11505. const tbody = document.getElementById('tools-ping-tbody');
  11506. if (tbody) tbody.innerHTML = '';
  11507. const rawEl = document.getElementById('tools-ping-raw');
  11508. if (rawEl) rawEl.innerText = '';
  11509. const sentEl = document.getElementById('tools-ping-stat-sent');
  11510. if (sentEl) sentEl.innerText = '0';
  11511. const recvEl = document.getElementById('tools-ping-stat-recv');
  11512. if (recvEl) recvEl.innerText = '0';
  11513. const lossEl = document.getElementById('tools-ping-stat-loss');
  11514. if (lossEl) lossEl.innerText = '0%';
  11515. const avgEl = document.getElementById('tools-ping-stat-avg');
  11516. if (avgEl) avgEl.innerText = '0 ms';
  11517. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  11518. if (minMaxEl) minMaxEl.innerText = '-';
  11519. const badge = document.getElementById('tools-ping-status-badge');
  11520. if (badge) {
  11521. badge.className = '';
  11522. badge.innerText = '';
  11523. }
  11524. }
  11525. function clearTracerouteTable() {
  11526. const tbody = document.getElementById('tools-tr-tbody');
  11527. if (tbody) tbody.innerHTML = '';
  11528. const rawEl = document.getElementById('tools-tr-raw');
  11529. if (rawEl) rawEl.innerText = '';
  11530. const statHops = document.getElementById('tools-tr-hops-count');
  11531. if (statHops) statHops.innerText = '0 Hops';
  11532. }
  11533. function resetPingButton() {
  11534. const btn = document.getElementById('tools-ping-btn');
  11535. const btnText = document.getElementById('tools-ping-btn-text');
  11536. const spinner = document.getElementById('tools-ping-spinner');
  11537. if (btn) {
  11538. btn.disabled = false;
  11539. 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';
  11540. }
  11541. if (btnText) btnText.innerText = 'Start Ping';
  11542. if (spinner) spinner.classList.add('hidden');
  11543. }
  11544. function setPingRunningButton() {
  11545. const btn = document.getElementById('tools-ping-btn');
  11546. const btnText = document.getElementById('tools-ping-btn-text');
  11547. const spinner = document.getElementById('tools-ping-spinner');
  11548. if (btn) {
  11549. btn.disabled = false;
  11550. 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';
  11551. }
  11552. if (btnText) btnText.innerText = 'Stop Ping';
  11553. if (spinner) spinner.classList.remove('hidden');
  11554. }
  11555. function resetTracerouteButton() {
  11556. const btn = document.getElementById('tools-tr-btn');
  11557. const btnText = document.getElementById('tools-tr-btn-text');
  11558. const spinner = document.getElementById('tools-tr-spinner');
  11559. if (btn) {
  11560. btn.disabled = false;
  11561. 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';
  11562. }
  11563. if (btnText) btnText.innerText = 'Start Traceroute';
  11564. if (spinner) spinner.classList.add('hidden');
  11565. }
  11566. function setTracerouteRunningButton() {
  11567. const btn = document.getElementById('tools-tr-btn');
  11568. const btnText = document.getElementById('tools-tr-btn-text');
  11569. const spinner = document.getElementById('tools-tr-spinner');
  11570. if (btn) {
  11571. btn.disabled = false;
  11572. 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';
  11573. }
  11574. if (btnText) btnText.innerText = 'Stop Traceroute';
  11575. if (spinner) spinner.classList.remove('hidden');
  11576. }
  11577. async function executePing(e) {
  11578. if (e) e.preventDefault();
  11579. // If already running, clicking the button stops the stream!
  11580. if (pingAbortController) {
  11581. pingAbortController.abort();
  11582. pingAbortController = null;
  11583. resetPingButton();
  11584. showToast('Ping Stopped', 'Live ping stopped by user', 'info');
  11585. return;
  11586. }
  11587. const target = document.getElementById('tools-ping-target')?.value?.trim();
  11588. const count = parseInt(document.getElementById('tools-ping-count')?.value || '4', 10);
  11589. const size = parseInt(document.getElementById('tools-ping-size')?.value || '56', 10);
  11590. const timeout = parseInt(document.getElementById('tools-ping-timeout')?.value || '3', 10);
  11591. const iface = document.getElementById('tools-ping-iface')?.value || '';
  11592. const dontFrag = document.getElementById('tools-ping-df')?.checked || false;
  11593. if (!target) {
  11594. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  11595. return;
  11596. }
  11597. clearPingTable();
  11598. const resCard = document.getElementById('tools-ping-results');
  11599. if (resCard) resCard.classList.remove('hidden');
  11600. pingAbortController = new AbortController();
  11601. setPingRunningButton();
  11602. try {
  11603. const res = await fetch(`${API_BASE}/tools/ping/stream`, {
  11604. method: 'POST',
  11605. headers: { 'Content-Type': 'application/json' },
  11606. body: JSON.stringify({
  11607. target,
  11608. count,
  11609. size,
  11610. timeout,
  11611. interface: iface,
  11612. dont_frag: dontFrag
  11613. }),
  11614. signal: pingAbortController.signal
  11615. });
  11616. if (!res.ok) {
  11617. const errText = await res.text();
  11618. showToast('Ping Error', errText || 'Failed to start live ping', 'error');
  11619. resetPingButton();
  11620. pingAbortController = null;
  11621. return;
  11622. }
  11623. const reader = res.body.getReader();
  11624. const decoder = new TextDecoder('utf-8');
  11625. let buffer = '';
  11626. while (true) {
  11627. const { done, value } = await reader.read();
  11628. if (done) break;
  11629. buffer += decoder.decode(value, { stream: true });
  11630. const blocks = buffer.split('\n\n');
  11631. buffer = blocks.pop() || '';
  11632. for (const block of blocks) {
  11633. const trimmed = block.trim();
  11634. if (!trimmed) continue;
  11635. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  11636. try {
  11637. const evt = JSON.parse(line);
  11638. handleLivePingEvent(evt);
  11639. } catch (parseErr) {
  11640. console.warn('Ping SSE parse error:', parseErr, line);
  11641. }
  11642. }
  11643. }
  11644. } catch (err) {
  11645. if (err.name === 'AbortError') {
  11646. // User aborted normally
  11647. } else {
  11648. showToast('Ping Error', err.message, 'error');
  11649. }
  11650. } finally {
  11651. pingAbortController = null;
  11652. resetPingButton();
  11653. }
  11654. }
  11655. function handleLivePingEvent(evt) {
  11656. const sentEl = document.getElementById('tools-ping-stat-sent');
  11657. const recvEl = document.getElementById('tools-ping-stat-recv');
  11658. const lossEl = document.getElementById('tools-ping-stat-loss');
  11659. const avgEl = document.getElementById('tools-ping-stat-avg');
  11660. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  11661. const badge = document.getElementById('tools-ping-status-badge');
  11662. const tbody = document.getElementById('tools-ping-tbody');
  11663. const rawEl = document.getElementById('tools-ping-raw');
  11664. if (evt.raw && rawEl) {
  11665. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  11666. rawEl.scrollTop = rawEl.scrollHeight;
  11667. }
  11668. if (evt.type === 'reply') {
  11669. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  11670. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  11671. if (lossEl && evt.packet_loss_pct !== undefined) {
  11672. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  11673. lossEl.className = evt.packet_loss_pct === 0
  11674. ? 'text-base font-bold font-mono text-emerald-400 mt-1'
  11675. : (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');
  11676. }
  11677. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  11678. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  11679. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  11680. }
  11681. if (badge) {
  11682. if (evt.packet_loss_pct === 0) {
  11683. 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';
  11684. badge.innerText = '100% OK';
  11685. } else {
  11686. 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';
  11687. badge.innerText = `${evt.packet_loss_pct.toFixed(0)}% LOSS`;
  11688. }
  11689. }
  11690. if (tbody) {
  11691. const tr = document.createElement('tr');
  11692. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  11693. tr.innerHTML = `
  11694. <td class="py-2 px-3 text-slate-300">#${evt.seq}</td>
  11695. <td class="py-2 px-3 font-semibold text-white">${escapeHtml(evt.from)}</td>
  11696. <td class="py-2 px-3 text-slate-400">${evt.bytes} bytes</td>
  11697. <td class="py-2 px-3 text-slate-300">${evt.ttl}</td>
  11698. <td class="py-2 px-3 font-bold text-amber-300">${evt.time_ms.toFixed(2)} ms</td>
  11699. <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>
  11700. `;
  11701. tbody.appendChild(tr);
  11702. }
  11703. } else if (evt.type === 'timeout') {
  11704. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  11705. if (lossEl && evt.packet_loss_pct !== undefined) {
  11706. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  11707. 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';
  11708. }
  11709. if (badge) {
  11710. 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';
  11711. badge.innerText = `${evt.packet_loss_pct?.toFixed(0) || 100}% LOSS`;
  11712. }
  11713. if (tbody) {
  11714. const tr = document.createElement('tr');
  11715. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs opacity-75';
  11716. tr.innerHTML = `
  11717. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  11718. <td class="py-2 px-3 font-semibold text-slate-500 italic">Request timed out</td>
  11719. <td class="py-2 px-3 text-slate-600">--</td>
  11720. <td class="py-2 px-3 text-slate-600">--</td>
  11721. <td class="py-2 px-3 font-bold text-slate-500">* * *</td>
  11722. <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>
  11723. `;
  11724. tbody.appendChild(tr);
  11725. }
  11726. } else if (evt.type === 'unreach') {
  11727. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  11728. if (lossEl && evt.packet_loss_pct !== undefined) {
  11729. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  11730. lossEl.className = 'text-base font-bold font-mono text-rose-400 mt-1';
  11731. }
  11732. if (badge) {
  11733. 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';
  11734. badge.innerText = 'UNREACHABLE';
  11735. }
  11736. if (tbody) {
  11737. const tr = document.createElement('tr');
  11738. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  11739. tr.innerHTML = `
  11740. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  11741. <td class="py-2 px-3 font-semibold text-rose-400">${escapeHtml(evt.from || 'Gateway')}</td>
  11742. <td class="py-2 px-3 text-slate-600">--</td>
  11743. <td class="py-2 px-3 text-slate-600">--</td>
  11744. <td class="py-2 px-3 font-bold text-rose-400 text-xs">${escapeHtml(evt.message || 'Unreachable')}</td>
  11745. <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>
  11746. `;
  11747. tbody.appendChild(tr);
  11748. }
  11749. } else if (evt.type === 'stats') {
  11750. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  11751. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  11752. if (lossEl && evt.packet_loss_pct !== undefined) lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  11753. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  11754. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  11755. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  11756. }
  11757. } else if (evt.type === 'done') {
  11758. 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');
  11759. }
  11760. }
  11761. async function executeTraceroute(e) {
  11762. if (e) e.preventDefault();
  11763. if (tracerouteAbortController) {
  11764. tracerouteAbortController.abort();
  11765. tracerouteAbortController = null;
  11766. resetTracerouteButton();
  11767. showToast('Traceroute Stopped', 'Traceroute stopped by user', 'info');
  11768. return;
  11769. }
  11770. const target = document.getElementById('tools-tr-target')?.value?.trim();
  11771. const maxHops = parseInt(document.getElementById('tools-tr-maxhops')?.value || '15', 10);
  11772. const protocol = document.getElementById('tools-tr-proto')?.value || 'icmp';
  11773. const iface = document.getElementById('tools-tr-iface')?.value || '';
  11774. const resolve = document.getElementById('tools-tr-resolve')?.checked || false;
  11775. if (!target) {
  11776. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  11777. return;
  11778. }
  11779. clearTracerouteTable();
  11780. const resCard = document.getElementById('tools-tr-results');
  11781. if (resCard) resCard.classList.remove('hidden');
  11782. tracerouteAbortController = new AbortController();
  11783. setTracerouteRunningButton();
  11784. try {
  11785. const res = await fetch(`${API_BASE}/tools/traceroute/stream`, {
  11786. method: 'POST',
  11787. headers: { 'Content-Type': 'application/json' },
  11788. body: JSON.stringify({
  11789. target,
  11790. max_hops: maxHops,
  11791. protocol,
  11792. interface: iface,
  11793. resolve
  11794. }),
  11795. signal: tracerouteAbortController.signal
  11796. });
  11797. if (!res.ok) {
  11798. const errText = await res.text();
  11799. showToast('Traceroute Error', errText || 'Failed to start traceroute', 'error');
  11800. resetTracerouteButton();
  11801. tracerouteAbortController = null;
  11802. return;
  11803. }
  11804. const reader = res.body.getReader();
  11805. const decoder = new TextDecoder('utf-8');
  11806. let buffer = '';
  11807. while (true) {
  11808. const { done, value } = await reader.read();
  11809. if (done) break;
  11810. buffer += decoder.decode(value, { stream: true });
  11811. const blocks = buffer.split('\n\n');
  11812. buffer = blocks.pop() || '';
  11813. for (const block of blocks) {
  11814. const trimmed = block.trim();
  11815. if (!trimmed) continue;
  11816. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  11817. try {
  11818. const evt = JSON.parse(line);
  11819. handleLiveTracerouteEvent(evt);
  11820. } catch (parseErr) {
  11821. console.warn('Traceroute SSE parse error:', parseErr, line);
  11822. }
  11823. }
  11824. }
  11825. } catch (err) {
  11826. if (err.name === 'AbortError') {
  11827. // User aborted normally
  11828. } else {
  11829. showToast('Traceroute Error', err.message, 'error');
  11830. }
  11831. } finally {
  11832. tracerouteAbortController = null;
  11833. resetTracerouteButton();
  11834. }
  11835. }
  11836. function handleLiveTracerouteEvent(evt) {
  11837. const statHops = document.getElementById('tools-tr-hops-count');
  11838. const tbody = document.getElementById('tools-tr-tbody');
  11839. const rawEl = document.getElementById('tools-tr-raw');
  11840. if (evt.raw && rawEl) {
  11841. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  11842. rawEl.scrollTop = rawEl.scrollHeight;
  11843. }
  11844. if (evt.hops_count !== undefined && statHops) {
  11845. statHops.innerText = `${evt.hops_count} Hops`;
  11846. }
  11847. if (evt.type === 'hop' && evt.hop && tbody) {
  11848. const h = evt.hop;
  11849. const isTimeout = h.status === 'timeout' || (!h.ip && !h.host);
  11850. const rtt1 = Array.isArray(h.times_ms) && h.times_ms[0] ? `${h.times_ms[0]} ms` : (isTimeout ? '*' : '--');
  11851. const rtt2 = Array.isArray(h.times_ms) && h.times_ms[1] ? `${h.times_ms[1]} ms` : (isTimeout ? '*' : '--');
  11852. const displayHost = h.host && h.host !== h.ip ? `${escapeHtml(h.host)} (${escapeHtml(h.ip || '')})` : escapeHtml(h.ip || (isTimeout ? 'Request timed out' : '--'));
  11853. const tr = document.createElement('tr');
  11854. tr.className = `hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs ${isTimeout ? 'opacity-60' : ''}`;
  11855. tr.innerHTML = `
  11856. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  11857. <td class="py-2.5 px-3 font-semibold ${isTimeout ? 'text-slate-500 italic' : 'text-cyan-300'}">${displayHost}</td>
  11858. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt1)}</td>
  11859. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt2)}</td>
  11860. <td class="py-2.5 px-3 text-right">
  11861. ${isTimeout
  11862. ? '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-slate-800 text-slate-400 border border-slate-700">TIMEOUT</span>'
  11863. : '<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>'}
  11864. </td>
  11865. `;
  11866. tbody.appendChild(tr);
  11867. } else if (evt.type === 'done') {
  11868. showToast('Traceroute Finished', `Traced ${evt.hops_count || 0} hops`, 'info');
  11869. }
  11870. }
  11871. async function executeMTR(e) {
  11872. if (e) e.preventDefault();
  11873. const target = document.getElementById('tools-mtr-target')?.value?.trim();
  11874. const cycles = parseInt(document.getElementById('tools-mtr-count')?.value || '3', 10);
  11875. if (!target) {
  11876. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  11877. return;
  11878. }
  11879. const btn = document.getElementById('tools-mtr-btn');
  11880. const spinner = document.getElementById('tools-mtr-spinner');
  11881. if (btn) btn.disabled = true;
  11882. if (spinner) spinner.classList.remove('hidden');
  11883. try {
  11884. const res = await fetch(`${API_BASE}/tools/mtr`, {
  11885. method: 'POST',
  11886. headers: { 'Content-Type': 'application/json' },
  11887. body: JSON.stringify({ target, count: cycles })
  11888. });
  11889. const data = await res.json();
  11890. if (!res.ok) {
  11891. showToast('MTR Error', data.error || 'Failed to execute MTR', 'error');
  11892. return;
  11893. }
  11894. const resCard = document.getElementById('tools-mtr-results');
  11895. if (resCard) resCard.classList.remove('hidden');
  11896. const hopsCount = Array.isArray(data.hops) ? data.hops.length : 0;
  11897. const statHops = document.getElementById('tools-mtr-hops-count');
  11898. if (statHops) statHops.innerText = `${hopsCount} Hops`;
  11899. const tbody = document.getElementById('tools-mtr-tbody');
  11900. if (tbody) {
  11901. if (hopsCount > 0) {
  11902. tbody.innerHTML = data.hops.map(h => {
  11903. 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');
  11904. return `
  11905. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  11906. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  11907. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(h.host || '--')}</td>
  11908. <td class="py-2.5 px-3 ${lossClass}">${h.loss_pct.toFixed(1)}%</td>
  11909. <td class="py-2.5 px-3 text-slate-300">${h.sent}</td>
  11910. <td class="py-2.5 px-3 text-slate-300">${h.last_ms.toFixed(1)}</td>
  11911. <td class="py-2.5 px-3 font-bold text-amber-300">${h.avg_ms.toFixed(1)}</td>
  11912. <td class="py-2.5 px-3 text-emerald-400">${h.best_ms.toFixed(1)}</td>
  11913. <td class="py-2.5 px-3 text-rose-400">${h.wrst_ms.toFixed(1)}</td>
  11914. <td class="py-2.5 px-3 text-slate-400">${h.stdev_ms.toFixed(1)}</td>
  11915. </tr>
  11916. `;
  11917. }).join('');
  11918. } else {
  11919. tbody.innerHTML = `<tr><td colspan="9" class="p-4 text-center text-xs text-rose-400 font-mono">No MTR data collected</td></tr>`;
  11920. }
  11921. }
  11922. const rawEl = document.getElementById('tools-mtr-raw');
  11923. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  11924. showToast('MTR Finished', `Report completed (${hopsCount} hops discovered)`, 'info');
  11925. } catch (err) {
  11926. showToast('MTR Error', err.message, 'error');
  11927. } finally {
  11928. if (btn) btn.disabled = false;
  11929. if (spinner) spinner.classList.add('hidden');
  11930. }
  11931. }
  11932. async function executeDNS(e) {
  11933. if (e) e.preventDefault();
  11934. const domain = document.getElementById('tools-dns-domain')?.value?.trim();
  11935. const type = document.getElementById('tools-dns-type')?.value || 'A';
  11936. const server = document.getElementById('tools-dns-server')?.value?.trim() || '';
  11937. if (!domain) {
  11938. showToast('Input Required', 'Please enter a hostname or domain', 'warning');
  11939. return;
  11940. }
  11941. const btn = document.getElementById('tools-dns-btn');
  11942. const spinner = document.getElementById('tools-dns-spinner');
  11943. if (btn) btn.disabled = true;
  11944. if (spinner) spinner.classList.remove('hidden');
  11945. try {
  11946. const res = await fetch(`${API_BASE}/tools/dns`, {
  11947. method: 'POST',
  11948. headers: { 'Content-Type': 'application/json' },
  11949. body: JSON.stringify({ domain, type, server })
  11950. });
  11951. const data = await res.json();
  11952. if (!res.ok) {
  11953. showToast('DNS Error', data.error || 'Failed to resolve DNS query', 'error');
  11954. return;
  11955. }
  11956. const resCard = document.getElementById('tools-dns-results');
  11957. if (resCard) resCard.classList.remove('hidden');
  11958. const metaEl = document.getElementById('tools-dns-meta');
  11959. if (metaEl) metaEl.innerText = `Resolved in ${data.query_time_ms ?? 0} ms via ${escapeHtml(data.server || 'System DNS')}`;
  11960. const tbody = document.getElementById('tools-dns-tbody');
  11961. if (tbody) {
  11962. if (Array.isArray(data.records) && data.records.length > 0) {
  11963. tbody.innerHTML = data.records.map(r => `
  11964. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  11965. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.name)}</td>
  11966. <td class="py-2.5 px-3 text-slate-400">${r.ttl}s</td>
  11967. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.class || 'IN')}</td>
  11968. <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>
  11969. <td class="py-2.5 px-3 font-bold text-amber-300 break-all">${escapeHtml(r.value)}</td>
  11970. </tr>
  11971. `).join('');
  11972. } else {
  11973. 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>`;
  11974. }
  11975. }
  11976. const rawEl = document.getElementById('tools-dns-raw');
  11977. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  11978. showToast('DNS Lookup Done', `Resolved ${domain} in ${data.query_time_ms} ms`, 'success');
  11979. } catch (err) {
  11980. showToast('DNS Error', err.message, 'error');
  11981. } finally {
  11982. if (btn) btn.disabled = false;
  11983. if (spinner) spinner.classList.add('hidden');
  11984. }
  11985. }
  11986. async function executePortProbe(e) {
  11987. if (e) e.preventDefault();
  11988. const target = document.getElementById('tools-port-target')?.value?.trim();
  11989. const port = parseInt(document.getElementById('tools-port-num')?.value || '80', 10);
  11990. const timeout = parseInt(document.getElementById('tools-port-timeout')?.value || '3', 10);
  11991. if (!target || !port) {
  11992. showToast('Input Required', 'Please enter a target host and TCP port', 'warning');
  11993. return;
  11994. }
  11995. const btn = document.getElementById('tools-port-btn');
  11996. const spinner = document.getElementById('tools-port-spinner');
  11997. if (btn) btn.disabled = true;
  11998. if (spinner) spinner.classList.remove('hidden');
  11999. try {
  12000. const res = await fetch(`${API_BASE}/tools/port-probe`, {
  12001. method: 'POST',
  12002. headers: { 'Content-Type': 'application/json' },
  12003. body: JSON.stringify({ target, port, timeout })
  12004. });
  12005. const data = await res.json();
  12006. if (!res.ok) {
  12007. showToast('Probe Error', data.error || 'Failed to probe TCP port', 'error');
  12008. return;
  12009. }
  12010. const resCard = document.getElementById('tools-port-results');
  12011. if (resCard) resCard.classList.remove('hidden');
  12012. const banner = document.getElementById('tools-port-banner');
  12013. const icon = document.getElementById('tools-port-icon');
  12014. const title = document.getElementById('tools-port-title');
  12015. const sub = document.getElementById('tools-port-sub');
  12016. const latency = document.getElementById('tools-port-latency');
  12017. if (data.open) {
  12018. if (banner) banner.className = 'rounded-xl p-5 border bg-emerald-950/30 border-emerald-800/50 flex items-center justify-between';
  12019. if (icon) {
  12020. 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';
  12021. icon.innerText = '✓';
  12022. }
  12023. if (title) {
  12024. title.className = 'text-sm font-bold text-emerald-300';
  12025. title.innerText = `PORT ${port} OPEN / LISTENING`;
  12026. }
  12027. if (sub) {
  12028. sub.className = 'text-xs mt-0.5 font-mono text-emerald-400/80';
  12029. sub.innerText = `TCP 3-way handshake established with ${escapeHtml(target)}:${port}${data.service ? ' (' + escapeHtml(data.service) + ')' : ''}`;
  12030. }
  12031. if (latency) {
  12032. latency.className = 'text-base font-bold font-mono text-emerald-300';
  12033. latency.innerText = `${data.latency_ms.toFixed(2)} ms`;
  12034. }
  12035. } else {
  12036. if (banner) banner.className = 'rounded-xl p-5 border bg-rose-950/30 border-rose-800/50 flex items-center justify-between';
  12037. if (icon) {
  12038. 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';
  12039. icon.innerText = '✕';
  12040. }
  12041. if (title) {
  12042. title.className = 'text-sm font-bold text-rose-300';
  12043. title.innerText = `PORT ${port} CLOSED / FILTERED`;
  12044. }
  12045. if (sub) {
  12046. sub.className = 'text-xs mt-0.5 font-mono text-rose-400/80';
  12047. sub.innerText = `Connection failed or timed out to ${escapeHtml(target)}:${port}`;
  12048. }
  12049. if (latency) {
  12050. latency.className = 'text-base font-bold font-mono text-slate-500';
  12051. latency.innerText = '--';
  12052. }
  12053. }
  12054. const rawEl = document.getElementById('tools-port-raw');
  12055. 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'}`);
  12056. showToast('Probe Complete', `Port ${port} is ${data.open ? 'OPEN' : 'CLOSED'}`, data.open ? 'success' : 'warning');
  12057. } catch (err) {
  12058. showToast('Probe Error', err.message, 'error');
  12059. } finally {
  12060. if (btn) btn.disabled = false;
  12061. if (spinner) spinner.classList.add('hidden');
  12062. }
  12063. }
  12064. // ==========================================
  12065. // DHCP CLIENT (/ip dhcp-client) CONTROLLER
  12066. // ==========================================
  12067. async function loadDHCPClients(showToastMsg = false) {
  12068. try {
  12069. const [clientsRes, sumRes] = await Promise.all([
  12070. fetch(`${API_BASE}/dhcp/clients`),
  12071. fetch(`${API_BASE}/dhcp/clients/summary`)
  12072. ]);
  12073. if (clientsRes.ok) {
  12074. state.dhcpClients = await clientsRes.json();
  12075. }
  12076. if (sumRes.ok) {
  12077. state.dhcpSummary = await sumRes.json();
  12078. }
  12079. renderDHCPClients();
  12080. updateDHCPSummaryCards();
  12081. const bDhcp = document.getElementById('badge-dhcp-client-count');
  12082. if (bDhcp && state.dhcpSummary) {
  12083. bDhcp.innerText = state.dhcpSummary.total_clients || 0;
  12084. }
  12085. if (showToastMsg) {
  12086. showToast('Refreshed', 'DHCP Client telemetry updated', 'info');
  12087. }
  12088. } catch (err) {
  12089. console.error('Failed to load DHCP clients:', err);
  12090. if (showToastMsg) {
  12091. showToast('Notice', 'Unable to fetch DHCP client status', 'warning');
  12092. }
  12093. }
  12094. }
  12095. function updateDHCPSummaryCards() {
  12096. const sum = state.dhcpSummary || {
  12097. total_clients: (state.dhcpClients || []).length,
  12098. bound_clients: (state.dhcpClients || []).filter(c => c.status === 'bound').length,
  12099. searching_clients: (state.dhcpClients || []).filter(c => c.status === 'searching').length,
  12100. disabled_clients: (state.dhcpClients || []).filter(c => !c.enabled).length
  12101. };
  12102. const totalEl = document.getElementById('dhcp-stat-total');
  12103. const boundEl = document.getElementById('dhcp-stat-bound');
  12104. const searchEl = document.getElementById('dhcp-stat-searching');
  12105. const disEl = document.getElementById('dhcp-stat-disabled');
  12106. if (totalEl) totalEl.innerText = sum.total_clients ?? 0;
  12107. if (boundEl) boundEl.innerText = sum.bound_clients ?? 0;
  12108. if (searchEl) searchEl.innerText = sum.searching_clients ?? 0;
  12109. if (disEl) disEl.innerText = sum.disabled_clients ?? 0;
  12110. }
  12111. function renderDHCPClients() {
  12112. const tbody = document.getElementById('dhcp-clients-tbody');
  12113. const emptyState = document.getElementById('dhcp-clients-empty');
  12114. if (!tbody) return;
  12115. const clients = Array.isArray(state.dhcpClients) ? state.dhcpClients : [];
  12116. if (clients.length === 0) {
  12117. tbody.innerHTML = '';
  12118. if (emptyState) emptyState.classList.remove('hidden');
  12119. return;
  12120. }
  12121. if (emptyState) emptyState.classList.add('hidden');
  12122. const sig = clients.map(c => `${c.id}:${c.status}:${c.ip_address}:${c.gateway}:${c.enabled}`).join(';');
  12123. if (tbody.dataset.sig === sig) return;
  12124. tbody.dataset.sig = sig;
  12125. tbody.innerHTML = clients.map(c => {
  12126. let statusBadge = '';
  12127. if (!c.enabled) {
  12128. 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>';
  12129. } else if (c.status === 'bound') {
  12130. 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>';
  12131. } else if (c.status === 'searching') {
  12132. 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>';
  12133. } else if (c.status === 'stopped') {
  12134. 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>';
  12135. } else {
  12136. 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>`;
  12137. }
  12138. 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>';
  12139. const gwDisplay = c.gateway ? `<span class="text-slate-300">${escapeHtml(c.gateway)}</span>` : '<span class="text-slate-600">--</span>';
  12140. const srvDisplay = c.dhcp_server ? `<span class="text-slate-300">${escapeHtml(c.dhcp_server)}</span>` : '<span class="text-slate-600">--</span>';
  12141. 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>';
  12142. const expDisplay = c.expires_in ? `<span class="text-purple-300">${escapeHtml(c.expires_in)}</span>` : '<span class="text-slate-600">--</span>';
  12143. // Option flags
  12144. const flags = [];
  12145. 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>');
  12146. 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>');
  12147. 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>');
  12148. 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>`);
  12149. return `
  12150. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 text-xs transition">
  12151. <td class="py-3 px-4">
  12152. <div class="flex items-center gap-2">
  12153. <span class="font-bold text-white text-sm">${escapeHtml(c.interface)}</span>
  12154. ${c.comment ? `<span class="text-[11px] text-slate-400 font-sans italic">(${escapeHtml(c.comment)})</span>` : ''}
  12155. </div>
  12156. </td>
  12157. <td class="py-3 px-4">${statusBadge}</td>
  12158. <td class="py-3 px-4 font-mono">${ipDisplay}</td>
  12159. <td class="py-3 px-4 font-mono">${gwDisplay}</td>
  12160. <td class="py-3 px-4 font-mono">${srvDisplay}</td>
  12161. <td class="py-3 px-4 font-mono text-[11px]">${dnsDisplay}</td>
  12162. <td class="py-3 px-4 font-mono text-[11px]">${expDisplay}</td>
  12163. <td class="py-3 px-4">
  12164. <div class="flex flex-wrap gap-1 font-mono">${flags.join('')}</div>
  12165. </td>
  12166. <td class="py-3 px-4 text-right space-x-1.5 font-sans whitespace-nowrap">
  12167. ${c.enabled ? `
  12168. <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>
  12169. <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>
  12170. <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>
  12171. ` : `
  12172. <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>
  12173. `}
  12174. <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>
  12175. <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>
  12176. </td>
  12177. </tr>
  12178. `;
  12179. }).join('');
  12180. }
  12181. function openDHCPClientModal(clientId = null) {
  12182. const modal = document.getElementById('modal-dhcp-client');
  12183. if (!modal) return;
  12184. const title = document.getElementById('modal-dhcp-title');
  12185. const idInput = document.getElementById('modal-dhcp-id');
  12186. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  12187. const distInput = document.getElementById('modal-dhcp-distance');
  12188. const commentInput = document.getElementById('modal-dhcp-comment');
  12189. const defRouteCheck = document.getElementById('modal-dhcp-def-route');
  12190. const peerDnsCheck = document.getElementById('modal-dhcp-peer-dns');
  12191. const peerNtpCheck = document.getElementById('modal-dhcp-peer-ntp');
  12192. const enabledCheck = document.getElementById('modal-dhcp-enabled');
  12193. // Populate interfaces
  12194. if (ifaceSelect) {
  12195. let opts = '<option value="">Select interface...</option>';
  12196. const allIfaces = state.interfaces || [];
  12197. const allVlans = state.vlans || [];
  12198. const usedIfaces = new Set((state.dhcpClients || []).map(c => c.interface));
  12199. // Group 1: Physical & Bridge Interfaces
  12200. opts += '<optgroup label="Physical & Bridge Interfaces">';
  12201. allIfaces.filter(i => supportsDHCPClient(i)).forEach(i => {
  12202. const isConfigured = usedIfaces.has(i.name) ? ' (Configured)' : '';
  12203. opts += `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)} [${escapeHtml(i.role || i.type)}]${isConfigured}</option>`;
  12204. });
  12205. opts += '</optgroup>';
  12206. // Group 2: VLAN Interfaces
  12207. if (allVlans.length > 0) {
  12208. opts += '<optgroup label="802.1Q VLAN Sub-interfaces">';
  12209. allVlans.forEach(v => {
  12210. const isConfigured = usedIfaces.has(v.name) ? ' (Configured)' : '';
  12211. opts += `<option value="${escapeHtml(v.name)}">${escapeHtml(v.name)} (VLAN ${v.vlan_id})${isConfigured}</option>`;
  12212. });
  12213. opts += '</optgroup>';
  12214. }
  12215. ifaceSelect.innerHTML = opts;
  12216. }
  12217. if (clientId) {
  12218. const client = (state.dhcpClients || []).find(c => c.id === clientId);
  12219. if (client) {
  12220. if (title) title.innerText = `Edit DHCP Client: ${client.interface}`;
  12221. if (idInput) idInput.value = client.id;
  12222. if (ifaceSelect) {
  12223. ifaceSelect.value = client.interface;
  12224. ifaceSelect.disabled = true; // interface cannot be changed on edit
  12225. }
  12226. if (distInput) distInput.value = client.default_route_distance || 1;
  12227. if (commentInput) commentInput.value = client.comment || '';
  12228. if (defRouteCheck) defRouteCheck.checked = client.add_default_route !== false;
  12229. if (peerDnsCheck) peerDnsCheck.checked = client.use_peer_dns !== false;
  12230. if (peerNtpCheck) peerNtpCheck.checked = client.use_peer_ntp !== false;
  12231. if (enabledCheck) enabledCheck.checked = client.enabled !== false;
  12232. }
  12233. } else {
  12234. if (title) title.innerText = 'Add DHCP Client';
  12235. if (idInput) idInput.value = '';
  12236. if (ifaceSelect) {
  12237. ifaceSelect.value = '';
  12238. ifaceSelect.disabled = false;
  12239. }
  12240. if (distInput) distInput.value = 1;
  12241. if (commentInput) commentInput.value = '';
  12242. if (defRouteCheck) defRouteCheck.checked = true;
  12243. if (peerDnsCheck) peerDnsCheck.checked = true;
  12244. if (peerNtpCheck) peerNtpCheck.checked = true;
  12245. if (enabledCheck) enabledCheck.checked = true;
  12246. }
  12247. modal.classList.remove('hidden');
  12248. }
  12249. function openDHCPClientModalForIface(ifaceName) {
  12250. openDHCPClientModal();
  12251. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  12252. if (ifaceSelect && ifaceName) {
  12253. ifaceSelect.value = ifaceName;
  12254. }
  12255. }
  12256. function closeDHCPClientModal() {
  12257. const modal = document.getElementById('modal-dhcp-client');
  12258. if (modal) modal.classList.add('hidden');
  12259. }
  12260. async function submitSaveDHCPClient(e) {
  12261. if (e) e.preventDefault();
  12262. const id = document.getElementById('modal-dhcp-id')?.value;
  12263. const iface = document.getElementById('modal-dhcp-iface')?.value?.trim();
  12264. const distance = parseInt(document.getElementById('modal-dhcp-distance')?.value || '1', 10);
  12265. const comment = document.getElementById('modal-dhcp-comment')?.value?.trim() || '';
  12266. const defRoute = document.getElementById('modal-dhcp-def-route')?.checked ?? true;
  12267. const peerDns = document.getElementById('modal-dhcp-peer-dns')?.checked ?? true;
  12268. const peerNtp = document.getElementById('modal-dhcp-peer-ntp')?.checked ?? true;
  12269. const enabled = document.getElementById('modal-dhcp-enabled')?.checked ?? true;
  12270. if (!id && !iface) {
  12271. showToast('Input Required', 'Please select an interface for the DHCP client', 'warning');
  12272. return;
  12273. }
  12274. try {
  12275. let res;
  12276. if (id) {
  12277. // PUT update
  12278. res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  12279. method: 'PUT',
  12280. headers: { 'Content-Type': 'application/json' },
  12281. body: JSON.stringify({
  12282. enabled,
  12283. add_default_route: defRoute,
  12284. default_route_distance: distance,
  12285. use_peer_dns: peerDns,
  12286. use_peer_ntp: peerNtp,
  12287. comment
  12288. })
  12289. });
  12290. } else {
  12291. // POST create
  12292. res = await fetch(`${API_BASE}/dhcp/clients`, {
  12293. method: 'POST',
  12294. headers: { 'Content-Type': 'application/json' },
  12295. body: JSON.stringify({
  12296. interface: iface,
  12297. enabled,
  12298. add_default_route: defRoute,
  12299. default_route_distance: distance,
  12300. use_peer_dns: peerDns,
  12301. use_peer_ntp: peerNtp,
  12302. comment
  12303. })
  12304. });
  12305. }
  12306. const data = await res.json();
  12307. if (!res.ok) {
  12308. showToast('Error', data.error || 'Failed to save DHCP client', 'error');
  12309. return;
  12310. }
  12311. closeDHCPClientModal();
  12312. showToast('Success', id ? 'DHCP Client updated successfully' : `DHCP Client activated on ${iface}`, 'success');
  12313. await loadDHCPClients();
  12314. fetchData(); // refresh interfaces list with new lease/status
  12315. } catch (err) {
  12316. showToast('Error', err.message, 'error');
  12317. }
  12318. }
  12319. async function toggleDHCPClientState(id, enabled) {
  12320. try {
  12321. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/state`, {
  12322. method: 'POST',
  12323. headers: { 'Content-Type': 'application/json' },
  12324. body: JSON.stringify({ enabled })
  12325. });
  12326. const data = await res.json();
  12327. if (!res.ok) {
  12328. showToast('Error', data.error || 'Failed to toggle client state', 'error');
  12329. return;
  12330. }
  12331. showToast('Updated', `DHCP client ${enabled ? 'enabled' : 'disabled'}`, 'info');
  12332. await loadDHCPClients();
  12333. fetchData();
  12334. } catch (err) {
  12335. showToast('Error', err.message, 'error');
  12336. }
  12337. }
  12338. async function renewDHCPClient(id) {
  12339. try {
  12340. showToast('Renewing...', 'Requesting DHCP lease renewal from upstream server', 'info');
  12341. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/renew`, {
  12342. method: 'POST'
  12343. });
  12344. const data = await res.json();
  12345. if (!res.ok) {
  12346. showToast('Error', data.error || 'Failed to renew lease', 'error');
  12347. return;
  12348. }
  12349. showToast('Lease Renewed', 'DHCP renewal signal sent successfully', 'success');
  12350. setTimeout(() => {
  12351. loadDHCPClients();
  12352. fetchData();
  12353. }, 1500);
  12354. } catch (err) {
  12355. showToast('Error', err.message, 'error');
  12356. }
  12357. }
  12358. async function releaseDHCPClient(id) {
  12359. try {
  12360. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/release`, {
  12361. method: 'POST'
  12362. });
  12363. const data = await res.json();
  12364. if (!res.ok) {
  12365. showToast('Error', data.error || 'Failed to release lease', 'error');
  12366. return;
  12367. }
  12368. showToast('Lease Released', 'DHCP lease released from upstream server', 'info');
  12369. await loadDHCPClients();
  12370. fetchData();
  12371. } catch (err) {
  12372. showToast('Error', err.message, 'error');
  12373. }
  12374. }
  12375. async function deleteDHCPClient(id, ifaceName) {
  12376. if (!confirm(`Are you sure you want to remove the DHCP Client on ${ifaceName}? The interface will release its dynamic IP.`)) {
  12377. return;
  12378. }
  12379. try {
  12380. const res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  12381. method: 'DELETE'
  12382. });
  12383. const data = await res.json();
  12384. if (!res.ok) {
  12385. showToast('Error', data.error || 'Failed to delete DHCP client', 'error');
  12386. return;
  12387. }
  12388. showToast('Deleted', `DHCP client removed from ${ifaceName}`, 'info');
  12389. await loadDHCPClients();
  12390. fetchData();
  12391. } catch (err) {
  12392. showToast('Error', err.message, 'error');
  12393. }
  12394. }
  12395. // ==================== DHCP SERVER (/ip dhcp-server) ====================
  12396. async function loadDHCPServer(populate = true) {
  12397. try {
  12398. const [sumRes, srvRes, netRes, leaseRes, optRes] = await Promise.all([
  12399. fetch(`${API_BASE}/dhcp-server/summary`),
  12400. fetch(`${API_BASE}/dhcp-server/servers`),
  12401. fetch(`${API_BASE}/dhcp-server/networks`),
  12402. fetch(`${API_BASE}/dhcp-server/leases`),
  12403. fetch(`${API_BASE}/dhcp-server/options`)
  12404. ]);
  12405. if (sumRes.ok) state.dhcpServerSummary = await sumRes.json();
  12406. if (srvRes.ok) state.dhcpServers = await srvRes.json();
  12407. if (netRes.ok) state.dhcpNetworks = await netRes.json();
  12408. if (leaseRes.ok) state.dhcpLeases = await leaseRes.json();
  12409. if (optRes.ok) state.dhcpOptions = await optRes.json();
  12410. const sum = state.dhcpServerSummary || {};
  12411. const srvs = state.dhcpServers || [];
  12412. const nets = state.dhcpNetworks || [];
  12413. const leases = state.dhcpLeases || [];
  12414. const opts = state.dhcpOptions || [];
  12415. // KPI Cards
  12416. const statActive = document.getElementById('dhcp-server-stat-active');
  12417. if (statActive) {
  12418. const activeCount = srvs.filter(s => s.running).length;
  12419. statActive.innerText = `${activeCount} / ${srvs.length}`;
  12420. }
  12421. const statLeases = document.getElementById('dhcp-server-stat-leases');
  12422. if (statLeases) {
  12423. statLeases.innerText = leases.length;
  12424. }
  12425. const statLeasesSub = document.getElementById('dhcp-server-stat-leases-sub');
  12426. if (statLeasesSub) {
  12427. const dyn = leases.filter(l => l.dynamic).length;
  12428. const st = leases.filter(l => !l.dynamic).length;
  12429. statLeasesSub.innerText = `${dyn} dynamic, ${st} static`;
  12430. }
  12431. const statNetworks = document.getElementById('dhcp-server-stat-networks');
  12432. if (statNetworks) {
  12433. statNetworks.innerText = nets.length;
  12434. }
  12435. // Subtab Badges
  12436. const bSrv = document.getElementById('dhcp-server-tab-badge-servers');
  12437. if (bSrv) bSrv.innerText = srvs.length;
  12438. const bNet = document.getElementById('dhcp-server-tab-badge-networks');
  12439. if (bNet) bNet.innerText = nets.length;
  12440. const bLease = document.getElementById('dhcp-server-tab-badge-leases');
  12441. if (bLease) bLease.innerText = leases.length;
  12442. const bOpt = document.getElementById('dhcp-server-tab-badge-options');
  12443. if (bOpt) bOpt.innerText = opts.length;
  12444. // Sidebar Badge
  12445. const sideBadge = document.getElementById('badge-dhcp-server-count');
  12446. if (sideBadge) sideBadge.innerText = leases.length || srvs.length;
  12447. renderCurrentDHCPServerTab();
  12448. } catch (err) {
  12449. console.error('Failed to load DHCP Server:', err);
  12450. }
  12451. }
  12452. function switchDHCPServerTab(tab) {
  12453. state.dhcpServerTab = tab;
  12454. const tabs = ['servers', 'networks', 'leases', 'options'];
  12455. tabs.forEach(t => {
  12456. const panel = document.getElementById(`dhcp-server-subtab-${t}`);
  12457. const btn = document.getElementById(`dhcp-server-tab-btn-${t}`);
  12458. if (panel) {
  12459. if (t === tab) panel.classList.remove('hidden');
  12460. else panel.classList.add('hidden');
  12461. }
  12462. if (btn) {
  12463. if (t === tab) {
  12464. 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';
  12465. } else {
  12466. 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';
  12467. }
  12468. }
  12469. });
  12470. const addBtn = document.getElementById('dhcp-server-primary-add-btn');
  12471. if (addBtn) {
  12472. if (tab === 'servers') addBtn.innerHTML = '<span>+ Add Server</span>';
  12473. else if (tab === 'networks') addBtn.innerHTML = '<span>+ Add Network</span>';
  12474. else if (tab === 'leases') addBtn.innerHTML = '<span>+ Add Static Lease</span>';
  12475. else if (tab === 'options') addBtn.innerHTML = '<span>+ Add Option</span>';
  12476. }
  12477. renderCurrentDHCPServerTab();
  12478. }
  12479. function handleDHCPServerPrimaryAdd() {
  12480. const tab = state.dhcpServerTab || 'servers';
  12481. if (tab === 'servers') openAddDHCPServerModal();
  12482. else if (tab === 'networks') openAddDHCPNetworkModal();
  12483. else if (tab === 'leases') openAddDHCPStaticLeaseModal();
  12484. else if (tab === 'options') openAddDHCPOptionModal();
  12485. }
  12486. function renderCurrentDHCPServerTab() {
  12487. const tab = state.dhcpServerTab || 'servers';
  12488. if (tab === 'servers') renderDHCPServers();
  12489. else if (tab === 'networks') renderDHCPNetworks();
  12490. else if (tab === 'leases') renderDHCPLeases();
  12491. else if (tab === 'options') renderDHCPOptions();
  12492. }
  12493. function renderDHCPServers() {
  12494. const tbody = document.getElementById('dhcp-server-tbody');
  12495. const empty = document.getElementById('dhcp-server-empty');
  12496. if (!tbody) return;
  12497. const servers = state.dhcpServers || [];
  12498. if (servers.length === 0) {
  12499. tbody.innerHTML = '';
  12500. empty?.classList.remove('hidden');
  12501. return;
  12502. }
  12503. empty?.classList.add('hidden');
  12504. const sig = servers.map(s => `${s.id}:${s.running}:${s.disabled}:${s.active_leases}:${s.interface}`).join(';');
  12505. if (tbody.dataset.sig === sig) return;
  12506. tbody.dataset.sig = sig;
  12507. tbody.innerHTML = '';
  12508. servers.forEach(s => {
  12509. const tr = document.createElement('tr');
  12510. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  12511. tr.innerHTML = `
  12512. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(s.running, s.disabled)}</td>
  12513. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(s.name)}</td>
  12514. <td class="py-2.5 px-3 font-mono text-cyan-400 font-semibold">${escapeHtml(s.interface)}</td>
  12515. <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>
  12516. <td class="py-2.5 px-3 font-mono text-emerald-400">${escapeHtml(s.address_pool)}</td>
  12517. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(s.lease_time || '12h')}</td>
  12518. <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>
  12519. <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>
  12520. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]" title="${escapeHtml(s.comment || '')}">${escapeHtml(s.comment || '-')}</td>
  12521. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  12522. <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>
  12523. <button onclick="openEditDHCPServerModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  12524. <button onclick="deleteDHCPServer('${s.id}', '${escapeHtml(s.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  12525. </td>
  12526. `;
  12527. tbody.appendChild(tr);
  12528. });
  12529. }
  12530. function renderDHCPNetworks() {
  12531. const tbody = document.getElementById('dhcp-networks-tbody');
  12532. const empty = document.getElementById('dhcp-networks-empty');
  12533. if (!tbody) return;
  12534. tbody.innerHTML = '';
  12535. const networks = state.dhcpNetworks || [];
  12536. if (networks.length === 0) {
  12537. empty?.classList.remove('hidden');
  12538. return;
  12539. }
  12540. empty?.classList.add('hidden');
  12541. networks.forEach(n => {
  12542. const tr = document.createElement('tr');
  12543. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  12544. const dnsStr = (n.dns_servers || []).join(', ') || '-';
  12545. const optionsChips = (n.dhcp_options || []).map(optId => {
  12546. const opt = (state.dhcpOptions || []).find(o => o.id === optId);
  12547. if (!opt) return '';
  12548. 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>`;
  12549. }).filter(Boolean).join('');
  12550. tr.innerHTML = `
  12551. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${escapeHtml(n.address)}</td>
  12552. <td class="py-2.5 px-3 font-mono text-cyan-300 font-semibold">${escapeHtml(n.gateway || '-')}</td>
  12553. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(n.netmask || '-')}</td>
  12554. <td class="py-2.5 px-3 font-mono text-slate-300 truncate max-w-[140px]" title="${escapeHtml(dnsStr)}">${escapeHtml(dnsStr)}</td>
  12555. <td class="py-2.5 px-3 font-mono text-slate-400">${escapeHtml(n.domain || '-')}</td>
  12556. <td class="py-2.5 px-3 font-mono">${optionsChips || '<span class="text-slate-600 font-sans">-</span>'}</td>
  12557. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(n.comment || '')}">${escapeHtml(n.comment || '-')}</td>
  12558. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  12559. <button onclick="openEditDHCPNetworkModal('${n.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  12560. <button onclick="deleteDHCPNetwork('${n.id}', '${escapeHtml(n.address)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  12561. </td>
  12562. `;
  12563. tbody.appendChild(tr);
  12564. });
  12565. }
  12566. function renderDHCPLeases() {
  12567. const tbody = document.getElementById('dhcp-leases-tbody');
  12568. const empty = document.getElementById('dhcp-leases-empty');
  12569. if (!tbody) return;
  12570. tbody.innerHTML = '';
  12571. const leases = state.dhcpLeases || [];
  12572. if (leases.length === 0) {
  12573. empty?.classList.remove('hidden');
  12574. return;
  12575. }
  12576. empty?.classList.add('hidden');
  12577. leases.forEach(l => {
  12578. const tr = document.createElement('tr');
  12579. tr.className = `hover:bg-slate-800/40 transition text-xs ${l.disabled ? 'opacity-50' : ''}`;
  12580. 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>';
  12581. const statusBadge = l.status === 'bound'
  12582. ? '<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>'
  12583. : l.status === 'static'
  12584. ? '<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>'
  12585. : '<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>';
  12586. const makeStaticBtn = l.dynamic
  12587. ? `<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>`
  12588. : `<button onclick="deleteDHCPStaticLease('${l.id}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Remove</button>`;
  12589. tr.innerHTML = `
  12590. <td class="py-2.5 px-3 text-center">${flag}</td>
  12591. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(l.address)}</td>
  12592. <td class="py-2.5 px-3 font-mono text-cyan-300">${escapeHtml(l.mac_address)}</td>
  12593. <td class="py-2.5 px-3 font-sans text-slate-200 font-medium">${escapeHtml(l.hostname || '*')}</td>
  12594. <td class="py-2.5 px-3 font-mono text-slate-400">${escapeHtml(l.server || 'all')}</td>
  12595. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(l.expires_in || 'never')}</td>
  12596. <td class="py-2.5 px-3">${statusBadge}</td>
  12597. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(l.comment || '')}">${escapeHtml(l.comment || '-')}</td>
  12598. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  12599. ${makeStaticBtn}
  12600. </td>
  12601. `;
  12602. tbody.appendChild(tr);
  12603. });
  12604. }
  12605. function renderDHCPOptions() {
  12606. const tbody = document.getElementById('dhcp-options-tbody');
  12607. const empty = document.getElementById('dhcp-options-empty');
  12608. if (!tbody) return;
  12609. tbody.innerHTML = '';
  12610. const options = state.dhcpOptions || [];
  12611. if (options.length === 0) {
  12612. empty?.classList.remove('hidden');
  12613. return;
  12614. }
  12615. empty?.classList.add('hidden');
  12616. options.forEach(o => {
  12617. const tr = document.createElement('tr');
  12618. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  12619. tr.innerHTML = `
  12620. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(o.name)}</td>
  12621. <td class="py-2.5 px-3 font-bold text-cyan-400 font-mono">${o.code}</td>
  12622. <td class="py-2.5 px-3 font-mono text-emerald-400 break-all max-w-xs">${escapeHtml(o.value)}</td>
  12623. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-xs" title="${escapeHtml(o.comment || '')}">${escapeHtml(o.comment || '-')}</td>
  12624. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  12625. <button onclick="openEditDHCPOptionModal('${o.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  12626. <button onclick="deleteDHCPOption('${o.id}', '${escapeHtml(o.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  12627. </td>
  12628. `;
  12629. tbody.appendChild(tr);
  12630. });
  12631. }
  12632. // ==================== MODALS & ACTIONS: SERVER ====================
  12633. function populateDHCPNetworkSelect(elemId, selectedVal) {
  12634. const sel = document.getElementById(elemId);
  12635. if (!sel) return;
  12636. sel.innerHTML = '<option value="">Select network subnet...</option>';
  12637. const networks = state.dhcpNetworks || [];
  12638. networks.forEach(n => {
  12639. const opt = document.createElement('option');
  12640. opt.value = n.address;
  12641. opt.innerText = `${n.address} (Gateway: ${n.gateway || 'None'}${n.comment ? ' - ' + n.comment : ''})`;
  12642. if (selectedVal && (selectedVal === n.address || selectedVal === n.id)) {
  12643. opt.selected = true;
  12644. }
  12645. sel.appendChild(opt);
  12646. });
  12647. }
  12648. function onDHCPServerNetworkChange() {
  12649. const netSel = document.getElementById('dhcp-server-modal-network');
  12650. if (!netSel) return;
  12651. const netVal = netSel.value;
  12652. if (!netVal) return;
  12653. const poolInput = document.getElementById('dhcp-server-modal-pool');
  12654. if (!poolInput) return;
  12655. // Auto-calculate suggested address pool based on subnet CIDR
  12656. const parts = netVal.split('/');
  12657. const ip = parts[0];
  12658. const cidr = parseInt(parts[1] || '24', 10);
  12659. if (cidr === 24) {
  12660. const octets = ip.split('.');
  12661. if (octets.length === 4) {
  12662. const base = `${octets[0]}.${octets[1]}.${octets[2]}`;
  12663. poolInput.value = `${base}.10-${base}.254`;
  12664. }
  12665. }
  12666. }
  12667. function openAddDHCPServerModal() {
  12668. document.getElementById('dhcp-server-modal-title').innerText = 'Add DHCP Server';
  12669. document.getElementById('dhcp-server-modal-id').value = '';
  12670. document.getElementById('dhcp-server-modal-name').value = `dhcp${(state.dhcpServers || []).length + 1}`;
  12671. document.getElementById('dhcp-server-modal-pool').value = '192.168.88.10-192.168.88.254';
  12672. document.getElementById('dhcp-server-modal-leasetime').value = '12h';
  12673. document.getElementById('dhcp-server-modal-comment').value = '';
  12674. document.getElementById('dhcp-server-modal-authoritative').checked = true;
  12675. document.getElementById('dhcp-server-modal-disabled').checked = false;
  12676. populateDHCPIfaceSelect('dhcp-server-modal-iface', '');
  12677. const networks = state.dhcpNetworks || [];
  12678. const defaultNet = networks.length > 0 ? networks[0].address : '';
  12679. populateDHCPNetworkSelect('dhcp-server-modal-network', defaultNet);
  12680. if (defaultNet) {
  12681. onDHCPServerNetworkChange();
  12682. }
  12683. document.getElementById('dhcp-server-instance-modal').classList.remove('hidden');
  12684. }
  12685. function openEditDHCPServerModal(id) {
  12686. const s = (state.dhcpServers || []).find(item => item.id === id);
  12687. if (!s) return;
  12688. document.getElementById('dhcp-server-modal-title').innerText = `Edit DHCP Server (${s.name})`;
  12689. document.getElementById('dhcp-server-modal-id').value = s.id;
  12690. document.getElementById('dhcp-server-modal-name').value = s.name;
  12691. document.getElementById('dhcp-server-modal-pool').value = s.address_pool;
  12692. document.getElementById('dhcp-server-modal-leasetime').value = s.lease_time || '12h';
  12693. document.getElementById('dhcp-server-modal-comment').value = s.comment || '';
  12694. document.getElementById('dhcp-server-modal-authoritative').checked = s.authoritative !== false;
  12695. document.getElementById('dhcp-server-modal-disabled').checked = !!s.disabled;
  12696. populateDHCPIfaceSelect('dhcp-server-modal-iface', s.interface);
  12697. populateDHCPNetworkSelect('dhcp-server-modal-network', s.network || '');
  12698. document.getElementById('dhcp-server-instance-modal').classList.remove('hidden');
  12699. }
  12700. function closeDHCPServerModal() {
  12701. document.getElementById('dhcp-server-instance-modal').classList.add('hidden');
  12702. }
  12703. async function submitSaveDHCPServer(e) {
  12704. e.preventDefault();
  12705. const id = document.getElementById('dhcp-server-modal-id').value;
  12706. const name = document.getElementById('dhcp-server-modal-name').value.trim();
  12707. const iface = document.getElementById('dhcp-server-modal-iface').value;
  12708. const network = document.getElementById('dhcp-server-modal-network').value.trim();
  12709. const pool = document.getElementById('dhcp-server-modal-pool').value.trim();
  12710. const leaseTime = document.getElementById('dhcp-server-modal-leasetime').value.trim() || '12h';
  12711. const comment = document.getElementById('dhcp-server-modal-comment').value.trim();
  12712. const authoritative = document.getElementById('dhcp-server-modal-authoritative').checked;
  12713. const disabled = document.getElementById('dhcp-server-modal-disabled').checked;
  12714. try {
  12715. const res = await fetch(`${API_BASE}/dhcp-server/servers`, {
  12716. method: 'POST',
  12717. headers: { 'Content-Type': 'application/json' },
  12718. body: JSON.stringify({
  12719. id,
  12720. name,
  12721. interface: iface,
  12722. network,
  12723. address_pool: pool,
  12724. lease_time: leaseTime,
  12725. authoritative,
  12726. disabled,
  12727. comment
  12728. })
  12729. });
  12730. if (res.ok) {
  12731. showToast('DHCP Server Saved', `Server ${name} configured successfully`, 'success');
  12732. closeDHCPServerModal();
  12733. loadDHCPServer(false);
  12734. fetchData(false);
  12735. } else {
  12736. const err = await res.text();
  12737. showToast('Error', err, 'error');
  12738. }
  12739. } catch (err) {
  12740. showToast('Error', err.message, 'error');
  12741. }
  12742. }
  12743. async function toggleDHCPServerState(id, disabled) {
  12744. try {
  12745. const res = await fetch(`${API_BASE}/dhcp-server/servers/${encodeURIComponent(id)}/state`, {
  12746. method: 'POST',
  12747. headers: { 'Content-Type': 'application/json' },
  12748. body: JSON.stringify({ disabled })
  12749. });
  12750. if (res.ok) {
  12751. showToast('State Updated', disabled ? 'Server disabled' : 'Server enabled', 'info');
  12752. loadDHCPServer(false);
  12753. fetchData(false);
  12754. }
  12755. } catch (err) {
  12756. showToast('Error', err.message, 'error');
  12757. }
  12758. }
  12759. async function deleteDHCPServer(id, name) {
  12760. if (!confirm(`Are you sure you want to delete DHCP Server "${name}"?`)) return;
  12761. try {
  12762. const res = await fetch(`${API_BASE}/dhcp-server/servers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12763. if (res.ok) {
  12764. showToast('Deleted', `DHCP Server ${name} removed`, 'success');
  12765. loadDHCPServer(false);
  12766. fetchData(false);
  12767. }
  12768. } catch (err) {
  12769. showToast('Error', err.message, 'error');
  12770. }
  12771. }
  12772. // ==================== MODALS & ACTIONS: NETWORKS ====================
  12773. function openAddDHCPNetworkModal() {
  12774. document.getElementById('dhcp-network-modal-title').innerText = 'Add DHCP Network';
  12775. document.getElementById('dhcp-network-modal-id').value = '';
  12776. document.getElementById('dhcp-network-modal-address').value = '192.168.88.0/24';
  12777. document.getElementById('dhcp-network-modal-gateway').value = '192.168.88.1';
  12778. document.getElementById('dhcp-network-modal-dns').value = '192.168.88.1, 1.1.1.1, 8.8.8.8';
  12779. document.getElementById('dhcp-network-modal-domain').value = 'lan';
  12780. document.getElementById('dhcp-network-modal-netmask').value = '';
  12781. document.getElementById('dhcp-network-modal-comment').value = '';
  12782. renderDHCPNetworkOptionsCheckboxes([]);
  12783. document.getElementById('dhcp-network-modal').classList.remove('hidden');
  12784. }
  12785. function openEditDHCPNetworkModal(id) {
  12786. const n = (state.dhcpNetworks || []).find(item => item.id === id);
  12787. if (!n) return;
  12788. document.getElementById('dhcp-network-modal-title').innerText = `Edit DHCP Network (${n.address})`;
  12789. document.getElementById('dhcp-network-modal-id').value = n.id;
  12790. document.getElementById('dhcp-network-modal-address').value = n.address;
  12791. document.getElementById('dhcp-network-modal-gateway').value = n.gateway || '';
  12792. document.getElementById('dhcp-network-modal-dns').value = (n.dns_servers || []).join(', ');
  12793. document.getElementById('dhcp-network-modal-domain').value = n.domain || '';
  12794. document.getElementById('dhcp-network-modal-netmask').value = n.netmask || '';
  12795. document.getElementById('dhcp-network-modal-comment').value = n.comment || '';
  12796. renderDHCPNetworkOptionsCheckboxes(n.dhcp_options || []);
  12797. document.getElementById('dhcp-network-modal').classList.remove('hidden');
  12798. }
  12799. function renderDHCPNetworkOptionsCheckboxes(selectedIds) {
  12800. const container = document.getElementById('dhcp-network-modal-options-list');
  12801. if (!container) return;
  12802. container.innerHTML = '';
  12803. const opts = state.dhcpOptions || [];
  12804. if (opts.length === 0) {
  12805. container.innerHTML = '<span class="text-slate-500 text-[11px] col-span-2">No custom options configured. Add some in the "Options" tab.</span>';
  12806. return;
  12807. }
  12808. opts.forEach(o => {
  12809. const isChecked = selectedIds.includes(o.id);
  12810. const label = document.createElement('label');
  12811. label.className = 'flex items-center space-x-2 text-slate-300 hover:text-white cursor-pointer';
  12812. label.innerHTML = `
  12813. <input type="checkbox" name="dhcp-net-opt" value="${o.id}" ${isChecked ? 'checked' : ''} class="rounded bg-slate-800 border-slate-700 text-emerald-600">
  12814. <span class="truncate" title="${escapeHtml(o.name)} (Code ${o.code})">${escapeHtml(o.name)} <span class="text-cyan-400">#${o.code}</span></span>
  12815. `;
  12816. container.appendChild(label);
  12817. });
  12818. }
  12819. function closeDHCPNetworkModal() {
  12820. document.getElementById('dhcp-network-modal').classList.add('hidden');
  12821. }
  12822. async function submitSaveDHCPNetwork(e) {
  12823. e.preventDefault();
  12824. const id = document.getElementById('dhcp-network-modal-id').value;
  12825. const address = document.getElementById('dhcp-network-modal-address').value.trim();
  12826. const gateway = document.getElementById('dhcp-network-modal-gateway').value.trim();
  12827. const dnsStr = document.getElementById('dhcp-network-modal-dns').value.trim();
  12828. const domain = document.getElementById('dhcp-network-modal-domain').value.trim();
  12829. const netmask = document.getElementById('dhcp-network-modal-netmask').value.trim();
  12830. const comment = document.getElementById('dhcp-network-modal-comment').value.trim();
  12831. const selectedOpts = [];
  12832. document.querySelectorAll('input[name="dhcp-net-opt"]:checked').forEach(cb => selectedOpts.push(cb.value));
  12833. const dnsServers = dnsStr ? dnsStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  12834. try {
  12835. const res = await fetch(`${API_BASE}/dhcp-server/networks`, {
  12836. method: 'POST',
  12837. headers: { 'Content-Type': 'application/json' },
  12838. body: JSON.stringify({
  12839. id,
  12840. address,
  12841. gateway,
  12842. netmask,
  12843. dns_servers: dnsServers,
  12844. domain,
  12845. dhcp_options: selectedOpts,
  12846. comment
  12847. })
  12848. });
  12849. if (res.ok) {
  12850. showToast('Network Saved', `Subnet ${address} configured successfully`, 'success');
  12851. closeDHCPNetworkModal();
  12852. loadDHCPServer(false);
  12853. fetchData(false);
  12854. } else {
  12855. const err = await res.text();
  12856. showToast('Error', err, 'error');
  12857. }
  12858. } catch (err) {
  12859. showToast('Error', err.message, 'error');
  12860. }
  12861. }
  12862. async function deleteDHCPNetwork(id, addr) {
  12863. if (!confirm(`Are you sure you want to delete DHCP Network "${addr}"?`)) return;
  12864. try {
  12865. const res = await fetch(`${API_BASE}/dhcp-server/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12866. if (res.ok) {
  12867. showToast('Deleted', `Network ${addr} removed`, 'success');
  12868. loadDHCPServer(false);
  12869. fetchData(false);
  12870. }
  12871. } catch (err) {
  12872. showToast('Error', err.message, 'error');
  12873. }
  12874. }
  12875. // ==================== MODALS & ACTIONS: LEASES ====================
  12876. function openAddDHCPStaticLeaseModal() {
  12877. document.getElementById('dhcp-static-lease-modal-title').innerText = 'Add Static Lease Reservation';
  12878. document.getElementById('dhcp-static-lease-modal-id').value = '';
  12879. document.getElementById('dhcp-static-lease-modal-mac').value = '';
  12880. document.getElementById('dhcp-static-lease-modal-ip').value = '';
  12881. document.getElementById('dhcp-static-lease-modal-hostname').value = '';
  12882. document.getElementById('dhcp-static-lease-modal-server').value = 'all';
  12883. document.getElementById('dhcp-static-lease-modal-comment').value = '';
  12884. document.getElementById('dhcp-static-lease-modal-disabled').checked = false;
  12885. document.getElementById('dhcp-static-lease-modal').classList.remove('hidden');
  12886. }
  12887. function closeDHCPStaticLeaseModal() {
  12888. document.getElementById('dhcp-static-lease-modal').classList.add('hidden');
  12889. }
  12890. async function submitSaveDHCPStaticLease(e) {
  12891. e.preventDefault();
  12892. const id = document.getElementById('dhcp-static-lease-modal-id').value;
  12893. const mac = document.getElementById('dhcp-static-lease-modal-mac').value.trim();
  12894. const ip = document.getElementById('dhcp-static-lease-modal-ip').value.trim();
  12895. const hostname = document.getElementById('dhcp-static-lease-modal-hostname').value.trim();
  12896. const server = document.getElementById('dhcp-static-lease-modal-server').value.trim() || 'all';
  12897. const comment = document.getElementById('dhcp-static-lease-modal-comment').value.trim();
  12898. const disabled = document.getElementById('dhcp-static-lease-modal-disabled').checked;
  12899. try {
  12900. const res = await fetch(`${API_BASE}/dhcp-server/leases/static`, {
  12901. method: 'POST',
  12902. headers: { 'Content-Type': 'application/json' },
  12903. body: JSON.stringify({
  12904. id,
  12905. mac_address: mac,
  12906. address: ip,
  12907. hostname,
  12908. server,
  12909. comment,
  12910. disabled
  12911. })
  12912. });
  12913. if (res.ok) {
  12914. showToast('Static Lease Saved', `IP ${ip} reserved for ${mac}`, 'success');
  12915. closeDHCPStaticLeaseModal();
  12916. loadDHCPServer(false);
  12917. fetchData(false);
  12918. } else {
  12919. const err = await res.text();
  12920. showToast('Error', err, 'error');
  12921. }
  12922. } catch (err) {
  12923. showToast('Error', err.message, 'error');
  12924. }
  12925. }
  12926. async function deleteDHCPStaticLease(id) {
  12927. if (!confirm('Are you sure you want to remove this static reservation?')) return;
  12928. try {
  12929. const res = await fetch(`${API_BASE}/dhcp-server/leases/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12930. if (res.ok) {
  12931. showToast('Deleted', 'Static lease removed', 'success');
  12932. loadDHCPServer(false);
  12933. fetchData(false);
  12934. }
  12935. } catch (err) {
  12936. showToast('Error', err.message, 'error');
  12937. }
  12938. }
  12939. async function makeDHCPLeaseStatic(mac, ip, hostname, comment) {
  12940. try {
  12941. const res = await fetch(`${API_BASE}/dhcp-server/leases/make-static`, {
  12942. method: 'POST',
  12943. headers: { 'Content-Type': 'application/json' },
  12944. body: JSON.stringify({
  12945. mac_address: mac,
  12946. address: ip,
  12947. hostname,
  12948. comment: comment || 'Converted to static'
  12949. })
  12950. });
  12951. if (res.ok) {
  12952. showToast('Lease Made Static', `IP ${ip} permanently reserved for ${mac}`, 'success');
  12953. loadDHCPServer(false);
  12954. fetchData(false);
  12955. } else {
  12956. const err = await res.text();
  12957. showToast('Error', err, 'error');
  12958. }
  12959. } catch (err) {
  12960. showToast('Error', err.message, 'error');
  12961. }
  12962. }
  12963. // ==================== MODALS & ACTIONS: OPTIONS ====================
  12964. function openAddDHCPOptionModal() {
  12965. document.getElementById('dhcp-option-modal-title').innerText = 'Add DHCP Option';
  12966. document.getElementById('dhcp-option-modal-id').value = '';
  12967. document.getElementById('dhcp-option-modal-name').value = '';
  12968. document.getElementById('dhcp-option-modal-code').value = '';
  12969. document.getElementById('dhcp-option-modal-value').value = '';
  12970. document.getElementById('dhcp-option-modal-comment').value = '';
  12971. document.getElementById('dhcp-option-modal').classList.remove('hidden');
  12972. }
  12973. function openEditDHCPOptionModal(id) {
  12974. const o = (state.dhcpOptions || []).find(item => item.id === id);
  12975. if (!o) return;
  12976. document.getElementById('dhcp-option-modal-title').innerText = `Edit DHCP Option (${o.name})`;
  12977. document.getElementById('dhcp-option-modal-id').value = o.id;
  12978. document.getElementById('dhcp-option-modal-name').value = o.name;
  12979. document.getElementById('dhcp-option-modal-code').value = o.code;
  12980. document.getElementById('dhcp-option-modal-value').value = o.value;
  12981. document.getElementById('dhcp-option-modal-comment').value = o.comment || '';
  12982. document.getElementById('dhcp-option-modal').classList.remove('hidden');
  12983. }
  12984. function closeDHCPOptionModal() {
  12985. document.getElementById('dhcp-option-modal').classList.add('hidden');
  12986. }
  12987. async function submitSaveDHCPOption(e) {
  12988. e.preventDefault();
  12989. const id = document.getElementById('dhcp-option-modal-id').value;
  12990. const name = document.getElementById('dhcp-option-modal-name').value.trim();
  12991. const code = parseInt(document.getElementById('dhcp-option-modal-code').value);
  12992. const value = document.getElementById('dhcp-option-modal-value').value.trim();
  12993. const comment = document.getElementById('dhcp-option-modal-comment').value.trim();
  12994. try {
  12995. const res = await fetch(`${API_BASE}/dhcp-server/options`, {
  12996. method: 'POST',
  12997. headers: { 'Content-Type': 'application/json' },
  12998. body: JSON.stringify({ id, name, code, value, comment })
  12999. });
  13000. if (res.ok) {
  13001. showToast('Option Saved', `DHCP option ${name} (#${code}) configured`, 'success');
  13002. closeDHCPOptionModal();
  13003. loadDHCPServer(false);
  13004. fetchData(false);
  13005. } else {
  13006. const err = await res.text();
  13007. showToast('Error', err, 'error');
  13008. }
  13009. } catch (err) {
  13010. showToast('Error', err.message, 'error');
  13011. }
  13012. }
  13013. async function deleteDHCPOption(id, name) {
  13014. if (!confirm(`Are you sure you want to delete DHCP Option "${name}"?`)) return;
  13015. try {
  13016. const res = await fetch(`${API_BASE}/dhcp-server/options/${encodeURIComponent(id)}`, { method: 'DELETE' });
  13017. if (res.ok) {
  13018. showToast('Deleted', `Option ${name} removed`, 'success');
  13019. loadDHCPServer(false);
  13020. fetchData(false);
  13021. }
  13022. } catch (err) {
  13023. showToast('Error', err.message, 'error');
  13024. }
  13025. }
  13026. // ==================== WIZARD: DHCP SETUP (MikroTik style) ====================
  13027. function openDHCPServerSetupModal() {
  13028. populateDHCPIfaceSelect('dhcp-wizard-iface', '');
  13029. onDHCPWizardIfaceChange();
  13030. document.getElementById('dhcp-setup-wizard-modal').classList.remove('hidden');
  13031. }
  13032. function closeDHCPServerSetupModal() {
  13033. document.getElementById('dhcp-setup-wizard-modal').classList.add('hidden');
  13034. }
  13035. function onDHCPWizardIfaceChange() {
  13036. const ifaceName = document.getElementById('dhcp-wizard-iface').value;
  13037. const iface = (state.interfaces || []).find(i => i.name === ifaceName);
  13038. let ip = '192.168.88.1';
  13039. let prefix = '24';
  13040. if (iface && iface.ip_address) {
  13041. const parts = iface.ip_address.split('/');
  13042. ip = parts[0];
  13043. if (parts.length > 1) prefix = parts[1];
  13044. }
  13045. // Calculate subnet base (e.g. 192.168.88.0/24)
  13046. const ipParts = ip.split('.');
  13047. if (ipParts.length === 4) {
  13048. const baseSpace = `${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.0/${prefix}`;
  13049. const pool = `${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.10-${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.254`;
  13050. document.getElementById('dhcp-wizard-space').value = baseSpace;
  13051. document.getElementById('dhcp-wizard-gateway').value = ip;
  13052. document.getElementById('dhcp-wizard-pool').value = pool;
  13053. document.getElementById('dhcp-wizard-dns').value = `${ip}, 1.1.1.1, 8.8.8.8`;
  13054. document.getElementById('dhcp-wizard-ntp').value = `${ip}`;
  13055. }
  13056. }
  13057. async function submitDHCPServerSetupWizard(e) {
  13058. e.preventDefault();
  13059. const iface = document.getElementById('dhcp-wizard-iface').value;
  13060. const space = document.getElementById('dhcp-wizard-space').value.trim();
  13061. const gw = document.getElementById('dhcp-wizard-gateway').value.trim();
  13062. const pool = document.getElementById('dhcp-wizard-pool').value.trim();
  13063. const dnsStr = document.getElementById('dhcp-wizard-dns').value.trim();
  13064. const leaseTime = document.getElementById('dhcp-wizard-leasetime').value.trim() || '12h';
  13065. const ntpStr = document.getElementById('dhcp-wizard-ntp').value.trim();
  13066. const tftp = document.getElementById('dhcp-wizard-tftp').value.trim();
  13067. const dnsServers = dnsStr ? dnsStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  13068. const ntpServers = ntpStr ? ntpStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  13069. try {
  13070. const res = await fetch(`${API_BASE}/dhcp-server/setup`, {
  13071. method: 'POST',
  13072. headers: { 'Content-Type': 'application/json' },
  13073. body: JSON.stringify({
  13074. interface: iface,
  13075. address_space: space,
  13076. gateway: gw,
  13077. address_pool: pool,
  13078. dns_servers: dnsServers,
  13079. lease_time: leaseTime,
  13080. ntp_servers: ntpServers,
  13081. next_server: tftp
  13082. })
  13083. });
  13084. if (res.ok) {
  13085. showToast('DHCP Setup Complete', `DHCP Server setup finished on ${iface}`, 'success');
  13086. closeDHCPServerSetupModal();
  13087. loadDHCPServer(false);
  13088. fetchData(false);
  13089. } else {
  13090. const err = await res.text();
  13091. showToast('Error', err, 'error');
  13092. }
  13093. } catch (err) {
  13094. showToast('Error', err.message, 'error');
  13095. }
  13096. }
  13097. function populateDHCPIfaceSelect(elemId, selectedVal) {
  13098. const sel = document.getElementById(elemId);
  13099. if (!sel) return;
  13100. sel.innerHTML = '<option value="">Select interface...</option>';
  13101. const ifaces = state.interfaces || [];
  13102. ifaces.forEach(i => {
  13103. if (i.name === 'lo') return;
  13104. const opt = document.createElement('option');
  13105. opt.value = i.name;
  13106. const ipStr = i.ip_address ? ` (${i.ip_address})` : '';
  13107. opt.textContent = `${i.name}${ipStr} [${i.role || i.type || 'interface'}]`;
  13108. if (i.name === selectedVal) opt.selected = true;
  13109. sel.appendChild(opt);
  13110. });
  13111. }
  13112. // ==================== UNIVERSAL TABLE ORDERING / SORTING (WINBOX / WEBFIG STYLE) ====================
  13113. function initTableSorting() {
  13114. document.querySelectorAll('table').forEach(setupSortableTable);
  13115. }
  13116. function setupSortableTable(table) {
  13117. const thead = table.querySelector('thead');
  13118. const tbody = table.querySelector('tbody');
  13119. if (!thead || !tbody) return;
  13120. const headerRows = thead.querySelectorAll('tr');
  13121. if (headerRows.length === 0) return;
  13122. const ths = headerRows[headerRows.length - 1].querySelectorAll('th');
  13123. ths.forEach((th, colIdx) => {
  13124. if (th._sortBound) return;
  13125. th._sortBound = true;
  13126. const rawText = th.innerText.trim().toLowerCase();
  13127. const isActionsCol = rawText === 'actions' || (rawText === 'action' && th.classList.contains('text-right'));
  13128. const isCheckboxCol = !!th.querySelector('input[type="checkbox"]');
  13129. const isExpandCol = (th.classList.contains('w-8') || th.classList.contains('w-6')) && !rawText;
  13130. const isExplicitNoSort = th.classList.contains('no-sort') || th.getAttribute('data-sortable') === 'false';
  13131. if (isActionsCol || isCheckboxCol || isExpandCol || isExplicitNoSort) {
  13132. return;
  13133. }
  13134. th.classList.add('table-sortable', 'group');
  13135. if (!th.title) th.title = 'Click to sort (Ascending / Descending / Default)';
  13136. let icon = th.querySelector('.table-sort-icon');
  13137. if (!icon) {
  13138. icon = document.createElement('span');
  13139. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  13140. icon.innerHTML = '⇅';
  13141. th.appendChild(icon);
  13142. }
  13143. th.addEventListener('click', (e) => {
  13144. if (e.target.tagName === 'INPUT' || e.target.tagName === 'BUTTON' || e.target.closest('button, input')) return;
  13145. handleHeaderClick(table, th, colIdx);
  13146. });
  13147. });
  13148. if (!tbody._sortObserved) {
  13149. tbody._sortObserved = true;
  13150. let sortDebounceTimer = null;
  13151. const observer = new MutationObserver((mutations) => {
  13152. if (tbody._isSorting) return;
  13153. const hasChildChanges = mutations.some(m => m.type === 'childList' && m.addedNodes.length > 0);
  13154. if (!hasChildChanges) return;
  13155. clearTimeout(sortDebounceTimer);
  13156. sortDebounceTimer = setTimeout(() => {
  13157. if (tbody._isSorting) return;
  13158. if (table._activeSort && table._activeSort.dir !== 'none') {
  13159. applyTableSort(table, table._activeSort.colIdx, table._activeSort.dir, false);
  13160. } else {
  13161. tagOriginalRowOrder(tbody);
  13162. }
  13163. }, 50);
  13164. });
  13165. tbody._sortObserver = observer;
  13166. observer.observe(tbody, { childList: true });
  13167. }
  13168. tagOriginalRowOrder(tbody);
  13169. }
  13170. function tagOriginalRowOrder(tbody) {
  13171. let idx = 0;
  13172. Array.from(tbody.children).forEach(tr => {
  13173. if (!tr.querySelector('td[colspan]')) {
  13174. if (!tr.hasAttribute('data-orig-idx')) {
  13175. tr.setAttribute('data-orig-idx', idx++);
  13176. }
  13177. }
  13178. });
  13179. }
  13180. function handleHeaderClick(table, th, colIdx) {
  13181. const currentSort = table._activeSort || { colIdx: -1, dir: 'none' };
  13182. let newDir = 'asc';
  13183. if (currentSort.colIdx === colIdx) {
  13184. if (currentSort.dir === 'asc') newDir = 'desc';
  13185. else if (currentSort.dir === 'desc') newDir = 'none';
  13186. else newDir = 'asc';
  13187. } else {
  13188. newDir = 'asc';
  13189. }
  13190. table._activeSort = { colIdx, dir: newDir };
  13191. updateHeaderIcons(table, colIdx, newDir);
  13192. applyTableSort(table, colIdx, newDir, true);
  13193. }
  13194. function updateHeaderIcons(table, activeColIdx, dir) {
  13195. const thead = table.querySelector('thead');
  13196. if (!thead) return;
  13197. const ths = thead.querySelectorAll('th');
  13198. ths.forEach((th, idx) => {
  13199. const icon = th.querySelector('.table-sort-icon');
  13200. if (!icon) return;
  13201. if (idx === activeColIdx && dir !== 'none') {
  13202. icon.innerHTML = dir === 'asc' ? '▲' : '▼';
  13203. icon.className = 'table-sort-icon text-cyan-400 font-bold opacity-100';
  13204. th.classList.add('table-sorted-active');
  13205. } else {
  13206. icon.innerHTML = '⇅';
  13207. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  13208. th.classList.remove('table-sorted-active');
  13209. }
  13210. });
  13211. }
  13212. function applyTableSort(table, colIdx, dir, userInitiated) {
  13213. const tbody = table.querySelector('tbody');
  13214. if (!tbody || tbody.children.length <= 1) return;
  13215. tbody._isSorting = true;
  13216. tagOriginalRowOrder(tbody);
  13217. // Group parent rows and any attached drawer/sub-rows
  13218. const groups = [];
  13219. let currentGroup = null;
  13220. Array.from(tbody.children).forEach(tr => {
  13221. if (tr.querySelector('td[colspan]')) {
  13222. if (currentGroup) {
  13223. currentGroup.subRows.push(tr);
  13224. } else {
  13225. groups.push({ mainRow: tr, subRows: [] });
  13226. }
  13227. } else {
  13228. currentGroup = { mainRow: tr, subRows: [] };
  13229. groups.push(currentGroup);
  13230. }
  13231. });
  13232. if (dir === 'none') {
  13233. groups.sort((a, b) => {
  13234. const idxA = parseInt(a.mainRow.getAttribute('data-orig-idx') || '0', 10);
  13235. const idxB = parseInt(b.mainRow.getAttribute('data-orig-idx') || '0', 10);
  13236. return idxA - idxB;
  13237. });
  13238. } else {
  13239. groups.sort((a, b) => {
  13240. const cellA = a.mainRow.children[colIdx];
  13241. const cellB = b.mainRow.children[colIdx];
  13242. const res = compareTableCells(cellA, cellB);
  13243. return dir === 'asc' ? res : -res;
  13244. });
  13245. }
  13246. // Check if rows are already in correct order to avoid modifying DOM
  13247. let alreadyOrdered = true;
  13248. let childIdx = 0;
  13249. for (const g of groups) {
  13250. if (tbody.children[childIdx] !== g.mainRow) {
  13251. alreadyOrdered = false;
  13252. break;
  13253. }
  13254. childIdx++;
  13255. for (const sub of g.subRows) {
  13256. if (tbody.children[childIdx] !== sub) {
  13257. alreadyOrdered = false;
  13258. break;
  13259. }
  13260. childIdx++;
  13261. }
  13262. }
  13263. if (alreadyOrdered) {
  13264. tbody._isSorting = false;
  13265. return;
  13266. }
  13267. // Disconnect observer while re-ordering to prevent recursion and thrashing
  13268. if (tbody._sortObserver) {
  13269. tbody._sortObserver.disconnect();
  13270. }
  13271. // Re-append rows in sorted order
  13272. groups.forEach(g => {
  13273. tbody.appendChild(g.mainRow);
  13274. g.subRows.forEach(sub => tbody.appendChild(sub));
  13275. });
  13276. // Drain any queued mutations and re-connect observer
  13277. if (tbody._sortObserver) {
  13278. tbody._sortObserver.takeRecords();
  13279. tbody._sortObserver.observe(tbody, { childList: true });
  13280. }
  13281. tbody._isSorting = false;
  13282. }
  13283. function getCellRawText(cell) {
  13284. if (!cell) return '';
  13285. if (cell.hasAttribute('data-sort-value')) return cell.getAttribute('data-sort-value');
  13286. const input = cell.querySelector('input, select');
  13287. if (input) {
  13288. if (input.type === 'checkbox') return input.checked ? '1' : '0';
  13289. return input.value;
  13290. }
  13291. return cell.innerText.trim();
  13292. }
  13293. function parseTrafficToNumber(str) {
  13294. const m = str.match(/^([\d.,]+)\s*([KMGTkmgt]?[iI]?[Bb](?:ps|\/s)?)/);
  13295. if (!m) return null;
  13296. const num = parseFloat(m[1].replace(/,/g, ''));
  13297. if (isNaN(num)) return null;
  13298. const unit = m[2].toUpperCase();
  13299. let mult = 1;
  13300. if (unit.startsWith('K')) mult = 1024;
  13301. else if (unit.startsWith('M')) mult = 1024 * 1024;
  13302. else if (unit.startsWith('G')) mult = 1024 * 1024 * 1024;
  13303. else if (unit.startsWith('T')) mult = 1024 * 1024 * 1024 * 1024;
  13304. return num * mult;
  13305. }
  13306. function parseIpToNumber(str) {
  13307. const clean = str.replace(/^[!~]/, '').trim();
  13308. const m = clean.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(?:\/(\d{1,2}))?/);
  13309. if (!m) return null;
  13310. const o1 = parseInt(m[1], 10);
  13311. const o2 = parseInt(m[2], 10);
  13312. const o3 = parseInt(m[3], 10);
  13313. const o4 = parseInt(m[4], 10);
  13314. if (o1 > 255 || o2 > 255 || o3 > 255 || o4 > 255) return null;
  13315. return ((o1 * 256 + o2) * 256 + o3) * 256 + o4;
  13316. }
  13317. function parseCompoundPackets(str) {
  13318. const m = str.match(/^([\d,]+)p/);
  13319. if (!m) return null;
  13320. return parseInt(m[1].replace(/,/g, ''), 10);
  13321. }
  13322. function compareTableCells(cellA, cellB) {
  13323. const a = getCellRawText(cellA);
  13324. const b = getCellRawText(cellB);
  13325. if (a === '' && b !== '') return 1;
  13326. if (b === '' && a !== '') return -1;
  13327. if (a === b) return 0;
  13328. // 1. IP Addresses / CIDR
  13329. const ipA = parseIpToNumber(a);
  13330. const ipB = parseIpToNumber(b);
  13331. if (ipA !== null && ipB !== null) return ipA - ipB;
  13332. // 2. Packet counts (e.g. "1,250p / 45 KB")
  13333. const pktA = parseCompoundPackets(a);
  13334. const pktB = parseCompoundPackets(b);
  13335. if (pktA !== null && pktB !== null) return pktA - pktB;
  13336. // 3. Traffic / Throughput / Bytes (e.g. "1.2 MB", "500 KiB", "10 Gbps")
  13337. const trafA = parseTrafficToNumber(a);
  13338. const trafB = parseTrafficToNumber(b);
  13339. if (trafA !== null && trafB !== null) return trafA - trafB;
  13340. // 4. Numbers with '#' or formatted with commas (e.g. "#1", "24", "1,200")
  13341. const cleanNumA = a.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  13342. const cleanNumB = b.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  13343. const numA = Number(cleanNumA);
  13344. const numB = Number(cleanNumB);
  13345. if (!isNaN(numA) && !isNaN(numB) && cleanNumA !== '' && cleanNumB !== '') {
  13346. return numA - numB;
  13347. }
  13348. // 5. Natural case-insensitive string compare
  13349. return a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' });
  13350. }
  13351. // ==================== VRRP HIGH AVAILABILITY CONTROLLER ====================
  13352. async function loadVRRP(showToastNotification = false) {
  13353. try {
  13354. const [instRes, sumRes] = await Promise.all([
  13355. fetch(`${API_BASE}/vrrp/instances`),
  13356. fetch(`${API_BASE}/vrrp/summary`)
  13357. ]);
  13358. if (instRes.ok) {
  13359. state.vrrpInstances = await instRes.json();
  13360. renderVRRP();
  13361. }
  13362. if (sumRes.ok) {
  13363. state.vrrpSummary = await sumRes.json();
  13364. renderVRRPSummary();
  13365. }
  13366. if (showToastNotification) {
  13367. showToast('Refreshed', 'VRRP telemetry refreshed', 'info');
  13368. }
  13369. } catch (err) {
  13370. console.error('Failed to load VRRP:', err);
  13371. }
  13372. }
  13373. function renderVRRPSummary() {
  13374. const s = state.vrrpSummary || { total_instances: 0, master_instances: 0, backup_instances: 0 };
  13375. const elTotal = document.getElementById('vrrp-stat-total');
  13376. if (elTotal) elTotal.innerText = s.total_instances || 0;
  13377. const elMaster = document.getElementById('vrrp-stat-master');
  13378. if (elMaster) elMaster.innerText = s.master_instances || 0;
  13379. const elBackup = document.getElementById('vrrp-stat-backup');
  13380. if (elBackup) elBackup.innerText = s.backup_instances || 0;
  13381. const bCount = document.getElementById('badge-vrrp-count');
  13382. if (bCount) bCount.innerText = s.total_instances || 0;
  13383. const dot = document.getElementById('badge-vrrp-dot');
  13384. if (dot) {
  13385. if (s.master_instances > 0) {
  13386. dot.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  13387. } else if (s.backup_instances > 0) {
  13388. dot.className = 'w-2 h-2 rounded-full bg-sky-400';
  13389. } else {
  13390. dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  13391. }
  13392. }
  13393. }
  13394. function renderVRRP() {
  13395. const tbody = document.getElementById('vrrp-table-tbody');
  13396. const empty = document.getElementById('vrrp-table-empty');
  13397. if (!tbody) return;
  13398. tbody.innerHTML = '';
  13399. const instances = state.vrrpInstances || [];
  13400. if (instances.length === 0) {
  13401. empty?.classList.remove('hidden');
  13402. return;
  13403. }
  13404. empty?.classList.add('hidden');
  13405. instances.forEach(inst => {
  13406. const tr = document.createElement('tr');
  13407. tr.className = `hover:bg-slate-800/40 transition text-xs ${inst.disabled ? 'opacity-50' : ''}`;
  13408. // Render Flag: M (Master), B (Backup), F (Fault), X (Disabled)
  13409. 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>`;
  13410. if (inst.disabled) {
  13411. 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>`;
  13412. } else if (inst.state === 'MASTER') {
  13413. 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>`;
  13414. } else if (inst.state === 'BACKUP') {
  13415. 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>`;
  13416. } else if (inst.state === 'FAULT') {
  13417. 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>`;
  13418. }
  13419. // Render State Badge
  13420. let stateBadge = `<span class="px-2 py-0.5 rounded text-[10px] bg-slate-800 text-slate-400 border border-slate-700">DISABLED</span>`;
  13421. if (!inst.disabled) {
  13422. if (inst.state === 'MASTER') {
  13423. 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>`;
  13424. } else if (inst.state === 'BACKUP') {
  13425. 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>`;
  13426. } else if (inst.state === 'FAULT') {
  13427. 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>`;
  13428. }
  13429. }
  13430. const vipsStr = (inst.virtual_ips || []).join(', ') || '-';
  13431. tr.innerHTML = `
  13432. <td class="py-2.5 px-3 text-center">${flagHtml}</td>
  13433. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(inst.name)}</td>
  13434. <td class="py-2.5 px-3 font-mono text-cyan-400 font-semibold">${escapeHtml(inst.interface)}</td>
  13435. <td class="py-2.5 px-3 font-mono font-bold text-center text-white">${inst.vrid}</td>
  13436. <td class="py-2.5 px-3 font-mono text-center text-slate-300 font-semibold">${inst.priority}</td>
  13437. <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>
  13438. <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>
  13439. <td class="py-2.5 px-3 font-mono text-slate-400 text-[11px]">${escapeHtml(inst.virtual_mac || '-')}</td>
  13440. <td class="py-2.5 px-3 text-center">${stateBadge}</td>
  13441. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]" title="${escapeHtml(inst.comment || '')}">${escapeHtml(inst.comment || '-')}</td>
  13442. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  13443. <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>
  13444. <button onclick="openEditVRRPModal('${inst.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  13445. <button onclick="deleteVRRP('${inst.id}', '${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  13446. </td>
  13447. `;
  13448. tbody.appendChild(tr);
  13449. });
  13450. }
  13451. function populateVRRPIfaceSelect(elemId, selectedIface) {
  13452. const sel = document.getElementById(elemId);
  13453. if (!sel) return;
  13454. sel.innerHTML = '<option value="">Select interface...</option>';
  13455. const ifaces = state.interfaces || [];
  13456. ifaces.forEach(i => {
  13457. const opt = document.createElement('option');
  13458. opt.value = i.name;
  13459. opt.innerText = `${i.name} (${i.type || 'net'}${i.ip ? ' - ' + i.ip : ''})`;
  13460. if (selectedIface && selectedIface === i.name) opt.selected = true;
  13461. sel.appendChild(opt);
  13462. });
  13463. }
  13464. function openAddVRRPModal() {
  13465. document.getElementById('modal-vrrp-title').innerText = 'Add VRRP Instance';
  13466. document.getElementById('modal-vrrp-id').value = '';
  13467. document.getElementById('modal-vrrp-name').value = `vrrp${(state.vrrpInstances || []).length + 1}`;
  13468. document.getElementById('modal-vrrp-vrid').value = 10 + (state.vrrpInstances || []).length;
  13469. document.getElementById('modal-vrrp-priority').value = 100;
  13470. document.getElementById('modal-vrrp-vip').value = '192.168.88.254/24';
  13471. document.getElementById('modal-vrrp-version').value = '3';
  13472. document.getElementById('modal-vrrp-interval').value = 1;
  13473. document.getElementById('modal-vrrp-authtype').value = 'none';
  13474. document.getElementById('modal-vrrp-authpass').value = '';
  13475. document.getElementById('modal-vrrp-comment').value = '';
  13476. document.getElementById('modal-vrrp-preempt').checked = true;
  13477. document.getElementById('modal-vrrp-disabled').checked = false;
  13478. populateVRRPIfaceSelect('modal-vrrp-iface', '');
  13479. document.getElementById('modal-vrrp-instance').classList.remove('hidden');
  13480. }
  13481. function openEditVRRPModal(id) {
  13482. const inst = (state.vrrpInstances || []).find(item => item.id === id);
  13483. if (!inst) return;
  13484. document.getElementById('modal-vrrp-title').innerText = `Edit VRRP Instance (${inst.name})`;
  13485. document.getElementById('modal-vrrp-id').value = inst.id;
  13486. document.getElementById('modal-vrrp-name').value = inst.name;
  13487. document.getElementById('modal-vrrp-vrid').value = inst.vrid;
  13488. document.getElementById('modal-vrrp-priority').value = inst.priority;
  13489. document.getElementById('modal-vrrp-vip').value = (inst.virtual_ips || []).join(', ');
  13490. document.getElementById('modal-vrrp-version').value = String(inst.version || 3);
  13491. document.getElementById('modal-vrrp-interval').value = inst.interval || 1;
  13492. document.getElementById('modal-vrrp-authtype').value = inst.auth_type || 'none';
  13493. document.getElementById('modal-vrrp-authpass').value = inst.auth_password || '';
  13494. document.getElementById('modal-vrrp-comment').value = inst.comment || '';
  13495. document.getElementById('modal-vrrp-preempt').checked = inst.preempt !== false;
  13496. document.getElementById('modal-vrrp-disabled').checked = !!inst.disabled;
  13497. populateVRRPIfaceSelect('modal-vrrp-iface', inst.interface);
  13498. document.getElementById('modal-vrrp-instance').classList.remove('hidden');
  13499. }
  13500. function closeVRRPModal() {
  13501. document.getElementById('modal-vrrp-instance').classList.add('hidden');
  13502. }
  13503. async function submitSaveVRRP(e) {
  13504. e.preventDefault();
  13505. const id = document.getElementById('modal-vrrp-id').value;
  13506. const name = document.getElementById('modal-vrrp-name').value.trim();
  13507. const iface = document.getElementById('modal-vrrp-iface').value;
  13508. const vrid = parseInt(document.getElementById('modal-vrrp-vrid').value, 10) || 1;
  13509. const priority = parseInt(document.getElementById('modal-vrrp-priority').value, 10) || 100;
  13510. const vipRaw = document.getElementById('modal-vrrp-vip').value.trim();
  13511. const version = parseInt(document.getElementById('modal-vrrp-version').value, 10) || 3;
  13512. const interval = parseInt(document.getElementById('modal-vrrp-interval').value, 10) || 1;
  13513. const authType = document.getElementById('modal-vrrp-authtype').value;
  13514. const authPass = document.getElementById('modal-vrrp-authpass').value.trim();
  13515. const comment = document.getElementById('modal-vrrp-comment').value.trim();
  13516. const preempt = document.getElementById('modal-vrrp-preempt').checked;
  13517. const disabled = document.getElementById('modal-vrrp-disabled').checked;
  13518. const vips = vipRaw.split(',').map(s => s.trim()).filter(Boolean);
  13519. try {
  13520. const res = await fetch(`${API_BASE}/vrrp/instances`, {
  13521. method: 'POST',
  13522. headers: { 'Content-Type': 'application/json' },
  13523. body: JSON.stringify({
  13524. id,
  13525. name,
  13526. interface: iface,
  13527. vrid,
  13528. priority,
  13529. virtual_ips: vips,
  13530. version,
  13531. interval,
  13532. auth_type: authType,
  13533. auth_password: authPass,
  13534. comment,
  13535. preempt,
  13536. disabled
  13537. })
  13538. });
  13539. if (res.ok) {
  13540. showToast('VRRP Saved', `VRRP instance ${name} configured`, 'success');
  13541. closeVRRPModal();
  13542. loadVRRP(false);
  13543. fetchData(false);
  13544. } else {
  13545. const err = await res.text();
  13546. showToast('Error', err, 'error');
  13547. }
  13548. } catch (err) {
  13549. showToast('Error', err.message, 'error');
  13550. }
  13551. }
  13552. async function deleteVRRP(id, name) {
  13553. if (!confirm(`Delete VRRP instance "${name}"?`)) return;
  13554. try {
  13555. const res = await fetch(`${API_BASE}/vrrp/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  13556. if (res.ok) {
  13557. showToast('Deleted', `VRRP instance ${name} removed`, 'info');
  13558. loadVRRP(false);
  13559. fetchData(false);
  13560. } else {
  13561. const err = await res.text();
  13562. showToast('Error', err, 'error');
  13563. }
  13564. } catch (err) {
  13565. showToast('Error', err.message, 'error');
  13566. }
  13567. }
  13568. async function toggleVRRPState(id, disabled) {
  13569. try {
  13570. const res = await fetch(`${API_BASE}/vrrp/instances/${encodeURIComponent(id)}/state`, {
  13571. method: 'POST',
  13572. headers: { 'Content-Type': 'application/json' },
  13573. body: JSON.stringify({ disabled })
  13574. });
  13575. if (res.ok) {
  13576. showToast('State Updated', disabled ? 'VRRP disabled' : 'VRRP enabled', 'info');
  13577. loadVRRP(false);
  13578. fetchData(false);
  13579. } else {
  13580. const err = await res.text();
  13581. showToast('Error', err, 'error');
  13582. }
  13583. } catch (err) {
  13584. showToast('Error', err.message, 'error');
  13585. }
  13586. }
  13587. // Global observer for dynamically injected tables (e.g. inside modals or drawers)
  13588. if (typeof MutationObserver !== 'undefined' && typeof document !== 'undefined') {
  13589. let docSortDebounce = null;
  13590. const docTableObserver = new MutationObserver((mutations) => {
  13591. let needsInit = false;
  13592. for (const m of mutations) {
  13593. for (const node of m.addedNodes) {
  13594. if (node.nodeType === 1) {
  13595. if (node.tagName === 'TABLE' && !node.closest('tbody, thead')) {
  13596. needsInit = true;
  13597. break;
  13598. } else if (node.querySelector && !node.closest('table') && node.querySelector('table')) {
  13599. needsInit = true;
  13600. break;
  13601. }
  13602. }
  13603. }
  13604. if (needsInit) break;
  13605. }
  13606. if (needsInit) {
  13607. clearTimeout(docSortDebounce);
  13608. docSortDebounce = setTimeout(initTableSorting, 100);
  13609. }
  13610. });
  13611. docTableObserver.observe(document.body || document.documentElement, { childList: true, subtree: true });
  13612. }
  13613. // =========================================================================
  13614. // BANDWIDTH TEST (BwTest) BENCHMARK ENGINE
  13615. // =========================================================================
  13616. const bwtestState = {
  13617. running: false,
  13618. pollTimer: null,
  13619. eventSource: null,
  13620. chartPoints: [],
  13621. maxChartPoints: 60,
  13622. serverConfig: null,
  13623. peakTx: 0,
  13624. peakRx: 0,
  13625. targetDuration: 10,
  13626. lastSampleElapsed: -1,
  13627. sessionID: null
  13628. };
  13629. async function loadBwTestView() {
  13630. resizeBwTestCanvas();
  13631. await Promise.all([fetchBwTestServerStatus(), loadBwTestHistory(), checkActiveBwTest()]);
  13632. }
  13633. async function fetchBwTestServerStatus() {
  13634. try {
  13635. const res = await fetch(`${API_BASE}/tools/bwtest/server`);
  13636. if (!res.ok) return;
  13637. const s = await res.json();
  13638. bwtestState.serverConfig = s;
  13639. // Update indicator and badges
  13640. const indicator = document.getElementById('bwtest-server-indicator');
  13641. const badge = document.getElementById('bwtest-server-badge');
  13642. const sideBadge = document.getElementById('badge-bwtest-server');
  13643. if (s.enabled && s.running) {
  13644. if (indicator) indicator.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  13645. if (badge) {
  13646. badge.innerText = `Port ${s.port} (Active)`;
  13647. badge.className = 'text-emerald-400 font-bold';
  13648. }
  13649. if (sideBadge) {
  13650. sideBadge.innerText = s.port;
  13651. 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';
  13652. }
  13653. } else {
  13654. if (indicator) indicator.className = 'w-2 h-2 rounded-full bg-slate-600';
  13655. if (badge) {
  13656. badge.innerText = `Disabled`;
  13657. badge.className = 'text-slate-500 font-bold';
  13658. }
  13659. if (sideBadge) {
  13660. sideBadge.innerText = 'Off';
  13661. sideBadge.className = 'text-[10px] bg-slate-800 text-slate-500 border border-slate-700 px-1.5 py-0.2 rounded-full font-mono';
  13662. }
  13663. }
  13664. // Modal fields
  13665. const toggle = document.getElementById('bwtest-server-enable-toggle');
  13666. const serverModal = document.getElementById('modal-bwtest-server');
  13667. const editing = serverModal && !serverModal.classList.contains('hidden');
  13668. if (toggle && !editing) toggle.checked = !!s.enabled;
  13669. const portInp = document.getElementById('bwtest-server-port-input');
  13670. if (portInp && !editing) portInp.value = s.port || 2000;
  13671. const actSess = document.getElementById('bwtest-modal-active-sessions');
  13672. if (actSess) actSess.innerText = s.active_sessions || 0;
  13673. const totServ = document.getElementById('bwtest-modal-total-served');
  13674. if (totServ) totServ.innerText = s.total_sessions_served || 0;
  13675. const totBytes = document.getElementById('bwtest-modal-total-bytes');
  13676. if (totBytes) totBytes.innerText = formatBytes(s.total_bytes_processed || 0);
  13677. } catch (err) {
  13678. console.error('Failed to fetch BwTest server status:', err);
  13679. }
  13680. }
  13681. function openBwTestServerModal() {
  13682. const cfg = bwtestState.serverConfig;
  13683. if (cfg) {
  13684. document.getElementById('bwtest-server-enable-toggle').checked = !!cfg.enabled;
  13685. document.getElementById('bwtest-server-port-input').value = cfg.port || 2000;
  13686. }
  13687. fetchBwTestServerStatus();
  13688. document.getElementById('modal-bwtest-server')?.classList.remove('hidden');
  13689. }
  13690. function closeBwTestServerModal() {
  13691. document.getElementById('modal-bwtest-server')?.classList.add('hidden');
  13692. }
  13693. async function submitBwTestServerSettings(e) {
  13694. e.preventDefault();
  13695. const enabled = document.getElementById('bwtest-server-enable-toggle').checked;
  13696. const port = parseInt(document.getElementById('bwtest-server-port-input').value, 10) || 2000;
  13697. try {
  13698. const res = await fetch(`${API_BASE}/tools/bwtest/server`, {
  13699. method: 'POST',
  13700. headers: { 'Content-Type': 'application/json' },
  13701. body: JSON.stringify({ enabled, port, listen_addr: '0.0.0.0', allow_anonymous: true })
  13702. });
  13703. if (!res.ok) {
  13704. const err = await res.json();
  13705. throw new Error(err.error || 'Failed to update server configuration');
  13706. }
  13707. showToast('BwTest Server', `Bandwidth Test server updated (Port ${port})`, 'success');
  13708. closeBwTestServerModal();
  13709. fetchBwTestServerStatus();
  13710. } catch (err) {
  13711. showToast('Server Configuration Error', err.message, 'error');
  13712. }
  13713. }
  13714. function setBwTestTarget(target) {
  13715. const inp = document.getElementById('bwtest-input-target');
  13716. if (inp) inp.value = target;
  13717. }
  13718. function setBwTestProtocol(proto) {
  13719. const hiddenInp = document.getElementById('bwtest-input-protocol');
  13720. if (hiddenInp) hiddenInp.value = proto;
  13721. const btnUdp = document.getElementById('bwtest-proto-udp');
  13722. const btnTcp = document.getElementById('bwtest-proto-tcp');
  13723. const badge = document.getElementById('bwtest-proto-badge');
  13724. const pktField = document.getElementById('bwtest-field-pktsize');
  13725. 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';
  13726. 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';
  13727. 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';
  13728. if (proto === 'udp') {
  13729. if (btnUdp) {
  13730. btnUdp.className = activeUdpCls;
  13731. const dot = btnUdp.querySelector('span');
  13732. if (dot) dot.className = 'w-2 h-2 rounded-full bg-emerald-400';
  13733. }
  13734. if (btnTcp) {
  13735. btnTcp.className = inactiveCls;
  13736. const dot = btnTcp.querySelector('span');
  13737. if (dot) dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  13738. }
  13739. if (badge) {
  13740. badge.innerText = 'UDP Mode (RFC 3550 Jitter + Loss %)';
  13741. badge.className = 'text-[10px] font-mono text-emerald-400 bg-emerald-500/10 px-2 py-0.5 rounded border border-emerald-500/20';
  13742. }
  13743. if (pktField) pktField.classList.remove('opacity-40');
  13744. } else {
  13745. if (btnUdp) {
  13746. btnUdp.className = inactiveCls;
  13747. const dot = btnUdp.querySelector('span');
  13748. if (dot) dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  13749. }
  13750. if (btnTcp) {
  13751. btnTcp.className = activeTcpCls;
  13752. const dot = btnTcp.querySelector('span');
  13753. if (dot) dot.className = 'w-2 h-2 rounded-full bg-blue-400';
  13754. }
  13755. if (badge) {
  13756. badge.innerText = 'TCP Mode (Sliding Window Throughput)';
  13757. badge.className = 'text-[10px] font-mono text-blue-400 bg-blue-500/10 px-2 py-0.5 rounded border border-blue-500/20';
  13758. }
  13759. if (pktField) pktField.classList.add('opacity-40');
  13760. }
  13761. }
  13762. function setBwTestDirection(dir) {
  13763. const hiddenInp = document.getElementById('bwtest-input-direction');
  13764. if (hiddenInp) hiddenInp.value = dir;
  13765. const btnBoth = document.getElementById('bwtest-dir-both');
  13766. const btnTx = document.getElementById('bwtest-dir-tx');
  13767. const btnRx = document.getElementById('bwtest-dir-rx');
  13768. 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';
  13769. 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';
  13770. if (btnBoth) btnBoth.className = dir === 'both' ? activeCls : inactiveCls;
  13771. if (btnTx) btnTx.className = dir === 'tx' ? activeCls : inactiveCls;
  13772. if (btnRx) btnRx.className = dir === 'rx' ? activeCls : inactiveCls;
  13773. }
  13774. function setBwTestLimit(bps) {
  13775. const sel = document.getElementById('bwtest-input-limit');
  13776. if (sel) sel.value = String(bps);
  13777. }
  13778. async function checkActiveBwTest() {
  13779. try {
  13780. const res = await fetch(`${API_BASE}/tools/bwtest/status`);
  13781. if (!res.ok) return;
  13782. const st = await res.json();
  13783. if (st.running) {
  13784. setBwTestRunningUI(true);
  13785. processBwTestStatus(st);
  13786. startBwTestTelemetry();
  13787. }
  13788. } catch (err) {
  13789. console.error('Failed to check active BwTest:', err);
  13790. }
  13791. }
  13792. async function startBwTest(e) {
  13793. if (e && e.preventDefault) e.preventDefault();
  13794. const target = document.getElementById('bwtest-input-target').value.trim() || '127.0.0.1';
  13795. const port = parseInt(document.getElementById('bwtest-input-port').value, 10) || 2000;
  13796. const direction = document.getElementById('bwtest-input-direction').value || 'both';
  13797. const protocol = document.getElementById('bwtest-input-protocol').value || 'udp';
  13798. const bandwidth_limit = parseInt(document.getElementById('bwtest-input-limit').value, 10) || 0;
  13799. const packet_size = parseInt(document.getElementById('bwtest-input-pktsize').value, 10) || 1472;
  13800. const streams = parseInt(document.getElementById('bwtest-input-streams').value, 10) || 1;
  13801. const duration = parseInt(document.getElementById('bwtest-input-duration').value, 10);
  13802. bwtestState.targetDuration = duration;
  13803. bwtestState.chartPoints = [];
  13804. bwtestState.peakTx = 0;
  13805. bwtestState.peakRx = 0;
  13806. bwtestState.lastSampleElapsed = -1;
  13807. bwtestState.sessionID = null;
  13808. // Clear UI elements
  13809. document.getElementById('bwtest-stat-tx-mbps').innerText = '0.00';
  13810. document.getElementById('bwtest-stat-tx-peak').innerText = '0.00 Mbps';
  13811. document.getElementById('bwtest-stat-tx-pkts').innerText = '0';
  13812. document.getElementById('bwtest-stat-rx-mbps').innerText = '0.00';
  13813. document.getElementById('bwtest-stat-rx-peak').innerText = '0.00 Mbps';
  13814. document.getElementById('bwtest-stat-rx-pkts').innerText = '0';
  13815. document.getElementById('bwtest-stat-loss').innerText = '0.0%';
  13816. document.getElementById('bwtest-stat-jitter').innerText = '0.00 ms';
  13817. document.getElementById('bwtest-stat-time').innerText = '0.0s';
  13818. document.getElementById('bwtest-stat-data').innerText = '0.0 MB';
  13819. document.getElementById('bwtest-stat-target-dur').innerText = duration > 0 ? `/ ${duration}s` : '/ ∞';
  13820. const tbody = document.getElementById('bwtest-samples-tbody');
  13821. if (tbody) tbody.innerHTML = '';
  13822. document.getElementById('bwtest-sample-count').innerText = '0 samples';
  13823. setBwTestRunningUI(true);
  13824. try {
  13825. const res = await fetch(`${API_BASE}/tools/bwtest/start`, {
  13826. method: 'POST',
  13827. headers: { 'Content-Type': 'application/json' },
  13828. body: JSON.stringify({
  13829. target,
  13830. port,
  13831. direction,
  13832. protocol,
  13833. bandwidth_limit,
  13834. packet_size,
  13835. streams,
  13836. duration
  13837. })
  13838. });
  13839. if (!res.ok) {
  13840. const err = await res.json();
  13841. throw new Error(err.error || 'Failed to start bandwidth test');
  13842. }
  13843. showToast('Benchmark Started', `Target: ${target}:${port} (${direction.toUpperCase()}, ${protocol.toUpperCase()})`, 'info');
  13844. startBwTestTelemetry();
  13845. } catch (err) {
  13846. setBwTestRunningUI(false);
  13847. showToast('Start Failed', err.message, 'error');
  13848. }
  13849. }
  13850. function setBwTestRunningUI(running) {
  13851. bwtestState.running = running;
  13852. const startBtn = document.getElementById('bwtest-btn-start');
  13853. const stopBtn = document.getElementById('bwtest-btn-stop');
  13854. const badge = document.getElementById('bwtest-run-status-badge');
  13855. const ph = document.getElementById('bwtest-chart-placeholder');
  13856. if (running) {
  13857. if (startBtn) {
  13858. startBtn.disabled = true;
  13859. startBtn.classList.add('opacity-50', 'cursor-not-allowed');
  13860. }
  13861. if (stopBtn) {
  13862. stopBtn.disabled = false;
  13863. stopBtn.classList.remove('opacity-40');
  13864. }
  13865. if (badge) {
  13866. badge.innerText = 'TESTING...';
  13867. 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';
  13868. }
  13869. if (ph) ph.style.display = 'none';
  13870. } else {
  13871. if (startBtn) {
  13872. startBtn.disabled = false;
  13873. startBtn.classList.remove('opacity-50', 'cursor-not-allowed');
  13874. }
  13875. if (stopBtn) {
  13876. stopBtn.disabled = true;
  13877. stopBtn.classList.add('opacity-40');
  13878. }
  13879. if (badge) {
  13880. badge.innerText = 'IDLE';
  13881. badge.className = 'px-2 py-0.5 rounded text-[10px] font-mono bg-slate-800 text-slate-400 border border-slate-700 font-semibold';
  13882. }
  13883. }
  13884. }
  13885. async function stopBwTest() {
  13886. try {
  13887. const res = await fetch(`${API_BASE}/tools/bwtest/stop`, { method: 'POST' });
  13888. if (!res.ok) throw new Error(await responseError(res));
  13889. showToast('Stop Requested', 'Waiting for the bandwidth test to finish', 'info');
  13890. if (!bwtestState.pollTimer) startBwTestTelemetry();
  13891. } catch (err) {
  13892. showToast('Stop Failed', err.message, 'error');
  13893. }
  13894. }
  13895. async function responseError(res) {
  13896. const text = await res.text();
  13897. try { const data = JSON.parse(text); return data.message || (typeof data.error === 'string' ? data.error : null) || `HTTP ${res.status}`; }
  13898. catch { return text || `HTTP ${res.status}`; }
  13899. }
  13900. function processBwTestStatus(st) {
  13901. if (st.session_id && bwtestState.sessionID !== st.session_id) {
  13902. bwtestState.sessionID = st.session_id;
  13903. bwtestState.lastSampleElapsed = -1;
  13904. }
  13905. for (const sample of st.recent_samples || []) {
  13906. if (sample.elapsed_sec > (bwtestState.lastSampleElapsed ?? -1)) {
  13907. handleBwTestSample(sample);
  13908. bwtestState.lastSampleElapsed = sample.elapsed_sec;
  13909. }
  13910. }
  13911. if (!st.running) {
  13912. if (bwtestState.pollTimer) clearInterval(bwtestState.pollTimer);
  13913. bwtestState.pollTimer = null;
  13914. setBwTestRunningUI(false);
  13915. handleBwTestFinish(st.summary, st.error);
  13916. }
  13917. }
  13918. function startBwTestTelemetry() {
  13919. if (!state.currentUser) return;
  13920. if (bwtestState.pollTimer) clearInterval(bwtestState.pollTimer);
  13921. let busy = false;
  13922. const poll = async () => {
  13923. if (busy || !state.currentUser || document.hidden) return;
  13924. busy = true;
  13925. try {
  13926. const res = await fetch(`${API_BASE}/tools/bwtest/status`);
  13927. if (!res.ok) throw new Error(await responseError(res));
  13928. processBwTestStatus(await res.json());
  13929. } catch (err) {
  13930. console.error('BwTest polling error:', err);
  13931. } finally { busy = false; }
  13932. };
  13933. bwtestState.pollTimer = setInterval(poll, 400);
  13934. poll();
  13935. }
  13936. function handleBwTestSample(s) {
  13937. if (!s) return;
  13938. const payloadHint = document.getElementById('bwtest-effective-payload');
  13939. if (payloadHint && s.packet_size) payloadHint.innerText = `Effective datagram: ${s.packet_size} bytes`;
  13940. const txMbps = s.tx_mbps || 0;
  13941. const rxMbps = s.rx_mbps || 0;
  13942. if (txMbps > bwtestState.peakTx) bwtestState.peakTx = txMbps;
  13943. if (rxMbps > bwtestState.peakRx) bwtestState.peakRx = rxMbps;
  13944. // KPI updates
  13945. const elTx = document.getElementById('bwtest-stat-tx-mbps');
  13946. if (elTx) {
  13947. elTx.innerText = txMbps.toFixed(2);
  13948. elTx.title = `Confirmed by peer; locally offered: ${(s.offered_tx_mbps || 0).toFixed(2)} Mbps`;
  13949. }
  13950. const elTxPeak = document.getElementById('bwtest-stat-tx-peak');
  13951. if (elTxPeak) elTxPeak.innerText = `${bwtestState.peakTx.toFixed(2)} Mbps`;
  13952. const elTxPkts = document.getElementById('bwtest-stat-tx-pkts');
  13953. if (elTxPkts) elTxPkts.innerText = s.tx_packets || 0;
  13954. const elRx = document.getElementById('bwtest-stat-rx-mbps');
  13955. if (elRx) elRx.innerText = rxMbps.toFixed(2);
  13956. const elRxPeak = document.getElementById('bwtest-stat-rx-peak');
  13957. if (elRxPeak) elRxPeak.innerText = `${bwtestState.peakRx.toFixed(2)} Mbps`;
  13958. const elRxPkts = document.getElementById('bwtest-stat-rx-pkts');
  13959. if (elRxPkts) elRxPkts.innerText = s.rx_packets || 0;
  13960. const elLoss = document.getElementById('bwtest-stat-loss');
  13961. if (elLoss) {
  13962. elLoss.innerText = `${(s.loss_pct || 0).toFixed(1)}%`;
  13963. elLoss.className = (s.loss_pct > 1.0) ? 'text-2xl font-bold text-rose-400' : 'text-2xl font-bold text-emerald-400';
  13964. }
  13965. const elLostPkts = document.getElementById('bwtest-stat-lost-pkts');
  13966. if (elLostPkts) elLostPkts.innerText = s.lost_packets || 0;
  13967. const elJitter = document.getElementById('bwtest-stat-jitter');
  13968. if (elJitter) elJitter.innerText = `${(s.jitter_ms || 0).toFixed(2)} ms`;
  13969. const elTime = document.getElementById('bwtest-stat-time');
  13970. if (elTime) elTime.innerText = `${(s.elapsed_sec || 0).toFixed(1)}s`;
  13971. const elData = document.getElementById('bwtest-stat-data');
  13972. if (elData) elData.innerText = formatBytes((s.tx_bytes || 0) + (s.rx_bytes || 0));
  13973. const elGraphRate = document.getElementById('bwtest-graph-rate');
  13974. if (elGraphRate) elGraphRate.innerText = `TX: ${txMbps.toFixed(1)} Mbps • RX: ${rxMbps.toFixed(1)} Mbps`;
  13975. // Append point to chart buffer
  13976. bwtestState.chartPoints.push({
  13977. elapsed: s.elapsed_sec || 0,
  13978. tx: txMbps,
  13979. rx: rxMbps
  13980. });
  13981. if (bwtestState.chartPoints.length > bwtestState.maxChartPoints) {
  13982. bwtestState.chartPoints.shift();
  13983. }
  13984. drawBwTestChart();
  13985. // Add row to breakdown table
  13986. const tbody = document.getElementById('bwtest-samples-tbody');
  13987. if (tbody) {
  13988. const tr = document.createElement('tr');
  13989. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  13990. tr.innerHTML = `
  13991. <td class="py-1.5 px-3 font-semibold text-white">${(s.elapsed_sec || 0).toFixed(1)}s</td>
  13992. <td class="py-1.5 px-3 font-bold text-cyan-400">${txMbps.toFixed(2)} Mbps</td>
  13993. <td class="py-1.5 px-3 font-bold text-purple-400">${rxMbps.toFixed(2)} Mbps</td>
  13994. <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>
  13995. <td class="py-1.5 px-3 text-slate-300">${(s.jitter_ms || 0).toFixed(2)} ms</td>
  13996. <td class="py-1.5 px-3 text-slate-400">${formatBytes((s.tx_bytes || 0) + (s.rx_bytes || 0))}</td>
  13997. `;
  13998. tbody.insertBefore(tr, tbody.firstChild);
  13999. const countEl = document.getElementById('bwtest-sample-count');
  14000. if (countEl) countEl.innerText = `${tbody.children.length} samples`;
  14001. }
  14002. }
  14003. function handleBwTestFinish(summary, error) {
  14004. const badge = document.getElementById('bwtest-run-status-badge');
  14005. if (error) {
  14006. showToast('Benchmark Error', error, 'error');
  14007. if (badge) {
  14008. badge.innerText = 'ERROR';
  14009. 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';
  14010. }
  14011. } else if (summary) {
  14012. const avgTx = summary.avg_tx_mbps.toFixed(1);
  14013. const avgRx = summary.avg_rx_mbps.toFixed(1);
  14014. showToast('Benchmark Complete', `Average TX: ${avgTx} Mbps | RX: ${avgRx} Mbps (Loss: ${summary.avg_loss_pct.toFixed(1)}%)`, 'success');
  14015. if (badge) {
  14016. badge.innerText = 'COMPLETED';
  14017. 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';
  14018. }
  14019. }
  14020. loadBwTestHistory();
  14021. fetchBwTestServerStatus();
  14022. }
  14023. function resizeBwTestCanvas() {
  14024. const canvas = document.getElementById('bwtest-chart');
  14025. if (!canvas || !canvas.parentElement) return;
  14026. const rect = canvas.parentElement.getBoundingClientRect();
  14027. const dpr = window.devicePixelRatio || 1;
  14028. canvas.width = rect.width * dpr;
  14029. canvas.height = rect.height * dpr;
  14030. const ctx = canvas.getContext('2d');
  14031. ctx.scale(dpr, dpr);
  14032. drawBwTestChart();
  14033. }
  14034. window.addEventListener('resize', () => {
  14035. if (state.activeTab === 'bwtest') resizeBwTestCanvas();
  14036. });
  14037. function drawBwTestChart() {
  14038. const canvas = document.getElementById('bwtest-chart');
  14039. if (!canvas) return;
  14040. const ctx = canvas.getContext('2d');
  14041. const dpr = window.devicePixelRatio || 1;
  14042. const width = canvas.width / dpr;
  14043. const height = canvas.height / dpr;
  14044. ctx.clearRect(0, 0, width, height);
  14045. const points = bwtestState.chartPoints;
  14046. if (!points || points.length === 0) return;
  14047. // Determine scale ceiling
  14048. let maxRate = 10;
  14049. for (const p of points) {
  14050. if (p.tx > maxRate) maxRate = p.tx;
  14051. if (p.rx > maxRate) maxRate = p.rx;
  14052. }
  14053. maxRate = Math.ceil(maxRate * 1.25); // 25% headroom
  14054. const paddingLeft = 55;
  14055. const paddingBottom = 24;
  14056. const paddingTop = 12;
  14057. const paddingRight = 16;
  14058. const chartW = width - paddingLeft - paddingRight;
  14059. const chartH = height - paddingTop - paddingBottom;
  14060. // Grid Lines and Y-Axis labels
  14061. ctx.strokeStyle = 'rgba(51, 65, 85, 0.4)';
  14062. ctx.lineWidth = 1;
  14063. ctx.fillStyle = '#94a3b8';
  14064. ctx.font = '10px monospace';
  14065. ctx.textAlign = 'right';
  14066. const gridSteps = 4;
  14067. for (let i = 0; i <= gridSteps; i++) {
  14068. const val = (maxRate / gridSteps) * i;
  14069. const y = paddingTop + chartH - (i / gridSteps) * chartH;
  14070. ctx.beginPath();
  14071. ctx.moveTo(paddingLeft, y);
  14072. ctx.lineTo(width - paddingRight, y);
  14073. ctx.stroke();
  14074. ctx.fillText(`${Math.round(val)}M`, paddingLeft - 8, y + 3);
  14075. }
  14076. // Draw TX Line (Cyan #22d3ee)
  14077. drawSeries(ctx, points, p => p.tx, maxRate, paddingLeft, paddingTop, chartW, chartH, '#22d3ee', 'rgba(34, 211, 238, 0.15)');
  14078. // Draw RX Line (Purple #a855f7)
  14079. drawSeries(ctx, points, p => p.rx, maxRate, paddingLeft, paddingTop, chartW, chartH, '#a855f7', 'rgba(168, 85, 247, 0.15)');
  14080. }
  14081. function drawSeries(ctx, points, valFn, maxVal, left, top, w, h, strokeColor, fillColor) {
  14082. if (points.length < 2) return;
  14083. const stepX = w / Math.max(points.length - 1, 1);
  14084. // Gradient area fill
  14085. const grad = ctx.createLinearGradient(0, top, 0, top + h);
  14086. grad.addColorStop(0, fillColor);
  14087. grad.addColorStop(1, 'rgba(0, 0, 0, 0)');
  14088. ctx.beginPath();
  14089. points.forEach((p, idx) => {
  14090. const x = left + idx * stepX;
  14091. const val = valFn(p);
  14092. const y = top + h - (val / maxVal) * h;
  14093. if (idx === 0) {
  14094. ctx.moveTo(x, y);
  14095. } else {
  14096. ctx.lineTo(x, y);
  14097. }
  14098. });
  14099. // Complete path for fill
  14100. ctx.lineTo(left + (points.length - 1) * stepX, top + h);
  14101. ctx.lineTo(left, top + h);
  14102. ctx.closePath();
  14103. ctx.fillStyle = grad;
  14104. ctx.fill();
  14105. // Draw line stroke
  14106. ctx.beginPath();
  14107. ctx.lineWidth = 2.5;
  14108. ctx.strokeStyle = strokeColor;
  14109. points.forEach((p, idx) => {
  14110. const x = left + idx * stepX;
  14111. const val = valFn(p);
  14112. const y = top + h - (val / maxVal) * h;
  14113. if (idx === 0) {
  14114. ctx.moveTo(x, y);
  14115. } else {
  14116. ctx.lineTo(x, y);
  14117. }
  14118. });
  14119. ctx.stroke();
  14120. // Draw end point halo
  14121. const lastP = points[points.length - 1];
  14122. const lastX = left + (points.length - 1) * stepX;
  14123. const lastY = top + h - (valFn(lastP) / maxVal) * h;
  14124. ctx.fillStyle = strokeColor;
  14125. ctx.beginPath();
  14126. ctx.arc(lastX, lastY, 4, 0, 2 * Math.PI);
  14127. ctx.fill();
  14128. }
  14129. async function loadBwTestHistory() {
  14130. try {
  14131. const res = await fetch(`${API_BASE}/tools/bwtest/history`);
  14132. if (!res.ok) return;
  14133. const list = await res.json();
  14134. renderBwTestHistory(Array.isArray(list) ? list : []);
  14135. } catch (err) {
  14136. console.error('Failed to load BwTest history:', err);
  14137. }
  14138. }
  14139. function renderBwTestHistory(list) {
  14140. const tbody = document.getElementById('bwtest-history-tbody');
  14141. if (!tbody) return;
  14142. if (list.length === 0) {
  14143. 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>`;
  14144. return;
  14145. }
  14146. tbody.innerHTML = '';
  14147. list.forEach(item => {
  14148. const s = item.summary || {};
  14149. const tr = document.createElement('tr');
  14150. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  14151. const dirBadge = item.direction === 'both'
  14152. ? `<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>`
  14153. : item.direction === 'tx'
  14154. ? `<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>`
  14155. : `<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>`;
  14156. const protoBadge = item.protocol === 'tcp'
  14157. ? `<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>`
  14158. : `<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>`;
  14159. const dateStr = item.timestamp ? new Date(item.timestamp).toLocaleString() : '-';
  14160. tr.innerHTML = `
  14161. <td class="py-2.5 px-4 font-bold text-white font-mono text-[11px]">${escapeHtml(item.id || '-')}</td>
  14162. <td class="py-2.5 px-4 text-emerald-400 font-mono font-medium">${escapeHtml(item.target || '-')}</td>
  14163. <td class="py-2.5 px-4">${protoBadge}</td>
  14164. <td class="py-2.5 px-4">${dirBadge}</td>
  14165. <td class="py-2.5 px-4 text-slate-300">${(s.duration_sec || 0).toFixed(1)}s</td>
  14166. <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>
  14167. <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>
  14168. <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>
  14169. <td class="py-2.5 px-4 text-slate-300 font-mono">${(s.avg_jitter_ms || 0).toFixed(2)} ms</td>
  14170. <td class="py-2.5 px-4 text-slate-400 text-[11px] font-sans">${escapeHtml(dateStr)}</td>
  14171. `;
  14172. tbody.appendChild(tr);
  14173. });
  14174. }
  14175. // ======================== SETTINGS & ROUTER DNS ========================
  14176. state.settingsSubTab = 'dns';
  14177. state.dnsSettings = null;
  14178. state.dnsStaticRecords = [];
  14179. state.dnsStatus = null;
  14180. function switchSettingsSubTab(sub) {
  14181. state.settingsSubTab = sub;
  14182. const btnDns = document.getElementById('btn-settings-subtab-dns');
  14183. const btnSys = document.getElementById('btn-settings-subtab-system');
  14184. const tabDns = document.getElementById('settings-subtab-dns');
  14185. const tabSys = document.getElementById('settings-subtab-system');
  14186. if (sub === 'dns') {
  14187. if (btnDns) {
  14188. 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';
  14189. }
  14190. if (btnSys) {
  14191. 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';
  14192. }
  14193. tabDns?.classList.remove('hidden');
  14194. tabSys?.classList.add('hidden');
  14195. loadDNSSettings();
  14196. } else {
  14197. if (btnSys) {
  14198. 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';
  14199. }
  14200. if (btnDns) {
  14201. 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';
  14202. }
  14203. tabSys?.classList.remove('hidden');
  14204. tabDns?.classList.add('hidden');
  14205. loadSystemSettings();
  14206. }
  14207. }
  14208. async function loadSettingsData(showLoading = false) {
  14209. if (state.settingsSubTab === 'system') {
  14210. await loadSystemSettings();
  14211. } else {
  14212. await loadDNSSettings();
  14213. }
  14214. }
  14215. async function loadDNSSettings() {
  14216. try {
  14217. const [settingsRes, staticRes, statusRes] = await Promise.all([
  14218. fetch(`${API_BASE}/dns/settings`),
  14219. fetch(`${API_BASE}/dns/static`),
  14220. fetch(`${API_BASE}/dns/status`)
  14221. ]);
  14222. if (settingsRes.ok) {
  14223. state.dnsSettings = await settingsRes.json();
  14224. populateDNSSettingsForm(state.dnsSettings);
  14225. }
  14226. if (staticRes.ok) {
  14227. state.dnsStaticRecords = await staticRes.json();
  14228. renderStaticDNSList();
  14229. }
  14230. if (statusRes.ok) {
  14231. state.dnsStatus = await statusRes.json();
  14232. updateDNSStatusView(state.dnsStatus);
  14233. }
  14234. } catch (err) {
  14235. console.error('Failed to load DNS settings:', err);
  14236. }
  14237. }
  14238. function populateDNSSettingsForm(s) {
  14239. if (!s) return;
  14240. const dnsForm = document.getElementById('form-dns-settings');
  14241. const isEditing = dnsForm && (dnsForm.contains(document.activeElement) || dnsForm.dataset.dirty === 'true');
  14242. const dynamicEl = document.getElementById('dns-dynamic-servers-list');
  14243. if (dynamicEl) {
  14244. if (Array.isArray(s.dynamic_servers) && s.dynamic_servers.length > 0) {
  14245. 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(' ');
  14246. } else {
  14247. dynamicEl.innerText = 'None';
  14248. }
  14249. }
  14250. // If user is actively typing or editing in the form, do not overwrite their inputs!
  14251. if (isEditing) return;
  14252. const serversInput = document.getElementById('dns-servers-input');
  14253. if (serversInput) serversInput.value = (s.servers || []).join(', ');
  14254. const cacheSizeInput = document.getElementById('dns-cache-size-input');
  14255. if (cacheSizeInput) cacheSizeInput.value = s.cache_size || 2048;
  14256. const domainInput = document.getElementById('dns-domain-input');
  14257. if (domainInput) domainInput.value = s.domain || '';
  14258. const allowRemoteInput = document.getElementById('dns-allow-remote-input');
  14259. if (allowRemoteInput) allowRemoteInput.checked = s.allow_remote_requests !== false;
  14260. }
  14261. function updateDNSStatusView(st) {
  14262. if (!st) return;
  14263. const preview = document.getElementById('dns-resolv-preview');
  14264. if (preview) preview.innerText = st.resolv_conf_content || '(empty)';
  14265. const pillText = document.getElementById('dns-live-status-text');
  14266. const pill = document.getElementById('dns-live-status-pill');
  14267. if (pill && pillText) {
  14268. if (st.service_running) {
  14269. 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';
  14270. pillText.innerText = 'DNS Service Active';
  14271. } else {
  14272. 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';
  14273. pillText.innerText = 'DNS Service Inactive';
  14274. }
  14275. }
  14276. }
  14277. function appendDNSPreset(preset) {
  14278. const input = document.getElementById('dns-servers-input');
  14279. if (!input) return;
  14280. const dnsForm = document.getElementById('form-dns-settings');
  14281. if (dnsForm) dnsForm.dataset.dirty = 'true';
  14282. const current = input.value.trim();
  14283. if (!current) {
  14284. input.value = preset;
  14285. } else {
  14286. const existing = current.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  14287. const toAdd = preset.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  14288. toAdd.forEach(ip => {
  14289. if (!existing.includes(ip)) existing.push(ip);
  14290. });
  14291. input.value = existing.join(', ');
  14292. }
  14293. }
  14294. async function saveDNSSettings(e) {
  14295. e.preventDefault();
  14296. const rawServers = document.getElementById('dns-servers-input')?.value || '';
  14297. const servers = rawServers.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  14298. if (servers.length === 0) {
  14299. showToast('Validation Error', 'Please enter at least one upstream DNS server IP', 'error');
  14300. return;
  14301. }
  14302. const cacheSize = parseInt(document.getElementById('dns-cache-size-input')?.value || '2048', 10);
  14303. const domain = (document.getElementById('dns-domain-input')?.value || '').trim();
  14304. const allowRemote = document.getElementById('dns-allow-remote-input')?.checked ?? true;
  14305. try {
  14306. const res = await fetch(`${API_BASE}/dns/settings`, {
  14307. method: 'POST',
  14308. headers: { 'Content-Type': 'application/json' },
  14309. body: JSON.stringify({
  14310. servers: servers,
  14311. cache_size: cacheSize,
  14312. domain: domain,
  14313. allow_remote_requests: allowRemote
  14314. })
  14315. });
  14316. const data = await res.json();
  14317. if (res.ok) {
  14318. const dnsForm = document.getElementById('form-dns-settings');
  14319. if (dnsForm) dnsForm.dataset.dirty = 'false';
  14320. showToast('DNS Applied', 'Router DNS forwarders and resolver settings updated successfully', 'success');
  14321. loadDNSSettings();
  14322. } else {
  14323. showToast('Error', data.error || data.message || 'Failed to save DNS settings', 'error');
  14324. }
  14325. } catch (err) {
  14326. showToast('Error', err.message, 'error');
  14327. }
  14328. }
  14329. async function flushDNSCache() {
  14330. try {
  14331. const res = await fetch(`${API_BASE}/dns/flush`, { method: 'POST' });
  14332. if (res.ok) {
  14333. showToast('Cache Flushed', 'Router DNS cache cleared and static hosts reloaded', 'success');
  14334. loadDNSSettings();
  14335. } else {
  14336. const err = await res.json();
  14337. showToast('Error', err.error || 'Failed to flush cache', 'error');
  14338. }
  14339. } catch (err) {
  14340. showToast('Error', err.message, 'error');
  14341. }
  14342. }
  14343. function renderStaticDNSList() {
  14344. const tbody = document.getElementById('dns-static-tbody');
  14345. const empty = document.getElementById('dns-static-empty');
  14346. const badge = document.getElementById('dns-static-count-badge');
  14347. if (!tbody) return;
  14348. tbody.innerHTML = '';
  14349. const records = state.dnsStaticRecords || [];
  14350. if (badge) badge.innerText = `${records.length} Records`;
  14351. if (records.length === 0) {
  14352. empty?.classList.remove('hidden');
  14353. return;
  14354. }
  14355. empty?.classList.add('hidden');
  14356. records.forEach(rec => {
  14357. const tr = document.createElement('tr');
  14358. tr.className = `hover:bg-slate-800/40 transition text-xs ${rec.disabled ? 'opacity-50' : ''}`;
  14359. tr.innerHTML = `
  14360. <td class="py-2.5 px-4 font-bold text-white">${escapeHtml(rec.name)}</td>
  14361. <td class="py-2.5 px-4">
  14362. <span class="px-2 py-0.5 rounded text-[10px] font-bold ${
  14363. rec.type === 'CNAME' ? 'bg-purple-950 text-purple-300 border border-purple-800' :
  14364. (rec.type === 'AAAA' ? 'bg-blue-950 text-blue-300 border border-blue-800' : 'bg-cyan-950 text-cyan-300 border border-cyan-800')
  14365. }">
  14366. ${rec.type || 'A'}
  14367. </span>
  14368. </td>
  14369. <td class="py-2.5 px-4 text-emerald-400 font-mono">${escapeHtml(rec.address)}</td>
  14370. <td class="py-2.5 px-4 text-slate-400 font-mono">${rec.ttl || 3600}s</td>
  14371. <td class="py-2.5 px-4 text-slate-400 italic truncate max-w-[140px]">${escapeHtml(rec.comment || '-')}</td>
  14372. <td class="py-2.5 px-4">
  14373. <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'}">
  14374. ${rec.disabled ? 'Disabled' : 'Active'}
  14375. </span>
  14376. </td>
  14377. <td class="py-2.5 px-4 text-right space-x-2 font-sans whitespace-nowrap">
  14378. <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>
  14379. <button onclick="openStaticDNSModal('${rec.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold">Edit</button>
  14380. <button onclick="deleteStaticDNS('${rec.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  14381. </td>
  14382. `;
  14383. tbody.appendChild(tr);
  14384. });
  14385. }
  14386. function openStaticDNSModal(id = null) {
  14387. const modal = document.getElementById('modal-static-dns');
  14388. const title = document.getElementById('modal-static-dns-title');
  14389. const form = document.getElementById('form-static-dns');
  14390. if (!modal || !form) return;
  14391. form.reset();
  14392. document.getElementById('modal-static-dns-id').value = '';
  14393. if (id) {
  14394. const rec = (state.dnsStaticRecords || []).find(r => r.id === id);
  14395. if (rec) {
  14396. if (title) title.innerText = 'Edit Static DNS Record';
  14397. document.getElementById('modal-static-dns-id').value = rec.id;
  14398. document.getElementById('modal-static-dns-name').value = rec.name;
  14399. document.getElementById('modal-static-dns-type').value = rec.type || 'A';
  14400. document.getElementById('modal-static-dns-addr').value = rec.address;
  14401. document.getElementById('modal-static-dns-ttl').value = rec.ttl || 3600;
  14402. document.getElementById('modal-static-dns-comment').value = rec.comment || '';
  14403. document.getElementById('modal-static-dns-disabled').checked = !!rec.disabled;
  14404. }
  14405. } else {
  14406. if (title) title.innerText = 'Add Static DNS Record';
  14407. }
  14408. modal.classList.remove('hidden');
  14409. }
  14410. function closeStaticDNSModal() {
  14411. document.getElementById('modal-static-dns')?.classList.add('hidden');
  14412. }
  14413. async function submitSaveStaticDNS(e) {
  14414. e.preventDefault();
  14415. const id = document.getElementById('modal-static-dns-id')?.value || '';
  14416. const name = (document.getElementById('modal-static-dns-name')?.value || '').trim();
  14417. const type = document.getElementById('modal-static-dns-type')?.value || 'A';
  14418. const address = (document.getElementById('modal-static-dns-addr')?.value || '').trim();
  14419. const ttl = parseInt(document.getElementById('modal-static-dns-ttl')?.value || '3600', 10);
  14420. const comment = (document.getElementById('modal-static-dns-comment')?.value || '').trim();
  14421. const disabled = document.getElementById('modal-static-dns-disabled')?.checked ?? false;
  14422. if (!name || !address) {
  14423. showToast('Validation Error', 'Name and Target Address are required', 'error');
  14424. return;
  14425. }
  14426. try {
  14427. const res = await fetch(`${API_BASE}/dns/static`, {
  14428. method: 'POST',
  14429. headers: { 'Content-Type': 'application/json' },
  14430. body: JSON.stringify({ id, name, type, address, ttl, comment, disabled })
  14431. });
  14432. const data = await res.json();
  14433. if (res.ok) {
  14434. showToast('Static DNS Saved', `Saved record ${name} -> ${address}`, 'success');
  14435. closeStaticDNSModal();
  14436. loadDNSSettings();
  14437. } else {
  14438. showToast('Error', data.error || data.message || 'Failed to save record', 'error');
  14439. }
  14440. } catch (err) {
  14441. showToast('Error', err.message, 'error');
  14442. }
  14443. }
  14444. async function deleteStaticDNS(id) {
  14445. if (!confirm('Are you sure you want to delete this static DNS entry?')) return;
  14446. try {
  14447. const res = await fetch(`${API_BASE}/dns/static/${encodeURIComponent(id)}`, { method: 'DELETE' });
  14448. if (res.ok) {
  14449. showToast('Deleted', 'Static DNS record deleted', 'success');
  14450. loadDNSSettings();
  14451. }
  14452. } catch (err) {
  14453. showToast('Error', err.message, 'error');
  14454. }
  14455. }
  14456. async function toggleStaticDNS(id, disabled) {
  14457. try {
  14458. const res = await fetch(`${API_BASE}/dns/static/${encodeURIComponent(id)}/state`, {
  14459. method: 'POST',
  14460. headers: { 'Content-Type': 'application/json' },
  14461. body: JSON.stringify({ disabled })
  14462. });
  14463. if (res.ok) {
  14464. showToast('Updated', `Record ${disabled ? 'disabled' : 'enabled'}`, 'success');
  14465. loadDNSSettings();
  14466. }
  14467. } catch (err) {
  14468. showToast('Error', err.message, 'error');
  14469. }
  14470. }
  14471. async function loadSystemSettings() {
  14472. try {
  14473. const sysForm = document.getElementById('form-system-settings');
  14474. const isEditing = sysForm && (sysForm.contains(document.activeElement) || sysForm.dataset.dirty === 'true');
  14475. const res = await fetch(`${API_BASE}/system/settings`);
  14476. if (res.ok) {
  14477. const data = await res.json();
  14478. if (!isEditing) {
  14479. const hostInput = document.getElementById('system-hostname-input');
  14480. if (hostInput) hostInput.value = data.hostname || '';
  14481. const tzInput = document.getElementById('system-timezone-input');
  14482. if (tzInput && data.timezone) tzInput.value = data.timezone;
  14483. }
  14484. }
  14485. } catch (err) {
  14486. console.error('Failed to load system settings:', err);
  14487. }
  14488. }
  14489. async function saveSystemSettings(e) {
  14490. e.preventDefault();
  14491. const hostname = (document.getElementById('system-hostname-input')?.value || '').trim();
  14492. const timezone = document.getElementById('system-timezone-input')?.value || 'UTC';
  14493. try {
  14494. const res = await fetch(`${API_BASE}/system/settings`, {
  14495. method: 'POST',
  14496. headers: { 'Content-Type': 'application/json' },
  14497. body: JSON.stringify({ hostname, timezone })
  14498. });
  14499. const data = await res.json();
  14500. if (res.ok) {
  14501. const sysForm = document.getElementById('form-system-settings');
  14502. if (sysForm) sysForm.dataset.dirty = 'false';
  14503. showToast('System Updated', 'Hostname and timezone saved successfully', 'success');
  14504. const sideH = document.getElementById('side-hostname');
  14505. if (sideH) sideH.innerText = data.hostname;
  14506. } else {
  14507. showToast('Error', data.error || 'Failed to save system settings', 'error');
  14508. }
  14509. } catch (err) {
  14510. showToast('Error', err.message, 'error');
  14511. }
  14512. }
  14513. // =============================================================================
  14514. // AUTHENTICATION & USER MANAGER
  14515. // =============================================================================
  14516. async function checkAuthStatus() {
  14517. try {
  14518. const res = await originalFetch(`${API_BASE}/auth/me`, {
  14519. headers: {
  14520. 'Authorization': `Bearer ${localStorage.getItem('debtik_token') || ''}`
  14521. }
  14522. });
  14523. if (res.ok) {
  14524. const user = await res.json();
  14525. state.currentUser = user;
  14526. updateUserProfileHeader(user);
  14527. hideLoginScreen();
  14528. state.isPolling = true;
  14529. fetchData();
  14530. initLiveTrafficStream();
  14531. return true;
  14532. } else {
  14533. showLoginScreen(false);
  14534. return false;
  14535. }
  14536. } catch (err) {
  14537. showLoginScreen(false);
  14538. return false;
  14539. }
  14540. }
  14541. function showLoginScreen(isExpired = false) {
  14542. const el = document.getElementById('login-screen');
  14543. if (el) el.classList.remove('hidden');
  14544. const errEl = document.getElementById('login-error');
  14545. const errTxt = document.getElementById('login-error-text');
  14546. if (isExpired && errEl && errTxt) {
  14547. errTxt.innerText = 'Session expired. Please sign in again.';
  14548. errEl.classList.remove('hidden');
  14549. } else if (errEl) {
  14550. errEl.classList.add('hidden');
  14551. }
  14552. const pwInput = document.getElementById('login-password');
  14553. if (pwInput) pwInput.value = '';
  14554. const userInput = document.getElementById('login-username');
  14555. if (userInput && !userInput.value) userInput.focus();
  14556. else if (pwInput) pwInput.focus();
  14557. }
  14558. function hideLoginScreen() {
  14559. const el = document.getElementById('login-screen');
  14560. if (el) el.classList.add('hidden');
  14561. const errEl = document.getElementById('login-error');
  14562. if (errEl) errEl.classList.add('hidden');
  14563. }
  14564. async function handleLoginSubmit(event) {
  14565. event.preventDefault();
  14566. const username = (document.getElementById('login-username')?.value || '').trim();
  14567. const password = document.getElementById('login-password')?.value || '';
  14568. const errEl = document.getElementById('login-error');
  14569. const errTxt = document.getElementById('login-error-text');
  14570. const btn = document.getElementById('login-submit-btn');
  14571. const btnText = document.getElementById('login-btn-text');
  14572. const spinner = document.getElementById('login-btn-spinner');
  14573. if (!username || !password) {
  14574. if (errTxt) errTxt.innerText = 'Username and password are required.';
  14575. if (errEl) errEl.classList.remove('hidden');
  14576. return;
  14577. }
  14578. if (errEl) errEl.classList.add('hidden');
  14579. if (btn) btn.disabled = true;
  14580. if (btnText) btnText.innerText = 'Authenticating...';
  14581. if (spinner) spinner.classList.remove('hidden');
  14582. try {
  14583. const res = await originalFetch(`${API_BASE}/auth/login`, {
  14584. method: 'POST',
  14585. headers: { 'Content-Type': 'application/json' },
  14586. body: JSON.stringify({ username, password })
  14587. });
  14588. const data = await res.json();
  14589. if (res.ok && data.success) {
  14590. localStorage.setItem('debtik_token', data.token);
  14591. state.currentUser = data.user;
  14592. updateUserProfileHeader(data.user);
  14593. hideLoginScreen();
  14594. state.isPolling = true;
  14595. showToast('Authenticated', `Signed in as ${data.user.username}`, 'success');
  14596. const hash = window.location.hash.replace('#', '') || 'dashboard';
  14597. navigate(hash);
  14598. fetchData();
  14599. initLiveTrafficStream();
  14600. // Ensure background telemetry polling is active
  14601. if (!window._telemetryInterval) {
  14602. window._telemetryInterval = setInterval(() => {
  14603. if (state.isPolling && state.currentUser && !document.hidden) {
  14604. fetchData(false);
  14605. }
  14606. }, 5000);
  14607. }
  14608. } else {
  14609. if (errTxt) errTxt.innerText = data.message || 'Invalid username or password';
  14610. if (errEl) errEl.classList.remove('hidden');
  14611. }
  14612. } catch (err) {
  14613. if (errTxt) errTxt.innerText = err.message || 'Failed to connect to router';
  14614. if (errEl) errEl.classList.remove('hidden');
  14615. } finally {
  14616. if (btn) btn.disabled = false;
  14617. if (btnText) btnText.innerText = 'Sign In to Controller';
  14618. if (spinner) spinner.classList.add('hidden');
  14619. }
  14620. }
  14621. async function handleLogoutClick() {
  14622. try {
  14623. await originalFetch(`${API_BASE}/auth/logout`, {
  14624. method: 'POST',
  14625. headers: {
  14626. 'Authorization': `Bearer ${localStorage.getItem('debtik_token') || ''}`
  14627. }
  14628. });
  14629. } catch (e) {}
  14630. stopSessionPolling();
  14631. localStorage.removeItem('debtik_token');
  14632. state.currentUser = null;
  14633. state.isPolling = false;
  14634. if (window._telemetryInterval) {
  14635. clearInterval(window._telemetryInterval);
  14636. window._telemetryInterval = null;
  14637. }
  14638. if (trafficEventSource) {
  14639. trafficEventSource.close();
  14640. trafficEventSource = null;
  14641. }
  14642. if (trafficPollFallback) {
  14643. clearInterval(trafficPollFallback);
  14644. trafficPollFallback = null;
  14645. }
  14646. showLoginScreen(false);
  14647. showToast('Signed Out', 'You have been signed out successfully', 'info');
  14648. }
  14649. function togglePasswordVisibility(id) {
  14650. const input = document.getElementById(id);
  14651. if (!input) return;
  14652. input.type = input.type === 'password' ? 'text' : 'password';
  14653. }
  14654. function toggleUserMenu() {
  14655. const menu = document.getElementById('user-menu-dropdown');
  14656. if (menu) menu.classList.toggle('hidden');
  14657. }
  14658. function closeUserMenu() {
  14659. const menu = document.getElementById('user-menu-dropdown');
  14660. if (menu) menu.classList.add('hidden');
  14661. }
  14662. // Close user menu on outside click
  14663. document.addEventListener('click', (e) => {
  14664. const menu = document.getElementById('user-menu-dropdown');
  14665. if (!menu || menu.classList.contains('hidden')) return;
  14666. if (!e.target.closest('#user-menu-dropdown') && !e.target.closest('button[onclick*="toggleUserMenu"]')) {
  14667. menu.classList.add('hidden');
  14668. }
  14669. });
  14670. function updateUserProfileHeader(user) {
  14671. if (!user) return;
  14672. const navName = document.getElementById('nav-user-name');
  14673. if (navName) navName.innerText = user.username;
  14674. const dropName = document.getElementById('dropdown-user-name');
  14675. if (dropName) dropName.innerText = user.username;
  14676. const navRole = document.getElementById('nav-user-role');
  14677. if (navRole) navRole.innerText = (user.role || 'read').toUpperCase();
  14678. const navAvatar = document.getElementById('nav-user-avatar');
  14679. if (navAvatar) {
  14680. const initials = (user.username || 'AD').slice(0, 2).toUpperCase();
  14681. navAvatar.innerText = initials;
  14682. }
  14683. const statCurUser = document.getElementById('stat-current-user');
  14684. if (statCurUser) statCurUser.innerText = user.username;
  14685. const statCurRole = document.getElementById('stat-current-role');
  14686. if (statCurRole) statCurRole.innerText = (user.role || 'read').toUpperCase();
  14687. // Role permissions UI visibility: hide user management for non-admins
  14688. const isFullAdmin = user.role === 'full';
  14689. const navUsers = document.getElementById('nav-users');
  14690. if (navUsers) {
  14691. if (isFullAdmin) navUsers.classList.remove('hidden');
  14692. else navUsers.classList.add('hidden');
  14693. }
  14694. const dropdownUsers = document.getElementById('dropdown-item-users');
  14695. if (dropdownUsers) {
  14696. if (isFullAdmin) dropdownUsers.classList.remove('hidden');
  14697. else dropdownUsers.classList.add('hidden');
  14698. }
  14699. }
  14700. // ================= User Management CRUD =================
  14701. async function loadUsers(isManual = false) {
  14702. try {
  14703. const res = await fetch(`${API_BASE}/users`);
  14704. if (res.status === 403) {
  14705. const tbody = document.getElementById('users-table-tbody');
  14706. if (tbody) {
  14707. tbody.innerHTML = `
  14708. <tr>
  14709. <td colspan="6" class="p-6 text-center text-amber-400 font-sans">
  14710. <div class="inline-flex items-center gap-2">
  14711. <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>
  14712. <span>Viewing and managing users requires Super Administrator (full) permissions.</span>
  14713. </div>
  14714. </td>
  14715. </tr>
  14716. `;
  14717. }
  14718. return;
  14719. }
  14720. if (res.ok) {
  14721. state.users = await res.json();
  14722. renderUsersTable();
  14723. const totalUsers = document.getElementById('stat-total-users');
  14724. if (totalUsers) totalUsers.innerText = state.users.length;
  14725. const adminCount = state.users.filter(u => u.role === 'full' && !u.disabled).length;
  14726. const adminUsers = document.getElementById('stat-admin-users');
  14727. if (adminUsers) adminUsers.innerText = adminCount;
  14728. const badgeCount = document.getElementById('badge-users-count');
  14729. if (badgeCount) badgeCount.innerText = state.users.length;
  14730. if (isManual) showToast('Refreshed', 'User list updated', 'info');
  14731. }
  14732. } catch (err) {
  14733. console.error('Failed to load users:', err);
  14734. }
  14735. }
  14736. function renderUsersTable() {
  14737. const tbody = document.getElementById('users-table-tbody');
  14738. const emptyState = document.getElementById('users-empty-state');
  14739. if (!tbody) return;
  14740. tbody.innerHTML = '';
  14741. const query = (document.getElementById('users-search-input')?.value || '').trim().toLowerCase();
  14742. const filtered = (state.users || []).filter(u => {
  14743. if (!query) return true;
  14744. return u.username.toLowerCase().includes(query) ||
  14745. (u.role || '').toLowerCase().includes(query) ||
  14746. (u.comment || '').toLowerCase().includes(query);
  14747. });
  14748. if (filtered.length === 0) {
  14749. if (emptyState) emptyState.classList.remove('hidden');
  14750. return;
  14751. }
  14752. if (emptyState) emptyState.classList.add('hidden');
  14753. const currentAuthUser = state.currentUser?.username || '';
  14754. filtered.forEach(u => {
  14755. const isSelf = u.username === currentAuthUser;
  14756. const isFull = u.role === 'full';
  14757. const isWrite = u.role === 'write';
  14758. 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>`;
  14759. if (isFull) {
  14760. 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>`;
  14761. } else if (isWrite) {
  14762. 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>`;
  14763. }
  14764. const statusBadge = u.disabled
  14765. ? `<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>`
  14766. : `<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>`;
  14767. let lastLoginText = 'Never';
  14768. if (u.last_login_at && !u.last_login_at.startsWith('0001-01-01')) {
  14769. const dt = new Date(u.last_login_at);
  14770. lastLoginText = dt.toLocaleString();
  14771. }
  14772. const initials = u.username.slice(0, 2).toUpperCase();
  14773. const tr = document.createElement('tr');
  14774. tr.className = 'hover:bg-slate-800/40 transition group';
  14775. tr.innerHTML = `
  14776. <td class="py-3 px-4">
  14777. <div class="flex items-center gap-3">
  14778. <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">
  14779. ${initials}
  14780. </div>
  14781. <div>
  14782. <div class="font-bold text-white text-xs flex items-center gap-2">
  14783. <span>${escapeHtml(u.username)}</span>
  14784. ${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>' : ''}
  14785. </div>
  14786. <div class="text-[10px] text-slate-500 font-sans">Created: ${u.created_at ? new Date(u.created_at).toLocaleDateString() : '-'}</div>
  14787. </div>
  14788. </div>
  14789. </td>
  14790. <td class="py-3 px-4 font-sans">
  14791. ${roleBadge}
  14792. </td>
  14793. <td class="py-3 px-4 font-sans">
  14794. ${statusBadge}
  14795. </td>
  14796. <td class="py-3 px-4 text-slate-300 font-sans text-xs">
  14797. ${escapeHtml(u.comment) || '<span class="text-slate-600">-</span>'}
  14798. </td>
  14799. <td class="py-3 px-4 text-slate-400 text-xs">
  14800. ${lastLoginText}
  14801. </td>
  14802. <td class="py-3 px-4 text-right space-x-1.5 font-sans">
  14803. <button onclick="openAdminResetPasswordModal('${escapeHtml(u.username)}')"
  14804. class="p-1.5 rounded-lg text-slate-400 hover:text-amber-400 hover:bg-slate-800 transition" title="Reset User Password">
  14805. <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>
  14806. </button>
  14807. <button onclick="openEditUserModal('${escapeHtml(u.username)}')"
  14808. class="p-1.5 rounded-lg text-slate-400 hover:text-cyan-400 hover:bg-slate-800 transition" title="Edit User">
  14809. <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>
  14810. </button>
  14811. ${!isSelf ? `
  14812. <button onclick="deleteUser('${escapeHtml(u.username)}')"
  14813. class="p-1.5 rounded-lg text-slate-400 hover:text-rose-400 hover:bg-slate-800 transition" title="Delete User">
  14814. <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>
  14815. </button>
  14816. ` : ''}
  14817. </td>
  14818. `;
  14819. tbody.appendChild(tr);
  14820. });
  14821. }
  14822. function openAddUserModal() {
  14823. document.getElementById('user-add-username').value = '';
  14824. document.getElementById('user-add-password').value = '';
  14825. document.getElementById('user-add-confirm').value = '';
  14826. document.getElementById('user-add-role').value = 'full';
  14827. document.getElementById('user-add-comment').value = '';
  14828. document.getElementById('modal-add-user')?.classList.remove('hidden');
  14829. document.getElementById('user-add-username')?.focus();
  14830. }
  14831. function closeAddUserModal() {
  14832. document.getElementById('modal-add-user')?.classList.add('hidden');
  14833. }
  14834. async function submitAddUser(event) {
  14835. event.preventDefault();
  14836. const username = (document.getElementById('user-add-username')?.value || '').trim();
  14837. const password = document.getElementById('user-add-password')?.value || '';
  14838. const confirm = document.getElementById('user-add-confirm')?.value || '';
  14839. const role = document.getElementById('user-add-role')?.value || 'full';
  14840. const comment = (document.getElementById('user-add-comment')?.value || '').trim();
  14841. if (password !== confirm) {
  14842. showToast('Validation Error', 'Passwords do not match', 'warning');
  14843. return;
  14844. }
  14845. if (password.length < 4) {
  14846. showToast('Validation Error', 'Password must be at least 4 characters', 'warning');
  14847. return;
  14848. }
  14849. try {
  14850. const res = await fetch(`${API_BASE}/users`, {
  14851. method: 'POST',
  14852. headers: { 'Content-Type': 'application/json' },
  14853. body: JSON.stringify({ username, password, role, comment })
  14854. });
  14855. const data = await res.json();
  14856. if (res.ok) {
  14857. showToast('User Created', `Created user ${username} with ${role.toUpperCase()} permissions`, 'success');
  14858. closeAddUserModal();
  14859. loadUsers(false);
  14860. } else {
  14861. showToast('Error', data.message || 'Failed to create user', 'error');
  14862. }
  14863. } catch (err) {
  14864. showToast('Error', err.message, 'error');
  14865. }
  14866. }
  14867. function openEditUserModal(username) {
  14868. const user = (state.users || []).find(u => u.username === username);
  14869. if (!user) return;
  14870. document.getElementById('user-edit-username').value = user.username;
  14871. document.getElementById('user-edit-username-title').innerText = `@${user.username}`;
  14872. document.getElementById('user-edit-role').value = user.role || 'read';
  14873. document.getElementById('user-edit-comment').value = user.comment || '';
  14874. document.getElementById('user-edit-disabled').checked = !!user.disabled;
  14875. document.getElementById('modal-edit-user')?.classList.remove('hidden');
  14876. }
  14877. function closeEditUserModal() {
  14878. document.getElementById('modal-edit-user')?.classList.add('hidden');
  14879. }
  14880. async function submitEditUser(event) {
  14881. event.preventDefault();
  14882. const username = document.getElementById('user-edit-username')?.value;
  14883. const role = document.getElementById('user-edit-role')?.value || 'read';
  14884. const comment = (document.getElementById('user-edit-comment')?.value || '').trim();
  14885. const disabled = document.getElementById('user-edit-disabled')?.checked || false;
  14886. try {
  14887. const res = await fetch(`${API_BASE}/users/${encodeURIComponent(username)}`, {
  14888. method: 'PUT',
  14889. headers: { 'Content-Type': 'application/json' },
  14890. body: JSON.stringify({ role, comment, disabled })
  14891. });
  14892. const data = await res.json();
  14893. if (res.ok) {
  14894. showToast('User Updated', `Updated settings for ${username}`, 'success');
  14895. closeEditUserModal();
  14896. loadUsers(false);
  14897. // If updated own role/disabled status, refresh self profile
  14898. if (username === state.currentUser?.username) {
  14899. checkAuthStatus();
  14900. }
  14901. } else {
  14902. showToast('Error', data.message || 'Failed to update user', 'error');
  14903. }
  14904. } catch (err) {
  14905. showToast('Error', err.message, 'error');
  14906. }
  14907. }
  14908. function openAdminResetPasswordModal(username) {
  14909. document.getElementById('admin-reset-username').value = username;
  14910. document.getElementById('admin-reset-username-title').innerText = `@${username}`;
  14911. document.getElementById('admin-reset-new-pw').value = '';
  14912. document.getElementById('admin-reset-confirm-pw').value = '';
  14913. document.getElementById('modal-admin-reset-pw')?.classList.remove('hidden');
  14914. document.getElementById('admin-reset-new-pw')?.focus();
  14915. }
  14916. function closeAdminResetPasswordModal() {
  14917. document.getElementById('modal-admin-reset-pw')?.classList.add('hidden');
  14918. }
  14919. async function submitAdminResetPassword(event) {
  14920. event.preventDefault();
  14921. const username = document.getElementById('admin-reset-username')?.value;
  14922. const newPassword = document.getElementById('admin-reset-new-pw')?.value || '';
  14923. const confirm = document.getElementById('admin-reset-confirm-pw')?.value || '';
  14924. if (newPassword !== confirm) {
  14925. showToast('Validation Error', 'Passwords do not match', 'warning');
  14926. return;
  14927. }
  14928. if (newPassword.length < 4) {
  14929. showToast('Validation Error', 'Password must be at least 4 characters', 'warning');
  14930. return;
  14931. }
  14932. try {
  14933. const res = await fetch(`${API_BASE}/users/${encodeURIComponent(username)}/password`, {
  14934. method: 'POST',
  14935. headers: { 'Content-Type': 'application/json' },
  14936. body: JSON.stringify({ new_password: newPassword })
  14937. });
  14938. const data = await res.json();
  14939. if (res.ok) {
  14940. showToast('Password Reset', `Password for user ${username} updated successfully`, 'success');
  14941. closeAdminResetPasswordModal();
  14942. } else {
  14943. showToast('Error', data.message || 'Failed to reset password', 'error');
  14944. }
  14945. } catch (err) {
  14946. showToast('Error', err.message, 'error');
  14947. }
  14948. }
  14949. async function deleteUser(username) {
  14950. if (username === state.currentUser?.username) {
  14951. showToast('Action Forbidden', 'You cannot delete your own account', 'warning');
  14952. return;
  14953. }
  14954. if (!confirm(`Are you sure you want to completely remove user "${username}"?`)) {
  14955. return;
  14956. }
  14957. try {
  14958. const res = await fetch(`${API_BASE}/users/${encodeURIComponent(username)}`, {
  14959. method: 'DELETE'
  14960. });
  14961. const data = await res.json();
  14962. if (res.ok) {
  14963. showToast('User Deleted', `User ${username} has been removed`, 'success');
  14964. loadUsers(false);
  14965. } else {
  14966. showToast('Error', data.message || 'Failed to delete user', 'error');
  14967. }
  14968. } catch (err) {
  14969. showToast('Error', err.message, 'error');
  14970. }
  14971. }
  14972. function openSelfPasswordModal() {
  14973. document.getElementById('self-current-password').value = '';
  14974. document.getElementById('self-new-password').value = '';
  14975. document.getElementById('self-confirm-password').value = '';
  14976. document.getElementById('modal-self-password')?.classList.remove('hidden');
  14977. document.getElementById('self-current-password')?.focus();
  14978. }
  14979. function closeSelfPasswordModal() {
  14980. document.getElementById('modal-self-password')?.classList.add('hidden');
  14981. }
  14982. async function submitSelfPassword(event) {
  14983. event.preventDefault();
  14984. const oldPassword = document.getElementById('self-current-password')?.value || '';
  14985. const newPassword = document.getElementById('self-new-password')?.value || '';
  14986. const confirm = document.getElementById('self-confirm-password')?.value || '';
  14987. if (newPassword !== confirm) {
  14988. showToast('Validation Error', 'New passwords do not match', 'warning');
  14989. return;
  14990. }
  14991. if (newPassword.length < 4) {
  14992. showToast('Validation Error', 'Password must be at least 4 characters', 'warning');
  14993. return;
  14994. }
  14995. try {
  14996. const res = await fetch(`${API_BASE}/auth/change-password`, {
  14997. method: 'POST',
  14998. headers: { 'Content-Type': 'application/json' },
  14999. body: JSON.stringify({ old_password: oldPassword, new_password: newPassword })
  15000. });
  15001. const data = await res.json();
  15002. if (res.ok) {
  15003. showToast('Password Changed', 'Your password has been changed successfully', 'success');
  15004. closeSelfPasswordModal();
  15005. } else {
  15006. showToast('Error', data.message || 'Failed to change password', 'error');
  15007. }
  15008. } catch (err) {
  15009. showToast('Error', err.message, 'error');
  15010. }
  15011. }
  15012. // ==================== MANAGEMENT SERVICES (/ip service) ====================
  15013. state.services = [];
  15014. async function loadServices(manual = false) {
  15015. try {
  15016. const res = await fetch(`${API_BASE}/system/services`);
  15017. if (!res.ok) throw new Error('Failed to load services');
  15018. const data = await res.json();
  15019. state.services = data || [];
  15020. renderServicesTable();
  15021. updateCertificatesBadges();
  15022. if (manual) showToast('Services Updated', 'Service status synchronized', 'success');
  15023. } catch (err) {
  15024. if (manual) showToast('Error', err.message, 'error');
  15025. }
  15026. }
  15027. function renderServicesTable() {
  15028. const tbody = document.getElementById('services-table-body');
  15029. if (!tbody) return;
  15030. if (!state.services || state.services.length === 0) {
  15031. tbody.innerHTML = '<tr><td colspan="5" class="py-6 text-center text-slate-500 text-xs">No services configured.</td></tr>';
  15032. return;
  15033. }
  15034. tbody.innerHTML = state.services.map(s => {
  15035. const isOff = s.disabled;
  15036. const statusBadge = isOff
  15037. ? '<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>'
  15038. : '<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>';
  15039. const toggleBtn = isOff
  15040. ? `<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>`
  15041. : `<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>`;
  15042. let certBadge = '';
  15043. if (s.name === 'www-ssl') {
  15044. if (s.certificate) {
  15045. certBadge = `<span class="ml-2 inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] bg-slate-800 text-amber-300 border border-slate-700 font-mono">🔒 ${escapeHtml(s.certificate)}</span>`;
  15046. } else {
  15047. certBadge = `<span class="ml-2 inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] bg-rose-500/10 text-rose-400 border border-rose-500/20 font-mono">⚠️ No Cert Selected</span>`;
  15048. }
  15049. }
  15050. const certArg = s.certificate ? `'${escapeHtml(s.certificate)}'` : "''";
  15051. return `
  15052. <tr class="hover:bg-slate-800/40 transition">
  15053. <td class="py-3 px-4 font-bold text-white uppercase">${s.name} ${certBadge}</td>
  15054. <td class="py-3 px-4">
  15055. <div class="flex items-center gap-2">
  15056. <span class="text-cyan-400 font-mono font-bold">${s.port}</span>
  15057. <button onclick="openEditServiceModal('${s.name}', ${s.port}, ${s.disabled}, ${certArg})" title="Edit Service" class="text-slate-500 hover:text-cyan-400 p-1 rounded hover:bg-slate-800/80 transition">
  15058. <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>
  15059. </button>
  15060. </div>
  15061. </td>
  15062. <td class="py-3 px-4">${statusBadge}</td>
  15063. <td class="py-3 px-4 text-slate-400 text-xs font-sans">${s.comment || '-'}</td>
  15064. <td class="py-3 px-4 text-right">
  15065. <div class="flex items-center justify-end gap-2">
  15066. <button onclick="openEditServiceModal('${s.name}', ${s.port}, ${s.disabled}, ${certArg})" 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">
  15067. <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>
  15068. <span>Edit</span>
  15069. </button>
  15070. ${toggleBtn}
  15071. </div>
  15072. </td>
  15073. </tr>
  15074. `;
  15075. }).join('');
  15076. }
  15077. function openEditServiceModal(serviceName, currentPort, isDisabled, currentCert = '') {
  15078. document.getElementById('modal-service-name').value = serviceName;
  15079. document.getElementById('modal-service-disabled').value = String(isDisabled);
  15080. document.getElementById('modal-service-display-name').textContent = serviceName.toUpperCase();
  15081. document.getElementById('modal-service-port').value = currentPort;
  15082. const hintEl = document.getElementById('modal-service-port-hint');
  15083. const warnEl = document.getElementById('modal-service-warning');
  15084. const certGroup = document.getElementById('modal-service-cert-group');
  15085. const certSelect = document.getElementById('modal-service-cert-select');
  15086. if (serviceName === 'www') {
  15087. hintEl.textContent = 'Default HTTP web port: 80';
  15088. warnEl.classList.remove('hidden');
  15089. certGroup.classList.add('hidden');
  15090. } else if (serviceName === 'www-ssl') {
  15091. hintEl.textContent = 'Default HTTPS web port: 443';
  15092. warnEl.classList.remove('hidden');
  15093. certGroup.classList.remove('hidden');
  15094. const populateCertOptions = (certs) => {
  15095. certSelect.innerHTML = '<option value="">-- No Certificate Selected --</option>';
  15096. (certs || []).forEach(c => {
  15097. const opt = document.createElement('option');
  15098. opt.value = c.name;
  15099. opt.textContent = `${c.name} (${c.common_name})${c.is_ca ? ' [CA]' : ''}`;
  15100. if (c.name === currentCert) opt.selected = true;
  15101. certSelect.appendChild(opt);
  15102. });
  15103. };
  15104. if (state.certificates && state.certificates.length > 0) {
  15105. populateCertOptions(state.certificates);
  15106. } else {
  15107. loadCertificates(false).then(() => {
  15108. populateCertOptions(state.certificates);
  15109. });
  15110. }
  15111. } else if (serviceName === 'telnet') {
  15112. hintEl.textContent = 'Default Telnet console port: 8282';
  15113. warnEl.classList.add('hidden');
  15114. certGroup.classList.add('hidden');
  15115. } else if (serviceName === 'ssh') {
  15116. hintEl.textContent = 'Default SSH port: 2222';
  15117. warnEl.classList.add('hidden');
  15118. certGroup.classList.add('hidden');
  15119. } else {
  15120. hintEl.textContent = '';
  15121. warnEl.classList.add('hidden');
  15122. certGroup.classList.add('hidden');
  15123. }
  15124. const modal = document.getElementById('modal-service-edit');
  15125. modal.classList.remove('hidden');
  15126. setTimeout(() => document.getElementById('modal-service-port').focus(), 50);
  15127. }
  15128. function closeEditServiceModal() {
  15129. const modal = document.getElementById('modal-service-edit');
  15130. if (modal) modal.classList.add('hidden');
  15131. }
  15132. async function submitSaveServicePort(event) {
  15133. event.preventDefault();
  15134. const name = document.getElementById('modal-service-name').value;
  15135. const disabled = document.getElementById('modal-service-disabled').value === 'true';
  15136. const port = parseInt(document.getElementById('modal-service-port').value, 10);
  15137. if (isNaN(port) || port < 1 || port > 65535) {
  15138. showToast('Invalid Port', 'Port must be a valid number between 1 and 65535', 'error');
  15139. return;
  15140. }
  15141. const certSelect = document.getElementById('modal-service-cert-select');
  15142. const certVal = (name === 'www-ssl' && certSelect) ? certSelect.value : '';
  15143. try {
  15144. const res = await fetch(`${API_BASE}/system/services/${name}`, {
  15145. method: 'POST',
  15146. headers: { 'Content-Type': 'application/json' },
  15147. body: JSON.stringify({ port: port, disabled: disabled, certificate: certVal })
  15148. });
  15149. if (!res.ok) {
  15150. const errData = await res.json();
  15151. throw new Error(errData.message || 'Failed to update service settings');
  15152. }
  15153. closeEditServiceModal();
  15154. showToast('Service Updated', `Service ${name.toUpperCase()} settings saved`, 'success');
  15155. await loadServices();
  15156. } catch (err) {
  15157. showToast('Error', err.message, 'error');
  15158. }
  15159. }
  15160. async function toggleServiceState(serviceName, newDisabled) {
  15161. if (serviceName === 'www' && newDisabled) {
  15162. 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?")) {
  15163. return;
  15164. }
  15165. }
  15166. if (serviceName === 'www-ssl' && !newDisabled) {
  15167. const sslSvc = (state.services || []).find(s => s.name === 'www-ssl');
  15168. if (!sslSvc || !sslSvc.certificate) {
  15169. showToast('Certificate Required', 'Please assign an SSL/TLS certificate to www-ssl before enabling HTTPS.', 'warning');
  15170. openEditServiceModal('www-ssl', sslSvc ? sslSvc.port : 443, false, '');
  15171. return;
  15172. }
  15173. }
  15174. try {
  15175. const res = await fetch(`${API_BASE}/system/services/${serviceName}/state`, {
  15176. method: 'POST',
  15177. headers: { 'Content-Type': 'application/json' },
  15178. body: JSON.stringify({ disabled: newDisabled })
  15179. });
  15180. if (!res.ok) {
  15181. const errData = await res.json();
  15182. throw new Error(errData.message || 'Failed to update service');
  15183. }
  15184. showToast('Service Updated', `Service ${serviceName} is now ${newDisabled ? 'disabled' : 'enabled'}`, 'success');
  15185. await loadServices();
  15186. } catch (err) {
  15187. showToast('Error', err.message, 'error');
  15188. }
  15189. }
  15190. // ==================== SYSTEM LOGS (/log) ====================
  15191. state.logs = [];
  15192. let logsTimer = null;
  15193. async function loadLogs(manual = false) {
  15194. const limitEl = document.getElementById('logs-limit-select');
  15195. const limit = limitEl ? limitEl.value : '100';
  15196. try {
  15197. const res = await fetch(`${API_BASE}/system/logs?limit=${limit}`);
  15198. if (!res.ok) throw new Error('Failed to load logs');
  15199. const data = await res.json();
  15200. state.logs = data.logs || [];
  15201. renderLogsTable();
  15202. if (manual) showToast('Logs Refreshed', `Fetched ${state.logs.length} log records`, 'success');
  15203. } catch (err) {
  15204. if (manual) showToast('Error', err.message, 'error');
  15205. }
  15206. // Setup auto-refresh if enabled and on logs tab
  15207. if (!logsTimer && state.currentUser) {
  15208. logsTimer = setInterval(() => {
  15209. if (state.currentUser && !document.hidden && state.activeTab === 'logs') {
  15210. const auto = document.getElementById('logs-auto-refresh');
  15211. if (auto && auto.checked) {
  15212. loadLogs(false);
  15213. }
  15214. }
  15215. }, 3000);
  15216. }
  15217. }
  15218. function renderLogsTable() {
  15219. const tbody = document.getElementById('logs-table-body');
  15220. if (!tbody) return;
  15221. const search = (document.getElementById('logs-search-input')?.value || '').toLowerCase();
  15222. const topicFilter = (document.getElementById('logs-topic-filter')?.value || '').toLowerCase();
  15223. const filtered = state.logs.filter(entry => {
  15224. if (topicFilter && !entry.topics.toLowerCase().includes(topicFilter)) {
  15225. return false;
  15226. }
  15227. if (search && !entry.message.toLowerCase().includes(search) && !entry.topics.toLowerCase().includes(search)) {
  15228. return false;
  15229. }
  15230. return true;
  15231. });
  15232. if (filtered.length === 0) {
  15233. tbody.innerHTML = '<tr><td colspan="4" class="py-8 text-center text-slate-500 text-xs">No matching log entries found.</td></tr>';
  15234. return;
  15235. }
  15236. tbody.innerHTML = filtered.map(l => {
  15237. let topicColor = 'bg-slate-800 text-slate-300 border-slate-700';
  15238. const topLower = l.topics.toLowerCase();
  15239. if (topLower.includes('auth')) {
  15240. topicColor = 'bg-amber-500/20 text-amber-300 border-amber-500/30';
  15241. } else if (topLower.includes('dhcp')) {
  15242. topicColor = 'bg-cyan-500/20 text-cyan-300 border-cyan-500/30';
  15243. } else if (topLower.includes('route')) {
  15244. topicColor = 'bg-blue-500/20 text-blue-300 border-blue-500/30';
  15245. } else if (topLower.includes('firewall')) {
  15246. topicColor = 'bg-rose-500/20 text-rose-300 border-rose-500/30';
  15247. } else if (topLower.includes('error')) {
  15248. topicColor = 'bg-red-500/20 text-red-300 border-red-500/30';
  15249. } else if (topLower.includes('system')) {
  15250. topicColor = 'bg-emerald-500/20 text-emerald-300 border-emerald-500/30';
  15251. }
  15252. const d = new Date(l.time);
  15253. const timeStr = d.toLocaleDateString('en-US', { month: 'short', day: '2-digit' }) + ' ' + d.toLocaleTimeString('en-US', { hour12: false });
  15254. return `
  15255. <tr class="hover:bg-slate-800/40 transition">
  15256. <td class="py-2 px-3 text-slate-500 font-mono">${l.id}</td>
  15257. <td class="py-2 px-3 text-slate-400 font-mono whitespace-nowrap">${timeStr}</td>
  15258. <td class="py-2 px-3 whitespace-nowrap">
  15259. <span class="px-2 py-0.5 rounded text-[10px] font-bold border ${topicColor}">${l.topics}</span>
  15260. </td>
  15261. <td class="py-2 px-3 text-slate-200 font-mono break-all">${escapeHtml(l.message)}</td>
  15262. </tr>
  15263. `;
  15264. }).join('');
  15265. }
  15266. // ==================== CERTIFICATES & SSL/TLS (/certificate) ====================
  15267. state.certificates = [];
  15268. async function loadCertificates(manual = false) {
  15269. try {
  15270. const res = await fetch(`${API_BASE}/certificates`);
  15271. if (!res.ok) throw new Error('Failed to load certificates');
  15272. state.certificates = await res.json() || [];
  15273. updateCertificatesBadges();
  15274. renderCertificatesTable();
  15275. if (manual) showToast('Certificates Updated', `Loaded ${state.certificates.length} certificates`, 'success');
  15276. } catch (err) {
  15277. if (manual) showToast('Error', err.message, 'error');
  15278. }
  15279. }
  15280. function updateCertificatesBadges() {
  15281. const total = (state.certificates || []).length;
  15282. const caCount = (state.certificates || []).filter(c => c.is_ca).length;
  15283. const bCount = document.getElementById('badge-certs-count');
  15284. if (bCount) bCount.innerText = total;
  15285. const kpiTotal = document.getElementById('kpi-certs-total');
  15286. if (kpiTotal) kpiTotal.innerText = total;
  15287. const kpiCA = document.getElementById('kpi-certs-ca');
  15288. if (kpiCA) kpiCA.innerText = caCount;
  15289. const kpiHttps = document.getElementById('kpi-https-status');
  15290. if (kpiHttps) {
  15291. const sslSvc = (state.services || []).find(s => s.name === 'www-ssl');
  15292. if (sslSvc) {
  15293. if (!sslSvc.disabled) {
  15294. kpiHttps.innerHTML = `<span class="text-emerald-400 font-bold">Enabled (Port ${sslSvc.port})</span><div class="text-[10px] text-slate-400 font-mono truncate">Cert: ${escapeHtml(sslSvc.certificate || 'None')}</div>`;
  15295. } else {
  15296. kpiHttps.innerHTML = `<span class="text-rose-400 font-bold">Disabled (Port ${sslSvc.port})</span><div class="text-[10px] text-slate-500 font-mono truncate">Cert: ${escapeHtml(sslSvc.certificate || 'None')}</div>`;
  15297. }
  15298. }
  15299. }
  15300. }
  15301. function renderCertificatesTable() {
  15302. const tbody = document.getElementById('certs-table-body');
  15303. if (!tbody) return;
  15304. if (!state.certificates || state.certificates.length === 0) {
  15305. tbody.innerHTML = '<tr><td colspan="6" class="py-8 text-center text-slate-500 text-xs">No certificates configured yet. Click "Create CA" or "Issue Cert" to begin.</td></tr>';
  15306. return;
  15307. }
  15308. tbody.innerHTML = state.certificates.map(c => {
  15309. let typeBadge = '';
  15310. if (c.is_ca) {
  15311. typeBadge = '<span class="px-2 py-0.5 rounded text-[10px] bg-blue-500/20 text-blue-300 border border-blue-500/30 font-bold uppercase">🏛 CA</span>';
  15312. } else if (c.type === 'acme') {
  15313. typeBadge = '<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">🔒 Let\'s Encrypt</span>';
  15314. } else if (c.issuer && c.issuer !== c.common_name) {
  15315. typeBadge = '<span class="px-2 py-0.5 rounded text-[10px] bg-cyan-500/20 text-cyan-300 border border-cyan-500/30 font-bold uppercase">📜 Signed</span>';
  15316. } else {
  15317. typeBadge = '<span class="px-2 py-0.5 rounded text-[10px] bg-slate-700/60 text-slate-300 border border-slate-600 font-bold uppercase">📜 Self-Signed</span>';
  15318. }
  15319. const sansHtml = (c.sans && c.sans.length > 0)
  15320. ? c.sans.map(s => `<span class="inline-block px-1.5 py-0.2 rounded text-[10px] bg-slate-800 text-slate-300 border border-slate-700 mr-1 mb-0.5">${escapeHtml(s)}</span>`).join('')
  15321. : '<span class="text-slate-500">-</span>';
  15322. const validTo = c.valid_to ? new Date(c.valid_to) : null;
  15323. let validStr = '-';
  15324. let validBadge = '';
  15325. if (validTo && !isNaN(validTo.getTime())) {
  15326. const now = new Date();
  15327. const daysLeft = Math.round((validTo - now) / (1000 * 60 * 60 * 24));
  15328. validStr = validTo.toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' });
  15329. if (daysLeft < 0) {
  15330. validBadge = '<span class="ml-1 text-[10px] text-rose-400 font-bold">(Expired)</span>';
  15331. } else if (daysLeft < 30) {
  15332. validBadge = `<span class="ml-1 text-[10px] text-amber-400 font-bold">(${daysLeft}d left)</span>`;
  15333. } else {
  15334. validBadge = `<span class="ml-1 text-[10px] text-slate-400">(${daysLeft}d left)</span>`;
  15335. }
  15336. }
  15337. return `
  15338. <tr class="hover:bg-slate-800/40 transition">
  15339. <td class="py-3 px-4">${typeBadge}</td>
  15340. <td class="py-3 px-4">
  15341. <div class="font-bold text-white">${escapeHtml(c.name)}</div>
  15342. <div class="text-[10px] text-slate-400 font-sans truncate max-w-xs" title="${escapeHtml(c.common_name)}">${escapeHtml(c.common_name)}</div>
  15343. </td>
  15344. <td class="py-3 px-4 text-slate-300 text-xs truncate max-w-xs" title="${escapeHtml(c.issuer || '-')}">${escapeHtml(c.issuer || '-')}</td>
  15345. <td class="py-3 px-4 max-w-xs">${sansHtml}</td>
  15346. <td class="py-3 px-4 whitespace-nowrap text-xs text-slate-300">
  15347. <span>${validStr}</span> ${validBadge}
  15348. ${c.type === 'acme' ? `<div class="text-[10px] ${c.renewal_error ? 'text-rose-400' : 'text-slate-400'}">${c.renewal_error ? 'Renewal failed: ' + escapeHtml(c.renewal_error) : 'Automatic renewal enabled'}</div>` : ''}
  15349. <div class="text-[10px] text-slate-500">${c.key_type || ''}</div>
  15350. </td>
  15351. <td class="py-3 px-4 text-right whitespace-nowrap">
  15352. <div class="flex items-center justify-end gap-1.5">
  15353. <button onclick="openViewCertModal('${c.name}')" title="View & Export PEM" 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">
  15354. <svg class="w-3.5 h-3.5 text-cyan-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"/></svg>
  15355. <span>View</span>
  15356. </button>
  15357. <button onclick="deleteCertificate('${c.name}')" title="Delete Certificate" class="px-2 py-1 rounded-lg bg-rose-500/10 hover:bg-rose-500/20 text-rose-400 border border-rose-500/30 text-[11px] transition">
  15358. <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="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>
  15359. </button>
  15360. </div>
  15361. </td>
  15362. </tr>
  15363. `;
  15364. }).join('');
  15365. }
  15366. // Create CA
  15367. function openCreateCAModal() {
  15368. document.getElementById('form-create-ca').reset();
  15369. document.getElementById('ca-days').value = '3650';
  15370. document.getElementById('ca-org').value = 'DebTik Network Appliance';
  15371. document.getElementById('ca-country').value = 'GR';
  15372. document.getElementById('ca-key-type').value = 'RSA-2048';
  15373. document.getElementById('modal-create-ca').classList.remove('hidden');
  15374. setTimeout(() => document.getElementById('ca-name').focus(), 50);
  15375. }
  15376. function closeCreateCAModal() {
  15377. document.getElementById('modal-create-ca').classList.add('hidden');
  15378. }
  15379. async function submitCreateCA(event) {
  15380. event.preventDefault();
  15381. const payload = {
  15382. name: document.getElementById('ca-name').value.trim(),
  15383. common_name: document.getElementById('ca-cn').value.trim(),
  15384. organization: document.getElementById('ca-org').value.trim(),
  15385. country: document.getElementById('ca-country').value.trim(),
  15386. days: parseInt(document.getElementById('ca-days').value, 10) || 3650,
  15387. key_type: document.getElementById('ca-key-type').value
  15388. };
  15389. try {
  15390. const res = await fetch(`${API_BASE}/certificates/ca`, {
  15391. method: 'POST',
  15392. headers: { 'Content-Type': 'application/json' },
  15393. body: JSON.stringify(payload)
  15394. });
  15395. if (!res.ok) {
  15396. const errData = await res.json();
  15397. throw new Error(errData.message || 'Failed to create CA');
  15398. }
  15399. closeCreateCAModal();
  15400. showToast('CA Created', `Root CA ${payload.name} generated successfully`, 'success');
  15401. await loadCertificates();
  15402. } catch (err) {
  15403. showToast('Error', err.message, 'error');
  15404. }
  15405. }
  15406. // Create Cert
  15407. function openCreateCertModal() {
  15408. document.getElementById('form-create-cert').reset();
  15409. document.getElementById('cert-days').value = '730';
  15410. document.getElementById('cert-key-type').value = 'RSA-2048';
  15411. const caSelect = document.getElementById('cert-ca-select');
  15412. caSelect.innerHTML = '<option value="">[ Self-Signed Certificate ]</option>';
  15413. (state.certificates || []).filter(c => c.is_ca).forEach(ca => {
  15414. const opt = document.createElement('option');
  15415. opt.value = ca.name;
  15416. opt.textContent = `${ca.name} (${ca.common_name})`;
  15417. caSelect.appendChild(opt);
  15418. });
  15419. document.getElementById('modal-create-cert').classList.remove('hidden');
  15420. setTimeout(() => document.getElementById('cert-name').focus(), 50);
  15421. }
  15422. function closeCreateCertModal() {
  15423. document.getElementById('modal-create-cert').classList.add('hidden');
  15424. }
  15425. async function submitCreateCert(event) {
  15426. event.preventDefault();
  15427. const rawSans = document.getElementById('cert-sans').value;
  15428. const sansList = rawSans ? rawSans.split(',').map(s => s.trim()).filter(Boolean) : [];
  15429. const caName = document.getElementById('cert-ca-select').value;
  15430. const payload = {
  15431. name: document.getElementById('cert-name').value.trim(),
  15432. common_name: document.getElementById('cert-cn').value.trim(),
  15433. ca_name: caName,
  15434. sans: sansList,
  15435. days: parseInt(document.getElementById('cert-days').value, 10) || 730,
  15436. key_type: document.getElementById('cert-key-type').value,
  15437. is_server: true
  15438. };
  15439. try {
  15440. const res = await fetch(`${API_BASE}/certificates/generate`, {
  15441. method: 'POST',
  15442. headers: { 'Content-Type': 'application/json' },
  15443. body: JSON.stringify(payload)
  15444. });
  15445. if (!res.ok) {
  15446. const errData = await res.json();
  15447. throw new Error(errData.message || 'Failed to issue certificate');
  15448. }
  15449. closeCreateCertModal();
  15450. showToast('Certificate Issued', `Certificate ${payload.name} generated successfully`, 'success');
  15451. await loadCertificates();
  15452. } catch (err) {
  15453. showToast('Error', err.message, 'error');
  15454. }
  15455. }
  15456. // Let's Encrypt
  15457. function openLetsEncryptModal() {
  15458. document.getElementById('form-letsencrypt').reset();
  15459. document.getElementById('modal-letsencrypt').classList.remove('hidden');
  15460. setTimeout(() => document.getElementById('le-domain').focus(), 50);
  15461. }
  15462. function closeLetsEncryptModal() {
  15463. document.getElementById('modal-letsencrypt').classList.add('hidden');
  15464. }
  15465. async function submitLetsEncrypt(event) {
  15466. event.preventDefault();
  15467. const domain = document.getElementById('le-domain').value.trim();
  15468. const email = document.getElementById('le-email').value.trim();
  15469. let name = document.getElementById('le-name').value.trim();
  15470. if (!name) name = domain.replace(/[^a-zA-Z0-9_-]/g, '-');
  15471. const staging = document.getElementById('le-staging').checked;
  15472. const btn = document.getElementById('btn-submit-letsencrypt');
  15473. const origBtnHtml = btn.innerHTML;
  15474. btn.disabled = true;
  15475. btn.innerHTML = `<svg class="w-4 h-4 animate-spin text-white" fill="none" viewBox="0 0 24 24"><circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle><path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v8H4z"></path></svg> <span>Issuing (may take up to 60s)...</span>`;
  15476. try {
  15477. const res = await fetch(`${API_BASE}/certificates/letsencrypt`, {
  15478. method: 'POST',
  15479. headers: { 'Content-Type': 'application/json' },
  15480. body: JSON.stringify({
  15481. name: name,
  15482. domain: domain,
  15483. email: email,
  15484. staging: staging
  15485. })
  15486. });
  15487. if (!res.ok) {
  15488. const errData = await res.json();
  15489. throw new Error(errData.message || 'Let\'s Encrypt challenge failed');
  15490. }
  15491. closeLetsEncryptModal();
  15492. showToast('Let\'s Encrypt Issued', `Successfully issued trusted certificate for ${domain}`, 'success');
  15493. await loadCertificates();
  15494. } catch (err) {
  15495. showToast('Let\'s Encrypt Error', err.message, 'error');
  15496. } finally {
  15497. btn.disabled = false;
  15498. btn.innerHTML = origBtnHtml;
  15499. }
  15500. }
  15501. // Import Cert
  15502. function openImportCertModal() {
  15503. document.getElementById('form-import-cert').reset();
  15504. document.getElementById('modal-import-cert').classList.remove('hidden');
  15505. setTimeout(() => document.getElementById('import-cert-name').focus(), 50);
  15506. }
  15507. function closeImportCertModal() {
  15508. document.getElementById('modal-import-cert').classList.add('hidden');
  15509. }
  15510. async function submitImportCert(event) {
  15511. event.preventDefault();
  15512. const payload = {
  15513. name: document.getElementById('import-cert-name').value.trim(),
  15514. cert_pem: document.getElementById('import-cert-pem').value.trim(),
  15515. key_pem: document.getElementById('import-key-pem').value.trim()
  15516. };
  15517. try {
  15518. const res = await fetch(`${API_BASE}/certificates/import`, {
  15519. method: 'POST',
  15520. headers: { 'Content-Type': 'application/json' },
  15521. body: JSON.stringify(payload)
  15522. });
  15523. if (!res.ok) {
  15524. const errData = await res.json();
  15525. throw new Error(errData.message || 'Failed to import certificate');
  15526. }
  15527. closeImportCertModal();
  15528. showToast('Certificate Imported', `Imported ${payload.name} successfully`, 'success');
  15529. await loadCertificates();
  15530. } catch (err) {
  15531. showToast('Error', err.message, 'error');
  15532. }
  15533. }
  15534. // View / Export Modal
  15535. async function openViewCertModal(name) {
  15536. const c = (state.certificates || []).find(x => x.name === name);
  15537. if (!c) return;
  15538. document.getElementById('view-cert-modal-title').textContent = `Certificate: ${c.name}`;
  15539. document.getElementById('view-cert-cn').textContent = c.common_name || '-';
  15540. document.getElementById('view-cert-issuer').textContent = c.issuer || '-';
  15541. document.getElementById('view-cert-type').textContent = `${c.is_ca ? 'CA' : 'Server/Client'} (${c.key_type || 'Unknown'})`;
  15542. document.getElementById('view-cert-validto').textContent = c.valid_to ? new Date(c.valid_to).toLocaleString() : '-';
  15543. document.getElementById('view-cert-sans').textContent = (c.sans && c.sans.length > 0) ? c.sans.join(', ') : 'None';
  15544. document.getElementById('view-cert-fp').textContent = c.fingerprint || '-';
  15545. document.getElementById('view-cert-pem-text').value = 'Loading PEM...';
  15546. document.getElementById('view-key-pem-text').value = 'Loading Key...';
  15547. document.getElementById('modal-view-cert').classList.remove('hidden');
  15548. try {
  15549. const res = await fetch(`${API_BASE}/certificates/${encodeURIComponent(name)}/export`);
  15550. if (!res.ok) throw new Error('Failed to export certificate PEM');
  15551. const data = await res.json();
  15552. document.getElementById('view-cert-pem-text').value = data.cert_pem || '';
  15553. document.getElementById('view-key-pem-text').value = data.key_pem || '(Private key not available)';
  15554. } catch (err) {
  15555. document.getElementById('view-cert-pem-text').value = 'Error loading certificate PEM: ' + err.message;
  15556. document.getElementById('view-key-pem-text').value = '';
  15557. }
  15558. }
  15559. function closeViewCertModal() {
  15560. document.getElementById('modal-view-cert').classList.add('hidden');
  15561. }
  15562. function copyCertPEM() {
  15563. const text = document.getElementById('view-cert-pem-text').value;
  15564. if (!text) return;
  15565. navigator.clipboard.writeText(text).then(() => {
  15566. showToast('Copied', 'Certificate PEM copied to clipboard', 'info');
  15567. }).catch(() => {
  15568. showToast('Error', 'Failed to copy to clipboard', 'error');
  15569. });
  15570. }
  15571. function copyKeyPEM() {
  15572. const text = document.getElementById('view-key-pem-text').value;
  15573. if (!text) return;
  15574. navigator.clipboard.writeText(text).then(() => {
  15575. showToast('Copied', 'Private Key PEM copied to clipboard', 'info');
  15576. }).catch(() => {
  15577. showToast('Error', 'Failed to copy to clipboard', 'error');
  15578. });
  15579. }
  15580. async function deleteCertificate(name) {
  15581. if (!confirm(`Are you sure you want to delete certificate "${name}"? This action cannot be undone.`)) {
  15582. return;
  15583. }
  15584. try {
  15585. const res = await fetch(`${API_BASE}/certificates/${encodeURIComponent(name)}`, {
  15586. method: 'DELETE'
  15587. });
  15588. if (!res.ok) {
  15589. const errData = await res.json();
  15590. throw new Error(errData.message || 'Failed to delete certificate');
  15591. }
  15592. showToast('Certificate Deleted', `Certificate "${name}" removed`, 'success');
  15593. await loadCertificates();
  15594. } catch (err) {
  15595. showToast('Error', err.message, 'error');
  15596. }
  15597. }
  15598. // Refresh immediately when returning to a backgrounded controller tab.
  15599. document.addEventListener('visibilitychange', () => {
  15600. if (!state.currentUser) return;
  15601. if (document.hidden) {
  15602. if (trafficEventSource) trafficEventSource.close();
  15603. trafficEventSource = null;
  15604. if (trafficPollFallback) clearInterval(trafficPollFallback);
  15605. trafficPollFallback = null;
  15606. } else {
  15607. fetchData(false);
  15608. initLiveTrafficStream();
  15609. if (state.activeTab === 'bwtest') loadBwTestView();
  15610. }
  15611. });
  15612. async function loadUpdateStatus(populate = true) {
  15613. try {
  15614. const res = await fetch(`${API_BASE}/update/status`);
  15615. if (!res.ok) throw new Error(await responseError(res));
  15616. const data = await res.json();
  15617. if (populate && document.activeElement?.id !== 'update-repository') document.getElementById('update-repository').value = data.repository || '';
  15618. if (populate && document.activeElement?.id !== 'update-tls-pin') document.getElementById('update-tls-pin').value = data.tls_key_pin || '';
  15619. document.getElementById('update-installed').textContent = data.installed_version || 'unknown';
  15620. document.getElementById('update-state').textContent = data.state || 'idle';
  15621. document.getElementById('update-log').textContent = data.log || '';
  15622. } catch (err) { showToast('Update Status', err.message, 'error'); }
  15623. }
  15624. async function saveUpdateConfig() {
  15625. try {
  15626. const repository = document.getElementById('update-repository').value.trim();
  15627. const branch = 'master';
  15628. const tls_key_pin = document.getElementById('update-tls-pin').value.trim();
  15629. const res = await fetch(`${API_BASE}/update/config`, {method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({repository,branch,tls_key_pin})});
  15630. if (!res.ok) throw new Error(await responseError(res));
  15631. document.getElementById('update-install-button').disabled = true;
  15632. document.getElementById('update-available').textContent = '—';
  15633. showToast('Update Source Saved', 'Repository and branch saved', 'success');
  15634. await loadUpdateStatus(false);
  15635. } catch (err) { showToast('Update Source', err.message, 'error'); }
  15636. }
  15637. async function checkUpdate() {
  15638. try {
  15639. const res = await fetch(`${API_BASE}/update/check`, {method:'POST'});
  15640. if (!res.ok) throw new Error(await responseError(res));
  15641. const data = await res.json();
  15642. document.getElementById('update-available').textContent = data.available_version;
  15643. document.getElementById('update-install-button').disabled = !data.update_available;
  15644. showToast('Git Check', data.update_available ? 'An update is available' : 'No newer version available', 'info');
  15645. } catch (err) { showToast('Git Check Failed', err.message, 'error'); }
  15646. }
  15647. async function startUpdate(action) {
  15648. if (!confirm(action === 'rollback' ? 'Restore the previous version and restart DebTik?' : 'Install the newer release version and restart DebTik?')) return;
  15649. try {
  15650. const res = await fetch(`${API_BASE}/update/${action}`, {method:'POST'});
  15651. if (!res.ok) throw new Error(await responseError(res));
  15652. showToast('Update Started', 'The service will restart; reconnect after a few seconds', 'info');
  15653. await loadUpdateStatus(false);
  15654. } catch (err) { showToast('Update Failed', err.message, 'error'); }
  15655. }
  15656. async function resetCurrentRuleCounters() { return resetFirewallRuleCounter('filter', resetRuleCounterDisplay); }
  15657. async function resetCurrentNATRuleCounters() { return resetFirewallRuleCounter('nat', resetNATCounterDisplay); }
  15658. async function resetCurrentMangleRuleCounters() { return resetFirewallRuleCounter('mangle', resetMangleCounterDisplay); }
  15659. function safeFirewallRow(row) {
  15660. const result = {...row};
  15661. for (const [key,value] of Object.entries(result)) if (typeof value === 'string') result[key] = escapeHtml(value);
  15662. result.id = encodeURIComponent(String(row.id || '')).replace(/'/g, '%27').replace(/\(/g, '%28').replace(/\)/g, '%29');
  15663. return result;
  15664. }
  15665. function setFirewallDays(prefix, days) {
  15666. const selected = days ? days.toLowerCase().split(',') : ['sun','mon','tue','wed','thu','fri','sat'];
  15667. for (const d of ['sun','mon','tue','wed','thu','fri','sat']) { const el = document.getElementById(prefix+'-day-'+d); if (el) el.checked = selected.includes(d); }
  15668. }
  15669. function getFirewallDays(prefix) {
  15670. if (document.getElementById(prefix+'-field-days')?.classList.contains('hidden')) return '';
  15671. const selected = ['sun','mon','tue','wed','thu','fri','sat'].filter(d => document.getElementById(prefix+'-day-'+d)?.checked);
  15672. if (!selected.length) throw new Error('Select at least one weekday, or remove the Days condition.');
  15673. return selected.join(',');
  15674. }
  15675. async function resetFirewallRuleCounter(kind, resetDisplay) {
  15676. const id = document.getElementById(kind+'-modal-id')?.value;
  15677. if (!id) { resetDisplay(); return; }
  15678. try {
  15679. const response = await fetch(`${API_BASE}/firewall/${kind}/${encodeURIComponent(id)}/reset-counters`, {method:'POST'});
  15680. if (!response.ok) { const error = await response.json(); throw new Error(error.message || 'Counter reset failed'); }
  15681. resetDisplay(); await loadFirewall(false);
  15682. } catch(error) { showToast('Error', error.message, 'error'); }
  15683. }
  15684. function reviewLegacyFirewallSettings(kind, id) {
  15685. if (!id) return true;
  15686. const rows = kind === 'filter' ? state.filterRules : kind === 'nat' ? state.natRules : state.mangleRules;
  15687. const rule = (rows || []).find(r => r.id === id);
  15688. if (!rule) return true;
  15689. const unsupported = ['layer7_protocol','connection_bytes','connection_rate','pcc','in_bridge_port_list','out_bridge_port_list','tls_host','ingress_priority','priority','ipv4_options','dst_limit','psd','hotspot','route','sniff_target'];
  15690. const present = unsupported.filter(key => rule[key]);
  15691. if (!present.length) return true;
  15692. return confirm('This saved rule contains unsupported settings: '+present.join(', ')+'. Saving removes them. Review the remaining match conditions before continuing.');
  15693. }
  15694. function refreshFirewallRejectTypes() {
  15695. const select=document.getElementById('filter-modal-rejectwith'); if(!select) return;
  15696. const old=select.value;
  15697. const ipv6=document.getElementById('filter-modal-family')?.value==='6';
  15698. const types=ipv6 ? ['icmp6-port-unreachable','icmp6-no-route','icmp6-adm-prohibited','icmp6-addr-unreachable','tcp-reset'] : ['icmp-port-unreachable','icmp-net-unreachable','icmp-host-unreachable','icmp-proto-unreachable','icmp-net-prohibited','icmp-host-prohibited','icmp-admin-prohibited','tcp-reset'];
  15699. select.replaceChildren(...types.map(value=>{const option=document.createElement('option');option.value=value;option.textContent=value;return option}));
  15700. if(types.includes(old))select.value=old;
  15701. }
  15702. function setFirewallActionSelection(kind, value) {
  15703. const select=document.getElementById(kind+'-modal-action'); if(!select)return;
  15704. if(!Array.from(select.options).some(option=>option.value===value)) {
  15705. const option=document.createElement('option');option.value=value;option.textContent='Unsupported saved action: '+value;option.disabled=true;select.appendChild(option);
  15706. }
  15707. select.value=value;
  15708. }