app.js 743 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493
  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. // ======================== IPTABLES FIREWALL ========================
  3369. state.fwSubTab = 'filter';
  3370. state.routesSubTab = 'routes';
  3371. function nativeNATChain(chain) {
  3372. const value = (chain || '').toLowerCase();
  3373. if (value === 'dstnat') return 'prerouting';
  3374. if (value === 'srcnat') return 'postrouting';
  3375. return ['prerouting', 'input', 'output', 'postrouting'].includes(value) ? value : (chain || '');
  3376. }
  3377. function nativeFirewallTarget(action) {
  3378. const name = (action || '').toLowerCase();
  3379. return ({'src-nat':'SNAT', 'dst-nat':'DNAT', 'add-src-to-address-list':'SET (add source)', 'add-dst-to-address-list':'SET (add destination)', 'mark-connection':'CONNMARK', 'mark-packet':'MARK', 'mark-routing':'MARK (routing)', 'change-dscp':'DSCP', 'change-mss':'TCPMSS', 'change-ttl':'TTL / HL', 'set-priority':'CLASSIFY', 'passthrough':'COUNT / continue', 'jump':'JUMP'})[name] || name.toUpperCase();
  3380. }
  3381. function renderRuleFlag(disabled, hasComment) {
  3382. let flags = '';
  3383. if (disabled) flags += '<span class="text-rose-400 font-bold" title="Disabled">X</span>';
  3384. if (hasComment) flags += '<span class="text-amber-400 font-bold ml-1" title="Has Comment">C</span>';
  3385. return flags || '<span class="text-slate-600">-</span>';
  3386. }
  3387. function renderActionBadge(action) {
  3388. const act = (action || '').toLowerCase();
  3389. let color = 'bg-slate-800 text-slate-300';
  3390. if (act === 'accept') color = 'bg-emerald-500/20 text-emerald-300 border border-emerald-500/30';
  3391. else if (act === 'drop' || act === 'reject') color = 'bg-rose-500/20 text-rose-300 border border-rose-500/30';
  3392. else if (act === 'masquerade' || act === 'src-nat' || act === 'dst-nat') color = 'bg-amber-500/20 text-amber-300 border border-amber-500/30';
  3393. else if (act.startsWith('mark-')) color = 'bg-purple-500/20 text-purple-300 border border-purple-500/30';
  3394. else if (act === 'log') color = 'bg-cyan-500/20 text-cyan-300 border border-cyan-500/30';
  3395. return `<span class="px-2 py-0.5 rounded text-[10px] font-mono font-semibold ${color}">${escapeHtml(nativeFirewallTarget(action))}</span>`;
  3396. }
  3397. function switchFWSubTab(tab) {
  3398. state.fwSubTab = tab;
  3399. const tabs = ['filter', 'nat', 'mangle', 'addrlist', 'geo', 'connections'];
  3400. tabs.forEach(t => {
  3401. const panel = document.getElementById(`fw-subtab-${t}`);
  3402. const btn = document.getElementById(`fw-subtab-btn-${t}`);
  3403. if (panel) {
  3404. if (t === tab) panel.classList.remove('hidden');
  3405. else panel.classList.add('hidden');
  3406. }
  3407. if (btn) {
  3408. if (t === tab) {
  3409. 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';
  3410. } else {
  3411. 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';
  3412. }
  3413. }
  3414. });
  3415. const addBtn = document.getElementById('fw-primary-add-btn');
  3416. if (addBtn) {
  3417. if (tab === 'filter') addBtn.innerHTML = '<span>+ Add Filter Rule</span>';
  3418. else if (tab === 'nat') addBtn.innerHTML = '<span>+ Add NAT Rule</span>';
  3419. else if (tab === 'mangle') addBtn.innerHTML = '<span>+ Add Mangle Rule</span>';
  3420. else if (tab === 'addrlist') addBtn.innerHTML = '<span>+ Add Address List</span>';
  3421. else if (tab === 'geo') addBtn.innerHTML = '<span>⚙️ Schedule Settings</span>';
  3422. else if (tab === 'connections') addBtn.innerHTML = '<span>Refresh Flows</span>';
  3423. }
  3424. if (tab === 'filter') renderFilterRules();
  3425. else if (tab === 'nat') renderNATRules();
  3426. else if (tab === 'mangle') renderMangleRules();
  3427. else if (tab === 'addrlist') renderAddressLists();
  3428. else if (tab === 'geo') loadGeoIP();
  3429. else if (tab === 'connections') loadConnections();
  3430. setTimeout(initTableSorting, 50);
  3431. }
  3432. function openCurrentFWModal() {
  3433. if (state.fwSubTab === 'filter') openAddFilterModal();
  3434. else if (state.fwSubTab === 'nat') openAddNATModal();
  3435. else if (state.fwSubTab === 'mangle') openAddMangleModal();
  3436. else if (state.fwSubTab === 'addrlist') openAddAddrListModal();
  3437. else if (state.fwSubTab === 'geo') openGeoIntervalModal();
  3438. else if (state.fwSubTab === 'connections') loadConnections();
  3439. }
  3440. async function loadFirewall(populateDropdowns = true) {
  3441. try {
  3442. const [summaryRes, filterRes, natRes, mangleRes, addrlistRes, geoStatusRes, geoCountriesRes] = await Promise.all([
  3443. fetch(`${API_BASE}/firewall/summary`),
  3444. fetch(`${API_BASE}/firewall/filter`),
  3445. fetch(`${API_BASE}/firewall/nat`),
  3446. fetch(`${API_BASE}/firewall/mangle`),
  3447. fetch(`${API_BASE}/firewall/address-lists`),
  3448. fetch(`${API_BASE}/firewall/geoip/status`),
  3449. fetch(`${API_BASE}/firewall/geoip/countries`)
  3450. ]);
  3451. if (summaryRes.ok) state.fwSummary = await summaryRes.json();
  3452. const applyError = document.getElementById('fw-apply-error');
  3453. if (applyError) {
  3454. applyError.textContent = state.fwSummary?.last_error ? 'Firewall configuration was not applied: ' + state.fwSummary.last_error : '';
  3455. applyError.classList.toggle('hidden', !state.fwSummary?.last_error);
  3456. }
  3457. if (filterRes.ok) state.filterRules = await filterRes.json();
  3458. if (natRes.ok) state.natRules = await natRes.json();
  3459. if (mangleRes.ok) state.mangleRules = await mangleRes.json();
  3460. if (addrlistRes.ok) state.addressLists = await addrlistRes.json();
  3461. if (geoStatusRes.ok) state.geoStatus = await geoStatusRes.json();
  3462. if (geoCountriesRes.ok) state.geoCountries = await geoCountriesRes.json();
  3463. 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); }
  3464. // Badges
  3465. const bFilter = document.getElementById('fw-badge-filter');
  3466. if (bFilter) bFilter.innerText = (state.filterRules || []).length;
  3467. const bNat = document.getElementById('fw-badge-nat');
  3468. if (bNat) bNat.innerText = (state.natRules || []).length;
  3469. const bMangle = document.getElementById('fw-badge-mangle');
  3470. if (bMangle) bMangle.innerText = (state.mangleRules || []).length;
  3471. const bAddr = document.getElementById('fw-badge-addrlist');
  3472. if (bAddr) bAddr.innerText = (state.addressLists || []).length;
  3473. const bGeo = document.getElementById('fw-badge-geo');
  3474. if (bGeo) bGeo.innerText = state.geoStatus?.enabled_count || 0;
  3475. const sigFilter = (state.filterRules || []).map(r => JSON.stringify({...r, packets: 0, bytes: 0})).join(';');
  3476. const sigNat = (state.natRules || []).map(r => JSON.stringify({...r, packets: 0, bytes: 0})).join(';');
  3477. const sigMangle = (state.mangleRules || []).map(r => JSON.stringify({...r, packets: 0, bytes: 0})).join(';');
  3478. const sigAddr = (state.addressLists || []).map(a => JSON.stringify(a)).join(';');
  3479. const tbodyFilter = document.getElementById('filter-table-body');
  3480. if (tbodyFilter) {
  3481. if (populateDropdowns || tbodyFilter.dataset.sig !== sigFilter) {
  3482. tbodyFilter.dataset.sig = sigFilter;
  3483. renderFilterRules();
  3484. } else {
  3485. // In-place live stats update (ZERO flicker)
  3486. (state.filterRules || []).forEach(r => {
  3487. const p = document.getElementById(`filter-pkts-${r.id}`);
  3488. if (p) p.innerText = `${(r.packets || 0).toLocaleString()}p`;
  3489. const b = document.getElementById(`filter-bytes-${r.id}`);
  3490. if (b) b.innerText = formatTraffic(r.bytes || 0).replace('/s', '');
  3491. });
  3492. }
  3493. }
  3494. const tbodyNat = document.getElementById('nat-table-body');
  3495. if (tbodyNat) {
  3496. if (populateDropdowns || tbodyNat.dataset.sig !== sigNat) {
  3497. tbodyNat.dataset.sig = sigNat;
  3498. renderNATRules();
  3499. } else {
  3500. (state.natRules || []).forEach(r => {
  3501. const p = document.getElementById(`nat-pkts-${r.id}`);
  3502. if (p) p.innerText = `${(r.packets || 0).toLocaleString()}p`;
  3503. const b = document.getElementById(`nat-bytes-${r.id}`);
  3504. if (b) b.innerText = formatTraffic(r.bytes || 0).replace('/s', '');
  3505. });
  3506. }
  3507. }
  3508. const tbodyMangle = document.getElementById('mangle-table-body');
  3509. if (tbodyMangle) {
  3510. if (populateDropdowns || tbodyMangle.dataset.sig !== sigMangle) {
  3511. tbodyMangle.dataset.sig = sigMangle;
  3512. renderMangleRules();
  3513. } else {
  3514. (state.mangleRules || []).forEach(r => {
  3515. const p = document.getElementById(`mangle-pkts-${r.id}`);
  3516. if (p) p.innerText = `${(r.packets || 0).toLocaleString()}p`;
  3517. const b = document.getElementById(`mangle-bytes-${r.id}`);
  3518. if (b) b.innerText = formatTraffic(r.bytes || 0).replace('/s', '');
  3519. });
  3520. }
  3521. }
  3522. const tbodyAddr = document.getElementById('addrlist-table-body');
  3523. if (tbodyAddr && (populateDropdowns || tbodyAddr.dataset.sig !== sigAddr)) {
  3524. tbodyAddr.dataset.sig = sigAddr;
  3525. renderAddressLists();
  3526. }
  3527. renderGeoCountries();
  3528. if (state.fwSubTab === 'connections') {
  3529. loadConnections();
  3530. }
  3531. } catch (err) {
  3532. console.error('Failed to load firewall:', err);
  3533. }
  3534. }
  3535. // ----------------- Filter Rules -----------------
  3536. function renderFilterRules() {
  3537. const chainFilter = document.getElementById('filter-filter-chain')?.value || '';
  3538. const tbody = document.getElementById('filter-table-body');
  3539. const empty = document.getElementById('filter-empty');
  3540. if (!tbody) return;
  3541. tbody.innerHTML = '';
  3542. const rules = (state.filterRules || []).filter(r => !chainFilter || (r.chain || '').toLowerCase() === chainFilter);
  3543. document.getElementById('filter-count-badge').innerText = `${rules.length} Rules`;
  3544. if (rules.length === 0) {
  3545. empty?.classList.remove('hidden');
  3546. return;
  3547. }
  3548. empty?.classList.add('hidden');
  3549. rules.forEach((raw, idx) => {
  3550. const r = safeFirewallRow(raw);
  3551. const tr = document.createElement('tr');
  3552. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  3553. const ports = [r.src_port ? 's:' + r.src_port : '', r.dst_port ? 'd:' + r.dst_port : ''].filter(Boolean).join(' ');
  3554. const ifaces = [r.in_interface ? 'in:' + r.in_interface : '', r.out_interface ? 'out:' + r.out_interface : ''].filter(Boolean).join(' ');
  3555. let actionExtra = '';
  3556. if (r.action === 'reject') {
  3557. actionExtra = `<span class="block text-[10px] text-rose-300 font-mono mt-0.5">(${r.reject_with || 'icmp-net-unreach'})</span>`;
  3558. } else if (r.action === 'jump') {
  3559. actionExtra = `<span class="block text-[10px] text-yellow-300 font-mono mt-0.5">&rarr; ${r.jump_target || '-'}</span>`;
  3560. } else if (r.action.includes('address-list') || r.action.includes('address list')) {
  3561. actionExtra = `<span class="block text-[10px] text-emerald-300 font-mono mt-0.5">&rarr; ${r.address_list || '-'}</span>`;
  3562. } else if (r.action === 'log' && r.log_prefix) {
  3563. actionExtra = `<span class="block text-[10px] text-slate-400 font-mono mt-0.5">${r.log_prefix}</span>`;
  3564. }
  3565. tr.innerHTML = `
  3566. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  3567. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  3568. <td class="py-2.5 px-3 font-bold text-white">${(r.chain || '').toUpperCase()}</td>
  3569. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  3570. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  3571. <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>
  3572. <td class="py-2.5 px-3 text-amber-400">${ports || '-'}</td>
  3573. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  3574. <td class="py-2.5 px-3">${renderActionBadge(r.action)}${actionExtra}</td>
  3575. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  3576. <span class="text-slate-300" id="filter-pkts-${r.id}">${(r.packets || 0).toLocaleString()}p</span> /
  3577. <span class="text-slate-500" id="filter-bytes-${r.id}">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  3578. </td>
  3579. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  3580. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  3581. <button onclick="moveFilterRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  3582. <button onclick="moveFilterRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  3583. <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>
  3584. <button onclick="openEditFilterModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  3585. <button onclick="deleteFilterRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  3586. </td>
  3587. `;
  3588. tbody.appendChild(tr);
  3589. });
  3590. }
  3591. function formatTarget(addr, list, geo) {
  3592. const parts = [];
  3593. if (addr) parts.push(`<span>${addr}</span>`);
  3594. if (list) {
  3595. const inv = list.startsWith('!') ? '!' : '';
  3596. const clean = list.replace(/^!/, '');
  3597. 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>`);
  3598. }
  3599. if (geo) {
  3600. const inv = geo.startsWith('!') ? '!' : '';
  3601. const clean = geo.replace(/^!/, '').replace(/^geo:/, '');
  3602. 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>`);
  3603. }
  3604. if (parts.length === 0) return '<span class="text-slate-600">0.0.0.0/0</span>';
  3605. return parts.join(' ');
  3606. }
  3607. function populateInterfaceSelect(selectId, currentVal = '') {
  3608. const sel = document.getElementById(selectId);
  3609. if (!sel) return;
  3610. sel.innerHTML = '<option value="">(Any Interface)</option>';
  3611. (state.interfaces || []).forEach(i => {
  3612. const opt = document.createElement('option');
  3613. opt.value = i.name;
  3614. opt.innerText = `${i.name} (${i.role || i.type})`;
  3615. if (i.name === currentVal) opt.selected = true;
  3616. sel.appendChild(opt);
  3617. });
  3618. }
  3619. function populateAddressListSelect(selectId, currentVal = '') {
  3620. const sel = document.getElementById(selectId);
  3621. if (!sel) return;
  3622. sel.innerHTML = '<option value="">(None)</option>';
  3623. const cleanVal = (currentVal || '').replace(/^!/, '');
  3624. 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_'));
  3625. const customNames = Array.from(new Set([...(state.addressLists || []).map(a => a.name), ...ruleLists])).sort();
  3626. customNames.forEach(name => {
  3627. const count = (state.addressLists || []).filter(a => a.name === name).length;
  3628. const opt = document.createElement('option');
  3629. opt.value = name;
  3630. opt.innerText = `${name} (${count} entries)`;
  3631. if (name === cleanVal) opt.selected = true;
  3632. sel.appendChild(opt);
  3633. });
  3634. if (cleanVal && !Array.from(sel.options).some(option => option.value === cleanVal)) {
  3635. const opt = document.createElement('option');
  3636. opt.value = cleanVal;
  3637. opt.innerText = cleanVal;
  3638. opt.selected = true;
  3639. sel.appendChild(opt);
  3640. }
  3641. populateCommonAddrListDatalist();
  3642. }
  3643. function populateCommonAddrListDatalist() {
  3644. const dl = document.getElementById('fw-addrlist-datalist');
  3645. if (!dl) return;
  3646. dl.innerHTML = '';
  3647. const names = Array.from(new Set((state.addressLists || []).map(a => a.name).filter(Boolean))).sort();
  3648. names.forEach(name => {
  3649. const opt = document.createElement('option');
  3650. opt.value = name;
  3651. dl.appendChild(opt);
  3652. });
  3653. }
  3654. function populateGeoIPSelect(selectId, currentVal = '') {
  3655. const sel = document.getElementById(selectId);
  3656. if (!sel) return;
  3657. sel.innerHTML = '<option value="">(None)</option>';
  3658. const cleanVal = (currentVal || '').replace(/^!/, '').replace(/^geo:/, '').toUpperCase();
  3659. // Presets optgroup
  3660. const grpPresets = document.createElement('optgroup');
  3661. grpPresets.label = '⚡ Regional Presets';
  3662. const presets = [
  3663. { code: 'EU', label: '🇪🇺 European Union (EU - 27 countries)' },
  3664. { code: 'BALKANS', label: '🏛️ Balkans (GR, CY, BG, RO, AL, etc.)' },
  3665. { code: 'BLOCKLIST', label: '🛡️ High-Risk Blocklist (CN, RU, IR, KP, BY)' }
  3666. ];
  3667. presets.forEach(p => {
  3668. const opt = document.createElement('option');
  3669. opt.value = p.code;
  3670. opt.innerText = p.label;
  3671. if (p.code === cleanVal) opt.selected = true;
  3672. grpPresets.appendChild(opt);
  3673. });
  3674. sel.appendChild(grpPresets);
  3675. // All Countries optgroup
  3676. const grpCountries = document.createElement('optgroup');
  3677. grpCountries.label = '🌍 All Countries';
  3678. const countries = (state.geoCountries || []).slice().sort((a, b) => a.name.localeCompare(b.name));
  3679. countries.forEach(c => {
  3680. const opt = document.createElement('option');
  3681. opt.value = c.code;
  3682. const subnetsInfo = c.subnet_count ? ` [${c.subnet_count.toLocaleString()} subnets]` : '';
  3683. opt.innerText = `${c.name} (${c.code})${subnetsInfo}`;
  3684. if (c.code === cleanVal) opt.selected = true;
  3685. grpCountries.appendChild(opt);
  3686. });
  3687. sel.appendChild(grpCountries);
  3688. }
  3689. // ==================== FIREWALL FILTER MODAL (DEBTIK WEBFIG / WINBOX V4) ====================
  3690. function switchFwRuleTab(tab) {
  3691. state.activeFwRuleTab = tab;
  3692. document.querySelectorAll('.fw-rule-tab-btn').forEach(btn => {
  3693. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  3694. btn.classList.add('text-slate-400', 'border-transparent');
  3695. });
  3696. const activeBtn = document.getElementById(`fw-tab-btn-${tab}`);
  3697. if (activeBtn) {
  3698. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  3699. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  3700. }
  3701. document.querySelectorAll('.fw-rule-pane').forEach(p => p.classList.add('hidden'));
  3702. const activePane = document.getElementById(`fw-pane-${tab}`);
  3703. if (activePane) activePane.classList.remove('hidden');
  3704. if (tab === 'statistics') {
  3705. startFwStatPolling();
  3706. } else {
  3707. stopFwStatPolling();
  3708. }
  3709. }
  3710. function toggleFwField(fieldKey, expand) {
  3711. const plusBtn = document.getElementById(`fw-plus-${fieldKey}`);
  3712. const fieldBox = document.getElementById(`fw-field-${fieldKey}`);
  3713. if (!plusBtn || !fieldBox) return;
  3714. if (expand) {
  3715. plusBtn.classList.add('hidden');
  3716. fieldBox.classList.remove('hidden');
  3717. const valInput = document.getElementById(`fw-val-${fieldKey}`);
  3718. if (valInput) valInput.focus();
  3719. } else {
  3720. fieldBox.classList.add('hidden');
  3721. plusBtn.classList.remove('hidden');
  3722. const valInput = document.getElementById(`fw-val-${fieldKey}`);
  3723. if (valInput) {
  3724. if (valInput.tagName === 'SELECT') {
  3725. valInput.selectedIndex = 0;
  3726. } else {
  3727. valInput.value = '';
  3728. }
  3729. }
  3730. const invInput = document.getElementById(`fw-inv-${fieldKey}`);
  3731. if (invInput) invInput.checked = false;
  3732. if (fieldKey === 'cs') {
  3733. ['filter-modal-cs-established', 'filter-modal-cs-related', 'filter-modal-cs-new', 'filter-modal-cs-invalid', 'filter-modal-cs-untracked'].forEach(id => {
  3734. const el = document.getElementById(id);
  3735. if (el) el.checked = false;
  3736. });
  3737. }
  3738. if (fieldKey === 'natstate') {
  3739. ['filter-modal-nat-srcnat', 'filter-modal-nat-dstnat'].forEach(id => {
  3740. const el = document.getElementById(id);
  3741. if (el) el.checked = false;
  3742. });
  3743. }
  3744. if (fieldKey === 'days') {
  3745. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3746. const el = document.getElementById(`fw-day-${d}`);
  3747. if (el) el.checked = true;
  3748. });
  3749. }
  3750. }
  3751. }
  3752. function setFwFieldVal(fieldKey, value, hasInvert = false) {
  3753. if (fieldKey === 'ipsec' && typeof value === 'string') value = value.replace(':', ',');
  3754. if (value !== undefined && value !== null && value !== '' && !(fieldKey === 'proto' && value === 'all')) {
  3755. toggleFwField(fieldKey, true);
  3756. let strVal = String(value);
  3757. if (hasInvert) {
  3758. const inv = strVal.startsWith('!');
  3759. if (inv) strVal = strVal.slice(1);
  3760. const invEl = document.getElementById(`fw-inv-${fieldKey}`);
  3761. if (invEl) invEl.checked = inv;
  3762. else if (inv) strVal = '!'+strVal;
  3763. }
  3764. const valEl = document.getElementById(`fw-val-${fieldKey}`);
  3765. 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; }
  3766. } else {
  3767. toggleFwField(fieldKey, false);
  3768. }
  3769. }
  3770. function getFwFieldVal(fieldKey, hasInvert = false) {
  3771. const fieldBox = document.getElementById(`fw-field-${fieldKey}`);
  3772. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  3773. const valEl = document.getElementById(`fw-val-${fieldKey}`);
  3774. let v = valEl ? valEl.value.trim() : '';
  3775. if (!v) return '';
  3776. if (hasInvert) {
  3777. const invEl = document.getElementById(`fw-inv-${fieldKey}`);
  3778. if (invEl && invEl.checked) {
  3779. v = '!' + v.replace(/^!/, '');
  3780. }
  3781. }
  3782. return v;
  3783. }
  3784. function toggleMaximizeFilterModal() {
  3785. const win = document.getElementById('filter-modal-window');
  3786. if (!win) return;
  3787. if (win.classList.contains('max-w-[720px]')) {
  3788. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  3789. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  3790. } else {
  3791. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  3792. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  3793. }
  3794. }
  3795. function openAddFilterModal() {
  3796. const tos = document.getElementById('fw-val-tos'); if (tos) tos.value = '';
  3797. switchFwRuleTab('general');
  3798. setFirewallDays('fw', '');
  3799. const badge = document.getElementById('fw-modal-badge');
  3800. if (badge) badge.innerText = 'New...';
  3801. document.getElementById('filter-modal-id').value = '';
  3802. document.getElementById('filter-modal-family').value = '4';
  3803. document.getElementById('filter-modal-enabled').checked = true;
  3804. document.getElementById('filter-modal-comment').value = '';
  3805. document.getElementById('filter-modal-chain').value = 'forward';
  3806. document.getElementById('filter-modal-action').value = 'accept';
  3807. document.getElementById('filter-modal-log').checked = false;
  3808. populateInterfaceSelect('fw-val-iniface');
  3809. populateInterfaceSelect('fw-val-outiface');
  3810. populateAddressListSelect('fw-val-srclist');
  3811. populateAddressListSelect('fw-val-dstlist');
  3812. populateGeoIPSelect('fw-val-srcgeo');
  3813. populateGeoIPSelect('fw-val-dstgeo');
  3814. const allFieldKeys = [
  3815. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  3816. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  3817. 'routingmark', 'conntype', 'cs', 'natstate',
  3818. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  3819. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  3820. 'ipsec', 'tlshost', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  3821. 'pktsize', 'random', 'tcpflags', 'icmpoptions', 'ipv4options', 'ttl',
  3822. 'time', 'days', 'limit', 'dstlimit', 'psd', 'logprefix'
  3823. ];
  3824. allFieldKeys.forEach(k => toggleFwField(k, false));
  3825. resetRuleCounterDisplay();
  3826. toggleFilterActionFields();
  3827. refreshFirewallRejectTypes();
  3828. document.getElementById('filter-modal').classList.remove('hidden');
  3829. }
  3830. function openEditFilterModal(id) {
  3831. id = decodeURIComponent(id);
  3832. const r = (state.filterRules || []).find(rule => rule.id === id);
  3833. if (!r) return;
  3834. switchFwRuleTab('general');
  3835. const badge = document.getElementById('fw-modal-badge');
  3836. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  3837. document.getElementById('filter-modal-id').value = r.id;
  3838. document.getElementById('filter-modal-family').value = String(r.ip_version || 4);
  3839. document.getElementById('filter-modal-enabled').checked = !r.disabled;
  3840. document.getElementById('filter-modal-comment').value = r.comment || '';
  3841. document.getElementById('filter-modal-chain').value = r.chain || 'forward';
  3842. setFirewallActionSelection('filter', r.action || 'accept');
  3843. document.getElementById('filter-modal-log').checked = !!r.log;
  3844. populateInterfaceSelect('fw-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  3845. populateInterfaceSelect('fw-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  3846. populateAddressListSelect('fw-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  3847. populateAddressListSelect('fw-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  3848. populateGeoIPSelect('fw-val-srcgeo', r.src_geoip || '');
  3849. populateGeoIPSelect('fw-val-dstgeo', r.dst_geoip || '');
  3850. setFwFieldVal('src', r.src_address, true);
  3851. setFwFieldVal('dst', r.dst_address, true);
  3852. setFwFieldVal('srclist', r.src_address_list, true);
  3853. setFwFieldVal('dstlist', r.dst_address_list, true);
  3854. setFwFieldVal('srcgeo', r.src_geoip, true);
  3855. setFwFieldVal('dstgeo', r.dst_geoip, true);
  3856. if (r.protocol && r.protocol !== 'all') {
  3857. setFwFieldVal('proto', r.protocol, true);
  3858. } else {
  3859. toggleFwField('proto', false);
  3860. }
  3861. setFwFieldVal('sport', r.src_port, true);
  3862. setFwFieldVal('dport', r.dst_port, true);
  3863. setFwFieldVal('anyport', r.any_port, true);
  3864. setFwFieldVal('iniface', r.in_interface, true);
  3865. setFwFieldVal('outiface', r.out_interface, true);
  3866. setFwFieldVal('inifacelist', r.in_interface_list, true);
  3867. setFwFieldVal('outifacelist', r.out_interface_list, true);
  3868. setFwFieldVal('pktmark', r.packet_mark, true);
  3869. setFwFieldVal('connmark', r.connection_mark, true);
  3870. setFwFieldVal('routingmark', r.routing_mark, true);
  3871. setFwFieldVal('conntype', r.connection_type, false);
  3872. const states = r.connection_state || [];
  3873. if (states.length > 0) {
  3874. toggleFwField('cs', true);
  3875. document.getElementById('filter-modal-cs-established').checked = states.includes('established');
  3876. document.getElementById('filter-modal-cs-related').checked = states.includes('related');
  3877. document.getElementById('filter-modal-cs-new').checked = states.includes('new');
  3878. document.getElementById('filter-modal-cs-invalid').checked = states.includes('invalid');
  3879. document.getElementById('filter-modal-cs-untracked').checked = states.includes('untracked');
  3880. } else {
  3881. toggleFwField('cs', false);
  3882. }
  3883. const natStates = r.connection_nat_state || [];
  3884. if (natStates.length > 0) {
  3885. toggleFwField('natstate', true);
  3886. document.getElementById('filter-modal-nat-srcnat').checked = natStates.includes('srcnat');
  3887. document.getElementById('filter-modal-nat-dstnat').checked = natStates.includes('dstnat');
  3888. } else {
  3889. toggleFwField('natstate', false);
  3890. }
  3891. // Advanced tab fields
  3892. setFwFieldVal('layer7', r.layer7_protocol, false);
  3893. setFwFieldVal('content', r.content, false);
  3894. setFwFieldVal('connbytes', r.connection_bytes, false);
  3895. setFwFieldVal('connrate', r.connection_rate, false);
  3896. setFwFieldVal('pcc', r.pcc, false);
  3897. setFwFieldVal('srcmac', r.src_mac_address, true);
  3898. setFwFieldVal('outbridgeport', r.out_bridge_port, false);
  3899. setFwFieldVal('inbridgeport', r.in_bridge_port, false);
  3900. setFwFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  3901. setFwFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  3902. setFwFieldVal('ipsec', r.ipsec_policy, false);
  3903. setFwFieldVal('tlshost', r.tls_host, false);
  3904. setFwFieldVal('ingresspriority', r.ingress_priority, false);
  3905. setFwFieldVal('priority', r.priority, false);
  3906. setFwFieldVal('dscp', r.dscp, false);
  3907. setFwFieldVal('tcpmss', r.tcp_mss, false);
  3908. { const tosEl = document.getElementById('fw-val-tos'); if (tosEl) tosEl.value = r.tos || ''; }
  3909. setFwFieldVal('pktsize', r.packet_size, false);
  3910. setFwFieldVal('random', r.random, false);
  3911. setFwFieldVal('tcpflags', r.tcp_flags, false);
  3912. setFwFieldVal('icmpoptions', r.icmp_options, false);
  3913. setFwFieldVal('ipv4options', r.ipv4_options, false);
  3914. setFwFieldVal('ttl', r.ttl, false);
  3915. // Extra tab fields
  3916. setFwFieldVal('time', r.time, false);
  3917. if (r.days) {
  3918. toggleFwField('days', true);
  3919. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3920. const chk = document.getElementById(`fw-day-${d}`);
  3921. if (chk) chk.checked = r.days.toLowerCase().includes(d);
  3922. });
  3923. } else {
  3924. toggleFwField('days', false);
  3925. }
  3926. setFwFieldVal('limit', r.limit, false);
  3927. setFwFieldVal('dstlimit', r.dst_limit, false);
  3928. setFwFieldVal('psd', r.psd, false);
  3929. // Action fields
  3930. if (r.reject_with) {
  3931. const rwEl = document.getElementById('filter-modal-rejectwith');
  3932. if (rwEl) rwEl.value = r.reject_with;
  3933. }
  3934. if (r.jump_target) {
  3935. const jtEl = document.getElementById('filter-modal-jumptarget');
  3936. if (jtEl) jtEl.value = r.jump_target;
  3937. }
  3938. if (r.address_list) {
  3939. const alEl = document.getElementById('filter-modal-action-addrlist');
  3940. if (alEl) alEl.value = r.address_list;
  3941. }
  3942. if (r.address_list_timeout) {
  3943. const toEl = document.getElementById('filter-modal-action-timeout');
  3944. if (toEl) toEl.value = r.address_list_timeout;
  3945. }
  3946. setFwFieldVal('logprefix', r.log_prefix, false);
  3947. // Statistics
  3948. const bEl = document.getElementById('fw-stat-bytes');
  3949. const pEl = document.getElementById('fw-stat-packets');
  3950. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  3951. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  3952. state.fwLastBytes = r.bytes || 0;
  3953. state.fwLastPackets = r.packets || 0;
  3954. state.fwLastTimestamp = Date.now();
  3955. state.fwStatRateHistory = new Array(30).fill(0);
  3956. state.fwStatPktHistory = new Array(30).fill(0);
  3957. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  3958. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  3959. toggleFilterActionFields();
  3960. refreshFirewallRejectTypes();
  3961. document.getElementById('filter-modal').classList.remove('hidden');
  3962. }
  3963. function closeFilterModal() {
  3964. stopFwStatPolling();
  3965. document.getElementById('filter-modal').classList.add('hidden');
  3966. }
  3967. function toggleFilterActionFields() {
  3968. const act = document.getElementById('filter-modal-action')?.value || 'accept';
  3969. const rejectBox = document.getElementById('filter-action-reject-box');
  3970. const jumpBox = document.getElementById('filter-action-jump-box');
  3971. const addrBox = document.getElementById('filter-action-addrlist-box');
  3972. if (rejectBox) {
  3973. if (act === 'reject') rejectBox.classList.remove('hidden');
  3974. else rejectBox.classList.add('hidden');
  3975. }
  3976. if (jumpBox) {
  3977. if (act === 'jump') jumpBox.classList.remove('hidden');
  3978. else jumpBox.classList.add('hidden');
  3979. }
  3980. if (addrBox) {
  3981. if (act === 'add-dst-to-address-list' || act === 'add-src-to-address-list' || act.includes('address-list') || act.includes('address list')) {
  3982. addrBox.classList.remove('hidden');
  3983. } else {
  3984. addrBox.classList.add('hidden');
  3985. }
  3986. }
  3987. if (act === 'log') {
  3988. const logEl = document.getElementById('filter-modal-log');
  3989. if (logEl) logEl.checked = true;
  3990. toggleFwField('logprefix', true);
  3991. }
  3992. }
  3993. function toggleFwLogPrefix() {
  3994. const isLog = document.getElementById('filter-modal-log')?.checked;
  3995. toggleFwField('logprefix', !!isLog);
  3996. }
  3997. function copyFilterRule() {
  3998. document.getElementById('filter-modal-id').value = '';
  3999. const badge = document.getElementById('fw-modal-badge');
  4000. if (badge) badge.innerText = 'New...';
  4001. showToast('Rule Cloned', 'Ready to save as a new rule copy', 'info');
  4002. }
  4003. function resetRuleCounterDisplay() {
  4004. state.fwStatRateHistory = new Array(30).fill(0);
  4005. state.fwStatPktHistory = new Array(30).fill(0);
  4006. state.fwLastBytes = 0;
  4007. state.fwLastPackets = 0;
  4008. state.fwLastTimestamp = Date.now();
  4009. const bEl = document.getElementById('fw-stat-bytes');
  4010. const pEl = document.getElementById('fw-stat-packets');
  4011. const rEl = document.getElementById('fw-stat-rate');
  4012. const prEl = document.getElementById('fw-stat-pktrate');
  4013. if (bEl) bEl.value = '0 B';
  4014. if (pEl) pEl.value = '0';
  4015. if (rEl) rEl.value = '0 bps';
  4016. if (prEl) prEl.value = '0 p/s';
  4017. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  4018. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  4019. showToast('Counters Reset', 'Rule counter display reset to 0', 'info');
  4020. }
  4021. async function resetAllFwCounters() {
  4022. try {
  4023. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  4024. if (res.ok) {
  4025. resetRuleCounterDisplay();
  4026. showToast('All Counters Reset', 'All firewall counters zeroed', 'success');
  4027. loadFirewall(false);
  4028. }
  4029. } catch (err) {
  4030. showToast('Error', err.message, 'error');
  4031. }
  4032. }
  4033. async function applyFilterRule(closeAfter = false) {
  4034. const id = document.getElementById('filter-modal-id').value;
  4035. if (!reviewLegacyFirewallSettings('filter', id)) return;
  4036. let selectedDays; try { selectedDays = getFirewallDays('fw'); } catch(error) { showToast('Error', error.message, 'error'); return; }
  4037. const chain = document.getElementById('filter-modal-chain').value;
  4038. const action = document.getElementById('filter-modal-action').value;
  4039. const comment = document.getElementById('filter-modal-comment').value.trim();
  4040. const enabled = document.getElementById('filter-modal-enabled').checked;
  4041. const src = getFwFieldVal('src', true);
  4042. const dst = getFwFieldVal('dst', true);
  4043. const srclist = getFwFieldVal('srclist', true);
  4044. const dstlist = getFwFieldVal('dstlist', true);
  4045. const srcgeo = getFwFieldVal('srcgeo', true);
  4046. const dstgeo = getFwFieldVal('dstgeo', true);
  4047. const proto = getFwFieldVal('proto', true);
  4048. const sport = getFwFieldVal('sport', true);
  4049. const dport = getFwFieldVal('dport', true);
  4050. const anyport = getFwFieldVal('anyport', true);
  4051. if ((sport || dport || anyport) && !['tcp', 'udp'].includes(proto)) {
  4052. switchFwRuleTab('general'); toggleFwField('proto', true);
  4053. showToast('Select protocol', 'Port matches require TCP or UDP without protocol inversion.', 'error'); document.getElementById('fw-val-proto').focus(); return;
  4054. }
  4055. const iniface = getFwFieldVal('iniface', true);
  4056. const outiface = getFwFieldVal('outiface', true);
  4057. const inifacelist = getFwFieldVal('inifacelist', true);
  4058. const outifacelist = getFwFieldVal('outifacelist', true);
  4059. const pktmark = getFwFieldVal('pktmark', true);
  4060. const connmark = getFwFieldVal('connmark', true);
  4061. const routingmark = getFwFieldVal('routingmark', true);
  4062. const conntype = getFwFieldVal('conntype', false);
  4063. const states = [];
  4064. const csBox = document.getElementById('fw-field-cs');
  4065. if (csBox && !csBox.classList.contains('hidden')) {
  4066. if (document.getElementById('filter-modal-cs-established')?.checked) states.push('established');
  4067. if (document.getElementById('filter-modal-cs-related')?.checked) states.push('related');
  4068. if (document.getElementById('filter-modal-cs-new')?.checked) states.push('new');
  4069. if (document.getElementById('filter-modal-cs-invalid')?.checked) states.push('invalid');
  4070. if (document.getElementById('filter-modal-cs-untracked')?.checked) states.push('untracked');
  4071. }
  4072. const natStates = [];
  4073. const natBox = document.getElementById('fw-field-natstate');
  4074. if (natBox && !natBox.classList.contains('hidden')) {
  4075. if (document.getElementById('filter-modal-nat-srcnat')?.checked) natStates.push('srcnat');
  4076. if (document.getElementById('filter-modal-nat-dstnat')?.checked) natStates.push('dstnat');
  4077. }
  4078. const payload = {
  4079. ip_version: Number(document.getElementById('filter-modal-family').value),
  4080. id,
  4081. chain,
  4082. action,
  4083. protocol: proto || 'all',
  4084. src_address: src,
  4085. dst_address: dst,
  4086. src_port: sport,
  4087. dst_port: dport,
  4088. any_port: anyport,
  4089. in_interface: iniface,
  4090. out_interface: outiface,
  4091. in_interface_list: inifacelist,
  4092. out_interface_list: outifacelist,
  4093. packet_mark: pktmark,
  4094. connection_mark: connmark,
  4095. routing_mark: routingmark,
  4096. connection_type: conntype,
  4097. connection_state: states,
  4098. connection_nat_state: natStates,
  4099. src_address_list: srclist,
  4100. dst_address_list: dstlist,
  4101. src_geoip: srcgeo,
  4102. dst_geoip: dstgeo,
  4103. comment,
  4104. disabled: !enabled,
  4105. // Advanced tab
  4106. content: getFwFieldVal('content', false),
  4107. src_mac_address: getFwFieldVal('srcmac', true),
  4108. out_bridge_port: getFwFieldVal('outbridgeport', false),
  4109. in_bridge_port: getFwFieldVal('inbridgeport', false),
  4110. ipsec_policy: getFwFieldVal('ipsec', false),
  4111. dscp: getFwFieldVal('dscp', false),
  4112. tcp_mss: getFwFieldVal('tcpmss', false),
  4113. tos: document.getElementById('fw-val-tos')?.value || '',
  4114. packet_size: getFwFieldVal('pktsize', false),
  4115. random: getFwFieldVal('random', false),
  4116. tcp_flags: getFwFieldVal('tcpflags', false),
  4117. icmp_options: getFwFieldVal('icmpoptions', false),
  4118. ttl: getFwFieldVal('ttl', false),
  4119. days: selectedDays,
  4120. // Extra tab
  4121. time: getFwFieldVal('time', false),
  4122. limit: getFwFieldVal('limit', false),
  4123. // Action tab
  4124. reject_with: action === 'reject' ? (document.getElementById('filter-modal-rejectwith')?.value || '') : '',
  4125. jump_target: action === 'jump' ? (document.getElementById('filter-modal-jumptarget')?.value || '') : '',
  4126. address_list: action.startsWith('add-') ? (document.getElementById('filter-modal-action-addrlist')?.value || '') : '',
  4127. address_list_timeout: action.startsWith('add-') ? (document.getElementById('filter-modal-action-timeout')?.value || '') : '',
  4128. log: document.getElementById('filter-modal-log')?.checked || false,
  4129. log_prefix: getFwFieldVal('logprefix', false)
  4130. };
  4131. try {
  4132. const res = await fetch(`${API_BASE}/firewall/filter`, {
  4133. method: 'POST',
  4134. headers: { 'Content-Type': 'application/json' },
  4135. body: JSON.stringify(payload)
  4136. });
  4137. if (res.ok) {
  4138. const data = await res.json();
  4139. showToast('Filter Rule Saved', 'Rule applied successfully to firewall', 'success');
  4140. loadFirewall(false);
  4141. if (closeAfter) {
  4142. closeFilterModal();
  4143. } else {
  4144. if (data.id) {
  4145. document.getElementById('filter-modal-id').value = data.id;
  4146. const badge = document.getElementById('fw-modal-badge');
  4147. if (badge) badge.innerText = `#${data.id}`;
  4148. }
  4149. }
  4150. } else {
  4151. const err = await res.json();
  4152. showToast('Error', err.message || 'Failed to save rule', 'error');
  4153. }
  4154. } catch (err) {
  4155. showToast('Error', err.message, 'error');
  4156. }
  4157. }
  4158. function submitSaveFilterRule(e) {
  4159. if (e && e.preventDefault) e.preventDefault();
  4160. return applyFilterRule(true);
  4161. }
  4162. function startFwStatPolling() {
  4163. stopFwStatPolling();
  4164. pollRuleStats();
  4165. state.fwStatInterval = setInterval(pollRuleStats, 1000);
  4166. }
  4167. function stopFwStatPolling() {
  4168. if (state.fwStatInterval) {
  4169. clearInterval(state.fwStatInterval);
  4170. state.fwStatInterval = null;
  4171. }
  4172. }
  4173. async function pollRuleStats() {
  4174. const id = document.getElementById('filter-modal-id')?.value;
  4175. if (!id) {
  4176. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory || new Array(30).fill(0), 'bps', 'fw-stat-legend-rate');
  4177. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory || new Array(30).fill(0), 'p/s', 'fw-stat-legend-pktrate');
  4178. return;
  4179. }
  4180. try {
  4181. const res = await fetch(`${API_BASE}/firewall/filter`);
  4182. if (!res.ok) return;
  4183. const rules = await res.json();
  4184. const r = rules.find(x => x.id === id);
  4185. if (!r) return;
  4186. const now = Date.now();
  4187. const dt = Math.max(0.2, (now - (state.fwLastTimestamp || now)) / 1000);
  4188. state.fwLastTimestamp = now;
  4189. const curBytes = r.bytes || 0;
  4190. const curPackets = r.packets || 0;
  4191. const deltaBytes = Math.max(0, curBytes - (state.fwLastBytes ?? curBytes));
  4192. const deltaPkts = Math.max(0, curPackets - (state.fwLastPackets ?? curPackets));
  4193. state.fwLastBytes = curBytes;
  4194. state.fwLastPackets = curPackets;
  4195. const rateBps = Math.round((deltaBytes * 8) / dt);
  4196. const ratePkt = Math.round(deltaPkts / dt);
  4197. if (!state.fwStatRateHistory) state.fwStatRateHistory = new Array(30).fill(0);
  4198. if (!state.fwStatPktHistory) state.fwStatPktHistory = new Array(30).fill(0);
  4199. state.fwStatRateHistory.push(rateBps);
  4200. if (state.fwStatRateHistory.length > 30) state.fwStatRateHistory.shift();
  4201. state.fwStatPktHistory.push(ratePkt);
  4202. if (state.fwStatPktHistory.length > 30) state.fwStatPktHistory.shift();
  4203. const bEl = document.getElementById('fw-stat-bytes');
  4204. const pEl = document.getElementById('fw-stat-packets');
  4205. const rEl = document.getElementById('fw-stat-rate');
  4206. const prEl = document.getElementById('fw-stat-pktrate');
  4207. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  4208. if (pEl) pEl.value = curPackets.toLocaleString();
  4209. if (rEl) rEl.value = formatBps(rateBps);
  4210. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  4211. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  4212. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  4213. } catch (e) {
  4214. console.error('Error polling rule stats', e);
  4215. }
  4216. }
  4217. function formatBps(bps) {
  4218. if (bps >= 1000000000) return (bps / 1000000000).toFixed(1) + ' Gbps';
  4219. if (bps >= 1000000) return (bps / 1000000).toFixed(1) + ' Mbps';
  4220. if (bps >= 1000) return (bps / 1000).toFixed(1) + ' kbps';
  4221. return bps + ' bps';
  4222. }
  4223. function renderFwSparkline(svgId, dataArray, unit, legendId) {
  4224. const svg = document.getElementById(svgId);
  4225. if (!svg) return;
  4226. const w = 500;
  4227. const h = 100;
  4228. const paddingRight = 45;
  4229. const graphWidth = w - paddingRight;
  4230. const maxVal = Math.max(5, ...dataArray);
  4231. const currentVal = dataArray[dataArray.length - 1] || 0;
  4232. const leg = document.getElementById(legendId);
  4233. if (leg) {
  4234. leg.innerText = unit === 'bps' ? formatBps(currentVal) : `${currentVal.toLocaleString()} p/s`;
  4235. }
  4236. let gridLines = '';
  4237. for (let i = 0; i <= 5; i++) {
  4238. const y = 8 + (i * (h - 18) / 5);
  4239. const valAtLevel = Math.round(maxVal * (5 - i) / 5);
  4240. const label = unit === 'bps' ? formatBps(valAtLevel) : `${valAtLevel} p/s`;
  4241. gridLines += `
  4242. <line x1="0" y1="${y.toFixed(1)}" x2="${graphWidth}" y2="${y.toFixed(1)}" stroke="#1e2c3e" stroke-width="1" />
  4243. <text x="${w - 2}" y="${(y + 3).toFixed(1)}" fill="#64748b" font-size="9" font-family="monospace" text-anchor="end">${label}</text>
  4244. `;
  4245. }
  4246. const step = graphWidth / (dataArray.length - 1);
  4247. const points = dataArray.map((val, idx) => {
  4248. const x = idx * step;
  4249. const y = (h - 10) - (val / maxVal) * (h - 20);
  4250. return `${x.toFixed(1)},${y.toFixed(1)}`;
  4251. });
  4252. const polylineStr = points.join(' ');
  4253. const areaPath = `M 0,${h - 10} L ${polylineStr} L ${graphWidth},${h - 10} Z`;
  4254. svg.innerHTML = `
  4255. ${gridLines}
  4256. <path d="${areaPath}" fill="rgba(14, 165, 233, 0.12)" />
  4257. <polyline fill="none" stroke="#38bdf8" stroke-width="1.8" stroke-linejoin="round" points="${polylineStr}" />
  4258. <circle cx="${graphWidth}" cy="${points[points.length - 1].split(',')[1]}" r="3" fill="#38bdf8" />
  4259. `;
  4260. }
  4261. async function moveFilterRule(id, dir) {
  4262. id = decodeURIComponent(id);
  4263. try {
  4264. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/move`, {
  4265. method: 'POST',
  4266. headers: { 'Content-Type': 'application/json' },
  4267. body: JSON.stringify({ direction: dir })
  4268. });
  4269. if (!res.ok) throw new Error(await responseError(res));
  4270. await loadFirewall(false);
  4271. } catch (err) {
  4272. showToast('Error', err.message, 'error');
  4273. }
  4274. }
  4275. async function toggleFilterRuleState(id, disabled) {
  4276. id = decodeURIComponent(id);
  4277. try {
  4278. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/state`, {
  4279. method: 'POST',
  4280. headers: { 'Content-Type': 'application/json' },
  4281. body: JSON.stringify({ disabled })
  4282. });
  4283. if (!res.ok) throw new Error(await responseError(res));
  4284. await loadFirewall(false);
  4285. } catch (err) {
  4286. showToast('Error', err.message, 'error');
  4287. }
  4288. }
  4289. async function deleteFilterRule(id) {
  4290. id = decodeURIComponent(id);
  4291. if (!confirm('Are you sure you want to delete this filter rule?')) return;
  4292. try {
  4293. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4294. if (!res.ok) throw new Error(await responseError(res));
  4295. {
  4296. showToast('Deleted', 'Filter rule removed', 'success');
  4297. loadFirewall(false);
  4298. }
  4299. } catch (err) {
  4300. showToast('Error', err.message, 'error');
  4301. }
  4302. }
  4303. // ----------------- NAT Rules -----------------
  4304. function renderNATRules() {
  4305. const chainFilter = document.getElementById('nat-filter-chain')?.value || '';
  4306. const tbody = document.getElementById('nat-table-body');
  4307. const empty = document.getElementById('nat-empty');
  4308. if (!tbody) return;
  4309. tbody.innerHTML = '';
  4310. const rules = (state.natRules || []).filter(r => !chainFilter || nativeNATChain(r.chain) === chainFilter);
  4311. document.getElementById('nat-count-badge').innerText = `${rules.length} Rules`;
  4312. if (rules.length === 0) {
  4313. empty?.classList.remove('hidden');
  4314. return;
  4315. }
  4316. empty?.classList.add('hidden');
  4317. rules.forEach((raw, idx) => {
  4318. const r = safeFirewallRow(raw);
  4319. const tr = document.createElement('tr');
  4320. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  4321. let toTarget = '-';
  4322. if (r.action === 'jump') {
  4323. toTarget = `<span class="text-yellow-300 font-mono font-bold">&rarr; ${r.jump_target || '-'}</span>`;
  4324. } else if (r.action.includes('address-list') || r.action.includes('address list')) {
  4325. toTarget = `<span class="text-emerald-300 font-mono font-bold">&rarr; ${r.address_list || '-'}</span>`;
  4326. } else if (r.action === 'redirect') {
  4327. toTarget = `<span class="text-amber-300 font-mono font-bold">ports:${r.to_ports || 'all'}</span>`;
  4328. } else if (r.action === 'masquerade') {
  4329. 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>`;
  4330. } else if (r.action === 'log') {
  4331. toTarget = `<span class="text-slate-400 font-mono font-bold">${r.log_prefix || 'log'}</span>`;
  4332. } else {
  4333. const parts = [r.to_addresses, r.to_ports].filter(Boolean);
  4334. toTarget = parts.length ? `<span class="text-amber-300 font-mono font-bold">${parts.join(':')}</span>` : '-';
  4335. }
  4336. const ifaces = [r.out_interface ? 'out:' + r.out_interface : r.out_interface_list ? 'out-list:' + r.out_interface_list : '', r.in_interface ? 'in:' + r.in_interface : r.in_interface_list ? 'in-list:' + r.in_interface_list : ''].filter(Boolean).join(' ');
  4337. tr.innerHTML = `
  4338. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  4339. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  4340. <td class="py-2.5 px-3 font-bold text-amber-400">${escapeHtml(nativeNATChain(raw.chain).toUpperCase())}</td>
  4341. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  4342. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  4343. <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>
  4344. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  4345. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  4346. <td class="py-2.5 px-3 font-mono text-xs">${toTarget}</td>
  4347. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  4348. <span class="text-slate-300" id="nat-pkts-${r.id}">${(r.packets || 0).toLocaleString()}p</span> /
  4349. <span class="text-slate-500" id="nat-bytes-${r.id}">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  4350. </td>
  4351. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  4352. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  4353. <button onclick="moveNATRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  4354. <button onclick="moveNATRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  4355. <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>
  4356. <button onclick="openEditNATModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  4357. <button onclick="deleteNATRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  4358. </td>
  4359. `;
  4360. tbody.appendChild(tr);
  4361. });
  4362. }
  4363. // ==================== FIREWALL NAT MODAL (DEBTIK WEBFIG / WINBOX V4) ====================
  4364. function switchNATRuleTab(tab) {
  4365. if (!document.getElementById(`nat-pane-${tab}`)) tab = 'general';
  4366. state.activeNATRuleTab = tab;
  4367. document.querySelectorAll('.nat-rule-tab-btn').forEach(btn => {
  4368. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  4369. btn.classList.add('text-slate-400', 'border-transparent');
  4370. });
  4371. const activeBtn = document.getElementById(`nat-tab-btn-${tab}`);
  4372. if (activeBtn) {
  4373. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  4374. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  4375. }
  4376. document.querySelectorAll('.nat-rule-pane').forEach(p => p.classList.add('hidden'));
  4377. const activePane = document.getElementById(`nat-pane-${tab}`);
  4378. if (activePane) activePane.classList.remove('hidden');
  4379. if (tab === 'statistics') {
  4380. startNATStatPolling();
  4381. } else {
  4382. stopNATStatPolling();
  4383. }
  4384. }
  4385. function toggleNATField(fieldKey, expand) {
  4386. const plusBtn = document.getElementById(`nat-plus-${fieldKey}`);
  4387. const fieldBox = document.getElementById(`nat-field-${fieldKey}`);
  4388. if (!plusBtn || !fieldBox) return;
  4389. if (expand) {
  4390. plusBtn.classList.add('hidden');
  4391. fieldBox.classList.remove('hidden');
  4392. const valInput = document.getElementById(`nat-val-${fieldKey}`);
  4393. if (valInput) valInput.focus();
  4394. } else {
  4395. fieldBox.classList.add('hidden');
  4396. plusBtn.classList.remove('hidden');
  4397. const valInput = document.getElementById(`nat-val-${fieldKey}`);
  4398. if (valInput) {
  4399. if (valInput.tagName === 'SELECT') {
  4400. valInput.selectedIndex = 0;
  4401. } else {
  4402. valInput.value = '';
  4403. }
  4404. }
  4405. const invInput = document.getElementById(`nat-inv-${fieldKey}`);
  4406. if (invInput) invInput.checked = false;
  4407. if (fieldKey === 'days') {
  4408. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  4409. const el = document.getElementById(`nat-day-${d}`);
  4410. if (el) el.checked = true;
  4411. });
  4412. }
  4413. }
  4414. }
  4415. function setNATFieldVal(fieldKey, value, hasInvert = false) {
  4416. if (fieldKey === 'ipsec' && typeof value === 'string') value = value.replace(':', ',');
  4417. if (value !== undefined && value !== null && value !== '' && !(fieldKey === 'proto' && value === 'all')) {
  4418. toggleNATField(fieldKey, true);
  4419. let strVal = String(value);
  4420. if (hasInvert) {
  4421. const inv = strVal.startsWith('!');
  4422. if (inv) strVal = strVal.slice(1);
  4423. const invEl = document.getElementById(`nat-inv-${fieldKey}`);
  4424. if (invEl) invEl.checked = inv;
  4425. else if (inv) strVal = '!'+strVal;
  4426. }
  4427. const valEl = document.getElementById(`nat-val-${fieldKey}`);
  4428. 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; }
  4429. } else {
  4430. toggleNATField(fieldKey, false);
  4431. }
  4432. }
  4433. function getNATFieldVal(fieldKey, hasInvert = false) {
  4434. const fieldBox = document.getElementById(`nat-field-${fieldKey}`);
  4435. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  4436. const valEl = document.getElementById(`nat-val-${fieldKey}`);
  4437. let v = valEl ? valEl.value.trim() : '';
  4438. if (!v) return '';
  4439. if (hasInvert) {
  4440. const invEl = document.getElementById(`nat-inv-${fieldKey}`);
  4441. if (invEl && invEl.checked) {
  4442. v = '!' + v.replace(/^!/, '');
  4443. }
  4444. }
  4445. return v;
  4446. }
  4447. function toggleMaximizeNATModal() {
  4448. const win = document.getElementById('nat-modal-window');
  4449. if (!win) return;
  4450. if (win.classList.contains('max-w-[720px]')) {
  4451. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  4452. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  4453. } else {
  4454. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  4455. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  4456. }
  4457. }
  4458. function handleNATChainChange() {
  4459. toggleNATActionFields();
  4460. }
  4461. function toggleNATActionFields() {
  4462. const act = document.getElementById('nat-modal-action')?.value || 'masquerade';
  4463. const rowAddr = document.getElementById('nat-row-toaddr');
  4464. const rowPort = document.getElementById('nat-row-toport');
  4465. const jumpBox = document.getElementById('nat-action-jump-box');
  4466. const addrBox = document.getElementById('nat-action-addrlist-box');
  4467. // Hide all dynamic rows first
  4468. if (rowAddr) rowAddr.classList.add('hidden');
  4469. if (rowPort) rowPort.classList.add('hidden');
  4470. if (jumpBox) jumpBox.classList.add('hidden');
  4471. if (addrBox) addrBox.classList.add('hidden');
  4472. if (['src-nat', 'dst-nat', 'netmap'].includes(act)) {
  4473. if (rowAddr) rowAddr.classList.remove('hidden');
  4474. if (rowPort && act !== 'netmap') rowPort.classList.remove('hidden');
  4475. } else if (act === 'redirect' || act === 'masquerade') {
  4476. if (rowPort) rowPort.classList.remove('hidden');
  4477. } else if (act === 'jump') {
  4478. if (jumpBox) jumpBox.classList.remove('hidden');
  4479. } else if (act.includes('address-list') || act.includes('address list')) {
  4480. if (addrBox) addrBox.classList.remove('hidden');
  4481. }
  4482. if (act === 'log') {
  4483. const logEl = document.getElementById('nat-modal-log');
  4484. if (logEl) logEl.checked = true;
  4485. toggleNATField('logprefix', true);
  4486. }
  4487. }
  4488. function handleNATActionChange() {
  4489. toggleNATActionFields();
  4490. }
  4491. function toggleNATLogPrefix() {
  4492. const isLog = document.getElementById('nat-modal-log')?.checked;
  4493. toggleNATField('logprefix', !!isLog);
  4494. }
  4495. function openAddNATModal() {
  4496. const tos = document.getElementById('nat-val-tos'); if (tos) tos.value = '';
  4497. switchNATRuleTab('general');
  4498. setFirewallDays('nat', '');
  4499. const badge = document.getElementById('nat-modal-badge');
  4500. if (badge) badge.innerText = 'New...';
  4501. document.getElementById('nat-modal-id').value = '';
  4502. document.getElementById('nat-modal-family').value = '4';
  4503. document.getElementById('nat-modal-enabled').checked = true;
  4504. document.getElementById('nat-modal-comment').value = '';
  4505. document.getElementById('nat-modal-chain').value = 'postrouting';
  4506. document.getElementById('nat-modal-action').value = 'masquerade';
  4507. document.getElementById('nat-modal-toaddr').value = '';
  4508. document.getElementById('nat-modal-toport').value = '';
  4509. document.getElementById('nat-modal-log').checked = false;
  4510. populateInterfaceSelect('nat-val-iniface');
  4511. populateInterfaceSelect('nat-val-outiface');
  4512. populateAddressListSelect('nat-val-srclist');
  4513. populateAddressListSelect('nat-val-dstlist');
  4514. populateGeoIPSelect('nat-val-srcgeo');
  4515. populateGeoIPSelect('nat-val-dstgeo');
  4516. const allFieldKeys = [
  4517. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  4518. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  4519. 'routingmark', 'conntype',
  4520. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  4521. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  4522. 'ipsec', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  4523. 'pktsize', 'random', 'icmpoptions', 'ipv4options', 'ttl',
  4524. 'time', 'days', 'limit', 'dstlimit', 'psd', 'logprefix'
  4525. ];
  4526. allFieldKeys.forEach(k => toggleNATField(k, false));
  4527. resetNATCounterDisplay();
  4528. toggleNATActionFields();
  4529. document.getElementById('nat-modal').classList.remove('hidden');
  4530. }
  4531. function openEditNATModal(id) {
  4532. id = decodeURIComponent(id);
  4533. const r = (state.natRules || []).find(rule => rule.id === id);
  4534. if (!r) return;
  4535. setFirewallDays('nat', r.days || '');
  4536. switchNATRuleTab('general');
  4537. const badge = document.getElementById('nat-modal-badge');
  4538. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  4539. document.getElementById('nat-modal-id').value = r.id;
  4540. document.getElementById('nat-modal-family').value = String(r.ip_version || 4);
  4541. document.getElementById('nat-modal-enabled').checked = !r.disabled;
  4542. document.getElementById('nat-modal-comment').value = r.comment || '';
  4543. document.getElementById('nat-modal-chain').value = nativeNATChain(r.chain || 'postrouting');
  4544. setFirewallActionSelection('nat', r.action || 'accept');
  4545. document.getElementById('nat-modal-toaddr').value = r.to_addresses || '';
  4546. document.getElementById('nat-modal-toport').value = r.to_ports || '';
  4547. document.getElementById('nat-modal-log').checked = !!r.log;
  4548. populateInterfaceSelect('nat-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  4549. populateInterfaceSelect('nat-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  4550. populateAddressListSelect('nat-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  4551. populateAddressListSelect('nat-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  4552. populateGeoIPSelect('nat-val-srcgeo', r.src_geoip || '');
  4553. populateGeoIPSelect('nat-val-dstgeo', r.dst_geoip || '');
  4554. setNATFieldVal('src', r.src_address, true);
  4555. setNATFieldVal('dst', r.dst_address, true);
  4556. setNATFieldVal('srclist', r.src_address_list, true);
  4557. setNATFieldVal('dstlist', r.dst_address_list, true);
  4558. setNATFieldVal('srcgeo', r.src_geoip, true);
  4559. setNATFieldVal('dstgeo', r.dst_geoip, true);
  4560. if (r.protocol && r.protocol !== 'all') {
  4561. setNATFieldVal('proto', r.protocol, true);
  4562. } else {
  4563. toggleNATField('proto', false);
  4564. }
  4565. setNATFieldVal('sport', r.src_port, true);
  4566. setNATFieldVal('dport', r.dst_port, true);
  4567. setNATFieldVal('anyport', r.any_port, true);
  4568. setNATFieldVal('iniface', r.in_interface, true);
  4569. setNATFieldVal('outiface', r.out_interface, true);
  4570. setNATFieldVal('inifacelist', r.in_interface_list, true);
  4571. setNATFieldVal('outifacelist', r.out_interface_list, true);
  4572. setNATFieldVal('pktmark', r.packet_mark, true);
  4573. setNATFieldVal('connmark', r.connection_mark, true);
  4574. setNATFieldVal('routingmark', r.routing_mark, true);
  4575. setNATFieldVal('conntype', r.connection_type, false);
  4576. // Advanced tab fields
  4577. setNATFieldVal('layer7', r.layer7_protocol, false);
  4578. setNATFieldVal('content', r.content, false);
  4579. setNATFieldVal('connbytes', r.connection_bytes, false);
  4580. setNATFieldVal('connrate', r.connection_rate, false);
  4581. setNATFieldVal('pcc', r.pcc, false);
  4582. setNATFieldVal('srcmac', r.src_mac_address, true);
  4583. setNATFieldVal('outbridgeport', r.out_bridge_port, false);
  4584. setNATFieldVal('inbridgeport', r.in_bridge_port, false);
  4585. setNATFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  4586. setNATFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  4587. setNATFieldVal('ipsec', r.ipsec_policy, false);
  4588. setNATFieldVal('ingresspriority', r.ingress_priority, false);
  4589. setNATFieldVal('priority', r.priority, false);
  4590. setNATFieldVal('dscp', r.dscp, false);
  4591. setNATFieldVal('tcpmss', r.tcp_mss, false);
  4592. { const tosEl = document.getElementById('nat-val-tos'); if (tosEl) tosEl.value = r.tos || ''; }
  4593. setNATFieldVal('pktsize', r.packet_size, false);
  4594. setNATFieldVal('random', r.random, false);
  4595. setNATFieldVal('icmpoptions', r.icmp_options, false);
  4596. setNATFieldVal('ipv4options', r.ipv4_options, false);
  4597. setNATFieldVal('ttl', r.ttl, false);
  4598. // Extra tab fields
  4599. setNATFieldVal('time', r.time, false);
  4600. if (r.days) {
  4601. toggleNATField('days', true);
  4602. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  4603. const chk = document.getElementById(`nat-day-${d}`);
  4604. if (chk) chk.checked = r.days.toLowerCase().includes(d);
  4605. });
  4606. } else {
  4607. toggleNATField('days', false);
  4608. }
  4609. setNATFieldVal('limit', r.limit, false);
  4610. setNATFieldVal('dstlimit', r.dst_limit, false);
  4611. setNATFieldVal('psd', r.psd, false);
  4612. // Action fields
  4613. if (r.jump_target) {
  4614. const jtEl = document.getElementById('nat-modal-jumptarget');
  4615. if (jtEl) jtEl.value = r.jump_target;
  4616. }
  4617. if (r.address_list) {
  4618. const alEl = document.getElementById('nat-modal-action-addrlist');
  4619. if (alEl) alEl.value = r.address_list;
  4620. }
  4621. if (r.address_list_timeout) {
  4622. const toEl = document.getElementById('nat-modal-action-timeout');
  4623. if (toEl) toEl.value = r.address_list_timeout;
  4624. }
  4625. setNATFieldVal('logprefix', r.log_prefix, false);
  4626. // Statistics
  4627. const bEl = document.getElementById('nat-stat-bytes');
  4628. const pEl = document.getElementById('nat-stat-packets');
  4629. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  4630. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  4631. state.natLastBytes = r.bytes || 0;
  4632. state.natLastPackets = r.packets || 0;
  4633. state.natLastTimestamp = Date.now();
  4634. state.natStatRateHistory = new Array(30).fill(0);
  4635. state.natStatPktHistory = new Array(30).fill(0);
  4636. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  4637. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  4638. toggleNATActionFields();
  4639. document.getElementById('nat-modal').classList.remove('hidden');
  4640. }
  4641. function closeNATModal() {
  4642. stopNATStatPolling();
  4643. document.getElementById('nat-modal').classList.add('hidden');
  4644. }
  4645. function copyNATRule() {
  4646. document.getElementById('nat-modal-id').value = '';
  4647. const badge = document.getElementById('nat-modal-badge');
  4648. if (badge) badge.innerText = 'New...';
  4649. showToast('Rule Cloned', 'Ready to save as a new NAT rule copy', 'info');
  4650. }
  4651. function resetNATCounterDisplay() {
  4652. state.natStatRateHistory = new Array(30).fill(0);
  4653. state.natStatPktHistory = new Array(30).fill(0);
  4654. state.natLastBytes = 0;
  4655. state.natLastPackets = 0;
  4656. state.natLastTimestamp = Date.now();
  4657. const bEl = document.getElementById('nat-stat-bytes');
  4658. const pEl = document.getElementById('nat-stat-packets');
  4659. const rEl = document.getElementById('nat-stat-rate');
  4660. const prEl = document.getElementById('nat-stat-pktrate');
  4661. if (bEl) bEl.value = '0 B';
  4662. if (pEl) pEl.value = '0';
  4663. if (rEl) rEl.value = '0 bps';
  4664. if (prEl) prEl.value = '0 p/s';
  4665. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  4666. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  4667. showToast('Counters Reset', 'NAT rule counter display reset to 0', 'info');
  4668. }
  4669. async function applyNATRule(closeAfter = false) {
  4670. const id = document.getElementById('nat-modal-id').value;
  4671. if (!reviewLegacyFirewallSettings('nat', id)) return;
  4672. let selectedDays; try { selectedDays = getFirewallDays('nat'); } catch(error) { showToast('Error', error.message, 'error'); return; }
  4673. const chain = document.getElementById('nat-modal-chain').value;
  4674. const action = document.getElementById('nat-modal-action').value;
  4675. const comment = document.getElementById('nat-modal-comment').value.trim();
  4676. const enabled = document.getElementById('nat-modal-enabled').checked;
  4677. const src = getNATFieldVal('src', true);
  4678. const dst = getNATFieldVal('dst', true);
  4679. const srclist = getNATFieldVal('srclist', true);
  4680. const dstlist = getNATFieldVal('dstlist', true);
  4681. const srcgeo = getNATFieldVal('srcgeo', true);
  4682. const dstgeo = getNATFieldVal('dstgeo', true);
  4683. const proto = getNATFieldVal('proto', true);
  4684. const sport = getNATFieldVal('sport', true);
  4685. const dport = getNATFieldVal('dport', true);
  4686. const anyport = getNATFieldVal('anyport', true);
  4687. const iniface = getNATFieldVal('iniface', true);
  4688. const outiface = getNATFieldVal('outiface', true);
  4689. const inifacelist = getNATFieldVal('inifacelist', true);
  4690. const outifacelist = getNATFieldVal('outifacelist', true);
  4691. const pktmark = getNATFieldVal('pktmark', true);
  4692. const connmark = getNATFieldVal('connmark', true);
  4693. const routingmark = getNATFieldVal('routingmark', true);
  4694. const conntype = getNATFieldVal('conntype', false);
  4695. const usesAddr = ['src-nat', 'dst-nat', 'netmap'].includes(action);
  4696. const usesPort = ['src-nat', 'dst-nat', 'redirect', 'masquerade'].includes(action);
  4697. if (!chain.trim()) { switchNATRuleTab('general'); showToast('NAT rule', 'Enter a chain.', 'error'); document.getElementById('nat-modal-chain').focus(); return; }
  4698. 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; }
  4699. if ((sport || dport || anyport || (usesPort && document.getElementById('nat-modal-toport').value.trim())) && !['tcp', 'udp'].includes(proto)) {
  4700. switchNATRuleTab('general'); toggleNATField('proto', true); document.getElementById('nat-val-proto').value = proto || 'all';
  4701. 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;
  4702. }
  4703. const payload = {
  4704. ip_version: Number(document.getElementById('nat-modal-family').value),
  4705. id,
  4706. chain,
  4707. action,
  4708. to_addresses: usesAddr ? (document.getElementById('nat-modal-toaddr')?.value.trim() || '') : '',
  4709. to_ports: usesPort ? (document.getElementById('nat-modal-toport')?.value.trim() || '') : '',
  4710. protocol: proto || 'all',
  4711. src_address: src,
  4712. dst_address: dst,
  4713. src_port: sport,
  4714. dst_port: dport,
  4715. any_port: anyport,
  4716. in_interface: iniface,
  4717. out_interface: outiface,
  4718. in_interface_list: inifacelist,
  4719. out_interface_list: outifacelist,
  4720. packet_mark: pktmark,
  4721. connection_mark: connmark,
  4722. routing_mark: routingmark,
  4723. connection_type: conntype,
  4724. src_address_list: srclist,
  4725. dst_address_list: dstlist,
  4726. src_geoip: srcgeo,
  4727. dst_geoip: dstgeo,
  4728. comment,
  4729. disabled: !enabled,
  4730. // Advanced tab
  4731. content: getNATFieldVal('content', false),
  4732. src_mac_address: getNATFieldVal('srcmac', true),
  4733. out_bridge_port: getNATFieldVal('outbridgeport', false),
  4734. in_bridge_port: getNATFieldVal('inbridgeport', false),
  4735. ipsec_policy: getNATFieldVal('ipsec', false),
  4736. dscp: getNATFieldVal('dscp', false),
  4737. tcp_mss: getNATFieldVal('tcpmss', false),
  4738. tos: document.getElementById('nat-val-tos')?.value || '',
  4739. packet_size: getNATFieldVal('pktsize', false),
  4740. random: getNATFieldVal('random', false),
  4741. icmp_options: getNATFieldVal('icmpoptions', false),
  4742. ttl: getNATFieldVal('ttl', false),
  4743. days: selectedDays,
  4744. // Extra tab
  4745. time: getNATFieldVal('time', false),
  4746. limit: getNATFieldVal('limit', false),
  4747. // Action tab
  4748. jump_target: action === 'jump' ? (document.getElementById('nat-modal-jumptarget')?.value || '') : '',
  4749. address_list: action.includes('address') ? (document.getElementById('nat-modal-action-addrlist')?.value || '') : '',
  4750. address_list_timeout: action.includes('address') ? (document.getElementById('nat-modal-action-timeout')?.value || '') : '',
  4751. log: document.getElementById('nat-modal-log')?.checked || false,
  4752. log_prefix: getNATFieldVal('logprefix', false)
  4753. };
  4754. try {
  4755. const res = await fetch(`${API_BASE}/firewall/nat`, {
  4756. method: 'POST',
  4757. headers: { 'Content-Type': 'application/json' },
  4758. body: JSON.stringify(payload)
  4759. });
  4760. if (res.ok) {
  4761. const data = await res.json();
  4762. showToast('NAT Rule Saved', 'NAT mapping updated', 'success');
  4763. loadFirewall(false);
  4764. if (closeAfter) {
  4765. closeNATModal();
  4766. } else {
  4767. if (data.id) {
  4768. document.getElementById('nat-modal-id').value = data.id;
  4769. const badge = document.getElementById('nat-modal-badge');
  4770. if (badge) badge.innerText = `#${data.id}`;
  4771. }
  4772. }
  4773. } else {
  4774. const err = await res.json();
  4775. showToast('Error', err.message || 'Failed to save rule', 'error');
  4776. }
  4777. } catch (err) {
  4778. showToast('Error', err.message, 'error');
  4779. }
  4780. }
  4781. function submitSaveNATRule(e) {
  4782. if (e && e.preventDefault) e.preventDefault();
  4783. return applyNATRule(true);
  4784. }
  4785. function startNATStatPolling() {
  4786. stopNATStatPolling();
  4787. pollNATRuleStats();
  4788. state.natStatInterval = setInterval(pollNATRuleStats, 1000);
  4789. }
  4790. function stopNATStatPolling() {
  4791. if (state.natStatInterval) {
  4792. clearInterval(state.natStatInterval);
  4793. state.natStatInterval = null;
  4794. }
  4795. }
  4796. async function pollNATRuleStats() {
  4797. const id = document.getElementById('nat-modal-id')?.value;
  4798. if (!id) {
  4799. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory || new Array(30).fill(0), 'bps', 'nat-stat-legend-rate');
  4800. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory || new Array(30).fill(0), 'p/s', 'nat-stat-legend-pktrate');
  4801. return;
  4802. }
  4803. try {
  4804. const res = await fetch(`${API_BASE}/firewall/nat`);
  4805. if (!res.ok) return;
  4806. const rules = await res.json();
  4807. const r = rules.find(x => x.id === id);
  4808. if (!r) return;
  4809. const now = Date.now();
  4810. const dt = Math.max(0.2, (now - (state.natLastTimestamp || now)) / 1000);
  4811. state.natLastTimestamp = now;
  4812. const curBytes = r.bytes || 0;
  4813. const curPackets = r.packets || 0;
  4814. const deltaBytes = Math.max(0, curBytes - (state.natLastBytes ?? curBytes));
  4815. const deltaPkts = Math.max(0, curPackets - (state.natLastPackets ?? curPackets));
  4816. state.natLastBytes = curBytes;
  4817. state.natLastPackets = curPackets;
  4818. const rateBps = Math.round((deltaBytes * 8) / dt);
  4819. const ratePkt = Math.round(deltaPkts / dt);
  4820. if (!state.natStatRateHistory) state.natStatRateHistory = new Array(30).fill(0);
  4821. if (!state.natStatPktHistory) state.natStatPktHistory = new Array(30).fill(0);
  4822. state.natStatRateHistory.push(rateBps);
  4823. if (state.natStatRateHistory.length > 30) state.natStatRateHistory.shift();
  4824. state.natStatPktHistory.push(ratePkt);
  4825. if (state.natStatPktHistory.length > 30) state.natStatPktHistory.shift();
  4826. const bEl = document.getElementById('nat-stat-bytes');
  4827. const pEl = document.getElementById('nat-stat-packets');
  4828. const rEl = document.getElementById('nat-stat-rate');
  4829. const prEl = document.getElementById('nat-stat-pktrate');
  4830. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  4831. if (pEl) pEl.value = curPackets.toLocaleString();
  4832. if (rEl) rEl.value = formatBps(rateBps);
  4833. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  4834. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  4835. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  4836. } catch (e) {
  4837. console.error('Error polling NAT rule stats', e);
  4838. }
  4839. }
  4840. async function moveNATRule(id, dir) {
  4841. id = decodeURIComponent(id);
  4842. try {
  4843. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/move`, {
  4844. method: 'POST',
  4845. headers: { 'Content-Type': 'application/json' },
  4846. body: JSON.stringify({ direction: dir })
  4847. });
  4848. if (!res.ok) throw new Error(await responseError(res));
  4849. await loadFirewall(false);
  4850. } catch (err) {
  4851. showToast('Error', err.message, 'error');
  4852. }
  4853. }
  4854. async function toggleNATRuleState(id, disabled) {
  4855. id = decodeURIComponent(id);
  4856. try {
  4857. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/state`, {
  4858. method: 'POST',
  4859. headers: { 'Content-Type': 'application/json' },
  4860. body: JSON.stringify({ disabled })
  4861. });
  4862. if (!res.ok) throw new Error(await responseError(res));
  4863. await loadFirewall(false);
  4864. } catch (err) {
  4865. showToast('Error', err.message, 'error');
  4866. }
  4867. }
  4868. async function deleteNATRule(id) {
  4869. id = decodeURIComponent(id);
  4870. if (!confirm('Are you sure you want to delete this NAT rule?')) return;
  4871. try {
  4872. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4873. if (!res.ok) throw new Error(await responseError(res));
  4874. {
  4875. showToast('Deleted', 'NAT rule removed', 'success');
  4876. loadFirewall(false);
  4877. }
  4878. } catch (err) {
  4879. showToast('Error', err.message, 'error');
  4880. }
  4881. }
  4882. // ----------------- Mangle Rules -----------------
  4883. function renderMangleRules() {
  4884. const chainFilter = document.getElementById('mangle-filter-chain')?.value || '';
  4885. const tbody = document.getElementById('mangle-table-body');
  4886. const empty = document.getElementById('mangle-empty');
  4887. if (!tbody) return;
  4888. tbody.innerHTML = '';
  4889. const rules = (state.mangleRules || []).filter(r => !chainFilter || (r.chain || '').toLowerCase() === chainFilter);
  4890. document.getElementById('mangle-count-badge').innerText = `${rules.length} Rules`;
  4891. if (rules.length === 0) {
  4892. empty?.classList.remove('hidden');
  4893. return;
  4894. }
  4895. empty?.classList.add('hidden');
  4896. rules.forEach((raw, idx) => {
  4897. const r = safeFirewallRow(raw);
  4898. const tr = document.createElement('tr');
  4899. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  4900. let markVal = '<span class="text-slate-500">-</span>';
  4901. if (r.new_connection_mark) markVal = `<span class="text-cyan-300 font-mono font-bold">${r.new_connection_mark}</span>`;
  4902. else if (r.new_routing_mark) markVal = `<span class="text-amber-300 font-mono font-bold">${r.new_routing_mark}</span>`;
  4903. else if (r.new_packet_mark) markVal = `<span class="text-emerald-300 font-mono font-bold">${r.new_packet_mark}</span>`;
  4904. else if (r.new_mss) markVal = `<span class="text-sky-300 font-mono font-bold">mss:${r.new_mss}</span>`;
  4905. else if (r.action === 'change-dscp') markVal = `<span class="text-purple-300 font-mono font-bold">dscp:${r.new_dscp}</span>`;
  4906. else if (r.new_ttl) markVal = `<span class="text-blue-300 font-mono font-bold">ttl:${r.new_ttl}</span>`;
  4907. else if (r.new_priority) markVal = `<span class="text-indigo-300 font-mono font-bold">prio:${r.new_priority}</span>`;
  4908. else if (r.route) markVal = `<span class="text-orange-300 font-mono font-bold">route:${r.route}</span>`;
  4909. else if (r.sniff_target) markVal = `<span class="text-pink-300 font-mono font-bold">sniff:${r.sniff_target}</span>`;
  4910. else if (r.action === 'jump') markVal = `<span class="text-yellow-300 font-mono font-bold">&rarr; ${r.jump_target || '-'}</span>`;
  4911. 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>`;
  4912. else if (r.action === 'log') markVal = `<span class="text-slate-400 font-mono font-bold">${r.log_prefix || 'log'}</span>`;
  4913. tr.innerHTML = `
  4914. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  4915. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  4916. <td class="py-2.5 px-3 font-bold text-purple-400">${(r.chain || '').toUpperCase()}</td>
  4917. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  4918. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  4919. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  4920. <td class="py-2.5 px-3 font-mono text-xs">${markVal}</td>
  4921. <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>
  4922. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  4923. <span class="text-slate-300" id="mangle-pkts-${r.id}">${(r.packets || 0).toLocaleString()}p</span> /
  4924. <span class="text-slate-500" id="mangle-bytes-${r.id}">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  4925. </td>
  4926. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  4927. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  4928. <button onclick="moveMangleRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  4929. <button onclick="moveMangleRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  4930. <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>
  4931. <button onclick="openEditMangleModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  4932. <button onclick="deleteMangleRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  4933. </td>
  4934. `;
  4935. tbody.appendChild(tr);
  4936. });
  4937. }
  4938. // ==================== FIREWALL MANGLE MODAL (DEBTIK WEBFIG / WINBOX V4) ====================
  4939. function switchMangleRuleTab(tab) {
  4940. state.activeMangleRuleTab = tab;
  4941. document.querySelectorAll('.mangle-rule-tab-btn').forEach(btn => {
  4942. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  4943. btn.classList.add('text-slate-400', 'border-transparent');
  4944. });
  4945. const activeBtn = document.getElementById(`mangle-tab-btn-${tab}`);
  4946. if (activeBtn) {
  4947. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  4948. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  4949. }
  4950. document.querySelectorAll('.mangle-rule-pane').forEach(p => p.classList.add('hidden'));
  4951. const activePane = document.getElementById(`mangle-pane-${tab}`);
  4952. if (activePane) activePane.classList.remove('hidden');
  4953. if (tab === 'statistics') {
  4954. startMangleStatPolling();
  4955. } else {
  4956. stopMangleStatPolling();
  4957. }
  4958. }
  4959. function toggleMangleField(fieldKey, expand) {
  4960. const plusBtn = document.getElementById(`mangle-plus-${fieldKey}`);
  4961. const fieldBox = document.getElementById(`mangle-field-${fieldKey}`);
  4962. if (!plusBtn || !fieldBox) return;
  4963. if (expand) {
  4964. plusBtn.classList.add('hidden');
  4965. fieldBox.classList.remove('hidden');
  4966. const valInput = document.getElementById(`mangle-val-${fieldKey}`);
  4967. if (valInput) valInput.focus();
  4968. } else {
  4969. fieldBox.classList.add('hidden');
  4970. plusBtn.classList.remove('hidden');
  4971. const valInput = document.getElementById(`mangle-val-${fieldKey}`);
  4972. if (valInput) {
  4973. if (valInput.tagName === 'SELECT') {
  4974. valInput.selectedIndex = 0;
  4975. } else {
  4976. valInput.value = '';
  4977. }
  4978. }
  4979. const invInput = document.getElementById(`mangle-inv-${fieldKey}`);
  4980. if (invInput) invInput.checked = false;
  4981. if (fieldKey === 'cs') {
  4982. ['mangle-modal-cs-established', 'mangle-modal-cs-related', 'mangle-modal-cs-new', 'mangle-modal-cs-invalid', 'mangle-modal-cs-untracked'].forEach(id => {
  4983. const el = document.getElementById(id);
  4984. if (el) el.checked = false;
  4985. });
  4986. }
  4987. if (fieldKey === 'natstate') {
  4988. ['mangle-modal-nat-srcnat', 'mangle-modal-nat-dstnat'].forEach(id => {
  4989. const el = document.getElementById(id);
  4990. if (el) el.checked = false;
  4991. });
  4992. }
  4993. }
  4994. }
  4995. function setMangleFieldVal(fieldKey, value, hasInvert = false) {
  4996. if (fieldKey === 'ipsec' && typeof value === 'string') value = value.replace(':', ',');
  4997. if (value !== undefined && value !== null && value !== '' && !(fieldKey === 'proto' && value === 'all')) {
  4998. toggleMangleField(fieldKey, true);
  4999. let strVal = String(value);
  5000. if (hasInvert) {
  5001. const inv = strVal.startsWith('!');
  5002. if (inv) strVal = strVal.slice(1);
  5003. const invEl = document.getElementById(`mangle-inv-${fieldKey}`);
  5004. if (invEl) invEl.checked = inv;
  5005. else if (inv) strVal = '!'+strVal;
  5006. }
  5007. const valEl = document.getElementById(`mangle-val-${fieldKey}`);
  5008. 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; }
  5009. } else {
  5010. toggleMangleField(fieldKey, false);
  5011. }
  5012. }
  5013. function getMangleFieldVal(fieldKey, hasInvert = false) {
  5014. const fieldBox = document.getElementById(`mangle-field-${fieldKey}`);
  5015. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  5016. const valEl = document.getElementById(`mangle-val-${fieldKey}`);
  5017. let v = valEl ? valEl.value.trim() : '';
  5018. if (!v) return '';
  5019. if (hasInvert) {
  5020. const invEl = document.getElementById(`mangle-inv-${fieldKey}`);
  5021. if (invEl && invEl.checked) {
  5022. v = '!' + v.replace(/^!/, '');
  5023. }
  5024. }
  5025. return v;
  5026. }
  5027. function toggleMaximizeMangleModal() {
  5028. const win = document.getElementById('mangle-modal-window');
  5029. if (!win) return;
  5030. if (win.classList.contains('max-w-[720px]')) {
  5031. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  5032. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  5033. } else {
  5034. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  5035. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  5036. }
  5037. }
  5038. function toggleMangleActionFields() {
  5039. const act = document.getElementById('mangle-modal-action')?.value || 'mark-connection';
  5040. // Hide all dynamic rows first
  5041. ['newconnmark', 'newroutingmark', 'newpktmark', 'newmss', 'newdscp', 'newttl', 'newpriority', 'route', 'sniff', 'passthrough'].forEach(id => {
  5042. const el = document.getElementById(`mangle-row-${id}`);
  5043. if (el) el.classList.add('hidden');
  5044. });
  5045. const jumpBox = document.getElementById('mangle-action-jump-box');
  5046. const addrBox = document.getElementById('mangle-action-addrlist-box');
  5047. if (jumpBox) jumpBox.classList.add('hidden');
  5048. if (addrBox) addrBox.classList.add('hidden');
  5049. // Activate matching rows
  5050. if (act === 'mark-connection') {
  5051. document.getElementById('mangle-row-newconnmark')?.classList.remove('hidden');
  5052. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5053. } else if (act === 'mark-routing') {
  5054. document.getElementById('mangle-row-newroutingmark')?.classList.remove('hidden');
  5055. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5056. } else if (act === 'mark-packet') {
  5057. document.getElementById('mangle-row-newpktmark')?.classList.remove('hidden');
  5058. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5059. } else if (act === 'change-mss') {
  5060. document.getElementById('mangle-row-newmss')?.classList.remove('hidden');
  5061. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5062. } else if (act === 'change-dscp') {
  5063. document.getElementById('mangle-row-newdscp')?.classList.remove('hidden');
  5064. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5065. } else if (act === 'change-ttl') {
  5066. document.getElementById('mangle-row-newttl')?.classList.remove('hidden');
  5067. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5068. } else if (act === 'set-priority') {
  5069. document.getElementById('mangle-row-newpriority')?.classList.remove('hidden');
  5070. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5071. } else if (act === 'route') {
  5072. document.getElementById('mangle-row-route')?.classList.remove('hidden');
  5073. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5074. } else if (act === 'sniff-pc' || act === 'sniff-tzsp') {
  5075. document.getElementById('mangle-row-sniff')?.classList.remove('hidden');
  5076. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5077. } else if (act === 'clear-df' || act === 'strip-ipv4-options') {
  5078. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5079. } else if (act === 'jump') {
  5080. if (jumpBox) jumpBox.classList.remove('hidden');
  5081. } else if (act.includes('address-list') || act.includes('address list')) {
  5082. if (addrBox) addrBox.classList.remove('hidden');
  5083. }
  5084. if (act === 'log') {
  5085. const logEl = document.getElementById('mangle-modal-log');
  5086. if (logEl) logEl.checked = true;
  5087. toggleMangleField('logprefix', true);
  5088. }
  5089. }
  5090. function toggleMangleLogPrefix() {
  5091. const isLog = document.getElementById('mangle-modal-log')?.checked;
  5092. toggleMangleField('logprefix', !!isLog);
  5093. }
  5094. const allMangleFieldKeys = [
  5095. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  5096. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  5097. 'routingmark', 'conntype', 'cs', 'natstate',
  5098. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  5099. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  5100. 'ipsec', 'tlshost', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  5101. 'pktsize', 'random', 'tcpflags', 'icmpoptions', 'ipv4options', 'ttl',
  5102. 'nth', 'connlimit', 'srcaddrtype', 'dstaddrtype', 'hotspot', 'ipfragment',
  5103. 'limit', 'dstlimit', 'time', 'psd', 'logprefix'
  5104. ];
  5105. function openAddMangleModal() {
  5106. const tos = document.getElementById('mangle-val-tos'); if (tos) tos.value = '';
  5107. switchMangleRuleTab('general');
  5108. const badge = document.getElementById('mangle-modal-badge');
  5109. if (badge) badge.innerText = 'New...';
  5110. document.getElementById('mangle-modal-id').value = '';
  5111. document.getElementById('mangle-modal-family').value = '4';
  5112. document.getElementById('mangle-modal-enabled').checked = true;
  5113. document.getElementById('mangle-modal-comment').value = '';
  5114. document.getElementById('mangle-modal-chain').value = 'prerouting';
  5115. document.getElementById('mangle-modal-action').value = 'mark-connection';
  5116. if (document.getElementById('mangle-modal-newconnmark')) document.getElementById('mangle-modal-newconnmark').value = '';
  5117. if (document.getElementById('mangle-modal-newroutingmark')) document.getElementById('mangle-modal-newroutingmark').value = '';
  5118. if (document.getElementById('mangle-modal-newpktmark')) document.getElementById('mangle-modal-newpktmark').value = '';
  5119. if (document.getElementById('mangle-modal-newmss')) document.getElementById('mangle-modal-newmss').value = '';
  5120. if (document.getElementById('mangle-modal-newdscp')) document.getElementById('mangle-modal-newdscp').value = '';
  5121. if (document.getElementById('mangle-modal-newttl')) document.getElementById('mangle-modal-newttl').value = '';
  5122. if (document.getElementById('mangle-modal-newpriority')) document.getElementById('mangle-modal-newpriority').value = '';
  5123. if (document.getElementById('mangle-modal-route')) document.getElementById('mangle-modal-route').value = '';
  5124. if (document.getElementById('mangle-modal-sniff')) document.getElementById('mangle-modal-sniff').value = '';
  5125. if (document.getElementById('mangle-modal-jumptarget')) document.getElementById('mangle-modal-jumptarget').value = '';
  5126. if (document.getElementById('mangle-modal-action-addrlist')) document.getElementById('mangle-modal-action-addrlist').value = '';
  5127. if (document.getElementById('mangle-modal-action-timeout')) document.getElementById('mangle-modal-action-timeout').value = '';
  5128. if (document.getElementById('mangle-modal-passthrough')) document.getElementById('mangle-modal-passthrough').checked = true;
  5129. if (document.getElementById('mangle-modal-log')) document.getElementById('mangle-modal-log').checked = false;
  5130. populateInterfaceSelect('mangle-val-iniface');
  5131. populateInterfaceSelect('mangle-val-outiface');
  5132. populateAddressListSelect('mangle-val-srclist');
  5133. populateAddressListSelect('mangle-val-dstlist');
  5134. populateGeoIPSelect('mangle-val-srcgeo');
  5135. populateGeoIPSelect('mangle-val-dstgeo');
  5136. allMangleFieldKeys.forEach(k => toggleMangleField(k, false));
  5137. resetMangleCounterDisplay();
  5138. toggleMangleActionFields();
  5139. document.getElementById('mangle-modal').classList.remove('hidden');
  5140. }
  5141. function openEditMangleModal(id) {
  5142. id = decodeURIComponent(id);
  5143. const r = (state.mangleRules || []).find(rule => rule.id === id);
  5144. if (!r) return;
  5145. switchMangleRuleTab('general');
  5146. const badge = document.getElementById('mangle-modal-badge');
  5147. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  5148. document.getElementById('mangle-modal-id').value = r.id;
  5149. document.getElementById('mangle-modal-family').value = String(r.ip_version || 4);
  5150. document.getElementById('mangle-modal-enabled').checked = !r.disabled;
  5151. document.getElementById('mangle-modal-comment').value = r.comment || '';
  5152. document.getElementById('mangle-modal-chain').value = r.chain || 'prerouting';
  5153. setFirewallActionSelection('mangle', r.action || 'accept');
  5154. if (document.getElementById('mangle-modal-newconnmark')) document.getElementById('mangle-modal-newconnmark').value = r.new_connection_mark || '';
  5155. if (document.getElementById('mangle-modal-newroutingmark')) document.getElementById('mangle-modal-newroutingmark').value = r.new_routing_mark || '';
  5156. if (document.getElementById('mangle-modal-newpktmark')) document.getElementById('mangle-modal-newpktmark').value = r.new_packet_mark || '';
  5157. if (document.getElementById('mangle-modal-newmss')) document.getElementById('mangle-modal-newmss').value = r.new_mss || '';
  5158. if (document.getElementById('mangle-modal-newdscp')) document.getElementById('mangle-modal-newdscp').value = r.new_dscp != null ? r.new_dscp : '';
  5159. if (document.getElementById('mangle-modal-newttl')) document.getElementById('mangle-modal-newttl').value = r.new_ttl || '';
  5160. if (document.getElementById('mangle-modal-newpriority')) document.getElementById('mangle-modal-newpriority').value = r.new_priority || '';
  5161. if (document.getElementById('mangle-modal-route')) document.getElementById('mangle-modal-route').value = r.route || '';
  5162. if (document.getElementById('mangle-modal-sniff')) document.getElementById('mangle-modal-sniff').value = r.sniff_target || '';
  5163. if (document.getElementById('mangle-modal-jumptarget')) document.getElementById('mangle-modal-jumptarget').value = r.jump_target || '';
  5164. if (document.getElementById('mangle-modal-action-addrlist')) document.getElementById('mangle-modal-action-addrlist').value = r.address_list || '';
  5165. if (document.getElementById('mangle-modal-action-timeout')) document.getElementById('mangle-modal-action-timeout').value = r.address_list_timeout || '';
  5166. if (document.getElementById('mangle-modal-passthrough')) document.getElementById('mangle-modal-passthrough').checked = r.passthrough ?? true;
  5167. if (document.getElementById('mangle-modal-log')) document.getElementById('mangle-modal-log').checked = !!r.log;
  5168. populateInterfaceSelect('mangle-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  5169. populateInterfaceSelect('mangle-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  5170. populateAddressListSelect('mangle-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  5171. populateAddressListSelect('mangle-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  5172. populateGeoIPSelect('mangle-val-srcgeo', r.src_geoip || '');
  5173. populateGeoIPSelect('mangle-val-dstgeo', r.dst_geoip || '');
  5174. setMangleFieldVal('src', r.src_address, true);
  5175. setMangleFieldVal('dst', r.dst_address, true);
  5176. setMangleFieldVal('srclist', r.src_address_list, true);
  5177. setMangleFieldVal('dstlist', r.dst_address_list, true);
  5178. setMangleFieldVal('srcgeo', r.src_geoip, true);
  5179. setMangleFieldVal('dstgeo', r.dst_geoip, true);
  5180. if (r.protocol && r.protocol !== 'all') {
  5181. setMangleFieldVal('proto', r.protocol, true);
  5182. } else {
  5183. toggleMangleField('proto', false);
  5184. }
  5185. setMangleFieldVal('sport', r.src_port, true);
  5186. setMangleFieldVal('dport', r.dst_port, true);
  5187. setMangleFieldVal('anyport', r.any_port, true);
  5188. setMangleFieldVal('iniface', r.in_interface, true);
  5189. setMangleFieldVal('outiface', r.out_interface, true);
  5190. setMangleFieldVal('inifacelist', r.in_interface_list, true);
  5191. setMangleFieldVal('outifacelist', r.out_interface_list, true);
  5192. setMangleFieldVal('pktmark', r.packet_mark, true);
  5193. setMangleFieldVal('connmark', r.connection_mark, true);
  5194. setMangleFieldVal('routingmark', r.routing_mark, true);
  5195. setMangleFieldVal('conntype', r.connection_type, false);
  5196. // Connection State
  5197. const states = r.connection_state || [];
  5198. if (states.length > 0) {
  5199. toggleMangleField('cs', true);
  5200. ['established', 'related', 'new', 'invalid', 'untracked'].forEach(s => {
  5201. const el = document.getElementById(`mangle-modal-cs-${s}`);
  5202. if (el) el.checked = states.includes(s);
  5203. });
  5204. } else {
  5205. toggleMangleField('cs', false);
  5206. }
  5207. // Connection NAT State
  5208. const natStates = r.connection_nat_state || [];
  5209. if (natStates.length > 0) {
  5210. toggleMangleField('natstate', true);
  5211. ['srcnat', 'dstnat'].forEach(s => {
  5212. const el = document.getElementById(`mangle-modal-nat-${s}`);
  5213. if (el) el.checked = natStates.includes(s);
  5214. });
  5215. } else {
  5216. toggleMangleField('natstate', false);
  5217. }
  5218. // Advanced tab fields
  5219. setMangleFieldVal('layer7', r.layer7_protocol, false);
  5220. setMangleFieldVal('content', r.content, false);
  5221. setMangleFieldVal('connbytes', r.connection_bytes, false);
  5222. setMangleFieldVal('connrate', r.connection_rate, false);
  5223. setMangleFieldVal('pcc', r.pcc, false);
  5224. setMangleFieldVal('srcmac', r.src_mac_address, true);
  5225. setMangleFieldVal('outbridgeport', r.out_bridge_port, false);
  5226. setMangleFieldVal('inbridgeport', r.in_bridge_port, false);
  5227. setMangleFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  5228. setMangleFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  5229. setMangleFieldVal('ipsec', r.ipsec_policy, false);
  5230. setMangleFieldVal('tlshost', r.tls_host, false);
  5231. setMangleFieldVal('ingresspriority', r.ingress_priority, false);
  5232. setMangleFieldVal('priority', r.priority, false);
  5233. setMangleFieldVal('dscp', r.dscp, false);
  5234. setMangleFieldVal('tcpmss', r.tcp_mss, false);
  5235. { const tosEl = document.getElementById('mangle-val-tos'); if (tosEl) tosEl.value = r.tos || ''; }
  5236. setMangleFieldVal('pktsize', r.packet_size, false);
  5237. setMangleFieldVal('random', r.random, false);
  5238. setMangleFieldVal('tcpflags', r.tcp_flags, false);
  5239. setMangleFieldVal('icmpoptions', r.icmp_options, false);
  5240. setMangleFieldVal('ipv4options', r.ipv4_options, false);
  5241. setMangleFieldVal('ttl', r.ttl, false);
  5242. // Extra tab fields
  5243. setMangleFieldVal('nth', r.nth, false);
  5244. setMangleFieldVal('connlimit', r.connection_limit, false);
  5245. setMangleFieldVal('srcaddrtype', r.src_address_type, false);
  5246. setMangleFieldVal('dstaddrtype', r.dst_address_type, false);
  5247. setMangleFieldVal('hotspot', r.hotspot, false);
  5248. setMangleFieldVal('ipfragment', r.ip_fragment, false);
  5249. setMangleFieldVal('limit', r.limit, false);
  5250. setMangleFieldVal('dstlimit', r.dst_limit, false);
  5251. setMangleFieldVal('time', r.time, false);
  5252. setMangleFieldVal('psd', r.psd, false);
  5253. // Action fields
  5254. if (r.jump_target) {
  5255. const jtEl = document.getElementById('mangle-modal-jumptarget');
  5256. if (jtEl) jtEl.value = r.jump_target;
  5257. }
  5258. if (r.address_list) {
  5259. const alEl = document.getElementById('mangle-modal-action-addrlist');
  5260. if (alEl) alEl.value = r.address_list;
  5261. }
  5262. if (r.address_list_timeout) {
  5263. const toEl = document.getElementById('mangle-modal-action-timeout');
  5264. if (toEl) toEl.value = r.address_list_timeout;
  5265. }
  5266. setMangleFieldVal('logprefix', r.log_prefix, false);
  5267. // Statistics
  5268. const bEl = document.getElementById('mangle-stat-bytes');
  5269. const pEl = document.getElementById('mangle-stat-packets');
  5270. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  5271. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  5272. state.mangleLastBytes = r.bytes || 0;
  5273. state.mangleLastPackets = r.packets || 0;
  5274. state.mangleLastTimestamp = Date.now();
  5275. state.mangleStatRateHistory = new Array(30).fill(0);
  5276. state.mangleStatPktHistory = new Array(30).fill(0);
  5277. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  5278. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  5279. toggleMangleActionFields();
  5280. document.getElementById('mangle-modal').classList.remove('hidden');
  5281. }
  5282. function closeMangleModal() {
  5283. stopMangleStatPolling();
  5284. document.getElementById('mangle-modal').classList.add('hidden');
  5285. }
  5286. function copyMangleRule() {
  5287. document.getElementById('mangle-modal-id').value = '';
  5288. const badge = document.getElementById('mangle-modal-badge');
  5289. if (badge) badge.innerText = 'New...';
  5290. showToast('Rule Cloned', 'Ready to save as a new Mangle rule copy', 'info');
  5291. }
  5292. function resetMangleCounterDisplay() {
  5293. state.mangleStatRateHistory = new Array(30).fill(0);
  5294. state.mangleStatPktHistory = new Array(30).fill(0);
  5295. state.mangleLastBytes = 0;
  5296. state.mangleLastPackets = 0;
  5297. state.mangleLastTimestamp = Date.now();
  5298. const bEl = document.getElementById('mangle-stat-bytes');
  5299. const pEl = document.getElementById('mangle-stat-packets');
  5300. const rEl = document.getElementById('mangle-stat-rate');
  5301. const prEl = document.getElementById('mangle-stat-pktrate');
  5302. if (bEl) bEl.value = '0 B';
  5303. if (pEl) pEl.value = '0';
  5304. if (rEl) rEl.value = '0 bps';
  5305. if (prEl) prEl.value = '0 p/s';
  5306. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  5307. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  5308. showToast('Counters Reset', 'Mangle rule counter display reset to 0', 'info');
  5309. }
  5310. async function applyMangleRule(closeAfter = false) {
  5311. const id = document.getElementById('mangle-modal-id').value;
  5312. if (!reviewLegacyFirewallSettings('mangle', id)) return;
  5313. const chain = document.getElementById('mangle-modal-chain').value;
  5314. const action = document.getElementById('mangle-modal-action').value;
  5315. const comment = document.getElementById('mangle-modal-comment').value.trim();
  5316. const enabled = document.getElementById('mangle-modal-enabled').checked;
  5317. const src = getMangleFieldVal('src', true);
  5318. const dst = getMangleFieldVal('dst', true);
  5319. const srclist = getMangleFieldVal('srclist', true);
  5320. const dstlist = getMangleFieldVal('dstlist', true);
  5321. const srcgeo = getMangleFieldVal('srcgeo', true);
  5322. const dstgeo = getMangleFieldVal('dstgeo', true);
  5323. const proto = getMangleFieldVal('proto', true);
  5324. const sport = getMangleFieldVal('sport', true);
  5325. const dport = getMangleFieldVal('dport', true);
  5326. const anyport = getMangleFieldVal('anyport', true);
  5327. if ((sport || dport || anyport) && !['tcp', 'udp'].includes(proto)) {
  5328. switchMangleRuleTab('general'); toggleMangleField('proto', true);
  5329. showToast('Select protocol', 'Port matches require TCP or UDP without protocol inversion.', 'error'); document.getElementById('mangle-val-proto').focus(); return;
  5330. }
  5331. const iniface = getMangleFieldVal('iniface', true);
  5332. const outiface = getMangleFieldVal('outiface', true);
  5333. const inifacelist = getMangleFieldVal('inifacelist', true);
  5334. const outifacelist = getMangleFieldVal('outifacelist', true);
  5335. const pktmark = getMangleFieldVal('pktmark', true);
  5336. const connmark = getMangleFieldVal('connmark', true);
  5337. const routingmark = getMangleFieldVal('routingmark', true);
  5338. const conntype = getMangleFieldVal('conntype', false);
  5339. const states = [];
  5340. const csBox = document.getElementById('mangle-field-cs');
  5341. if (csBox && !csBox.classList.contains('hidden')) {
  5342. ['established', 'related', 'new', 'invalid', 'untracked'].forEach(s => {
  5343. if (document.getElementById(`mangle-modal-cs-${s}`)?.checked) states.push(s);
  5344. });
  5345. }
  5346. const natStates = [];
  5347. const natBox = document.getElementById('mangle-field-natstate');
  5348. if (natBox && !natBox.classList.contains('hidden')) {
  5349. ['srcnat', 'dstnat'].forEach(s => {
  5350. if (document.getElementById(`mangle-modal-nat-${s}`)?.checked) natStates.push(s);
  5351. });
  5352. }
  5353. const payload = {
  5354. ip_version: Number(document.getElementById('mangle-modal-family').value),
  5355. id,
  5356. chain,
  5357. action,
  5358. protocol: proto || 'all',
  5359. src_address: src,
  5360. dst_address: dst,
  5361. src_port: sport,
  5362. dst_port: dport,
  5363. any_port: anyport,
  5364. in_interface: iniface,
  5365. out_interface: outiface,
  5366. in_interface_list: inifacelist,
  5367. out_interface_list: outifacelist,
  5368. packet_mark: pktmark,
  5369. connection_mark: connmark,
  5370. routing_mark: routingmark,
  5371. connection_type: conntype,
  5372. connection_state: states,
  5373. connection_nat_state: natStates,
  5374. src_address_list: srclist,
  5375. dst_address_list: dstlist,
  5376. src_geoip: srcgeo,
  5377. dst_geoip: dstgeo,
  5378. comment,
  5379. disabled: !enabled,
  5380. // Advanced tab
  5381. content: getMangleFieldVal('content', false),
  5382. src_mac_address: getMangleFieldVal('srcmac', true),
  5383. out_bridge_port: getMangleFieldVal('outbridgeport', false),
  5384. in_bridge_port: getMangleFieldVal('inbridgeport', false),
  5385. ipsec_policy: getMangleFieldVal('ipsec', false),
  5386. dscp: getMangleFieldVal('dscp', false),
  5387. tcp_mss: getMangleFieldVal('tcpmss', false),
  5388. tos: document.getElementById('mangle-val-tos')?.value || '',
  5389. packet_size: getMangleFieldVal('pktsize', false),
  5390. random: getMangleFieldVal('random', false),
  5391. tcp_flags: getMangleFieldVal('tcpflags', false),
  5392. icmp_options: getMangleFieldVal('icmpoptions', false),
  5393. ttl: getMangleFieldVal('ttl', false),
  5394. // Extra tab
  5395. nth: getMangleFieldVal('nth', false),
  5396. connection_limit: getMangleFieldVal('connlimit', false),
  5397. src_address_type: getMangleFieldVal('srcaddrtype', false),
  5398. dst_address_type: getMangleFieldVal('dstaddrtype', false),
  5399. ip_fragment: getMangleFieldVal('ipfragment', false),
  5400. limit: getMangleFieldVal('limit', false),
  5401. time: getMangleFieldVal('time', false),
  5402. // Action tab
  5403. new_connection_mark: action === 'mark-connection' ? (document.getElementById('mangle-modal-newconnmark')?.value.trim() || '') : '',
  5404. new_routing_mark: action === 'mark-routing' ? (document.getElementById('mangle-modal-newroutingmark')?.value.trim() || '') : '',
  5405. new_packet_mark: action === 'mark-packet' ? (document.getElementById('mangle-modal-newpktmark')?.value.trim() || '') : '',
  5406. new_mss: action === 'change-mss' ? (document.getElementById('mangle-modal-newmss')?.value.trim() || '') : '',
  5407. new_dscp: action === 'change-dscp' ? parseInt(document.getElementById('mangle-modal-newdscp')?.value || '0', 10) : 0,
  5408. new_ttl: action === 'change-ttl' ? (document.getElementById('mangle-modal-newttl')?.value.trim() || '') : '',
  5409. new_priority: action === 'set-priority' ? (document.getElementById('mangle-modal-newpriority')?.value.trim() || '') : '',
  5410. passthrough: document.getElementById('mangle-modal-passthrough')?.checked ?? true,
  5411. jump_target: action === 'jump' ? (document.getElementById('mangle-modal-jumptarget')?.value || '') : '',
  5412. address_list: action.includes('address') ? (document.getElementById('mangle-modal-action-addrlist')?.value || '') : '',
  5413. address_list_timeout: action.includes('address') ? (document.getElementById('mangle-modal-action-timeout')?.value || '') : '',
  5414. log: document.getElementById('mangle-modal-log')?.checked || false,
  5415. log_prefix: getMangleFieldVal('logprefix', false)
  5416. };
  5417. try {
  5418. const res = await fetch(`${API_BASE}/firewall/mangle`, {
  5419. method: 'POST',
  5420. headers: { 'Content-Type': 'application/json' },
  5421. body: JSON.stringify(payload)
  5422. });
  5423. if (res.ok) {
  5424. const data = await res.json();
  5425. showToast('Mangle Rule Saved', 'Marking rule updated', 'success');
  5426. loadFirewall(false);
  5427. if (closeAfter) {
  5428. closeMangleModal();
  5429. } else {
  5430. if (data.id) {
  5431. document.getElementById('mangle-modal-id').value = data.id;
  5432. const badge = document.getElementById('mangle-modal-badge');
  5433. if (badge) badge.innerText = `#${data.id}`;
  5434. }
  5435. }
  5436. } else {
  5437. const err = await res.json();
  5438. showToast('Error', err.message || 'Failed to save mangle rule', 'error');
  5439. }
  5440. } catch (err) {
  5441. showToast('Error', err.message, 'error');
  5442. }
  5443. }
  5444. function submitSaveMangleRule(e) {
  5445. if (e && e.preventDefault) e.preventDefault();
  5446. return applyMangleRule(true);
  5447. }
  5448. function startMangleStatPolling() {
  5449. stopMangleStatPolling();
  5450. pollMangleRuleStats();
  5451. state.mangleStatInterval = setInterval(pollMangleRuleStats, 1000);
  5452. }
  5453. function stopMangleStatPolling() {
  5454. if (state.mangleStatInterval) {
  5455. clearInterval(state.mangleStatInterval);
  5456. state.mangleStatInterval = null;
  5457. }
  5458. }
  5459. async function pollMangleRuleStats() {
  5460. const id = document.getElementById('mangle-modal-id')?.value;
  5461. if (!id) {
  5462. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory || new Array(30).fill(0), 'bps', 'mangle-stat-legend-rate');
  5463. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory || new Array(30).fill(0), 'p/s', 'mangle-stat-legend-pktrate');
  5464. return;
  5465. }
  5466. try {
  5467. const res = await fetch(`${API_BASE}/firewall/mangle`);
  5468. if (!res.ok) return;
  5469. const rules = await res.json();
  5470. const r = rules.find(x => x.id === id);
  5471. if (!r) return;
  5472. const now = Date.now();
  5473. const dt = Math.max(0.2, (now - (state.mangleLastTimestamp || now)) / 1000);
  5474. state.mangleLastTimestamp = now;
  5475. const curBytes = r.bytes || 0;
  5476. const curPackets = r.packets || 0;
  5477. const deltaBytes = Math.max(0, curBytes - (state.mangleLastBytes ?? curBytes));
  5478. const deltaPkts = Math.max(0, curPackets - (state.mangleLastPackets ?? curPackets));
  5479. state.mangleLastBytes = curBytes;
  5480. state.mangleLastPackets = curPackets;
  5481. const rateBps = Math.round((deltaBytes * 8) / dt);
  5482. const ratePkt = Math.round(deltaPkts / dt);
  5483. if (!state.mangleStatRateHistory) state.mangleStatRateHistory = new Array(30).fill(0);
  5484. if (!state.mangleStatPktHistory) state.mangleStatPktHistory = new Array(30).fill(0);
  5485. state.mangleStatRateHistory.push(rateBps);
  5486. if (state.mangleStatRateHistory.length > 30) state.mangleStatRateHistory.shift();
  5487. state.mangleStatPktHistory.push(ratePkt);
  5488. if (state.mangleStatPktHistory.length > 30) state.mangleStatPktHistory.shift();
  5489. const bEl = document.getElementById('mangle-stat-bytes');
  5490. const pEl = document.getElementById('mangle-stat-packets');
  5491. const rEl = document.getElementById('mangle-stat-rate');
  5492. const prEl = document.getElementById('mangle-stat-pktrate');
  5493. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  5494. if (pEl) pEl.value = curPackets.toLocaleString();
  5495. if (rEl) rEl.value = formatBps(rateBps);
  5496. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  5497. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  5498. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  5499. } catch (e) {
  5500. console.error('Error polling Mangle rule stats', e);
  5501. }
  5502. }
  5503. async function moveMangleRule(id, dir) {
  5504. id = decodeURIComponent(id);
  5505. try {
  5506. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/move`, {
  5507. method: 'POST',
  5508. headers: { 'Content-Type': 'application/json' },
  5509. body: JSON.stringify({ direction: dir })
  5510. });
  5511. if (!res.ok) throw new Error(await responseError(res));
  5512. await loadFirewall(false);
  5513. } catch (err) {
  5514. showToast('Error', err.message, 'error');
  5515. }
  5516. }
  5517. async function toggleMangleRuleState(id, disabled) {
  5518. id = decodeURIComponent(id);
  5519. try {
  5520. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/state`, {
  5521. method: 'POST',
  5522. headers: { 'Content-Type': 'application/json' },
  5523. body: JSON.stringify({ disabled })
  5524. });
  5525. if (!res.ok) throw new Error(await responseError(res));
  5526. await loadFirewall(false);
  5527. } catch (err) {
  5528. showToast('Error', err.message, 'error');
  5529. }
  5530. }
  5531. async function deleteMangleRule(id) {
  5532. id = decodeURIComponent(id);
  5533. if (!confirm('Are you sure you want to delete this mangle rule?')) return;
  5534. try {
  5535. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5536. if (!res.ok) throw new Error(await responseError(res));
  5537. {
  5538. showToast('Deleted', 'Mangle rule removed', 'success');
  5539. loadFirewall(false);
  5540. }
  5541. } catch (err) {
  5542. showToast('Error', err.message, 'error');
  5543. }
  5544. }
  5545. // ----------------- Address Lists -----------------
  5546. function renderAddressLists() {
  5547. const filterList = document.getElementById('addrlist-filter-name')?.value || '';
  5548. const tbody = document.getElementById('addrlist-table-body');
  5549. const empty = document.getElementById('addrlist-empty');
  5550. if (!tbody) return;
  5551. tbody.innerHTML = '';
  5552. const entries = (state.addressLists || []).filter(e => !filterList || e.name === filterList);
  5553. document.getElementById('addrlist-count-badge').innerText = `${entries.length} Entries${entries.filter(e => e.dynamic).length >= 2000 ? ' (dynamic results capped at 2000)' : ''}`;
  5554. // Update filter select
  5555. const sel = document.getElementById('addrlist-filter-name');
  5556. if (sel) {
  5557. const cur = sel.value;
  5558. sel.innerHTML = '<option value="">All Lists</option>';
  5559. const set = new Set((state.addressLists || []).map(a => a.name));
  5560. set.forEach(n => {
  5561. const opt = document.createElement('option');
  5562. opt.value = n;
  5563. opt.innerText = n;
  5564. if (n === cur) opt.selected = true;
  5565. sel.appendChild(opt);
  5566. });
  5567. }
  5568. if (entries.length === 0) {
  5569. empty?.classList.remove('hidden');
  5570. return;
  5571. }
  5572. empty?.classList.add('hidden');
  5573. entries.forEach((raw, idx) => {
  5574. const e = safeFirewallRow(raw);
  5575. const tr = document.createElement('tr');
  5576. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${e.disabled ? 'opacity-50' : ''}`;
  5577. if (!e.dynamic) tr.setAttribute('ondblclick', `openEditAddrListModal('${e.id}')`);
  5578. tr.innerHTML = `
  5579. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  5580. <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>
  5581. <td class="py-2.5 px-3 font-bold text-white font-mono">${e.name}</td>
  5582. <td class="py-2.5 px-3 font-mono font-bold text-emerald-400">${e.address}</td>
  5583. <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>
  5584. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  5585. ${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>
  5586. <button onclick="openEditAddrListModal('${e.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-medium">Edit</button>
  5587. `}
  5588. <button onclick="deleteAddrList('${e.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  5589. </td>
  5590. `;
  5591. tbody.appendChild(tr);
  5592. });
  5593. populateCommonAddrListDatalist();
  5594. }
  5595. function openAddAddrListModal() {
  5596. document.getElementById('addrlist-modal-title').innerText = 'Add Address List Entry';
  5597. document.getElementById('addrlist-modal-id').value = '';
  5598. document.getElementById('addrlist-modal-name').value = '';
  5599. document.getElementById('addrlist-modal-addr').value = '';
  5600. document.getElementById('addrlist-modal-comment').value = '';
  5601. document.getElementById('addrlist-modal-disabled').checked = false;
  5602. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  5603. if (submitBtn) submitBtn.innerText = 'Add to List';
  5604. document.getElementById('addrlist-modal').classList.remove('hidden');
  5605. }
  5606. function openEditAddrListModal(id) {
  5607. id = decodeURIComponent(id);
  5608. const e = (state.addressLists || []).find(item => item.id === id);
  5609. if (!e) return;
  5610. document.getElementById('addrlist-modal-title').innerText = `Edit Address List Entry: ${e.name}`;
  5611. document.getElementById('addrlist-modal-id').value = e.id;
  5612. document.getElementById('addrlist-modal-name').value = e.name;
  5613. document.getElementById('addrlist-modal-addr').value = e.address;
  5614. document.getElementById('addrlist-modal-comment').value = e.comment || '';
  5615. document.getElementById('addrlist-modal-disabled').checked = !!e.disabled;
  5616. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  5617. if (submitBtn) submitBtn.innerText = 'Save Changes';
  5618. document.getElementById('addrlist-modal').classList.remove('hidden');
  5619. }
  5620. function closeAddrListModal() {
  5621. document.getElementById('addrlist-modal').classList.add('hidden');
  5622. }
  5623. async function submitSaveAddrList(e) {
  5624. e.preventDefault();
  5625. const id = document.getElementById('addrlist-modal-id').value;
  5626. const name = document.getElementById('addrlist-modal-name').value.trim();
  5627. const addr = document.getElementById('addrlist-modal-addr').value.trim();
  5628. const comment = document.getElementById('addrlist-modal-comment').value.trim();
  5629. const disabled = document.getElementById('addrlist-modal-disabled').checked;
  5630. try {
  5631. const res = await fetch(`${API_BASE}/firewall/address-lists`, {
  5632. method: 'POST',
  5633. headers: { 'Content-Type': 'application/json' },
  5634. body: JSON.stringify({ id, name, address: addr, comment, disabled })
  5635. });
  5636. if (res.ok) {
  5637. showToast('Address List Item Saved', `Saved ${addr} in ${name}`, 'success');
  5638. closeAddrListModal();
  5639. loadFirewall(false);
  5640. } else {
  5641. const err = await res.json();
  5642. showToast('Error', err.message || 'Failed to save address list', 'error');
  5643. }
  5644. } catch (err) {
  5645. showToast('Error', err.message, 'error');
  5646. }
  5647. }
  5648. async function toggleAddrListState(id, disabled) {
  5649. id = decodeURIComponent(id);
  5650. try {
  5651. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}/state`, {
  5652. method: 'POST',
  5653. headers: { 'Content-Type': 'application/json' },
  5654. body: JSON.stringify({ disabled })
  5655. });
  5656. if (res.ok) {
  5657. loadFirewall(false);
  5658. }
  5659. } catch (err) {
  5660. showToast('Error', err.message, 'error');
  5661. }
  5662. }
  5663. async function deleteAddrList(id) {
  5664. id = decodeURIComponent(id);
  5665. if (!confirm('Are you sure you want to delete this address list item?')) return;
  5666. try {
  5667. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5668. if (res.ok) {
  5669. showToast('Deleted', 'Address list item removed', 'info');
  5670. loadFirewall(false);
  5671. }
  5672. } catch (err) {
  5673. showToast('Error', err.message, 'error');
  5674. }
  5675. }
  5676. // ----------------- Geo-Location IP Management -----------------
  5677. async function loadGeoIP() {
  5678. try {
  5679. const [statusRes, countriesRes] = await Promise.all([
  5680. fetch(`${API_BASE}/firewall/geoip/status`),
  5681. fetch(`${API_BASE}/firewall/geoip/countries`)
  5682. ]);
  5683. if (statusRes.ok) state.geoStatus = await statusRes.json();
  5684. if (countriesRes.ok) state.geoCountries = await countriesRes.json();
  5685. updateGeoHeader();
  5686. renderGeoCountries();
  5687. } catch (err) {
  5688. console.error('Failed to load GeoIP:', err);
  5689. }
  5690. }
  5691. function getGeoUsageMap() {
  5692. const usage = {};
  5693. const checkRule = (r, type) => {
  5694. ['src_geoip', 'dst_geoip'].forEach(field => {
  5695. let val = (r && r[field]) || '';
  5696. let code = val.replace(/^!/, '').replace(/^geo:/, '').replace(/^geo_/, '').toUpperCase().trim();
  5697. if (code) {
  5698. if (!usage[code]) usage[code] = [];
  5699. const label = `${type} #${r.priority !== undefined ? r.priority : (r.id || '')}`;
  5700. if (!usage[code].includes(label)) usage[code].push(label);
  5701. }
  5702. });
  5703. };
  5704. (state.filterRules || []).forEach(r => checkRule(r, 'Filter'));
  5705. (state.natRules || []).forEach(r => checkRule(r, 'NAT'));
  5706. (state.mangleRules || []).forEach(r => checkRule(r, 'Mangle'));
  5707. return usage;
  5708. }
  5709. function updateGeoHeader() {
  5710. const s = state.geoStatus || {};
  5711. const statusBadge = document.getElementById('geo-status-badge');
  5712. if (statusBadge) {
  5713. statusBadge.innerText = s.auto_update ? 'Auto-Update ON' : 'Auto-Update OFF';
  5714. statusBadge.className = s.auto_update
  5715. ? 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-emerald-500/20 text-emerald-300 border border-emerald-500/30'
  5716. : 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 text-slate-400';
  5717. }
  5718. const intervalLabel = document.getElementById('geo-interval-label');
  5719. if (intervalLabel) {
  5720. intervalLabel.innerText = `Every ${s.interval_hours || 24}h`;
  5721. }
  5722. const usageMap = getGeoUsageMap();
  5723. const inUseCount = Object.keys(usageMap).length;
  5724. const activeCountEl = document.getElementById('geo-stat-active-countries');
  5725. if (activeCountEl) activeCountEl.innerText = inUseCount.toLocaleString();
  5726. const totalSubnetsEl = document.getElementById('geo-stat-total-subnets');
  5727. if (totalSubnetsEl) totalSubnetsEl.innerText = (s.total_subnets || 0).toLocaleString();
  5728. const lastSyncEl = document.getElementById('geo-stat-last-sync');
  5729. if (lastSyncEl) {
  5730. if (s.last_updated && !s.last_updated.startsWith('0001')) {
  5731. const d = new Date(s.last_updated);
  5732. lastSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  5733. } else {
  5734. lastSyncEl.innerText = 'Never (Sync Pending)';
  5735. }
  5736. }
  5737. const nextSyncEl = document.getElementById('geo-stat-next-sync');
  5738. if (nextSyncEl) {
  5739. if (s.next_update && !s.next_update.startsWith('0001')) {
  5740. const d = new Date(s.next_update);
  5741. nextSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  5742. } else {
  5743. nextSyncEl.innerText = '-';
  5744. }
  5745. }
  5746. const badge = document.getElementById('fw-badge-geo');
  5747. if (badge) badge.innerText = inUseCount || (state.geoCountries || []).filter(c => c.subnet_count > 0).length || 0;
  5748. }
  5749. function renderGeoCountries() {
  5750. const tbody = document.getElementById('geo-table-body');
  5751. const empty = document.getElementById('geo-empty');
  5752. if (!tbody) return;
  5753. tbody.innerHTML = '';
  5754. const q = (document.getElementById('geo-search-input')?.value || '').trim().toLowerCase();
  5755. const continent = document.getElementById('geo-continent-filter')?.value || '';
  5756. const inUseOnly = document.getElementById('geo-filter-inuse-only')?.checked;
  5757. const cachedOnly = document.getElementById('geo-filter-cached-only')?.checked;
  5758. const usageMap = getGeoUsageMap();
  5759. const countries = (state.geoCountries || []).filter(c => {
  5760. const isUsed = !!usageMap[c.code];
  5761. if (inUseOnly && !isUsed) return false;
  5762. if (cachedOnly && (!c.subnet_count || c.subnet_count === 0)) return false;
  5763. if (continent && c.continent !== continent) return false;
  5764. if (q) {
  5765. const matchCode = c.code.toLowerCase().includes(q);
  5766. const matchName = c.name.toLowerCase().includes(q);
  5767. if (!matchCode && !matchName) return false;
  5768. }
  5769. return true;
  5770. });
  5771. if (countries.length === 0) {
  5772. empty?.classList.remove('hidden');
  5773. return;
  5774. }
  5775. empty?.classList.add('hidden');
  5776. countries.forEach(c => {
  5777. const tr = document.createElement('tr');
  5778. const isUsed = !!usageMap[c.code];
  5779. const rulesUsing = usageMap[c.code] || [];
  5780. tr.className = `hover:bg-slate-800/40 transition text-xs ${isUsed ? 'bg-emerald-950/20' : ''}`;
  5781. let statusHtml = '';
  5782. if (isUsed) {
  5783. 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>`;
  5784. } else if (c.subnet_count > 0) {
  5785. 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>';
  5786. } else {
  5787. statusHtml = '<span class="px-2 py-0.5 rounded text-[10px] font-mono text-slate-500 bg-slate-800/60">READY</span>';
  5788. }
  5789. tr.innerHTML = `
  5790. <td class="py-2.5 px-3 text-center">
  5791. <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'}">
  5792. ${c.code}
  5793. </span>
  5794. </td>
  5795. <td class="py-2.5 px-3 font-bold text-white">${c.name}</td>
  5796. <td class="py-2.5 px-3 text-slate-400">${c.continent}</td>
  5797. <td class="py-2.5 px-3 font-mono ${c.subnet_count > 0 ? 'text-emerald-400 font-bold' : 'text-slate-500'}">
  5798. ${c.subnet_count > 0 ? c.subnet_count.toLocaleString() + ' CIDRs' : 'Not Cached'}
  5799. </td>
  5800. <td class="py-2.5 px-3 font-mono text-purple-300">${c.ipset_name}</td>
  5801. <td class="py-2.5 px-3">
  5802. ${statusHtml}
  5803. </td>
  5804. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  5805. <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>
  5806. <button onclick="viewGeoSubnets('${c.code}')" class="text-xs text-slate-400 hover:text-white" title="Preview Subnet Ranges">View</button>
  5807. </td>
  5808. `;
  5809. tbody.appendChild(tr);
  5810. });
  5811. }
  5812. function quickFilterGeo(preset) {
  5813. const searchInput = document.getElementById('geo-search-input');
  5814. const continentSel = document.getElementById('geo-continent-filter');
  5815. const inUseCheck = document.getElementById('geo-filter-inuse-only');
  5816. const cachedCheck = document.getElementById('geo-filter-cached-only');
  5817. if (searchInput) searchInput.value = '';
  5818. if (continentSel) continentSel.value = '';
  5819. if (inUseCheck) inUseCheck.checked = false;
  5820. if (cachedCheck) cachedCheck.checked = false;
  5821. if (preset === 'GR') {
  5822. if (searchInput) searchInput.value = 'Greece';
  5823. } else if (preset === 'Europe') {
  5824. if (continentSel) continentSel.value = 'Europe';
  5825. } else if (preset === 'HIGHRISK') {
  5826. if (searchInput) searchInput.value = 'China';
  5827. }
  5828. renderGeoCountries();
  5829. }
  5830. async function toggleGeoCountry(code, enabled) {
  5831. try {
  5832. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/toggle`, {
  5833. method: 'POST',
  5834. headers: { 'Content-Type': 'application/json' },
  5835. body: JSON.stringify({ enabled })
  5836. });
  5837. if (res.ok) {
  5838. showToast(enabled ? 'Country Enabled' : 'Country Disabled', `${code} ${enabled ? 'active in firewall' : 'removed from firewall'}`, 'success');
  5839. loadGeoIP();
  5840. } else {
  5841. const err = await res.json();
  5842. showToast('Error', err.message || 'Failed to toggle country', 'error');
  5843. }
  5844. } catch (err) {
  5845. showToast('Error', err.message, 'error');
  5846. }
  5847. }
  5848. async function updateGeoCountry(code) {
  5849. try {
  5850. showToast('Syncing Country', `Downloading latest IP blocks for ${code}...`, 'info');
  5851. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/update`, { method: 'POST' });
  5852. if (res.ok) {
  5853. const data = await res.json();
  5854. showToast('Synced', `Loaded ${data.subnets} CIDR blocks for ${code}`, 'success');
  5855. loadGeoIP();
  5856. } else {
  5857. const err = await res.json();
  5858. showToast('Sync Error', err.message || 'Failed to sync country', 'error');
  5859. }
  5860. } catch (err) {
  5861. showToast('Error', err.message, 'error');
  5862. }
  5863. }
  5864. async function triggerGeoUpdateNow() {
  5865. const spinner = document.getElementById('geo-update-spinner');
  5866. if (spinner) spinner.classList.remove('hidden');
  5867. try {
  5868. const res = await fetch(`${API_BASE}/firewall/geoip/update-now`, { method: 'POST' });
  5869. if (res.ok) {
  5870. showToast('Update Started', 'Updating all active GeoIP country zones in background...', 'info');
  5871. setTimeout(() => {
  5872. loadGeoIP();
  5873. if (spinner) spinner.classList.add('hidden');
  5874. }, 2500);
  5875. } else {
  5876. const err = await res.json();
  5877. showToast('Notice', err.message || 'Update in progress', 'info');
  5878. if (spinner) spinner.classList.add('hidden');
  5879. }
  5880. } catch (err) {
  5881. showToast('Error', err.message, 'error');
  5882. if (spinner) spinner.classList.add('hidden');
  5883. }
  5884. }
  5885. async function applyGeoPreset(preset) {
  5886. try {
  5887. const res = await fetch(`${API_BASE}/firewall/geoip/batch-toggle`, {
  5888. method: 'POST',
  5889. headers: { 'Content-Type': 'application/json' },
  5890. body: JSON.stringify({ preset, enabled: preset !== 'NONE' })
  5891. });
  5892. if (res.ok) {
  5893. showToast('Preset Applied', `Preset ${preset} updated in firewall`, 'success');
  5894. loadGeoIP();
  5895. }
  5896. } catch (err) {
  5897. showToast('Error', err.message, 'error');
  5898. }
  5899. }
  5900. function openGeoIntervalModal() {
  5901. const s = state.geoStatus || {};
  5902. document.getElementById('geo-cfg-autoupdate').checked = s.auto_update !== false;
  5903. const sel = document.getElementById('geo-cfg-interval');
  5904. const customBox = document.getElementById('geo-cfg-custom-box');
  5905. const customHoursInput = document.getElementById('geo-cfg-custom-hours');
  5906. const curHours = s.interval_hours || 24;
  5907. const matchOption = Array.from(sel.options).find(o => parseInt(o.value, 10) === curHours);
  5908. if (matchOption) {
  5909. sel.value = String(curHours);
  5910. customBox.classList.add('hidden');
  5911. } else {
  5912. sel.value = 'custom';
  5913. customHoursInput.value = curHours;
  5914. customBox.classList.remove('hidden');
  5915. }
  5916. document.getElementById('geo-interval-modal').classList.remove('hidden');
  5917. }
  5918. function closeGeoIntervalModal() {
  5919. document.getElementById('geo-interval-modal').classList.add('hidden');
  5920. }
  5921. function toggleCustomGeoInterval() {
  5922. const val = document.getElementById('geo-cfg-interval').value;
  5923. const customBox = document.getElementById('geo-cfg-custom-box');
  5924. if (val === 'custom') {
  5925. customBox.classList.remove('hidden');
  5926. } else {
  5927. customBox.classList.add('hidden');
  5928. }
  5929. }
  5930. async function submitGeoIntervalSettings(e) {
  5931. e.preventDefault();
  5932. const autoUpdate = document.getElementById('geo-cfg-autoupdate').checked;
  5933. const intervalVal = document.getElementById('geo-cfg-interval').value;
  5934. let hours = 24;
  5935. if (intervalVal === 'custom') {
  5936. hours = parseInt(document.getElementById('geo-cfg-custom-hours').value, 10) || 24;
  5937. } else {
  5938. hours = parseInt(intervalVal, 10) || 24;
  5939. }
  5940. try {
  5941. const res = await fetch(`${API_BASE}/firewall/geoip/config`, {
  5942. method: 'POST',
  5943. headers: { 'Content-Type': 'application/json' },
  5944. body: JSON.stringify({ auto_update: autoUpdate, interval_hours: hours })
  5945. });
  5946. if (res.ok) {
  5947. showToast('Schedule Saved', `Auto-update set to every ${hours} hours`, 'success');
  5948. closeGeoIntervalModal();
  5949. loadGeoIP();
  5950. } else {
  5951. const err = await res.json();
  5952. showToast('Error', err.message || 'Failed to save schedule', 'error');
  5953. }
  5954. } catch (err) {
  5955. showToast('Error', err.message, 'error');
  5956. }
  5957. }
  5958. async function viewGeoSubnets(code, name) {
  5959. if (!name) {
  5960. const found = (state.geoCountries || []).find(x => x.code === code);
  5961. name = found ? found.name : code;
  5962. }
  5963. document.getElementById('geo-subnets-title').innerText = `${name} (${code}) Subnets`;
  5964. document.getElementById('geo-subnets-subtitle').innerText = `Kernel IPSet: mk_geo_${code}`;
  5965. const listEl = document.getElementById('geo-subnets-list');
  5966. listEl.innerHTML = '<span class="text-slate-500">Loading subnets...</span>';
  5967. document.getElementById('geo-subnets-modal').classList.remove('hidden');
  5968. try {
  5969. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/subnets`);
  5970. if (res.ok) {
  5971. const data = await res.json();
  5972. const subnets = data.subnets || [];
  5973. if (subnets.length === 0) {
  5974. listEl.innerHTML = '<span class="text-slate-500">No cached subnets found. Click Sync to download this zone.</span>';
  5975. } else {
  5976. listEl.innerHTML = subnets.map(s => `<div>${s}</div>`).join('');
  5977. }
  5978. } else {
  5979. listEl.innerHTML = '<span class="text-rose-400">Failed to load subnets.</span>';
  5980. }
  5981. } catch (err) {
  5982. listEl.innerHTML = `<span class="text-rose-400">Error: ${err.message}</span>`;
  5983. }
  5984. }
  5985. function closeGeoSubnetsModal() {
  5986. document.getElementById('geo-subnets-modal').classList.add('hidden');
  5987. }
  5988. // ----------------- Active Connections Tracking -----------------
  5989. async function loadConnections() {
  5990. try {
  5991. const res = await fetch(`${API_BASE}/firewall/connections`);
  5992. const data = await res.json();
  5993. if (!res.ok) throw new Error(data.message || 'Connection tracking unavailable');
  5994. state.connections = Array.isArray(data) ? data : [];
  5995. document.getElementById('fw-badge-connections').innerText = state.connections.length;
  5996. document.getElementById('conns-count-badge').innerText = `${state.connections.length} Flows`;
  5997. renderConnections();
  5998. } catch (err) {
  5999. console.error('Failed to load connections:', err);
  6000. const badge=document.getElementById('conns-count-badge'); if(badge) badge.textContent='Unavailable: '+err.message;
  6001. }
  6002. }
  6003. function renderConnections() {
  6004. const search = (document.getElementById('conns-search-input')?.value || '').toLowerCase();
  6005. const protoFilter = document.getElementById('conns-filter-proto')?.value || '';
  6006. const tbody = document.getElementById('conns-table-body');
  6007. const empty = document.getElementById('conns-empty');
  6008. if (!tbody) return;
  6009. tbody.innerHTML = '';
  6010. const conns = (state.connections || []).filter(c => {
  6011. if (protoFilter && c.protocol !== protoFilter) return false;
  6012. if (search) {
  6013. const line = `${c.protocol} ${c.src_address} ${c.dst_address} ${c.src_port} ${c.dst_port} ${c.tcp_state} ${c.connection_mark}`.toLowerCase();
  6014. if (!line.includes(search)) return false;
  6015. }
  6016. return true;
  6017. });
  6018. if (conns.length === 0) {
  6019. empty?.classList.remove('hidden');
  6020. return;
  6021. }
  6022. empty?.classList.add('hidden');
  6023. conns.slice(0, 150).forEach(c => {
  6024. const tr = document.createElement('tr');
  6025. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  6026. let stateColor = 'text-slate-400';
  6027. if (c.tcp_state === 'ESTABLISHED') stateColor = 'text-emerald-400 font-bold';
  6028. else if (c.tcp_state === 'TIME_WAIT' || c.tcp_state === 'SYN_SENT') stateColor = 'text-amber-400';
  6029. tr.innerHTML = `
  6030. <td class="py-2.5 px-3 font-bold text-cyan-400">${c.protocol}</td>
  6031. <td class="py-2.5 px-3 font-mono text-white">${c.src_address}:${c.src_port}</td>
  6032. <td class="py-2.5 px-3 font-mono text-white">${c.dst_address}:${c.dst_port}</td>
  6033. <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>
  6034. <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>
  6035. <td class="py-2.5 px-3 font-mono ${stateColor}">${c.tcp_state}</td>
  6036. <td class="py-2.5 px-3 font-mono text-purple-300">${c.connection_mark || '-'}</td>
  6037. <td class="py-2.5 px-3 text-slate-500">${c.timeout ? c.timeout + 's' : '-'}</td>
  6038. <td class="py-2.5 px-3 text-right font-sans">
  6039. ${['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>` : ''}
  6040. </td>
  6041. `;
  6042. tbody.appendChild(tr);
  6043. });
  6044. }
  6045. async function killConnection(protocol, src, sport, dst, dport, ip_version, zone, icmp_id, icmp_type, icmp_code) {
  6046. try {
  6047. const res = await fetch(`${API_BASE}/firewall/connections/kill`, {
  6048. method: 'POST',
  6049. headers: { 'Content-Type': 'application/json' },
  6050. body: JSON.stringify({ protocol, src, sport, dst, dport, ip_version, zone, icmp_id, icmp_type, icmp_code })
  6051. });
  6052. if (res.ok) {
  6053. showToast('Terminated', `Killed flow ${src}:${sport} -> ${dst}:${dport}`, 'info');
  6054. loadConnections();
  6055. } else { const error = await res.json(); showToast('Error', error.message || 'Unable to terminate this flow', 'error'); }
  6056. } catch (err) {
  6057. showToast('Error', err.message, 'error');
  6058. }
  6059. }
  6060. async function resetFirewallCounters() {
  6061. if (!confirm('Reset all firewall packet and byte counters to zero?')) return;
  6062. try {
  6063. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  6064. if (res.ok) {
  6065. showToast('Counters Reset', 'All rules counters reset to 0', 'success');
  6066. loadFirewall(false);
  6067. }
  6068. } catch (err) {
  6069. showToast('Error', err.message, 'error');
  6070. }
  6071. }
  6072. // ======================== MIKROTIK ROUTING & POLICY (/ip route) ========================
  6073. function switchRoutesSubTab(tab) {
  6074. state.routesSubTab = tab;
  6075. const tabs = ['routes', 'rules', 'tables'];
  6076. tabs.forEach(t => {
  6077. const panel = document.getElementById(`routes-subtab-${t}`);
  6078. const btn = document.getElementById(`routes-subtab-btn-${t}`);
  6079. if (panel) {
  6080. if (t === tab) panel.classList.remove('hidden');
  6081. else panel.classList.add('hidden');
  6082. }
  6083. if (btn) {
  6084. if (t === tab) {
  6085. 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';
  6086. } else {
  6087. 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';
  6088. }
  6089. }
  6090. });
  6091. setTimeout(initTableSorting, 50);
  6092. }
  6093. async function loadRoutes() {
  6094. try {
  6095. const [routesRes, rulesRes, tablesRes] = await Promise.all([
  6096. fetch(`${API_BASE}/routes`),
  6097. fetch(`${API_BASE}/routing/rules`),
  6098. fetch(`${API_BASE}/routing/tables`)
  6099. ]);
  6100. if (routesRes.ok) state.routes = await routesRes.json();
  6101. if (rulesRes.ok) state.policyRules = await rulesRes.json();
  6102. if (tablesRes.ok) state.routingTables = await tablesRes.json();
  6103. const bRoutes = document.getElementById('routes-badge-routes');
  6104. if (bRoutes) bRoutes.innerText = (state.routes || []).length;
  6105. const showSystem = document.getElementById('prule-show-system')?.checked;
  6106. const userRules = (state.policyRules || []).filter(pr => showSystem || (!pr.is_default && !pr.is_system));
  6107. const bRules = document.getElementById('routes-badge-rules');
  6108. if (bRules) bRules.innerText = userRules.length;
  6109. const bTables = document.getElementById('routes-badge-tables');
  6110. if (bTables) bTables.innerText = (state.routingTables || []).length;
  6111. const bRoutesCount = document.getElementById('badge-routes-count');
  6112. if (bRoutesCount) bRoutesCount.innerText = (state.routes || []).length;
  6113. renderRoutesList();
  6114. renderPolicyRules();
  6115. renderRoutingTables();
  6116. } catch (err) {
  6117. console.error('Failed to load routing:', err);
  6118. }
  6119. }
  6120. function getRouteProtocolBadge(proto) {
  6121. const p = (proto || 'static').toLowerCase();
  6122. switch (p) {
  6123. case 'bgp':
  6124. 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>`;
  6125. case 'ibgp':
  6126. 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>`;
  6127. case 'ospf':
  6128. 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>`;
  6129. case 'rip':
  6130. 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>`;
  6131. case 'static':
  6132. 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>`;
  6133. case 'connected':
  6134. 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>`;
  6135. case 'dhcp':
  6136. 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>`;
  6137. case 'multicast':
  6138. 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>`;
  6139. default:
  6140. 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>`;
  6141. }
  6142. }
  6143. function renderRoutesList() {
  6144. const tableFilter = document.getElementById('routes-filter-table')?.value || '';
  6145. const typeFilter = document.getElementById('routes-filter-type')?.value || '';
  6146. const tbody = document.getElementById('routes-table-body');
  6147. const empty = document.getElementById('routes-empty');
  6148. if (!tbody) return;
  6149. // Update table filter select
  6150. const sel = document.getElementById('routes-filter-table');
  6151. if (sel) {
  6152. const cur = sel.value;
  6153. sel.innerHTML = '<option value="">All Tables</option>';
  6154. (state.routingTables || []).forEach(t => {
  6155. const opt = document.createElement('option');
  6156. opt.value = t.name;
  6157. opt.innerText = t.name;
  6158. if (t.name === cur) opt.selected = true;
  6159. sel.appendChild(opt);
  6160. });
  6161. }
  6162. const routes = (state.routes || []).filter(r => {
  6163. if (tableFilter && r.routing_table !== tableFilter) return false;
  6164. if (typeFilter === 'ecmp' && !r.ecmp) return false;
  6165. if (typeFilter === 'multicast' && !r.multicast) return false;
  6166. if (typeFilter === 'static' && !r.static) return false;
  6167. if (typeFilter === 'dynamic' && !r.dynamic) return false;
  6168. if (typeFilter === 'connected' && !r.connect) return false;
  6169. if (typeFilter === 'bgp' && (r.protocol || '').toLowerCase() !== 'bgp' && (r.protocol || '').toLowerCase() !== 'ibgp') return false;
  6170. if (typeFilter === 'ospf' && (r.protocol || '').toLowerCase() !== 'ospf') return false;
  6171. if (typeFilter === 'dhcp' && (r.protocol || '').toLowerCase() !== 'dhcp') return false;
  6172. return true;
  6173. });
  6174. const ecmpCount = (state.routes || []).filter(r => r.ecmp).length;
  6175. const mcCount = (state.routes || []).filter(r => r.multicast).length;
  6176. let summaryText = `${routes.length} Routes`;
  6177. if (ecmpCount > 0) summaryText += ` • ${ecmpCount} ECMP`;
  6178. if (mcCount > 0) summaryText += ` • ${mcCount} Multicast/IGMP`;
  6179. const badgeEl = document.getElementById('routes-count-badge');
  6180. if (badgeEl) badgeEl.innerText = summaryText;
  6181. if (routes.length === 0) {
  6182. empty?.classList.remove('hidden');
  6183. tbody.innerHTML = '';
  6184. return;
  6185. }
  6186. empty?.classList.add('hidden');
  6187. 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(';');
  6188. if (tbody.dataset.sig === sig) {
  6189. return; // Routes table unchanged! Do not wipe DOM or flicker!
  6190. }
  6191. tbody.dataset.sig = sig;
  6192. tbody.innerHTML = '';
  6193. routes.forEach(r => {
  6194. const tr = document.createElement('tr');
  6195. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${r.disabled ? 'opacity-50' : ''}`;
  6196. tr.setAttribute('ondblclick', `openEditRouteModal('${r.id}')`);
  6197. // Routing Flags string: D=Dynamic, A=Active, C=Connect, S=Static, E=ECMP, M=Multicast, X=Disabled
  6198. let flags = '';
  6199. if (r.dynamic) flags += 'D';
  6200. if (r.active) flags += 'A';
  6201. if (r.connect) flags += 'C';
  6202. if (r.static) flags += 'S';
  6203. if (r.ecmp) flags += 'E';
  6204. if (r.multicast) flags += 'M';
  6205. if (r.disabled) flags += 'X';
  6206. const isDefault = r.dst_address === 'default' || r.dst_address === '0.0.0.0/0';
  6207. let healthCell = `<span class="text-slate-600 font-mono text-[11px]">-</span>`;
  6208. if (r.check_gateway === 'internet') {
  6209. if (r.health_status === 'online') {
  6210. const ms = (r.health_rtt_ms || 0).toFixed(0);
  6211. healthCell = `
  6212. <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)">
  6213. <span class="w-1.5 h-1.5 rounded-full bg-emerald-400 animate-pulse"></span>
  6214. <span>Internet OK (${ms}ms)</span>
  6215. </span>
  6216. `;
  6217. } else if (r.health_status === 'offline') {
  6218. healthCell = `
  6219. <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.">
  6220. <span class="w-1.5 h-1.5 rounded-full bg-rose-400"></span>
  6221. <span>Internet Down</span>
  6222. </span>
  6223. `;
  6224. } else {
  6225. healthCell = `
  6226. <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">
  6227. <span class="w-1.5 h-1.5 rounded-full bg-amber-400 animate-ping"></span>
  6228. <span>Checking...</span>
  6229. </span>
  6230. `;
  6231. }
  6232. } else if (r.check_gateway === 'ping') {
  6233. if (r.health_status === 'online') {
  6234. healthCell = `
  6235. <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">
  6236. <span class="w-1.5 h-1.5 rounded-full bg-cyan-400"></span>
  6237. <span>Gateway OK (${(r.health_rtt_ms || 0).toFixed(0)}ms)</span>
  6238. </span>
  6239. `;
  6240. } else if (r.health_status === 'offline') {
  6241. healthCell = `
  6242. <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">
  6243. <span class="w-1.5 h-1.5 rounded-full bg-rose-400"></span>
  6244. <span>Gateway Dead</span>
  6245. </span>
  6246. `;
  6247. }
  6248. }
  6249. const flagDescriptions = [];
  6250. if (r.dynamic) flagDescriptions.push('Dynamic (D)');
  6251. if (r.active) flagDescriptions.push('Active (A)');
  6252. if (r.connect) flagDescriptions.push('Connected (C)');
  6253. if (r.static) flagDescriptions.push('Static (S)');
  6254. if (r.ecmp) flagDescriptions.push('ECMP - Equal-Cost Multi-Path (E)');
  6255. if (r.multicast) flagDescriptions.push('Multicast / IGMP Group (M)');
  6256. if (r.disabled) flagDescriptions.push('Disabled (X)');
  6257. tr.innerHTML = `
  6258. <td class="py-2.5 px-3 text-center">
  6259. <span class="px-1.5 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 ${
  6260. 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')
  6261. }" title="Flags: ${flagDescriptions.join(', ')}">
  6262. ${flags || '-'}
  6263. </span>
  6264. </td>
  6265. <td class="py-2.5 px-3">
  6266. <div class="flex items-center gap-1.5 flex-wrap">
  6267. <span class="font-bold ${isDefault ? 'text-cyan-300' : 'text-white'}">${escapeHtml(r.dst_address)}</span>
  6268. ${r.ecmp ? `
  6269. <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)">
  6270. <span>⚡ ECMP</span>
  6271. </span>
  6272. ` : ''}
  6273. ${r.multicast ? `
  6274. <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">
  6275. <span>IGMP</span>
  6276. </span>
  6277. ` : ''}
  6278. </div>
  6279. </td>
  6280. <td class="py-2.5 px-3">${getRouteProtocolBadge(r.protocol)}</td>
  6281. <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>
  6282. <td class="py-2.5 px-3 text-slate-400 font-mono">${(r.distance !== undefined && r.distance !== null) ? r.distance : 0}</td>
  6283. <td class="py-2.5 px-3 font-mono font-semibold text-purple-300">${r.routing_table || 'main'}</td>
  6284. <td class="py-2.5 px-3 text-emerald-400 font-mono">${r.interface || '-'}</td>
  6285. <td class="py-2.5 px-3">${healthCell}</td>
  6286. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]">${r.comment || '-'}</td>
  6287. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  6288. ${r.static ? `
  6289. <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>
  6290. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold">Edit</button>
  6291. <button onclick="deleteRoute('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  6292. ` : `
  6293. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">View</button>
  6294. `}
  6295. </td>
  6296. `;
  6297. tbody.appendChild(tr);
  6298. });
  6299. }
  6300. function openAddRouteModal() {
  6301. document.getElementById('route-modal-title').innerText = 'Add Static Route';
  6302. document.getElementById('route-modal-id').value = '';
  6303. document.getElementById('route-modal-old-dst').value = '';
  6304. document.getElementById('route-modal-old-gw').value = '';
  6305. document.getElementById('route-modal-old-distance').value = '';
  6306. document.getElementById('route-modal-old-table').value = '';
  6307. document.getElementById('route-modal-old-iface').value = '';
  6308. const dstInput = document.getElementById('route-modal-dst');
  6309. const gwInput = document.getElementById('route-modal-gw');
  6310. const distInput = document.getElementById('route-modal-distance');
  6311. const ifaceSelect = document.getElementById('route-modal-iface');
  6312. const tableSelect = document.getElementById('route-modal-table');
  6313. const commentInput = document.getElementById('route-modal-comment');
  6314. const disCheck = document.getElementById('route-modal-disabled');
  6315. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  6316. dstInput.disabled = false;
  6317. dstInput.value = '0.0.0.0/0';
  6318. gwInput.disabled = false;
  6319. gwInput.value = '';
  6320. distInput.disabled = false;
  6321. distInput.value = '1';
  6322. ifaceSelect.disabled = false;
  6323. tableSelect.disabled = false;
  6324. commentInput.disabled = false;
  6325. commentInput.value = '';
  6326. disCheck.disabled = false;
  6327. disCheck.checked = false;
  6328. if (saveBtn) saveBtn.classList.remove('hidden');
  6329. const checkGw = document.getElementById('route-modal-check-gw');
  6330. if (checkGw) checkGw.value = 'internet';
  6331. const checkTarget = document.getElementById('route-modal-check-target');
  6332. if (checkTarget) checkTarget.value = '1.1.1.1';
  6333. const checkInterval = document.getElementById('route-modal-check-interval');
  6334. if (checkInterval) checkInterval.value = '5';
  6335. const checkThresh = document.getElementById('route-modal-check-threshold');
  6336. if (checkThresh) checkThresh.value = '3';
  6337. toggleRouteCheckModeUI();
  6338. populateInterfaceSelect('route-modal-iface');
  6339. // Populate tables
  6340. tableSelect.innerHTML = '';
  6341. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  6342. const opt = document.createElement('option');
  6343. opt.value = t.name;
  6344. opt.innerText = t.name;
  6345. if (t.name === 'main') opt.selected = true;
  6346. tableSelect.appendChild(opt);
  6347. });
  6348. document.getElementById('route-modal').classList.remove('hidden');
  6349. }
  6350. function openEditRouteModal(id) {
  6351. const r = (state.routes || []).find(route => route.id === id);
  6352. if (!r) return;
  6353. const isStatic = !!r.static;
  6354. document.getElementById('route-modal-title').innerText = isStatic
  6355. ? `Edit Route: ${r.dst_address}`
  6356. : `Route Properties (Read Only): ${r.dst_address}`;
  6357. document.getElementById('route-modal-id').value = r.id;
  6358. document.getElementById('route-modal-old-dst').value = r.dst_address || '';
  6359. document.getElementById('route-modal-old-gw').value = r.gateway || '';
  6360. document.getElementById('route-modal-old-distance').value = (r.distance !== undefined && r.distance !== null) ? r.distance : '';
  6361. document.getElementById('route-modal-old-table').value = r.routing_table || 'main';
  6362. document.getElementById('route-modal-old-iface').value = r.interface || '';
  6363. const dstInput = document.getElementById('route-modal-dst');
  6364. const gwInput = document.getElementById('route-modal-gw');
  6365. const distInput = document.getElementById('route-modal-distance');
  6366. const ifaceSelect = document.getElementById('route-modal-iface');
  6367. const tableSelect = document.getElementById('route-modal-table');
  6368. const commentInput = document.getElementById('route-modal-comment');
  6369. const disCheck = document.getElementById('route-modal-disabled');
  6370. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  6371. dstInput.value = r.dst_address;
  6372. gwInput.value = r.gateway || '';
  6373. distInput.value = (r.distance !== undefined && r.distance !== null) ? r.distance : 1;
  6374. commentInput.value = r.comment || '';
  6375. disCheck.checked = !!r.disabled;
  6376. const checkGw = document.getElementById('route-modal-check-gw');
  6377. if (checkGw) checkGw.value = r.check_gateway || 'none';
  6378. const checkTarget = document.getElementById('route-modal-check-target');
  6379. if (checkTarget) checkTarget.value = r.check_target || '1.1.1.1';
  6380. const checkInterval = document.getElementById('route-modal-check-interval');
  6381. if (checkInterval) checkInterval.value = r.check_interval || 5;
  6382. const checkThresh = document.getElementById('route-modal-check-threshold');
  6383. if (checkThresh) checkThresh.value = r.check_threshold || 3;
  6384. toggleRouteCheckModeUI();
  6385. dstInput.disabled = !isStatic;
  6386. gwInput.disabled = !isStatic;
  6387. distInput.disabled = !isStatic;
  6388. ifaceSelect.disabled = !isStatic;
  6389. tableSelect.disabled = !isStatic;
  6390. commentInput.disabled = !isStatic;
  6391. disCheck.disabled = !isStatic;
  6392. if (checkGw) checkGw.disabled = !isStatic;
  6393. if (checkTarget) checkTarget.disabled = !isStatic;
  6394. if (checkInterval) checkInterval.disabled = !isStatic;
  6395. if (checkThresh) checkThresh.disabled = !isStatic;
  6396. if (saveBtn) {
  6397. if (isStatic) {
  6398. saveBtn.classList.remove('hidden');
  6399. } else {
  6400. saveBtn.classList.add('hidden');
  6401. }
  6402. }
  6403. populateInterfaceSelect('route-modal-iface', r.interface);
  6404. tableSelect.innerHTML = '';
  6405. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  6406. const opt = document.createElement('option');
  6407. opt.value = t.name;
  6408. opt.innerText = t.name;
  6409. if (t.name === (r.routing_table || 'main')) opt.selected = true;
  6410. tableSelect.appendChild(opt);
  6411. });
  6412. document.getElementById('route-modal').classList.remove('hidden');
  6413. }
  6414. function closeRouteModal() {
  6415. document.getElementById('route-modal').classList.add('hidden');
  6416. }
  6417. function setRouteCheckTarget(ip) {
  6418. const inp = document.getElementById('route-modal-check-target');
  6419. if (inp) inp.value = ip;
  6420. }
  6421. function toggleRouteCheckModeUI() {
  6422. const mode = document.getElementById('route-modal-check-gw')?.value || 'none';
  6423. const targetRow = document.getElementById('route-row-check-target');
  6424. const paramsRow = document.getElementById('route-row-check-params');
  6425. if (mode === 'none') {
  6426. if (targetRow) targetRow.classList.add('opacity-40', 'pointer-events-none');
  6427. if (paramsRow) paramsRow.classList.add('opacity-40', 'pointer-events-none');
  6428. } else if (mode === 'ping') {
  6429. if (targetRow) targetRow.classList.add('opacity-40', 'pointer-events-none');
  6430. if (paramsRow) paramsRow.classList.remove('opacity-40', 'pointer-events-none');
  6431. } else { // internet
  6432. if (targetRow) targetRow.classList.remove('opacity-40', 'pointer-events-none');
  6433. if (paramsRow) paramsRow.classList.remove('opacity-40', 'pointer-events-none');
  6434. }
  6435. }
  6436. async function submitSaveRoute(e) {
  6437. e.preventDefault();
  6438. const id = document.getElementById('route-modal-id').value;
  6439. const oldDst = document.getElementById('route-modal-old-dst')?.value || '';
  6440. const oldGw = document.getElementById('route-modal-old-gw')?.value || '';
  6441. const oldDistStr = document.getElementById('route-modal-old-distance')?.value;
  6442. const oldTable = document.getElementById('route-modal-old-table')?.value || '';
  6443. const oldIface = document.getElementById('route-modal-old-iface')?.value || '';
  6444. const dst = document.getElementById('route-modal-dst').value.trim();
  6445. const gw = document.getElementById('route-modal-gw').value.trim();
  6446. const table = document.getElementById('route-modal-table').value;
  6447. const distance = parseInt(document.getElementById('route-modal-distance').value, 10) || 0;
  6448. const iface = document.getElementById('route-modal-iface').value;
  6449. const comment = document.getElementById('route-modal-comment').value.trim();
  6450. const disabled = document.getElementById('route-modal-disabled').checked;
  6451. const check_gateway = document.getElementById('route-modal-check-gw')?.value || 'none';
  6452. const check_target = document.getElementById('route-modal-check-target')?.value.trim() || '1.1.1.1';
  6453. const check_interval = parseInt(document.getElementById('route-modal-check-interval')?.value, 10) || 5;
  6454. const check_threshold = parseInt(document.getElementById('route-modal-check-threshold')?.value, 10) || 3;
  6455. if (!dst) {
  6456. showToast('Error', 'Destination address is required', 'error');
  6457. return;
  6458. }
  6459. if (!gw && !iface) {
  6460. showToast('Error', 'Either Gateway IP or Interface must be specified', 'error');
  6461. return;
  6462. }
  6463. const payload = {
  6464. id,
  6465. old_dst_address: oldDst,
  6466. old_gateway: oldGw,
  6467. old_routing_table: oldTable,
  6468. old_interface: oldIface,
  6469. dst_address: dst,
  6470. gateway: gw || iface,
  6471. routing_table: table,
  6472. distance,
  6473. interface: iface,
  6474. comment,
  6475. disabled,
  6476. check_gateway,
  6477. check_target,
  6478. check_interval,
  6479. check_threshold
  6480. };
  6481. if (oldDistStr !== undefined && oldDistStr !== '') {
  6482. payload.old_distance = parseInt(oldDistStr, 10);
  6483. }
  6484. try {
  6485. const res = await fetch(`${API_BASE}/routes`, {
  6486. method: 'POST',
  6487. headers: { 'Content-Type': 'application/json' },
  6488. body: JSON.stringify(payload)
  6489. });
  6490. if (res.ok) {
  6491. showToast('Route Saved', `Route to ${dst} installed`, 'success');
  6492. closeRouteModal();
  6493. loadRoutes();
  6494. } else {
  6495. const err = await res.json();
  6496. showToast('Error', err.message || 'Failed to save route', 'error');
  6497. }
  6498. } catch (err) {
  6499. showToast('Error', err.message, 'error');
  6500. }
  6501. }
  6502. async function toggleRouteState(id, disabled) {
  6503. try {
  6504. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}/state`, {
  6505. method: 'POST',
  6506. headers: { 'Content-Type': 'application/json' },
  6507. body: JSON.stringify({ disabled })
  6508. });
  6509. if (res.ok) loadRoutes();
  6510. } catch (err) {
  6511. showToast('Error', err.message, 'error');
  6512. }
  6513. }
  6514. async function deleteRoute(id) {
  6515. if (!confirm('Are you sure you want to delete this route?')) return;
  6516. try {
  6517. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6518. if (res.ok) {
  6519. showToast('Deleted', 'Route removed', 'success');
  6520. loadRoutes();
  6521. }
  6522. } catch (err) {
  6523. showToast('Error', err.message, 'error');
  6524. }
  6525. }
  6526. // ----------------- Policy Rules (/ip route rule) -----------------
  6527. function renderPolicyRules() {
  6528. const tbody = document.getElementById('rules-table-body');
  6529. const empty = document.getElementById('rules-empty');
  6530. if (!tbody) return;
  6531. const showSystem = document.getElementById('prule-show-system')?.checked;
  6532. const filtered = (state.policyRules || []).filter(pr => showSystem || (!pr.is_default && !pr.is_system));
  6533. const countBadge = document.getElementById('rules-count-badge');
  6534. if (countBadge) countBadge.innerText = `${filtered.length} Rules`;
  6535. const bRules = document.getElementById('routes-badge-rules');
  6536. if (bRules) bRules.innerText = filtered.length;
  6537. if (filtered.length === 0) {
  6538. empty?.classList.remove('hidden');
  6539. tbody.innerHTML = '';
  6540. return;
  6541. }
  6542. empty?.classList.add('hidden');
  6543. const sig = `${showSystem}|` + filtered.map(pr => `${pr.id}:${pr.priority}:${pr.src_address}:${pr.dst_address}:${pr.table}:${pr.routing_mark}`).join(';');
  6544. if (tbody.dataset.sig === sig) return;
  6545. tbody.dataset.sig = sig;
  6546. tbody.innerHTML = '';
  6547. filtered.forEach(pr => {
  6548. const isSys = pr.is_default || pr.is_system;
  6549. const tr = document.createElement('tr');
  6550. tr.className = `hover:bg-slate-800/40 transition text-xs ${isSys ? 'opacity-70 bg-slate-950/20' : ''}`;
  6551. tr.innerHTML = `
  6552. <td class="py-2.5 px-3 font-mono text-cyan-400 font-bold">${pr.priority}</td>
  6553. <td class="py-2.5 px-3 font-mono text-white">${pr.src_address || '<span class="text-slate-600">all</span>'}</td>
  6554. <td class="py-2.5 px-3 font-mono text-white">${pr.dst_address || '<span class="text-slate-600">all</span>'}</td>
  6555. <td class="py-2.5 px-3 font-mono font-bold text-purple-300">${pr.routing_mark || '<span class="text-slate-600">-</span>'}</td>
  6556. <td class="py-2.5 px-3 font-mono font-bold text-amber-300">${pr.table}</td>
  6557. <td class="py-2.5 px-3 font-mono text-slate-300">${pr.action}</td>
  6558. <td class="py-2.5 px-3 text-right font-sans">
  6559. ${!pr.is_default ? `
  6560. <button onclick="deletePolicyRule('${pr.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  6561. ` : `<span class="text-slate-600 text-[10px]">Default</span>`}
  6562. </td>
  6563. `;
  6564. tbody.appendChild(tr);
  6565. });
  6566. }
  6567. function openAddPolicyRuleModal() {
  6568. const userRules = (state.policyRules || []).filter(pr => !pr.is_default && !pr.is_system);
  6569. document.getElementById('prule-modal-pref').value = userRules.length * 10 + 1000;
  6570. document.getElementById('prule-modal-mark').value = '';
  6571. document.getElementById('prule-modal-src').value = '';
  6572. document.getElementById('prule-modal-dst').value = '';
  6573. const sel = document.getElementById('prule-modal-table');
  6574. sel.innerHTML = '';
  6575. (state.routingTables || []).forEach(t => {
  6576. const opt = document.createElement('option');
  6577. opt.value = t.name;
  6578. opt.innerText = t.name;
  6579. sel.appendChild(opt);
  6580. });
  6581. document.getElementById('prule-modal').classList.remove('hidden');
  6582. }
  6583. function closePolicyRuleModal() {
  6584. document.getElementById('prule-modal').classList.add('hidden');
  6585. }
  6586. async function submitSavePolicyRule(e) {
  6587. e.preventDefault();
  6588. const pref = parseInt(document.getElementById('prule-modal-pref').value, 10) || 1000;
  6589. const mark = document.getElementById('prule-modal-mark').value.trim();
  6590. const src = document.getElementById('prule-modal-src').value.trim();
  6591. const dst = document.getElementById('prule-modal-dst').value.trim();
  6592. const table = document.getElementById('prule-modal-table').value;
  6593. const action = document.getElementById('prule-modal-action').value;
  6594. try {
  6595. const res = await fetch(`${API_BASE}/routing/rules`, {
  6596. method: 'POST',
  6597. headers: { 'Content-Type': 'application/json' },
  6598. body: JSON.stringify({ priority: pref, routing_mark: mark, src_address: src, dst_address: dst, table, action })
  6599. });
  6600. if (res.ok) {
  6601. showToast('Rule Added', `Policy rule installed for table ${table}`, 'success');
  6602. closePolicyRuleModal();
  6603. loadRoutes();
  6604. } else {
  6605. const err = await res.json();
  6606. showToast('Error', err.message, 'error');
  6607. }
  6608. } catch (err) {
  6609. showToast('Error', err.message, 'error');
  6610. }
  6611. }
  6612. async function deletePolicyRule(id) {
  6613. if (!confirm('Are you sure you want to remove this policy rule?')) return;
  6614. try {
  6615. const res = await fetch(`${API_BASE}/routing/rules/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6616. if (res.ok) {
  6617. showToast('Rule Removed', 'Policy rule deleted', 'success');
  6618. loadRoutes();
  6619. }
  6620. } catch (err) {
  6621. showToast('Error', err.message, 'error');
  6622. }
  6623. }
  6624. // ----------------- Routing Tables -----------------
  6625. function renderRoutingTables() {
  6626. const tbody = document.getElementById('tables-table-body');
  6627. if (!tbody) return;
  6628. const tables = state.routingTables || [];
  6629. const sig = tables.map(t => `${t.table_id}:${t.name}:${t.comment}`).join(';');
  6630. if (tbody.dataset.sig === sig) return;
  6631. tbody.dataset.sig = sig;
  6632. tbody.innerHTML = '';
  6633. (state.routingTables || []).forEach(t => {
  6634. const tr = document.createElement('tr');
  6635. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  6636. tr.innerHTML = `
  6637. <td class="py-2.5 px-3 text-cyan-400 font-bold">${t.table_id}</td>
  6638. <td class="py-2.5 px-3 font-bold text-white">${t.name}</td>
  6639. <td class="py-2.5 px-3 text-slate-400 italic">${t.comment || '-'}</td>
  6640. `;
  6641. tbody.appendChild(tr);
  6642. });
  6643. }
  6644. function openAddTableModal() {
  6645. document.getElementById('table-modal-name').value = '';
  6646. document.getElementById('table-modal-id').value = '';
  6647. document.getElementById('table-modal-comment').value = '';
  6648. document.getElementById('table-modal').classList.remove('hidden');
  6649. }
  6650. function closeTableModal() {
  6651. document.getElementById('table-modal').classList.add('hidden');
  6652. }
  6653. async function submitSaveTable(e) {
  6654. e.preventDefault();
  6655. const name = document.getElementById('table-modal-name').value.trim();
  6656. const id = parseInt(document.getElementById('table-modal-id').value, 10) || 0;
  6657. const comment = document.getElementById('table-modal-comment').value.trim();
  6658. try {
  6659. const res = await fetch(`${API_BASE}/routing/tables`, {
  6660. method: 'POST',
  6661. headers: { 'Content-Type': 'application/json' },
  6662. body: JSON.stringify({ name, table_id: id, comment })
  6663. });
  6664. if (res.ok) {
  6665. showToast('Table Created', `Routing table ${name} registered`, 'success');
  6666. closeTableModal();
  6667. loadRoutes();
  6668. } else {
  6669. const err = await res.json();
  6670. showToast('Error', err.message, 'error');
  6671. }
  6672. } catch (err) {
  6673. showToast('Error', err.message, 'error');
  6674. }
  6675. }
  6676. async function loadDebianConfig() {
  6677. const view = document.getElementById('debian-config-view');
  6678. view.innerText = 'Generating live configuration...';
  6679. try {
  6680. const res = await fetch(`${API_BASE}/debian/config`);
  6681. const data = await res.json();
  6682. view.innerText = data.content || '# Empty config';
  6683. } catch (err) {
  6684. view.innerText = 'Failed to generate Debian network config.';
  6685. }
  6686. }
  6687. async function saveDebianConfig() {
  6688. try {
  6689. const res = await fetch(`${API_BASE}/debian/apply`, { method: 'POST' });
  6690. const data = await res.json();
  6691. if (res.ok) {
  6692. showToast('Configuration Saved', data.message || 'Saved to /etc/network/interfaces.d/vlans.cfg', 'success');
  6693. loadDebianConfig();
  6694. }
  6695. } catch (err) {
  6696. showToast('Error', err.message, 'error');
  6697. }
  6698. }
  6699. function showToast(title, message, type = 'info') {
  6700. const container = document.getElementById('toast-container');
  6701. const toast = document.createElement('div');
  6702. const borderColors = {
  6703. success: 'border-emerald-500/40 bg-slate-900/95 text-emerald-400',
  6704. error: 'border-rose-500/40 bg-slate-900/95 text-rose-400',
  6705. info: 'border-cyan-500/40 bg-slate-900/95 text-cyan-400'
  6706. };
  6707. 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}`;
  6708. toast.innerHTML = `
  6709. <div class="flex-1">
  6710. <div class="font-bold text-xs text-white">${escapeHtml(title)}</div>
  6711. <div class="text-[11px] text-slate-300 mt-0.5 leading-relaxed font-sans">${escapeHtml(message)}</div>
  6712. </div>
  6713. `;
  6714. container.appendChild(toast);
  6715. requestAnimationFrame(() => toast.classList.remove('translate-y-2', 'opacity-0'));
  6716. setTimeout(() => {
  6717. toast.classList.add('opacity-0', 'translate-y-2');
  6718. setTimeout(() => toast.remove(), 300);
  6719. }, 4000);
  6720. }
  6721. function formatTraffic(bytesPerSec) {
  6722. if (bytesPerSec < 1024) return `${Math.round(bytesPerSec)} B/s`;
  6723. const kb = bytesPerSec / 1024;
  6724. if (kb < 1024) return `${kb.toFixed(1)} KB/s`;
  6725. const mb = kb / 1024;
  6726. return `${mb.toFixed(2)} MB/s`;
  6727. }
  6728. function toggleSidebar() {
  6729. const sb = document.getElementById('sidebar');
  6730. sb.classList.toggle('-translate-x-full');
  6731. }
  6732. // ======================== EoIP (Ethernet over IP) ========================
  6733. async function loadEoIP(populate = true) {
  6734. try {
  6735. const res = await fetch(`${API_BASE}/vpn/eoip`);
  6736. const data = await res.json();
  6737. state.eoipTunnels = Array.isArray(data) ? data : [];
  6738. const badge = document.getElementById('eoip-count-badge');
  6739. if (badge) badge.innerText = `${state.eoipTunnels.length} Tunnels`;
  6740. const sideBadge = document.getElementById('badge-eoip-count');
  6741. if (sideBadge) sideBadge.innerText = state.eoipTunnels.length;
  6742. renderEoIPTunnels();
  6743. } catch (err) {
  6744. console.error('Failed to load EoIP:', err);
  6745. }
  6746. }
  6747. function renderEoIPTunnels() {
  6748. const tbody = document.getElementById('eoip-table-body');
  6749. const empty = document.getElementById('eoip-empty');
  6750. if (!tbody) return;
  6751. tbody.innerHTML = '';
  6752. const tunnels = state.eoipTunnels || [];
  6753. if (tunnels.length === 0) {
  6754. empty?.classList.remove('hidden');
  6755. return;
  6756. }
  6757. empty?.classList.add('hidden');
  6758. tunnels.forEach(t => {
  6759. const tr = document.createElement('tr');
  6760. tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
  6761. tr.innerHTML = `
  6762. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.running, t.disabled)}</td>
  6763. <td class="py-2.5 px-3 font-bold text-white font-mono">${t.name}</td>
  6764. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${t.tunnel_id}</td>
  6765. <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>
  6766. <td class="py-2.5 px-3 text-cyan-300 font-mono">${t.remote_address}</td>
  6767. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.local_address || '(any)'}</td>
  6768. <td class="py-2.5 px-3 text-slate-300 font-mono text-[11px]">${t.mac_address || '-'}</td>
  6769. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.mtu || 1500}</td>
  6770. <td class="py-2.5 px-3 font-mono text-[11px]">
  6771. <span class="text-emerald-400">↓ ${t.rx_human || '0 B'}</span>
  6772. <span class="text-cyan-400 ml-1">↑ ${t.tx_human || '0 B'}</span>
  6773. </td>
  6774. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${t.comment || ''}">${t.comment || '-'}</td>
  6775. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  6776. <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>
  6777. <button onclick="openEditEoIPModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  6778. <button onclick="deleteEoIP('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  6779. </td>
  6780. `;
  6781. tbody.appendChild(tr);
  6782. });
  6783. }
  6784. function openAddEoIPModal() {
  6785. document.getElementById('eoip-modal-title').innerText = 'Add EoIP Tunnel';
  6786. document.getElementById('eoip-modal-id').value = '';
  6787. document.getElementById('eoip-modal-name').value = `eoip-tunnel${(state.eoipTunnels || []).length + 1}`;
  6788. document.getElementById('eoip-modal-tunnelid').value = (state.eoipTunnels || []).length + 10;
  6789. document.getElementById('eoip-modal-remote').value = '';
  6790. document.getElementById('eoip-modal-ip').value = '';
  6791. document.getElementById('eoip-modal-local').value = '';
  6792. document.getElementById('eoip-modal-mac').value = '';
  6793. document.getElementById('eoip-modal-mtu').value = '1500';
  6794. document.getElementById('eoip-modal-comment').value = '';
  6795. document.getElementById('eoip-modal-clampmss').checked = true;
  6796. document.getElementById('eoip-modal-disabled').checked = false;
  6797. document.getElementById('eoip-modal').classList.remove('hidden');
  6798. }
  6799. function openEditEoIPModal(id) {
  6800. const t = (state.eoipTunnels || []).find(tun => tun.id === id);
  6801. if (!t) return;
  6802. document.getElementById('eoip-modal-title').innerText = `Edit EoIP Tunnel (${t.name})`;
  6803. document.getElementById('eoip-modal-id').value = t.id;
  6804. document.getElementById('eoip-modal-name').value = t.name;
  6805. document.getElementById('eoip-modal-tunnelid').value = t.tunnel_id;
  6806. document.getElementById('eoip-modal-remote').value = t.remote_address;
  6807. document.getElementById('eoip-modal-ip').value = t.ip_address || '';
  6808. document.getElementById('eoip-modal-local').value = t.local_address || '';
  6809. document.getElementById('eoip-modal-mac').value = t.mac_address || '';
  6810. document.getElementById('eoip-modal-mtu').value = t.mtu || 1500;
  6811. document.getElementById('eoip-modal-comment').value = t.comment || '';
  6812. document.getElementById('eoip-modal-clampmss').checked = !!t.clamp_mss;
  6813. document.getElementById('eoip-modal-disabled').checked = !!t.disabled;
  6814. document.getElementById('eoip-modal').classList.remove('hidden');
  6815. }
  6816. function closeEoIPModal() {
  6817. document.getElementById('eoip-modal').classList.add('hidden');
  6818. }
  6819. async function submitSaveEoIP(e) {
  6820. e.preventDefault();
  6821. const id = document.getElementById('eoip-modal-id').value;
  6822. const name = document.getElementById('eoip-modal-name').value.trim();
  6823. const tunnelId = parseInt(document.getElementById('eoip-modal-tunnelid').value);
  6824. const remote = document.getElementById('eoip-modal-remote').value.trim();
  6825. const ipAddress = document.getElementById('eoip-modal-ip').value.trim();
  6826. const local = document.getElementById('eoip-modal-local').value.trim();
  6827. const mac = document.getElementById('eoip-modal-mac').value.trim();
  6828. const mtu = parseInt(document.getElementById('eoip-modal-mtu').value) || 1500;
  6829. const comment = document.getElementById('eoip-modal-comment').value.trim();
  6830. const clampMss = document.getElementById('eoip-modal-clampmss').checked;
  6831. const disabled = document.getElementById('eoip-modal-disabled').checked;
  6832. try {
  6833. const res = await fetch(`${API_BASE}/vpn/eoip`, {
  6834. method: 'POST',
  6835. headers: { 'Content-Type': 'application/json' },
  6836. body: JSON.stringify({
  6837. id,
  6838. name,
  6839. tunnel_id: tunnelId,
  6840. remote_address: remote,
  6841. ip_address: ipAddress,
  6842. local_address: local,
  6843. mac_address: mac,
  6844. mtu,
  6845. clamp_mss: clampMss,
  6846. comment,
  6847. disabled
  6848. })
  6849. });
  6850. if (res.ok) {
  6851. showToast('EoIP Saved', `Tunnel ${name} configured successfully`, 'success');
  6852. closeEoIPModal();
  6853. loadEoIP(false);
  6854. fetchData(false);
  6855. } else {
  6856. const err = await res.json();
  6857. showToast('Error', err.message, 'error');
  6858. }
  6859. } catch (err) {
  6860. showToast('Error', err.message, 'error');
  6861. }
  6862. }
  6863. async function toggleEoIPState(id, disabled) {
  6864. try {
  6865. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}/state`, {
  6866. method: 'POST',
  6867. headers: { 'Content-Type': 'application/json' },
  6868. body: JSON.stringify({ disabled })
  6869. });
  6870. if (res.ok) {
  6871. showToast(disabled ? 'Disabled' : 'Enabled', 'EoIP tunnel state updated', 'info');
  6872. loadEoIP(false);
  6873. fetchData(false);
  6874. }
  6875. } catch (err) {
  6876. showToast('Error', err.message, 'error');
  6877. }
  6878. }
  6879. async function deleteEoIP(id) {
  6880. if (!confirm('Are you sure you want to delete this EoIP tunnel?')) return;
  6881. try {
  6882. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6883. if (res.ok) {
  6884. showToast('Deleted', 'EoIP tunnel removed', 'success');
  6885. loadEoIP(false);
  6886. fetchData(false);
  6887. }
  6888. } catch (err) {
  6889. showToast('Error', err.message, 'error');
  6890. }
  6891. }
  6892. // ======================== AeroTUN (Custom Encrypted VPN with Adaptive LZ4) ========================
  6893. async function loadAeroTUN(populate = true) {
  6894. try {
  6895. const [tunnelsRes, statsRes] = await Promise.all([
  6896. fetch(`${API_BASE}/vpn/aerotun/tunnels`),
  6897. fetch(`${API_BASE}/vpn/aerotun/stats`)
  6898. ]);
  6899. if (tunnelsRes.ok) {
  6900. const data = await tunnelsRes.json();
  6901. state.aerotunTunnels = Array.isArray(data) ? data : [];
  6902. }
  6903. if (statsRes.ok) {
  6904. state.aerotunStats = await statsRes.json();
  6905. }
  6906. const countBadge = document.getElementById('aerotun-count-badge');
  6907. if (countBadge) countBadge.innerText = `${(state.aerotunTunnels || []).length} Tunnels`;
  6908. const sideBadge = document.getElementById('badge-aerotun-count');
  6909. if (sideBadge) sideBadge.innerText = (state.aerotunTunnels || []).length;
  6910. renderAeroTUN();
  6911. } catch (err) {
  6912. console.error('Failed to load AeroTUN:', err);
  6913. }
  6914. }
  6915. function renderAeroTUN() {
  6916. const tbody = document.getElementById('aerotun-table-body');
  6917. const empty = document.getElementById('aerotun-empty');
  6918. // Update summary cards
  6919. const stats = state.aerotunStats || {};
  6920. const tunnels = state.aerotunTunnels || [];
  6921. const statActive = document.getElementById('aerotun-stat-active');
  6922. if (statActive) {
  6923. const activeCount = tunnels.filter(t => t.connected).length;
  6924. statActive.innerText = `${activeCount} / ${tunnels.length}`;
  6925. }
  6926. const statSaved = document.getElementById('aerotun-stat-saved');
  6927. if (statSaved) {
  6928. statSaved.innerText = formatBytes(stats.total_saved_bytes || 0);
  6929. }
  6930. const statRatio = document.getElementById('aerotun-stat-ratio');
  6931. if (statRatio) {
  6932. statRatio.innerText = stats.average_ratio || '1.00x (0% saved)';
  6933. }
  6934. const statTraffic = document.getElementById('aerotun-stat-traffic');
  6935. if (statTraffic) {
  6936. statTraffic.innerText = `↓ ${formatBytes(stats.total_rx_bytes || 0)} / ↑ ${formatBytes(stats.total_tx_bytes || 0)}`;
  6937. }
  6938. if (!tbody) return;
  6939. tbody.innerHTML = '';
  6940. if (tunnels.length === 0) {
  6941. empty?.classList.remove('hidden');
  6942. return;
  6943. }
  6944. empty?.classList.add('hidden');
  6945. tunnels.forEach(t => {
  6946. const tr = document.createElement('tr');
  6947. tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
  6948. const modeBadge = t.mode === 'server'
  6949. ? `<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>`
  6950. : `<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>`;
  6951. const endpointInfo = t.mode === 'server'
  6952. ? `<span class="text-sky-300 font-mono">Port :${t.listen_port || 51830}</span>`
  6953. : `<span class="text-indigo-300 font-mono">${escapeHtml(t.remote_endpoint || '(not set)')}</span>`;
  6954. const compBadge = t.compression
  6955. ? `<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>`
  6956. : `<span class="text-slate-500 text-[10px]">Off</span>`;
  6957. const activePeer = t.connected && t.active_peer_endpoint
  6958. ? `<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>`
  6959. : `<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>`;
  6960. const rawRx = formatBytes(t.rx_bytes || 0);
  6961. const rawTx = formatBytes(t.tx_bytes || 0);
  6962. const wireRx = formatBytes(t.wire_bytes_in || 0);
  6963. const wireTx = formatBytes(t.wire_bytes_out || 0);
  6964. tr.innerHTML = `
  6965. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.connected, t.disabled)}</td>
  6966. <td class="py-2.5 px-3 font-bold text-white font-mono flex items-center gap-1.5">
  6967. <span>${escapeHtml(t.name)}</span>
  6968. ${t.default_route ? '<span class="text-[9px] px-1 rounded bg-amber-500/20 text-amber-300 border border-amber-500/30">DEF</span>' : ''}
  6969. <span class="text-slate-400 text-[10px]">v${t.protocol_version || 2}</span>
  6970. </td>
  6971. <td class="py-2.5 px-3">${modeBadge}</td>
  6972. <td class="py-2.5 px-3 text-xs font-mono">${endpointInfo}</td>
  6973. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${escapeHtml(t.local_address || '-')}</td>
  6974. <td class="py-2.5 px-3">${compBadge}</td>
  6975. <td class="py-2.5 px-3">${activePeer}</td>
  6976. <td class="py-2.5 px-3 font-mono text-[11px]">
  6977. <span class="text-emerald-400">↓ ${rawRx}</span>
  6978. <span class="text-cyan-400 ml-1">↑ ${rawTx}</span>
  6979. </td>
  6980. <td class="py-2.5 px-3 font-mono text-[11px]">
  6981. <span class="text-slate-400">↓ ${wireRx}</span>
  6982. <span class="text-slate-400 ml-1">↑ ${wireTx}</span>
  6983. </td>
  6984. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(t.comment || '')}">${escapeHtml(t.comment || '-')}</td>
  6985. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  6986. ${t.running
  6987. ? `<button onclick="stopAeroTUNTunnel('${t.id}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Stop</button>`
  6988. : `<button onclick="startAeroTUNTunnel('${t.id}')" class="text-xs text-emerald-400 hover:text-emerald-300 font-medium">Start</button>`
  6989. }
  6990. <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>
  6991. <button onclick="openEditAeroTUNModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  6992. <button onclick="deleteAeroTUN('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  6993. </td>
  6994. `;
  6995. tbody.appendChild(tr);
  6996. });
  6997. }
  6998. let aeroModalGeneration = 0;
  6999. let aeroIdentityDraft = '';
  7000. let aeroSaving = false;
  7001. let aeroPSKRequest = 0;
  7002. function discardAeroIdentityDraft(id) {
  7003. if (id) fetch(`${API_BASE}/vpn/aerotun/identity-drafts/${encodeURIComponent(id)}`, {method:'DELETE'}).catch(() => {});
  7004. }
  7005. async function generateAeroTUNIdentity() {
  7006. const generation = aeroModalGeneration;
  7007. const retry = document.getElementById('aerotun-retry-identity');
  7008. if (aeroIdentityDraft) { discardAeroIdentityDraft(aeroIdentityDraft); aeroIdentityDraft = ''; }
  7009. retry.classList.add('hidden');
  7010. document.getElementById('aerotun-modal-public').value = '';
  7011. try {
  7012. const res = await fetch(`${API_BASE}/vpn/aerotun/identity-drafts`, {method:'POST'});
  7013. if (!res.ok) throw new Error(await responseError(res));
  7014. const draft = await res.json();
  7015. if (generation !== aeroModalGeneration) { discardAeroIdentityDraft(draft.draft_id); return; }
  7016. aeroIdentityDraft = draft.draft_id;
  7017. document.getElementById('aerotun-modal-public').value = draft.public_key;
  7018. updateAeroTUNSetupHint();
  7019. } catch (err) {
  7020. if (generation !== aeroModalGeneration) return;
  7021. retry.classList.remove('hidden');
  7022. updateAeroTUNSetupHint();
  7023. showToast('Identity Generation Failed', err.message, 'error');
  7024. }
  7025. }
  7026. function onAeroTUNModeChange() {
  7027. const mode = document.getElementById('aerotun-modal-mode').value;
  7028. const endpointInput = document.getElementById('aerotun-modal-endpoint');
  7029. const portInput = document.getElementById('aerotun-modal-port');
  7030. if (mode === 'server') {
  7031. if (!portInput.value) portInput.value = '51830';
  7032. endpointInput.placeholder = 'Optional / learned roaming peer';
  7033. } else {
  7034. endpointInput.placeholder = 'vpn.example.com:51830 (required)';
  7035. if (!portInput.value) portInput.value = '';
  7036. }
  7037. }
  7038. function onAeroTUNPeerChange() {
  7039. const peer = document.getElementById('aerotun-modal-peer');
  7040. const allowed = document.getElementById('aerotun-modal-allowed');
  7041. const previous = peer.dataset.allowedDefault || '';
  7042. const host = peer.value.trim().split('/')[0];
  7043. const next = host ? `${host}/${host.includes(':') ? 128 : 32}` : '';
  7044. if (allowed.value.trim() === previous) allowed.value = next;
  7045. peer.dataset.allowedDefault = next;
  7046. }
  7047. async function generateAeroTUNKey(automatic = false) {
  7048. const generation = aeroModalGeneration, request = ++aeroPSKRequest;
  7049. const input = document.getElementById('aerotun-modal-psk'), previous = input.value;
  7050. try {
  7051. const res = await fetch(`${API_BASE}/vpn/aerotun/genkey`);
  7052. if (!res.ok) throw new Error(await responseError(res));
  7053. const data = await res.json();
  7054. if (generation !== aeroModalGeneration || request !== aeroPSKRequest || (automatic && input.value !== previous)) return;
  7055. input.value = data.key;
  7056. if (!automatic) showToast('Key Generated', 'Share this PSK securely with the peer before enabling', 'success');
  7057. } catch (err) {
  7058. if (generation === aeroModalGeneration && request === aeroPSKRequest) showToast('Key Generation Failed', err.message, 'error');
  7059. }
  7060. }
  7061. function updateAeroTUNSetupHint() {
  7062. const version = document.getElementById('aerotun-modal-protocol').value;
  7063. const key = document.getElementById('aerotun-modal-public').value;
  7064. const peer = document.getElementById('aerotun-modal-peerkey').value.trim();
  7065. const hint = document.getElementById('aerotun-setup-hint');
  7066. document.getElementById('aerotun-v3-fields').classList.toggle('hidden', version !== '3');
  7067. if (!hint) return;
  7068. 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.';
  7069. }
  7070. async function copyAeroTUNPublicKey() {
  7071. const input = document.getElementById('aerotun-modal-public');
  7072. if (!input.value) { showToast('Key Not Ready', 'Wait for the local identity or retry key generation.', 'info'); return; }
  7073. try {
  7074. await navigator.clipboard.writeText(input.value);
  7075. showToast('Public Key Copied', 'Paste it into the other endpoint’s pinned peer key', 'success');
  7076. } catch {
  7077. input.focus(); input.select();
  7078. showToast('Copy Public Key', 'Key selected; press Ctrl+C to copy', 'info');
  7079. }
  7080. }
  7081. async function copyAeroTUNPSK() {
  7082. const input = document.getElementById('aerotun-modal-psk');
  7083. if (!input.value) { showToast('PSK Not Available', 'Generate or enter a PSK to copy it. Existing keys are not displayed.', 'info'); return; }
  7084. try { await navigator.clipboard.writeText(input.value); showToast('PSK Copied', 'Share it securely with the peer.', 'success'); }
  7085. catch { input.type = 'text'; input.focus(); input.select(); showToast('Copy PSK', 'Key selected; press Ctrl+C to copy.', 'info'); }
  7086. }
  7087. function openAddAeroTUNModal() {
  7088. if (aeroSaving) return;
  7089. aeroModalGeneration++; discardAeroIdentityDraft(aeroIdentityDraft); aeroIdentityDraft = '';
  7090. const tunnels = state.aerotunTunnels || [];
  7091. const usedNames = new Set(tunnels.map(t => t.name));
  7092. const usedPorts = new Set(tunnels.map(t => Number(t.listen_port)));
  7093. 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++;
  7094. if (index >= 256) index = 0;
  7095. document.getElementById('aerotun-modal-title').innerText = 'Add AeroTUN Interface';
  7096. document.getElementById('aerotun-modal-id').value = '';
  7097. document.getElementById('aerotun-modal-protocol').value='3';
  7098. document.getElementById('aerotun-modal-public').value='';
  7099. document.getElementById('aerotun-modal-peerkey').value='';
  7100. document.getElementById('aerotun-modal-allowed').value=`10.99.${index}.2/32`;
  7101. document.getElementById('aerotun-modal-name').value = `aerotun${index}`;
  7102. document.getElementById('aerotun-modal-mode').value = 'server';
  7103. document.getElementById('aerotun-modal-port').value = 51830 + index;
  7104. document.getElementById('aerotun-modal-endpoint').value = '';
  7105. document.getElementById('aerotun-modal-local').value = `10.99.${index}.1/24`;
  7106. document.getElementById('aerotun-modal-peer').value = `10.99.${index}.2/24`;
  7107. document.getElementById('aerotun-modal-peer').dataset.allowedDefault = `10.99.${index}.2/32`;
  7108. document.getElementById('aerotun-modal-psk').value = '';
  7109. document.getElementById('aerotun-modal-mtu').value = '1420';
  7110. document.getElementById('aerotun-modal-comment').value = '';
  7111. document.getElementById('aerotun-modal-compression').checked = false;
  7112. document.getElementById('aerotun-modal-defroute').checked = false;
  7113. document.getElementById('aerotun-modal-disabled').checked = true;
  7114. document.getElementById('aerotun-modal-psk').type = 'password';
  7115. document.getElementById('aerotun-modal-psk').placeholder = 'Generate or enter the shared key';
  7116. onAeroTUNModeChange();
  7117. updateAeroTUNSetupHint();
  7118. document.getElementById('aerotun-modal').classList.remove('hidden');
  7119. generateAeroTUNKey(true);
  7120. generateAeroTUNIdentity();
  7121. }
  7122. function openEditAeroTUNModal(id) {
  7123. if (aeroSaving) return;
  7124. const t = (state.aerotunTunnels || []).find(tun => tun.id === id);
  7125. if (!t) return;
  7126. aeroModalGeneration++; discardAeroIdentityDraft(aeroIdentityDraft); aeroIdentityDraft = '';
  7127. document.getElementById('aerotun-retry-identity').classList.add('hidden');
  7128. document.getElementById('aerotun-modal-title').innerText = `Edit AeroTUN Interface (${t.name})`;
  7129. document.getElementById('aerotun-modal-id').value = t.id;
  7130. document.getElementById('aerotun-modal-protocol').value=String(t.protocol_version || 2);
  7131. document.getElementById('aerotun-modal-public').value=t.public_key || '';
  7132. document.getElementById('aerotun-modal-peerkey').value=t.peer_public_key || '';
  7133. document.getElementById('aerotun-modal-allowed').value=(t.allowed_ips || []).join(', ');
  7134. document.getElementById('aerotun-modal-name').value = t.name;
  7135. document.getElementById('aerotun-modal-mode').value = t.mode || 'server';
  7136. document.getElementById('aerotun-modal-port').value = t.listen_port || '';
  7137. document.getElementById('aerotun-modal-endpoint').value = t.remote_endpoint || '';
  7138. document.getElementById('aerotun-modal-local').value = t.local_address || '';
  7139. document.getElementById('aerotun-modal-peer').value = t.peer_address || '';
  7140. const peerHost = (t.peer_address || '').split('/')[0];
  7141. document.getElementById('aerotun-modal-peer').dataset.allowedDefault = peerHost ? `${peerHost}/${peerHost.includes(':') ? 128 : 32}` : '';
  7142. document.getElementById('aerotun-modal-psk').value = '';
  7143. document.getElementById('aerotun-modal-psk').type = 'password';
  7144. document.getElementById('aerotun-modal-psk').placeholder = t.has_psk ? 'Leave blank to keep the existing key' : 'New random 256-bit PSK';
  7145. document.getElementById('aerotun-modal-mtu').value = t.mtu || 1420;
  7146. document.getElementById('aerotun-modal-comment').value = t.comment || '';
  7147. document.getElementById('aerotun-modal-compression').checked = !!t.compression;
  7148. document.getElementById('aerotun-modal-defroute').checked = !!t.default_route;
  7149. document.getElementById('aerotun-modal-disabled').checked = !!t.disabled;
  7150. onAeroTUNModeChange();
  7151. updateAeroTUNSetupHint();
  7152. document.getElementById('aerotun-modal').classList.remove('hidden');
  7153. }
  7154. function closeAeroTUNModal() {
  7155. if (aeroSaving) return;
  7156. aeroModalGeneration++; discardAeroIdentityDraft(aeroIdentityDraft); aeroIdentityDraft = '';
  7157. document.getElementById('aerotun-modal-psk').value = '';
  7158. document.getElementById('aerotun-modal').classList.add('hidden');
  7159. }
  7160. async function submitSaveAeroTUN(e) {
  7161. e.preventDefault();
  7162. if (aeroSaving) return;
  7163. const id = document.getElementById('aerotun-modal-id').value;
  7164. const name = document.getElementById('aerotun-modal-name').value.trim();
  7165. const mode = document.getElementById('aerotun-modal-mode').value;
  7166. const port = parseInt(document.getElementById('aerotun-modal-port').value) || 0;
  7167. const endpoint = document.getElementById('aerotun-modal-endpoint').value.trim();
  7168. const local = document.getElementById('aerotun-modal-local').value.trim();
  7169. const peer = document.getElementById('aerotun-modal-peer').value.trim();
  7170. const psk = document.getElementById('aerotun-modal-psk').value.trim();
  7171. const mtuValue = document.getElementById('aerotun-modal-mtu').value;
  7172. const mtu = mtuValue === '' ? 1420 : Number(mtuValue);
  7173. const comment = document.getElementById('aerotun-modal-comment').value.trim();
  7174. const compression = document.getElementById('aerotun-modal-compression').checked;
  7175. const defaultRoute = document.getElementById('aerotun-modal-defroute').checked;
  7176. const disabled = document.getElementById('aerotun-modal-disabled').checked;
  7177. if (mode === 'client' && !endpoint) {
  7178. showToast('Validation Error', 'Remote endpoint (host:port) is required in client mode', 'error');
  7179. return;
  7180. }
  7181. if (defaultRoute && (mode !== 'client' || !endpoint)) {
  7182. showToast('Validation Error', 'Default route requires client mode and a fixed remote endpoint.', 'error');
  7183. return;
  7184. }
  7185. if (!Number.isInteger(mtu) || mtu < 576 || mtu > 9000) {
  7186. showToast('Validation Error', 'MTU must be between 576 and 9000.', 'error');
  7187. return;
  7188. }
  7189. const version = parseInt(document.getElementById('aerotun-modal-protocol').value, 10);
  7190. if (version === 3 && !id && !aeroIdentityDraft) {
  7191. showToast('Local Key Not Ready', 'Wait for the local identity or retry key generation before saving.', 'error');
  7192. return;
  7193. }
  7194. if (version === 3 && !document.getElementById('aerotun-modal-allowed').value.trim()) {
  7195. showToast('Allowed Prefix Required', 'Enter at least one allowed peer source prefix, such as the peer tunnel IP /32.', 'error');
  7196. document.getElementById('aerotun-modal-allowed').focus();
  7197. return;
  7198. }
  7199. if (version === 3 && !disabled && !document.getElementById('aerotun-modal-peerkey').value.trim()) {
  7200. showToast('Peer Key Required', 'Enter the peer public key, or save this tunnel disabled until it is available.', 'error');
  7201. return;
  7202. }
  7203. if (!psk && !id) {
  7204. showToast('Validation Error', 'Pre-shared key (PSK) is required', 'error');
  7205. return;
  7206. }
  7207. aeroSaving = true;
  7208. const submit = document.querySelector('#aerotun-modal button[type="submit"]');
  7209. if (submit) submit.disabled = true;
  7210. try {
  7211. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels`, {
  7212. method: 'POST',
  7213. headers: { 'Content-Type': 'application/json' },
  7214. body: JSON.stringify({
  7215. protocol_version:parseInt(document.getElementById('aerotun-modal-protocol').value,10),
  7216. identity_draft_id: version === 3 && !id ? aeroIdentityDraft : '',
  7217. peer_public_key:document.getElementById('aerotun-modal-peerkey').value.trim(),
  7218. allowed_ips:document.getElementById('aerotun-modal-allowed').value.split(',').map(s=>s.trim()).filter(Boolean),
  7219. id,
  7220. name,
  7221. mode,
  7222. listen_port: port,
  7223. remote_endpoint: endpoint,
  7224. local_address: local,
  7225. peer_address: peer,
  7226. psk,
  7227. mtu,
  7228. compression,
  7229. default_route: defaultRoute,
  7230. comment,
  7231. disabled
  7232. })
  7233. });
  7234. if (res.ok) {
  7235. await res.json();
  7236. if (version !== 3) discardAeroIdentityDraft(aeroIdentityDraft);
  7237. aeroIdentityDraft = '';
  7238. aeroSaving = false;
  7239. closeAeroTUNModal();
  7240. await loadAeroTUN(false);
  7241. showToast('AeroTUN Saved', disabled ? 'Configuration saved; tunnel is disabled' : 'Configuration saved; waiting for authenticated peer traffic', 'success');
  7242. fetchData(false);
  7243. } else {
  7244. const err = await responseError(res);
  7245. if (err.includes('configuration saved but tunnel failed to start')) {
  7246. aeroIdentityDraft = '';
  7247. aeroSaving = false;
  7248. closeAeroTUNModal();
  7249. await loadAeroTUN(false);
  7250. showToast('Saved, but not started', err, 'error');
  7251. } else showToast('Error Saving Tunnel', err, 'error');
  7252. }
  7253. } catch (err) {
  7254. showToast('Network Error', err.message, 'error');
  7255. } finally {
  7256. aeroSaving = false;
  7257. if (submit) submit.disabled = false;
  7258. }
  7259. }
  7260. async function startAeroTUNTunnel(id) {
  7261. try {
  7262. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/start`, { method: 'POST' });
  7263. if (res.ok) {
  7264. showToast('AeroTUN Started', 'Interface started; connection is confirmed by authenticated peer traffic', 'info');
  7265. loadAeroTUN(false);
  7266. fetchData(false);
  7267. } else {
  7268. const err = await res.text();
  7269. showToast('Failed to Start', err, 'error');
  7270. }
  7271. } catch (err) {
  7272. showToast('Error', err.message, 'error');
  7273. }
  7274. }
  7275. async function stopAeroTUNTunnel(id) {
  7276. try {
  7277. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/stop`, { method: 'POST' });
  7278. if (res.ok) {
  7279. showToast('AeroTUN Stopped', 'Tunnel stopped', 'info');
  7280. loadAeroTUN(false);
  7281. fetchData(false);
  7282. } else {
  7283. const err = await res.text();
  7284. showToast('Failed to Stop', err, 'error');
  7285. }
  7286. } catch (err) {
  7287. showToast('Error', err.message, 'error');
  7288. }
  7289. }
  7290. async function toggleAeroTUNState(id, disabled) {
  7291. try {
  7292. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/state`, {
  7293. method: 'POST',
  7294. headers: { 'Content-Type': 'application/json' },
  7295. body: JSON.stringify({ disabled })
  7296. });
  7297. if (res.ok) {
  7298. showToast('State Updated', disabled ? 'Tunnel disabled' : 'Tunnel enabled', 'info');
  7299. loadAeroTUN(false);
  7300. fetchData(false);
  7301. }
  7302. } catch (err) {
  7303. showToast('Error', err.message, 'error');
  7304. }
  7305. }
  7306. async function deleteAeroTUN(id) {
  7307. if (!confirm('Are you sure you want to delete this AeroTUN tunnel?')) return;
  7308. try {
  7309. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7310. if (res.ok) {
  7311. showToast('Deleted', 'AeroTUN tunnel removed', 'success');
  7312. loadAeroTUN(false);
  7313. fetchData(false);
  7314. }
  7315. } catch (err) {
  7316. showToast('Error', err.message, 'error');
  7317. }
  7318. }
  7319. // ======================== PPP Central Hub & Servers ========================
  7320. function switchPPPSubTab(tab) {
  7321. state.pppSubTab = tab;
  7322. const tabs = ['secrets', 'profiles', 'pppoe', 'pptp', 'l2tp', 'active'];
  7323. tabs.forEach(t => {
  7324. const panel = document.getElementById(`ppp-subtab-${t}`);
  7325. const btn = document.getElementById(`ppp-subtab-btn-${t}`);
  7326. if (panel) {
  7327. if (t === tab) panel.classList.remove('hidden');
  7328. else panel.classList.add('hidden');
  7329. }
  7330. if (btn) {
  7331. if (t === tab) {
  7332. 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';
  7333. } else {
  7334. 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';
  7335. }
  7336. }
  7337. });
  7338. const addBtn = document.getElementById('ppp-primary-add-btn');
  7339. if (addBtn) {
  7340. if (tab === 'secrets') addBtn.innerHTML = '<span>+ Add User (Secret)</span>';
  7341. else if (tab === 'profiles') addBtn.innerHTML = '<span>+ Add Profile</span>';
  7342. else if (tab === 'active') addBtn.innerHTML = '<span>Refresh Sessions</span>';
  7343. else addBtn.innerHTML = '<span>Save Config</span>';
  7344. }
  7345. if (tab === 'active') loadPPPSessions();
  7346. }
  7347. function openCurrentPPPModal() {
  7348. if (state.pppSubTab === 'secrets') openAddPPPSecretModal();
  7349. else if (state.pppSubTab === 'profiles') openAddPPPProfileModal();
  7350. else if (state.pppSubTab === 'active') loadPPPSessions();
  7351. else if (state.pppSubTab === 'pppoe') document.querySelector('#ppp-subtab-pppoe form')?.requestSubmit();
  7352. else if (state.pppSubTab === 'pptp') document.querySelector('#ppp-subtab-pptp form')?.requestSubmit();
  7353. else if (state.pppSubTab === 'l2tp') document.querySelector('#ppp-subtab-l2tp form')?.requestSubmit();
  7354. }
  7355. async function loadPPP(populateDropdowns = true) {
  7356. await Promise.all([
  7357. loadPPPSecrets(),
  7358. loadPPPProfiles(),
  7359. loadPPPServers(),
  7360. loadPPPSessions()
  7361. ]);
  7362. }
  7363. async function loadPPPSecrets() {
  7364. try {
  7365. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`);
  7366. const data = await res.json();
  7367. state.pppSecrets = Array.isArray(data) ? data : [];
  7368. const b = document.getElementById('ppp-badge-secrets');
  7369. if (b) b.innerText = state.pppSecrets.length;
  7370. const b2 = document.getElementById('secrets-count-badge');
  7371. if (b2) b2.innerText = `${state.pppSecrets.length} Users`;
  7372. renderPPPSecrets();
  7373. } catch (err) {
  7374. console.error('Failed to load PPP secrets:', err);
  7375. }
  7376. }
  7377. function renderPPPSecrets() {
  7378. const tbody = document.getElementById('secrets-table-body');
  7379. const empty = document.getElementById('secrets-empty');
  7380. if (!tbody) return;
  7381. tbody.innerHTML = '';
  7382. const secrets = state.pppSecrets || [];
  7383. if (secrets.length === 0) {
  7384. empty?.classList.remove('hidden');
  7385. return;
  7386. }
  7387. empty?.classList.add('hidden');
  7388. secrets.forEach(s => {
  7389. const tr = document.createElement('tr');
  7390. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  7391. tr.innerHTML = `
  7392. <td class="py-2.5 px-3 text-center">${renderRuleFlag(s.disabled, !!s.comment)}</td>
  7393. <td class="py-2.5 px-3 font-bold text-white font-mono">${s.name}</td>
  7394. <td class="py-2.5 px-3 text-purple-300 font-mono font-semibold">${s.service}</td>
  7395. <td class="py-2.5 px-3 text-amber-300 font-mono">${s.profile}</td>
  7396. <td class="py-2.5 px-3 text-slate-400 font-mono">${s.local_address || '(profile)'}</td>
  7397. <td class="py-2.5 px-3 text-cyan-400 font-mono font-bold">${s.remote_address || '(profile)'}</td>
  7398. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]">${s.comment || '-'}</td>
  7399. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  7400. <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>
  7401. <button onclick="openEditPPPSecretModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  7402. <button onclick="deletePPPSecret('${s.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  7403. </td>
  7404. `;
  7405. tbody.appendChild(tr);
  7406. });
  7407. }
  7408. async function loadPPPProfiles() {
  7409. try {
  7410. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`);
  7411. const data = await res.json();
  7412. state.pppProfiles = Array.isArray(data) ? data : [];
  7413. const b = document.getElementById('ppp-badge-profiles');
  7414. if (b) b.innerText = state.pppProfiles.length;
  7415. const b2 = document.getElementById('profiles-count-badge');
  7416. if (b2) b2.innerText = `${state.pppProfiles.length} Profiles`;
  7417. // Populate profile selects across modals
  7418. const selects = ['secret-modal-profile', 'pppoe-server-profile', 'pptp-server-profile', 'l2tp-server-profile'];
  7419. selects.forEach(sid => {
  7420. const el = document.getElementById(sid);
  7421. if (!el) return;
  7422. const cur = el.value;
  7423. el.innerHTML = '';
  7424. state.pppProfiles.forEach(p => {
  7425. const opt = document.createElement('option');
  7426. opt.value = p.name;
  7427. opt.innerText = `${p.name} (${p.remote_address})`;
  7428. if (p.name === cur) opt.selected = true;
  7429. el.appendChild(opt);
  7430. });
  7431. });
  7432. renderPPPProfiles();
  7433. } catch (err) {
  7434. console.error('Failed to load PPP profiles:', err);
  7435. }
  7436. }
  7437. function renderPPPProfiles() {
  7438. const tbody = document.getElementById('profiles-table-body');
  7439. if (!tbody) return;
  7440. tbody.innerHTML = '';
  7441. (state.pppProfiles || []).forEach(p => {
  7442. const isDefault = p.name.startsWith('default');
  7443. const tr = document.createElement('tr');
  7444. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  7445. tr.innerHTML = `
  7446. <td class="py-2.5 px-3 font-bold text-white">${p.name}</td>
  7447. <td class="py-2.5 px-3 text-slate-300">${p.local_address}</td>
  7448. <td class="py-2.5 px-3 text-cyan-400 font-bold">${p.remote_address}</td>
  7449. <td class="py-2.5 px-3 text-slate-400">${p.dns_servers || '-'}</td>
  7450. <td class="py-2.5 px-3 text-purple-300 font-semibold">${p.use_encryption}</td>
  7451. <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>
  7452. <td class="py-2.5 px-3 text-slate-400 italic">${p.comment || '-'}</td>
  7453. <td class="py-2.5 px-3 text-right font-sans whitespace-nowrap">
  7454. ${!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>`}
  7455. </td>
  7456. `;
  7457. tbody.appendChild(tr);
  7458. });
  7459. }
  7460. async function loadPPPServers() {
  7461. try {
  7462. const [pppoeRes, pptpRes, l2tpRes, ipsecRes] = await Promise.all([
  7463. fetch(`${API_BASE}/vpn/servers/pppoe`),
  7464. fetch(`${API_BASE}/vpn/servers/pptp`),
  7465. fetch(`${API_BASE}/vpn/servers/l2tp`),
  7466. fetch(`${API_BASE}/vpn/servers/ipsec`)
  7467. ]);
  7468. if (pppoeRes.ok) {
  7469. state.pppoeServer = await pppoeRes.json();
  7470. const s = state.pppoeServer;
  7471. document.getElementById('pppoe-server-enabled').checked = !!s.enabled;
  7472. document.getElementById('pppoe-server-name').value = s.service_name || 'proxmox-pppoe';
  7473. populateInterfaceSelect('pppoe-server-iface', s.interface || 'eth0');
  7474. document.getElementById('pppoe-server-profile').value = s.default_profile || 'default';
  7475. document.getElementById('pppoe-server-mtu').value = s.max_mtu || 1480;
  7476. document.getElementById('pppoe-server-onesession').checked = !!s.one_session_per_host;
  7477. const pill = document.getElementById('pppoe-server-status-pill');
  7478. if (pill) {
  7479. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  7480. 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';
  7481. }
  7482. setDotBadge('ppp-badge-pppoe-state', s.running);
  7483. }
  7484. if (pptpRes.ok) {
  7485. state.pptpServer = await pptpRes.json();
  7486. const s = state.pptpServer;
  7487. document.getElementById('pptp-server-enabled').checked = !!s.enabled;
  7488. document.getElementById('pptp-server-port').value = s.port || 1723;
  7489. document.getElementById('pptp-server-profile').value = s.default_profile || 'default-encryption';
  7490. document.getElementById('pptp-server-mppe').checked = s.require_mppe !== false;
  7491. const pill = document.getElementById('pptp-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-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';
  7495. }
  7496. setDotBadge('ppp-badge-pptp-state', s.running);
  7497. }
  7498. if (l2tpRes.ok) {
  7499. state.l2tpServer = await l2tpRes.json();
  7500. const s = state.l2tpServer;
  7501. document.getElementById('l2tp-server-enabled').checked = !!s.enabled;
  7502. document.getElementById('l2tp-server-port').value = s.port || 1701;
  7503. document.getElementById('l2tp-server-profile').value = s.default_profile || 'default';
  7504. document.getElementById('l2tp-server-useipsec').value = s.use_ipsec || 'no';
  7505. document.getElementById('l2tp-server-ipsecsecret').value = s.ipsec_secret || '';
  7506. const pill = document.getElementById('l2tp-server-status-pill');
  7507. if (pill) {
  7508. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  7509. 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';
  7510. }
  7511. setDotBadge('ppp-badge-l2tp-state', s.running);
  7512. }
  7513. if (ipsecRes.ok) {
  7514. state.ipsecServer = await ipsecRes.json();
  7515. const s = state.ipsecServer;
  7516. const modalEn = document.getElementById('modal-ipsec-server-enabled');
  7517. if (modalEn) modalEn.checked = !!s.enabled;
  7518. const modalPsk = document.getElementById('modal-ipsec-server-psk');
  7519. if (modalPsk) modalPsk.value = s.preshared_key || '';
  7520. const modalPool = document.getElementById('modal-ipsec-server-pool');
  7521. if (modalPool) modalPool.value = s.pool_address || '10.10.30.0/24';
  7522. const modalDns = document.getElementById('modal-ipsec-server-dns');
  7523. if (modalDns) modalDns.value = s.dns_servers || '1.1.1.1,8.8.8.8';
  7524. const modalSubnet = document.getElementById('modal-ipsec-server-subnet');
  7525. if (modalSubnet) modalSubnet.value = s.local_subnet || '0.0.0.0/0';
  7526. const pill = document.getElementById('modal-ipsec-server-status');
  7527. if (pill) {
  7528. pill.innerText = s.running ? 'ACTIVE RESPONDER' : 'STOPPED';
  7529. 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';
  7530. }
  7531. }
  7532. } catch (err) {
  7533. console.error('Failed to load VPN servers:', err);
  7534. }
  7535. }
  7536. async function loadPPPSessions() {
  7537. try {
  7538. const res = await fetch(`${API_BASE}/vpn/ppp/active`);
  7539. const data = await res.json();
  7540. state.pppActiveSessions = Array.isArray(data) ? data : [];
  7541. const b = document.getElementById('ppp-badge-active');
  7542. if (b) b.innerText = state.pppActiveSessions.length;
  7543. const sideB = document.getElementById('badge-ppp-sessions');
  7544. if (sideB) sideB.innerText = state.pppActiveSessions.length;
  7545. renderPPPSessions();
  7546. } catch (err) {
  7547. console.error('Failed to load active PPP sessions:', err);
  7548. }
  7549. }
  7550. function renderPPPSessions() {
  7551. const tbody = document.getElementById('active-ppp-table-body');
  7552. const empty = document.getElementById('active-ppp-empty');
  7553. if (!tbody) return;
  7554. tbody.innerHTML = '';
  7555. const list = state.pppActiveSessions || [];
  7556. if (list.length === 0) {
  7557. empty?.classList.remove('hidden');
  7558. return;
  7559. }
  7560. empty?.classList.add('hidden');
  7561. list.forEach(s => {
  7562. const tr = document.createElement('tr');
  7563. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  7564. tr.innerHTML = `
  7565. <td class="py-2.5 px-3 font-bold text-white">${s.interface}</td>
  7566. <td class="py-2.5 px-3 font-semibold text-violet-300">${s.username}</td>
  7567. <td class="py-2.5 px-3 text-cyan-400 uppercase">${s.service}</td>
  7568. <td class="py-2.5 px-3 text-emerald-400 font-bold">${s.address || '-'}</td>
  7569. <td class="py-2.5 px-3 text-slate-400">${s.uptime}</td>
  7570. <td class="py-2.5 px-3 text-[11px]">
  7571. <span class="text-emerald-400">↓ ${s.rx_human || '0 B'}</span>
  7572. <span class="text-cyan-400 ml-1">↑ ${s.tx_human || '0 B'}</span>
  7573. </td>
  7574. <td class="py-2.5 px-3 text-right font-sans">
  7575. <button onclick="disconnectPPPSession('${s.interface}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  7576. </td>
  7577. `;
  7578. tbody.appendChild(tr);
  7579. });
  7580. }
  7581. async function disconnectPPPSession(iface) {
  7582. if (!confirm(`Disconnect session ${iface}?`)) return;
  7583. try {
  7584. const res = await fetch(`${API_BASE}/vpn/ppp/active/${encodeURIComponent(iface)}`, { method: 'DELETE' });
  7585. if (res.ok) {
  7586. showToast('Disconnected', `Session ${iface} terminated`, 'info');
  7587. loadPPPSessions();
  7588. }
  7589. } catch (err) {
  7590. showToast('Error', err.message, 'error');
  7591. }
  7592. }
  7593. // PPP Secret Modal handlers
  7594. function openAddPPPSecretModal() {
  7595. document.getElementById('secret-modal-title').innerText = 'Add PPP Secret';
  7596. document.getElementById('secret-modal-id').value = '';
  7597. document.getElementById('secret-modal-name').value = '';
  7598. document.getElementById('secret-modal-password').value = '';
  7599. document.getElementById('secret-modal-service').value = 'any';
  7600. document.getElementById('secret-modal-profile').value = 'default';
  7601. document.getElementById('secret-modal-local').value = '';
  7602. document.getElementById('secret-modal-remote').value = '';
  7603. document.getElementById('secret-modal-comment').value = '';
  7604. document.getElementById('secret-modal-disabled').checked = false;
  7605. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  7606. }
  7607. function openEditPPPSecretModal(id) {
  7608. const s = (state.pppSecrets || []).find(sec => sec.id === id);
  7609. if (!s) return;
  7610. document.getElementById('secret-modal-title').innerText = `Edit PPP Secret (${s.name})`;
  7611. document.getElementById('secret-modal-id').value = s.id;
  7612. document.getElementById('secret-modal-name').value = s.name;
  7613. document.getElementById('secret-modal-password').value = s.password;
  7614. document.getElementById('secret-modal-service').value = s.service || 'any';
  7615. document.getElementById('secret-modal-profile').value = s.profile || 'default';
  7616. document.getElementById('secret-modal-local').value = s.local_address || '';
  7617. document.getElementById('secret-modal-remote').value = s.remote_address || '';
  7618. document.getElementById('secret-modal-comment').value = s.comment || '';
  7619. document.getElementById('secret-modal-disabled').checked = !!s.disabled;
  7620. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  7621. }
  7622. function closePPPSecretModal() {
  7623. document.getElementById('ppp-secret-modal').classList.add('hidden');
  7624. }
  7625. async function submitSavePPPSecret(e) {
  7626. e.preventDefault();
  7627. const id = document.getElementById('secret-modal-id').value;
  7628. const name = document.getElementById('secret-modal-name').value.trim();
  7629. const password = document.getElementById('secret-modal-password').value.trim();
  7630. const service = document.getElementById('secret-modal-service').value;
  7631. const profile = document.getElementById('secret-modal-profile').value;
  7632. const local = document.getElementById('secret-modal-local').value.trim();
  7633. const remote = document.getElementById('secret-modal-remote').value.trim();
  7634. const comment = document.getElementById('secret-modal-comment').value.trim();
  7635. const disabled = document.getElementById('secret-modal-disabled').checked;
  7636. try {
  7637. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`, {
  7638. method: 'POST',
  7639. headers: { 'Content-Type': 'application/json' },
  7640. body: JSON.stringify({
  7641. id,
  7642. name,
  7643. password,
  7644. service,
  7645. profile,
  7646. local_address: local,
  7647. remote_address: remote,
  7648. comment,
  7649. disabled
  7650. })
  7651. });
  7652. if (res.ok) {
  7653. showToast('Secret Saved', `User ${name} saved to PPP database`, 'success');
  7654. closePPPSecretModal();
  7655. loadPPPSecrets();
  7656. } else {
  7657. const err = await res.json();
  7658. showToast('Error', err.message, 'error');
  7659. }
  7660. } catch (err) {
  7661. showToast('Error', err.message, 'error');
  7662. }
  7663. }
  7664. async function togglePPPSecretState(id, disabled) {
  7665. try {
  7666. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}/state`, {
  7667. method: 'POST',
  7668. headers: { 'Content-Type': 'application/json' },
  7669. body: JSON.stringify({ disabled })
  7670. });
  7671. if (res.ok) {
  7672. showToast(disabled ? 'Disabled' : 'Enabled', 'Secret user state updated', 'info');
  7673. loadPPPSecrets();
  7674. }
  7675. } catch (err) {
  7676. showToast('Error', err.message, 'error');
  7677. }
  7678. }
  7679. async function deletePPPSecret(id) {
  7680. if (!confirm('Are you sure you want to delete this secret account?')) return;
  7681. try {
  7682. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7683. if (res.ok) {
  7684. showToast('Deleted', 'Secret account removed', 'success');
  7685. loadPPPSecrets();
  7686. }
  7687. } catch (err) {
  7688. showToast('Error', err.message, 'error');
  7689. }
  7690. }
  7691. // PPP Profile Modal handlers
  7692. function openAddPPPProfileModal() {
  7693. document.getElementById('profile-modal-name').value = '';
  7694. document.getElementById('profile-modal-local').value = '10.10.10.1';
  7695. document.getElementById('profile-modal-remote').value = '10.10.10.10-10.10.10.50';
  7696. document.getElementById('profile-modal-dns').value = '1.1.1.1,8.8.8.8';
  7697. document.getElementById('profile-modal-encryption').value = 'required';
  7698. document.getElementById('profile-modal-onlyone').checked = true;
  7699. document.getElementById('profile-modal-comment').value = '';
  7700. document.getElementById('ppp-profile-modal').classList.remove('hidden');
  7701. }
  7702. function closePPPProfileModal() {
  7703. document.getElementById('ppp-profile-modal').classList.add('hidden');
  7704. }
  7705. async function submitSavePPPProfile(e) {
  7706. e.preventDefault();
  7707. const name = document.getElementById('profile-modal-name').value.trim();
  7708. const local = document.getElementById('profile-modal-local').value.trim();
  7709. const remote = document.getElementById('profile-modal-remote').value.trim();
  7710. const dns = document.getElementById('profile-modal-dns').value.trim();
  7711. const enc = document.getElementById('profile-modal-encryption').value;
  7712. const onlyone = document.getElementById('profile-modal-onlyone').checked;
  7713. const comment = document.getElementById('profile-modal-comment').value.trim();
  7714. try {
  7715. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`, {
  7716. method: 'POST',
  7717. headers: { 'Content-Type': 'application/json' },
  7718. body: JSON.stringify({
  7719. id: name,
  7720. name,
  7721. local_address: local,
  7722. remote_address: remote,
  7723. dns_servers: dns,
  7724. use_encryption: enc,
  7725. only_one: onlyone,
  7726. comment
  7727. })
  7728. });
  7729. if (res.ok) {
  7730. showToast('Profile Saved', `PPP profile ${name} created`, 'success');
  7731. closePPPProfileModal();
  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. async function deletePPPProfile(name) {
  7742. if (!confirm(`Delete PPP profile ${name}?`)) return;
  7743. try {
  7744. const res = await fetch(`${API_BASE}/vpn/ppp/profiles/${encodeURIComponent(name)}`, { method: 'DELETE' });
  7745. if (res.ok) {
  7746. showToast('Deleted', 'Profile removed', 'success');
  7747. loadPPPProfiles();
  7748. } else {
  7749. const err = await res.json();
  7750. showToast('Error', err.message, 'error');
  7751. }
  7752. } catch (err) {
  7753. showToast('Error', err.message, 'error');
  7754. }
  7755. }
  7756. // Server Config submissions
  7757. async function savePPPoEServerConfig(e) {
  7758. e.preventDefault();
  7759. const enabled = document.getElementById('pppoe-server-enabled').checked;
  7760. const name = document.getElementById('pppoe-server-name').value.trim();
  7761. const iface = document.getElementById('pppoe-server-iface').value;
  7762. const profile = document.getElementById('pppoe-server-profile').value;
  7763. const mtu = parseInt(document.getElementById('pppoe-server-mtu').value) || 1480;
  7764. const onesession = document.getElementById('pppoe-server-onesession').checked;
  7765. try {
  7766. const res = await fetch(`${API_BASE}/vpn/servers/pppoe`, {
  7767. method: 'POST',
  7768. headers: { 'Content-Type': 'application/json' },
  7769. body: JSON.stringify({
  7770. enabled,
  7771. service_name: name,
  7772. interface: iface,
  7773. default_profile: profile,
  7774. max_mtu: mtu,
  7775. max_mru: mtu,
  7776. one_session_per_host: onesession
  7777. })
  7778. });
  7779. if (res.ok) {
  7780. showToast('PPPoE Server', enabled ? 'PPPoE Server started' : 'PPPoE Server stopped', 'success');
  7781. loadPPPServers();
  7782. fetchData(false);
  7783. } else {
  7784. const err = await res.json();
  7785. showToast('Error', err.message, 'error');
  7786. }
  7787. } catch (err) {
  7788. showToast('Error', err.message, 'error');
  7789. }
  7790. }
  7791. async function savePPTPServerConfig(e) {
  7792. e.preventDefault();
  7793. const enabled = document.getElementById('pptp-server-enabled').checked;
  7794. const port = parseInt(document.getElementById('pptp-server-port').value) || 1723;
  7795. const profile = document.getElementById('pptp-server-profile').value;
  7796. const mppe = document.getElementById('pptp-server-mppe').checked;
  7797. try {
  7798. const res = await fetch(`${API_BASE}/vpn/servers/pptp`, {
  7799. method: 'POST',
  7800. headers: { 'Content-Type': 'application/json' },
  7801. body: JSON.stringify({
  7802. enabled,
  7803. port,
  7804. default_profile: profile,
  7805. require_mppe: mppe
  7806. })
  7807. });
  7808. if (res.ok) {
  7809. showToast('PPTP Server', enabled ? 'PPTP Server started' : 'PPTP Server stopped', 'success');
  7810. loadPPPServers();
  7811. fetchData(false);
  7812. } else {
  7813. const err = await res.json();
  7814. showToast('Error', err.message, 'error');
  7815. }
  7816. } catch (err) {
  7817. showToast('Error', err.message, 'error');
  7818. }
  7819. }
  7820. async function saveL2TPServerConfig(e) {
  7821. e.preventDefault();
  7822. const enabled = document.getElementById('l2tp-server-enabled').checked;
  7823. const port = parseInt(document.getElementById('l2tp-server-port').value) || 1701;
  7824. const profile = document.getElementById('l2tp-server-profile').value;
  7825. const useipsec = document.getElementById('l2tp-server-useipsec').value;
  7826. const psk = document.getElementById('l2tp-server-ipsecsecret').value.trim();
  7827. try {
  7828. const res = await fetch(`${API_BASE}/vpn/servers/l2tp`, {
  7829. method: 'POST',
  7830. headers: { 'Content-Type': 'application/json' },
  7831. body: JSON.stringify({
  7832. enabled,
  7833. port,
  7834. default_profile: profile,
  7835. use_ipsec: useipsec,
  7836. ipsec_secret: psk
  7837. })
  7838. });
  7839. if (res.ok) {
  7840. showToast('L2TP Server', enabled ? 'L2TP Server started' : 'L2TP Server stopped', 'success');
  7841. loadPPPServers();
  7842. fetchData(false);
  7843. } else {
  7844. const err = await res.json();
  7845. showToast('Error', err.message, 'error');
  7846. }
  7847. } catch (err) {
  7848. showToast('Error', err.message, 'error');
  7849. }
  7850. }
  7851. // IPSec Server Modal
  7852. function openIPSecServerModal() {
  7853. loadPPPServers();
  7854. document.getElementById('ipsec-server-modal').classList.remove('hidden');
  7855. }
  7856. function closeIPSecServerModal() {
  7857. document.getElementById('ipsec-server-modal').classList.add('hidden');
  7858. }
  7859. async function submitSaveIPSecServer(e) {
  7860. e.preventDefault();
  7861. const enabled = document.getElementById('modal-ipsec-server-enabled').checked;
  7862. const psk = document.getElementById('modal-ipsec-server-psk').value.trim();
  7863. const pool = document.getElementById('modal-ipsec-server-pool').value.trim();
  7864. const dns = document.getElementById('modal-ipsec-server-dns').value.trim();
  7865. const subnet = document.getElementById('modal-ipsec-server-subnet').value.trim();
  7866. try {
  7867. const res = await fetch(`${API_BASE}/vpn/servers/ipsec`, {
  7868. method: 'POST',
  7869. headers: { 'Content-Type': 'application/json' },
  7870. body: JSON.stringify({
  7871. enabled,
  7872. preshared_key: psk,
  7873. pool_address: pool,
  7874. dns_servers: dns,
  7875. local_subnet: subnet
  7876. })
  7877. });
  7878. if (res.ok) {
  7879. showToast('IPSec Server', enabled ? 'IKEv2 Roadwarrior responder active' : 'IPSec Server stopped', 'success');
  7880. closeIPSecServerModal();
  7881. loadPPPServers();
  7882. fetchData(false);
  7883. } else {
  7884. const err = await res.json();
  7885. showToast('Error', err.message, 'error');
  7886. }
  7887. } catch (err) {
  7888. showToast('Error', err.message, 'error');
  7889. }
  7890. }
  7891. // WireGuard Client Config Viewer
  7892. let currentWGClientConf = '';
  7893. async function openWGClientConfModal(iface, clientIP) {
  7894. try {
  7895. const res = await fetch(`${API_BASE}/vpn/wireguard/client-config`, {
  7896. method: 'POST',
  7897. headers: { 'Content-Type': 'application/json' },
  7898. body: JSON.stringify({
  7899. interface: iface,
  7900. address: clientIP || '10.10.0.2/32',
  7901. dns: '1.1.1.1, 8.8.8.8'
  7902. })
  7903. });
  7904. if (res.ok) {
  7905. const data = await res.json();
  7906. currentWGClientConf = data.config;
  7907. document.getElementById('wg-client-conf-text').value = currentWGClientConf;
  7908. document.getElementById('wg-client-conf-modal').classList.remove('hidden');
  7909. } else {
  7910. const err = await res.json();
  7911. showToast('Error', err.message, 'error');
  7912. }
  7913. } catch (err) {
  7914. showToast('Error', err.message, 'error');
  7915. }
  7916. }
  7917. function closeWGClientConfModal() {
  7918. document.getElementById('wg-client-conf-modal').classList.add('hidden');
  7919. }
  7920. function copyWGClientConf() {
  7921. if (!currentWGClientConf) return;
  7922. copyToClipboard(currentWGClientConf, 'WireGuard Client Profile');
  7923. }
  7924. function downloadWGClientConf() {
  7925. if (!currentWGClientConf) return;
  7926. const blob = new Blob([currentWGClientConf], { type: 'text/plain;charset=utf-8' });
  7927. const a = document.createElement('a');
  7928. a.href = URL.createObjectURL(blob);
  7929. a.download = 'wireguard-client.conf';
  7930. document.body.appendChild(a);
  7931. a.click();
  7932. document.body.removeChild(a);
  7933. showToast('Downloaded', 'wireguard-client.conf saved', 'success');
  7934. }
  7935. // =========================================================================
  7936. // DYNAMIC ROUTING (FRRouting BGP & OSPFv2)
  7937. // =========================================================================
  7938. state.activeDynSubTab = 'bgp-peers';
  7939. state.activeBgpSubTab = 'bgp-peers';
  7940. state.activeOspfTab = 'instances';
  7941. state.bgpInstance = null;
  7942. state.bgpPeers = [];
  7943. state.bgpNets = [];
  7944. state.bgpRoutes = [];
  7945. state.ospfInstance = null;
  7946. state.ospfInstances = [];
  7947. state.ospfAreas = [];
  7948. state.ospfAreaRanges = [];
  7949. state.ospfTemplates = [];
  7950. state.ospfLiveInterfaces = [];
  7951. state.ospfStaticNbrs = [];
  7952. state.ospfNeighbors = [];
  7953. state.ospfLSA = [];
  7954. state.ospfRoutes = [];
  7955. state.selectedOspfRow = {
  7956. instances: null,
  7957. areas: null,
  7958. 'area-ranges': null,
  7959. templates: null,
  7960. interfaces: null,
  7961. 'static-nbrs': null,
  7962. neighbors: null,
  7963. lsa: null,
  7964. };
  7965. state.ospfSort = {
  7966. instances: { col: 'name', asc: true },
  7967. areas: { col: 'name', asc: true },
  7968. ranges: { col: 'area', asc: true },
  7969. templates: { col: 'interfaces', asc: true },
  7970. live_ifaces: { col: 'interface', asc: true },
  7971. snbrs: { col: 'address', asc: true },
  7972. neighbors: { col: 'address', asc: true },
  7973. lsa: { col: 'instance', asc: true },
  7974. };
  7975. function switchBgpSubTab(subTab) {
  7976. state.activeBgpSubTab = subTab;
  7977. const tabs = ['bgp-peers', 'bgp-nets', 'bgp-routes'];
  7978. tabs.forEach(t => {
  7979. const el = document.getElementById(`dyn-subtab-${t}`);
  7980. const btn = document.getElementById(`bgp-subtab-btn-${t}`);
  7981. if (el) el.classList.toggle('hidden', t !== subTab);
  7982. if (btn) {
  7983. if (t === subTab) {
  7984. 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';
  7985. } else {
  7986. 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';
  7987. }
  7988. }
  7989. });
  7990. }
  7991. function switchOspfTab(tabName) {
  7992. state.activeOspfTab = tabName;
  7993. const tabs = ['instances', 'areas', 'area-ranges', 'templates', 'interfaces', 'static-nbrs', 'neighbors', 'lsa'];
  7994. tabs.forEach(t => {
  7995. const pane = document.getElementById(`ospf-pane-${t}`);
  7996. const btn = document.getElementById(`ospf-tab-btn-${t}`);
  7997. if (pane) pane.classList.toggle('hidden', t !== tabName);
  7998. if (btn) {
  7999. if (t === tabName) {
  8000. 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';
  8001. } else {
  8002. 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';
  8003. }
  8004. }
  8005. });
  8006. }
  8007. function switchOspfSubTab(tab) {
  8008. // Legacy alias
  8009. if (tab === 'ospf-ifaces') switchOspfTab('templates');
  8010. else if (tab === 'ospf-areas') switchOspfTab('areas');
  8011. else if (tab === 'ospf-nbrs') switchOspfTab('neighbors');
  8012. else switchOspfTab('instances');
  8013. }
  8014. function switchDynSubTab(subTab) {
  8015. if (subTab.startsWith('bgp')) {
  8016. if (state.activeTab !== 'bgp') navigate('bgp');
  8017. switchBgpSubTab(subTab);
  8018. } else if (subTab.startsWith('ospf')) {
  8019. if (state.activeTab !== 'ospf') navigate('ospf');
  8020. switchOspfTab('instances');
  8021. }
  8022. }
  8023. async function loadDynamicRouting(showToastMsg = false) {
  8024. try {
  8025. const fetchSafeJson = async (url) => {
  8026. try {
  8027. const r = await fetch(url);
  8028. return r.ok ? await r.json() : null;
  8029. } catch (e) {
  8030. return null;
  8031. }
  8032. };
  8033. const [
  8034. sum, bgpInst, bgpPeers, bgpNets, bgpRoutes,
  8035. ospfInsts, ospfAreas, ospfRanges, ospfTemplates, ospfLiveIfaces, ospfStaticNbrs, ospfNbrs, ospfLsa, filters,
  8036. selectRules, commLists, asLists
  8037. ] = await Promise.all([
  8038. fetchSafeJson(`${API_BASE}/routing/dynamic/summary`),
  8039. fetchSafeJson(`${API_BASE}/routing/bgp/instance`),
  8040. fetchSafeJson(`${API_BASE}/routing/bgp/peers`),
  8041. fetchSafeJson(`${API_BASE}/routing/bgp/networks`),
  8042. fetchSafeJson(`${API_BASE}/routing/bgp/routes`),
  8043. fetchSafeJson(`${API_BASE}/routing/ospf/instances`),
  8044. fetchSafeJson(`${API_BASE}/routing/ospf/areas`),
  8045. fetchSafeJson(`${API_BASE}/routing/ospf/area-ranges`),
  8046. fetchSafeJson(`${API_BASE}/routing/ospf/templates`),
  8047. fetchSafeJson(`${API_BASE}/routing/ospf/interfaces-live`),
  8048. fetchSafeJson(`${API_BASE}/routing/ospf/static-neighbors`),
  8049. fetchSafeJson(`${API_BASE}/routing/ospf/neighbors`),
  8050. fetchSafeJson(`${API_BASE}/routing/ospf/lsa`),
  8051. fetchSafeJson(`${API_BASE}/routing/filters`),
  8052. fetchSafeJson(`${API_BASE}/routing/filters/select-rules`),
  8053. fetchSafeJson(`${API_BASE}/routing/filters/community-lists`),
  8054. fetchSafeJson(`${API_BASE}/routing/filters/as-lists`)
  8055. ]);
  8056. if (sum) state.dynSummary = sum;
  8057. if (bgpInst) state.bgpInstance = bgpInst;
  8058. if (bgpPeers) state.bgpPeers = bgpPeers;
  8059. if (bgpNets) state.bgpNets = bgpNets;
  8060. if (bgpRoutes) state.bgpRoutes = bgpRoutes;
  8061. if (ospfInsts) state.ospfInstances = ospfInsts;
  8062. if (ospfAreas) state.ospfAreas = ospfAreas;
  8063. if (ospfRanges) state.ospfAreaRanges = ospfRanges;
  8064. if (ospfTemplates) state.ospfTemplates = ospfTemplates;
  8065. if (ospfLiveIfaces) state.ospfLiveInterfaces = ospfLiveIfaces;
  8066. if (ospfStaticNbrs) state.ospfStaticNbrs = ospfStaticNbrs;
  8067. if (ospfNbrs) state.ospfNeighbors = ospfNbrs;
  8068. if (ospfLsa) state.ospfLSA = ospfLsa;
  8069. if (filters) state.routingFilters = filters;
  8070. if (selectRules) state.routingSelectRules = selectRules;
  8071. if (commLists) state.routingCommunityLists = commLists;
  8072. if (asLists) state.routingASLists = asLists;
  8073. try { renderBgpStatusPill(); } catch(e) { console.error('renderBgpStatusPill error:', e); }
  8074. try { renderBgpPeers(); } catch(e) { console.error('renderBgpPeers error:', e); }
  8075. try { renderBgpNetworks(); } catch(e) { console.error('renderBgpNetworks error:', e); }
  8076. try { renderBgpRoutes(); } catch(e) { console.error('renderBgpRoutes error:', e); }
  8077. try { renderOspfInstances(); } catch(e) { console.error('renderOspfInstances error:', e); }
  8078. try { renderOspfAreas(); } catch(e) { console.error('renderOspfAreas error:', e); }
  8079. try { renderOspfAreaRanges(); } catch(e) { console.error('renderOspfAreaRanges error:', e); }
  8080. try { renderOspfTemplates(); } catch(e) { console.error('renderOspfTemplates error:', e); }
  8081. try { renderOspfLiveInterfaces(); } catch(e) { console.error('renderOspfLiveInterfaces error:', e); }
  8082. try { renderOspfStaticNbrs(); } catch(e) { console.error('renderOspfStaticNbrs error:', e); }
  8083. try { renderOspfNeighbors(); } catch(e) { console.error('renderOspfNeighbors error:', e); }
  8084. try { renderOspfLSA(); } catch(e) { console.error('renderOspfLSA error:', e); }
  8085. try { renderRoutingFilters(); } catch(e) { console.error('renderRoutingFilters error:', e); }
  8086. try { updateBadges(); } catch(e) { console.error('updateBadges error:', e); }
  8087. if (showToastMsg) showToast('Refreshed', 'Dynamic routing telemetry updated', 'info');
  8088. } catch (err) {
  8089. console.error('Failed to load dynamic routing:', err);
  8090. if (showToastMsg) showToast('Notice', 'Unable to refresh dynamic routing telemetry', 'warning');
  8091. }
  8092. }
  8093. async function loadOspfAll() {
  8094. await loadDynamicRouting(true);
  8095. }
  8096. function renderBgpStatusPill() {
  8097. const pills = document.querySelectorAll('.bgp-live-status-pill');
  8098. pills.forEach(pill => {
  8099. const inst = state.bgpInstance;
  8100. if (!inst || !inst.enabled) {
  8101. 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';
  8102. pill.innerText = 'BGP DISABLED';
  8103. } else if (inst.running) {
  8104. 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';
  8105. pill.innerText = `BGP ACTIVE (AS ${inst.as})`;
  8106. } else {
  8107. 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';
  8108. pill.innerText = 'BGP STARTING...';
  8109. }
  8110. });
  8111. }
  8112. function renderBgpPeers() {
  8113. const tbody = document.getElementById('bgp-peers-table-body');
  8114. if (!tbody) return;
  8115. const empty = document.getElementById('bgp-peers-empty');
  8116. const countBadge = document.getElementById('bgp-peers-count-badge');
  8117. const navBadge = document.getElementById('dyn-badge-bgp-peers');
  8118. const peers = state.bgpPeers || [];
  8119. if (countBadge) countBadge.innerText = `${peers.length} Peers`;
  8120. if (navBadge) navBadge.innerText = peers.length;
  8121. if (peers.length === 0) {
  8122. tbody.innerHTML = '';
  8123. if (empty) empty.classList.remove('hidden');
  8124. return;
  8125. }
  8126. if (empty) empty.classList.add('hidden');
  8127. const sig = peers.map(p => `${p.name}:${p.state}:${p.uptime}:${p.prefix_received}:${p.prefix_sent}:${p.disabled}`).join(';');
  8128. if (tbody.dataset.sig === sig) return;
  8129. tbody.dataset.sig = sig;
  8130. tbody.innerHTML = peers.map(p => {
  8131. let flagA = !p.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  8132. let flagE = p.state === 'Established' ? '<span class="text-emerald-400 font-bold ml-1" title="Established">E</span>' : '';
  8133. let flagX = p.disabled ? '<span class="text-rose-400 font-bold ml-1" title="Disabled">X</span>' : '';
  8134. let stateBadge = '';
  8135. if (p.disabled) {
  8136. 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>';
  8137. } else if (p.state === 'Established') {
  8138. 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>';
  8139. } else if (p.state === 'Connect' || p.state === 'Active') {
  8140. 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>`;
  8141. } else {
  8142. 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>`;
  8143. }
  8144. return `
  8145. <tr class="hover:bg-slate-800/40 transition">
  8146. <td class="py-2.5 px-3 text-center tracking-wider">${flagA}${flagE}${flagX}</td>
  8147. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(p.name)}</td>
  8148. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(p.remote_address)}</td>
  8149. <td class="py-2.5 px-3">
  8150. <div class="font-bold text-slate-200">AS ${p.remote_as}</div>
  8151. ${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>`}
  8152. </td>
  8153. <td class="py-2.5 px-3">${stateBadge}</td>
  8154. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(p.uptime || '-')}</td>
  8155. <td class="py-2.5 px-3 text-slate-300">
  8156. <span class="text-emerald-400 font-bold">↓ ${p.prefix_received || 0}</span> /
  8157. <span class="text-blue-400 font-bold">↑ ${p.prefix_sent || 0}</span>
  8158. </td>
  8159. <td class="py-2.5 px-3 font-mono text-[11px] whitespace-nowrap">
  8160. ${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> ` : ''}
  8161. ${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>` : ''}
  8162. ${!p.in_filter && !p.out_filter ? '<span class="text-slate-600">-</span>' : ''}
  8163. </td>
  8164. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(p.comment || '')}</td>
  8165. <td class="py-2.5 px-3 text-right space-x-1.5 whitespace-nowrap font-sans">
  8166. <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'}">
  8167. ${p.disabled ? 'Enable' : 'Disable'}
  8168. </button>
  8169. <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">
  8170. Edit
  8171. </button>
  8172. <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">
  8173. Delete
  8174. </button>
  8175. </td>
  8176. </tr>
  8177. `;
  8178. }).join('');
  8179. }
  8180. function renderBgpNetworks() {
  8181. const tbody = document.getElementById('bgp-nets-table-body');
  8182. if (!tbody) return;
  8183. const empty = document.getElementById('bgp-nets-empty');
  8184. const countBadge = document.getElementById('bgp-nets-count-badge');
  8185. const navBadge = document.getElementById('dyn-badge-bgp-nets');
  8186. const nets = state.bgpNets || [];
  8187. if (countBadge) countBadge.innerText = `${nets.length} Networks`;
  8188. if (navBadge) navBadge.innerText = nets.length;
  8189. if (nets.length === 0) {
  8190. tbody.innerHTML = '';
  8191. if (empty) empty.classList.remove('hidden');
  8192. return;
  8193. }
  8194. if (empty) empty.classList.add('hidden');
  8195. const sig = nets.map(n => `${n.network}:${n.disabled}:${n.comment}`).join(';');
  8196. if (tbody.dataset.sig === sig) return;
  8197. tbody.dataset.sig = sig;
  8198. tbody.innerHTML = nets.map(n => `
  8199. <tr class="hover:bg-slate-800/40 transition">
  8200. <td class="py-2.5 px-3 font-semibold text-purple-300 font-mono">${escapeHtml(n.network)}</td>
  8201. <td class="py-2.5 px-3">
  8202. ${n.disabled
  8203. ? '<span class="px-2 py-0.5 rounded-full text-[10px] bg-slate-800 text-slate-400 border border-slate-700">Disabled</span>'
  8204. : '<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>'}
  8205. </td>
  8206. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(n.comment || '')}</td>
  8207. <td class="py-2.5 px-3 text-right space-x-1 font-sans">
  8208. <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">
  8209. Delete
  8210. </button>
  8211. </td>
  8212. </tr>
  8213. `).join('');
  8214. }
  8215. function renderBgpRoutes() {
  8216. const tbody = document.getElementById('bgp-routes-table-body');
  8217. if (!tbody) return;
  8218. const empty = document.getElementById('bgp-routes-empty');
  8219. const countBadge = document.getElementById('bgp-routes-count-badge');
  8220. const navBadge = document.getElementById('dyn-badge-bgp-routes');
  8221. const routes = state.bgpRoutes || [];
  8222. if (countBadge) countBadge.innerText = `${routes.length} Routes`;
  8223. if (navBadge) navBadge.innerText = routes.length;
  8224. if (routes.length === 0) {
  8225. tbody.innerHTML = '';
  8226. if (empty) empty.classList.remove('hidden');
  8227. return;
  8228. }
  8229. if (empty) empty.classList.add('hidden');
  8230. const sig = routes.map(r => `${r.prefix}:${r.next_hop}:${r.metric}:${r.path}`).join(';');
  8231. if (tbody.dataset.sig === sig) return;
  8232. tbody.dataset.sig = sig;
  8233. tbody.innerHTML = routes.map(r => `
  8234. <tr class="hover:bg-slate-800/40 transition">
  8235. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.prefix)}</td>
  8236. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(r.next_hop || '-')}</td>
  8237. <td class="py-2.5 px-3 text-slate-300">${r.metric}</td>
  8238. <td class="py-2.5 px-3 text-slate-300">${r.weight}</td>
  8239. <td class="py-2.5 px-3 text-amber-300">${escapeHtml(r.path || 'i')}</td>
  8240. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.origin || 'IGP')}</td>
  8241. </tr>
  8242. `).join('');
  8243. }
  8244. // =========================================================================
  8245. // DEBTIK v7 OSPF TABLE RENDERING & SORTING
  8246. // =========================================================================
  8247. function sortOspfTable(tab, col) {
  8248. if (!state.ospfSort) state.ospfSort = {};
  8249. if (!state.ospfSort[tab]) state.ospfSort[tab] = { col: col, asc: true };
  8250. if (state.ospfSort[tab].col === col) {
  8251. state.ospfSort[tab].asc = !state.ospfSort[tab].asc;
  8252. } else {
  8253. state.ospfSort[tab].col = col;
  8254. state.ospfSort[tab].asc = true;
  8255. }
  8256. const asc = state.ospfSort[tab].asc;
  8257. let list = [];
  8258. if (tab === 'instances') list = state.ospfInstances || [];
  8259. else if (tab === 'areas') list = state.ospfAreas || [];
  8260. else if (tab === 'ranges') list = state.ospfAreaRanges || [];
  8261. else if (tab === 'templates') list = state.ospfTemplates || [];
  8262. else if (tab === 'live_ifaces') list = state.ospfLiveInterfaces || [];
  8263. else if (tab === 'snbrs') list = state.ospfStaticNbrs || [];
  8264. else if (tab === 'neighbors') list = state.ospfNeighbors || [];
  8265. else if (tab === 'lsa') list = state.ospfLSA || [];
  8266. list.sort((a, b) => {
  8267. let valA = a[col] ?? '';
  8268. let valB = b[col] ?? '';
  8269. if (typeof valA === 'number' && typeof valB === 'number') {
  8270. return asc ? valA - valB : valB - valA;
  8271. }
  8272. return asc ? String(valA).localeCompare(String(valB)) : String(valB).localeCompare(String(valA));
  8273. });
  8274. if (tab === 'instances') renderOspfInstances();
  8275. else if (tab === 'areas') renderOspfAreas();
  8276. else if (tab === 'ranges') renderOspfAreaRanges();
  8277. else if (tab === 'templates') renderOspfTemplates();
  8278. else if (tab === 'live_ifaces') renderOspfLiveInterfaces();
  8279. else if (tab === 'snbrs') renderOspfStaticNbrs();
  8280. else if (tab === 'neighbors') renderOspfNeighbors();
  8281. else if (tab === 'lsa') renderOspfLSA();
  8282. }
  8283. function selectOspfRow(tab, id) {
  8284. if (!state.selectedOspfRow) state.selectedOspfRow = {};
  8285. state.selectedOspfRow[tab] = id;
  8286. if (tab === 'instances') {
  8287. renderOspfInstances();
  8288. const btnEn = document.getElementById('btn-ospf-inst-enable');
  8289. const btnDis = document.getElementById('btn-ospf-inst-disable');
  8290. const btnRem = document.getElementById('btn-ospf-inst-remove');
  8291. const btnCom = document.getElementById('btn-ospf-inst-comment');
  8292. if (btnEn) btnEn.disabled = false;
  8293. if (btnDis) btnDis.disabled = false;
  8294. if (btnRem) btnRem.disabled = false;
  8295. if (btnCom) btnCom.disabled = false;
  8296. } else if (tab === 'areas') {
  8297. renderOspfAreas();
  8298. const btnEn = document.getElementById('btn-ospf-area-enable');
  8299. const btnDis = document.getElementById('btn-ospf-area-disable');
  8300. const btnRem = document.getElementById('btn-ospf-area-remove');
  8301. const btnCom = document.getElementById('btn-ospf-area-comment');
  8302. if (btnEn) btnEn.disabled = false;
  8303. if (btnDis) btnDis.disabled = false;
  8304. if (btnRem) btnRem.disabled = false;
  8305. if (btnCom) btnCom.disabled = false;
  8306. } else if (tab === 'ranges') {
  8307. renderOspfAreaRanges();
  8308. const btnEn = document.getElementById('btn-ospf-range-enable');
  8309. const btnDis = document.getElementById('btn-ospf-range-disable');
  8310. const btnRem = document.getElementById('btn-ospf-range-remove');
  8311. const btnCom = document.getElementById('btn-ospf-range-comment');
  8312. if (btnEn) btnEn.disabled = false;
  8313. if (btnDis) btnDis.disabled = false;
  8314. if (btnRem) btnRem.disabled = false;
  8315. if (btnCom) btnCom.disabled = false;
  8316. } else if (tab === 'templates') {
  8317. renderOspfTemplates();
  8318. const btnEn = document.getElementById('btn-ospf-tmpl-enable');
  8319. const btnDis = document.getElementById('btn-ospf-tmpl-disable');
  8320. const btnRem = document.getElementById('btn-ospf-tmpl-remove');
  8321. const btnCom = document.getElementById('btn-ospf-tmpl-comment');
  8322. if (btnEn) btnEn.disabled = false;
  8323. if (btnDis) btnDis.disabled = false;
  8324. if (btnRem) btnRem.disabled = false;
  8325. if (btnCom) btnCom.disabled = false;
  8326. } else if (tab === 'snbrs') {
  8327. renderOspfStaticNbrs();
  8328. const btnEn = document.getElementById('btn-ospf-snbr-enable');
  8329. const btnDis = document.getElementById('btn-ospf-snbr-disable');
  8330. const btnRem = document.getElementById('btn-ospf-snbr-remove');
  8331. const btnCom = document.getElementById('btn-ospf-snbr-comment');
  8332. if (btnEn) btnEn.disabled = false;
  8333. if (btnDis) btnDis.disabled = false;
  8334. if (btnRem) btnRem.disabled = false;
  8335. if (btnCom) btnCom.disabled = false;
  8336. }
  8337. }
  8338. // TAB 1: INSTANCES
  8339. function renderOspfInstances() {
  8340. const tbody = document.getElementById('ospf-instances-table-body');
  8341. if (!tbody) return;
  8342. const countEl = document.getElementById('ospf-instances-footer-count');
  8343. const filter = (document.getElementById('filter-ospf-instances')?.value || '').toLowerCase();
  8344. let list = state.ospfInstances || [];
  8345. if (filter) {
  8346. list = list.filter(i => (i.name || '').toLowerCase().includes(filter) || (i.router_id || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  8347. }
  8348. if (countEl) countEl.innerText = list.length;
  8349. const selId = state.selectedOspfRow?.instances;
  8350. tbody.innerHTML = list.map((inst, idx) => {
  8351. const isSel = inst.id === selId;
  8352. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  8353. const flagD = inst.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  8354. return `
  8355. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('instances', '${inst.id}')" ondblclick="openEditOspfInstanceModal('${inst.id}')">
  8356. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  8357. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🔀'}</td>
  8358. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(inst.comment || '')}</td>
  8359. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  8360. <span class="text-sky-400">↳</span> <span>${escapeHtml(inst.name || 'Default')}</span>
  8361. </td>
  8362. <td class="py-1.5 px-3">${inst.version || 2}</td>
  8363. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(inst.vrf || 'main')}</td>
  8364. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(inst.router_id || '192.168.131.56')}</td>
  8365. </tr>
  8366. `;
  8367. }).join('');
  8368. }
  8369. // TAB 2: AREAS
  8370. function renderOspfAreas() {
  8371. const tbody = document.getElementById('ospf-areas-table-body');
  8372. if (!tbody) return;
  8373. const countEl = document.getElementById('ospf-areas-footer-count');
  8374. const filter = (document.getElementById('filter-ospf-areas')?.value || '').toLowerCase();
  8375. let list = state.ospfAreas || [];
  8376. if (filter) {
  8377. list = list.filter(a => (a.name || '').toLowerCase().includes(filter) || (a.area_id || '').toLowerCase().includes(filter) || (a.comment || '').toLowerCase().includes(filter));
  8378. }
  8379. if (countEl) countEl.innerText = list.length;
  8380. const selId = state.selectedOspfRow?.areas;
  8381. tbody.innerHTML = list.map((a, idx) => {
  8382. const isSel = a.id === selId;
  8383. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  8384. const flagD = a.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  8385. return `
  8386. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('areas', '${a.id}')" ondblclick="openEditOspfAreaModal('${a.id}')">
  8387. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  8388. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🌐'}</td>
  8389. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(a.comment || '')}</td>
  8390. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  8391. <span class="text-sky-400">↳</span> <span>${escapeHtml(a.name || 'Default')}</span>
  8392. </td>
  8393. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(a.instance || 'Default')}</td>
  8394. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(a.area_id || '0.0.0.0')}</td>
  8395. <td class="py-1.5 px-3 font-mono text-slate-400">${escapeHtml(a.area_type || 'default')}</td>
  8396. </tr>
  8397. `;
  8398. }).join('');
  8399. }
  8400. // TAB 3: AREA RANGES
  8401. function renderOspfAreaRanges() {
  8402. const tbody = document.getElementById('ospf-ranges-table-body');
  8403. if (!tbody) return;
  8404. const countEl = document.getElementById('ospf-ranges-footer-count');
  8405. const filter = (document.getElementById('filter-ospf-area-ranges')?.value || '').toLowerCase();
  8406. let list = state.ospfAreaRanges || [];
  8407. if (filter) {
  8408. list = list.filter(r => (r.prefix || '').toLowerCase().includes(filter) || (r.area || '').toLowerCase().includes(filter) || (r.comment || '').toLowerCase().includes(filter));
  8409. }
  8410. if (countEl) countEl.innerText = list.length;
  8411. const selId = state.selectedOspfRow?.['area-ranges'];
  8412. tbody.innerHTML = list.map((r, idx) => {
  8413. const isSel = r.id === selId;
  8414. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  8415. const flagD = r.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  8416. return `
  8417. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('ranges', '${r.id}')" ondblclick="openEditOspfAreaRangeModal('${r.id}')">
  8418. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  8419. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🏷'}</td>
  8420. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(r.comment || '')}</td>
  8421. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(r.area || 'Default')}</td>
  8422. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(r.prefix || '')}</td>
  8423. <td class="py-1.5 px-3">${r.cost || 1}</td>
  8424. <td class="py-1.5 px-3">${r.advertise !== false ? 'yes' : 'no'}</td>
  8425. </tr>
  8426. `;
  8427. }).join('');
  8428. }
  8429. // TAB 4: INTERFACE TEMPLATES
  8430. function renderOspfTemplates() {
  8431. const tbody = document.getElementById('ospf-templates-table-body');
  8432. if (!tbody) return;
  8433. const countEl = document.getElementById('ospf-templates-footer-count');
  8434. const filter = (document.getElementById('filter-ospf-templates')?.value || '').toLowerCase();
  8435. let list = state.ospfTemplates || [];
  8436. if (filter) {
  8437. list = list.filter(t => (t.interfaces || t.interface || '').toLowerCase().includes(filter) || (t.networks || t.network || '').toLowerCase().includes(filter) || (t.comment || '').toLowerCase().includes(filter));
  8438. }
  8439. if (countEl) countEl.innerText = list.length;
  8440. const selId = state.selectedOspfRow?.templates;
  8441. tbody.innerHTML = list.map((t, idx) => {
  8442. const isSel = t.id === selId;
  8443. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  8444. const ifaces = t.interfaces || t.interface || 'all';
  8445. const nets = t.networks || t.network || '';
  8446. const flagD = t.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  8447. return `
  8448. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('templates', '${t.id}')" ondblclick="openEditOspfTemplateModal('${t.id}')">
  8449. <td class="py-1.5 px-3 w-8 text-center text-slate-500 font-bold">${idx}</td>
  8450. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🔀'}</td>
  8451. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(t.comment || '')}</td>
  8452. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  8453. <span class="text-sky-400">↳</span> <span>${escapeHtml(ifaces)}</span>
  8454. </td>
  8455. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(t.area || 'Default')}</td>
  8456. <td class="py-1.5 px-3 font-mono text-sky-300">${escapeHtml(nets)}</td>
  8457. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(t.network_type || 'broadcast')}</td>
  8458. <td class="py-1.5 px-3">${t.cost || 1}</td>
  8459. <td class="py-1.5 px-3">${t.priority || 128}</td>
  8460. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(t.auth || t.auth_type || '')}</td>
  8461. </tr>
  8462. `;
  8463. }).join('');
  8464. }
  8465. // TAB 5: LIVE INTERFACES
  8466. function renderOspfLiveInterfaces() {
  8467. const tbody = document.getElementById('ospf-live-interfaces-table-body');
  8468. if (!tbody) return;
  8469. const countEl = document.getElementById('ospf-live-interfaces-footer-count');
  8470. const filter = (document.getElementById('filter-ospf-interfaces')?.value || '').toLowerCase();
  8471. let list = state.ospfLiveInterfaces || [];
  8472. if (filter) {
  8473. list = list.filter(i => (i.interface || '').toLowerCase().includes(filter) || (i.address || '').toLowerCase().includes(filter) || (i.state || '').toLowerCase().includes(filter));
  8474. }
  8475. if (countEl) countEl.innerText = list.length;
  8476. tbody.innerHTML = list.map(i => `
  8477. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  8478. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(i.flags || 'D')}</td>
  8479. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(i.interface || '')}</td>
  8480. <td class="py-1.5 px-3 font-mono text-sky-300 font-medium">${escapeHtml(i.address || '')}</td>
  8481. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(i.area || 'Default')}</td>
  8482. <td class="py-1.5 px-3 text-center text-slate-400">${i.instance_id || 0}</td>
  8483. <td class="py-1.5 px-3 font-mono text-amber-300 lowercase">${escapeHtml(i.state || 'waiting')}</td>
  8484. <td class="py-1.5 px-3">${i.cost || 1}</td>
  8485. <td class="py-1.5 px-3">${i.priority || 128}</td>
  8486. </tr>
  8487. `).join('');
  8488. }
  8489. // TAB 6: STATIC NEIGHBORS
  8490. function renderOspfStaticNbrs() {
  8491. const tbody = document.getElementById('ospf-snbrs-table-body');
  8492. if (!tbody) return;
  8493. const countEl = document.getElementById('ospf-snbrs-footer-count');
  8494. const filter = (document.getElementById('filter-ospf-static-nbrs')?.value || '').toLowerCase();
  8495. let list = state.ospfStaticNbrs || [];
  8496. if (filter) {
  8497. list = list.filter(n => (n.address || '').toLowerCase().includes(filter) || (n.area || '').toLowerCase().includes(filter) || (n.comment || '').toLowerCase().includes(filter));
  8498. }
  8499. if (countEl) countEl.innerText = list.length;
  8500. const selId = state.selectedOspfRow?.['static-nbrs'];
  8501. tbody.innerHTML = list.map((n, idx) => {
  8502. const isSel = n.id === selId;
  8503. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  8504. const flagD = n.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  8505. return `
  8506. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('snbrs', '${n.id}')" ondblclick="openEditOspfStaticNbrModal('${n.id}')">
  8507. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  8508. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '📡'}</td>
  8509. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(n.comment || '')}</td>
  8510. <td class="py-1.5 px-3 font-semibold font-mono text-sky-300">${escapeHtml(n.address || '')}</td>
  8511. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(n.area || 'Default')}</td>
  8512. <td class="py-1.5 px-3">${n.poll_interval || 120}s</td>
  8513. <td class="py-1.5 px-3">${n.cost || 1}</td>
  8514. </tr>
  8515. `;
  8516. }).join('');
  8517. }
  8518. // TAB 7: LIVE NEIGHBORS
  8519. function renderOspfNeighbors() {
  8520. const tbody = document.getElementById('ospf-neighbors-table-body');
  8521. if (!tbody) return;
  8522. const countEl = document.getElementById('ospf-neighbors-footer-count');
  8523. const filter = (document.getElementById('filter-ospf-neighbors')?.value || '').toLowerCase();
  8524. let list = state.ospfNeighbors || [];
  8525. if (filter) {
  8526. list = list.filter(n => (n.address || '').toLowerCase().includes(filter) || (n.state || '').toLowerCase().includes(filter) || (n.instance || '').toLowerCase().includes(filter));
  8527. }
  8528. if (countEl) countEl.innerText = list.length;
  8529. tbody.innerHTML = list.map(n => `
  8530. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  8531. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(n.flags || 'D')}</td>
  8532. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(n.comment || '')}</td>
  8533. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  8534. <span class="text-sky-400">↳</span> <span>${escapeHtml(n.instance || 'Default')}</span>
  8535. </td>
  8536. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(n.area || 'Default')}</td>
  8537. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(n.address || '')}</td>
  8538. <td class="py-1.5 px-3 font-mono font-bold text-emerald-400">${escapeHtml(n.state || 'Full')}</td>
  8539. <td class="py-1.5 px-3 text-slate-400">${n.state_changes ?? 6}</td>
  8540. </tr>
  8541. `).join('');
  8542. }
  8543. // TAB 8: LINK-STATE DATABASE (LSA)
  8544. function renderOspfLSA() {
  8545. const tbody = document.getElementById('ospf-lsa-table-body');
  8546. if (!tbody) return;
  8547. const countEl = document.getElementById('ospf-lsa-footer-count');
  8548. const filter = (document.getElementById('filter-ospf-lsa')?.value || '').toLowerCase();
  8549. let list = state.ospfLSA || [];
  8550. if (filter) {
  8551. list = list.filter(l => (l.type || '').toLowerCase().includes(filter) || (l.originator || '').toLowerCase().includes(filter) || (l.id || '').toLowerCase().includes(filter));
  8552. }
  8553. if (countEl) countEl.innerText = list.length;
  8554. tbody.innerHTML = list.map(l => `
  8555. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  8556. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(l.flags || 'D')}</td>
  8557. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  8558. <span class="text-sky-400">↳</span> <span>${escapeHtml(l.instance || 'Default')}</span>
  8559. </td>
  8560. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(l.area || 'Default')}</td>
  8561. <td class="py-1.5 px-3 font-mono text-amber-300">${escapeHtml(l.type || 'router')}</td>
  8562. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(l.originator || '')}</td>
  8563. <td class="py-1.5 px-3 font-mono text-sky-300 font-medium">${escapeHtml(l.id || '')}</td>
  8564. <td class="py-1.5 px-3 text-slate-500">${escapeHtml(l.link || '')}</td>
  8565. <td class="py-1.5 px-3 text-slate-500">${l.link_index ?? 0}</td>
  8566. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(l.sequence || '')}</td>
  8567. <td class="py-1.5 px-3 text-slate-400">${l.age ?? 0}</td>
  8568. </tr>
  8569. `).join('');
  8570. }
  8571. function renderOspfStatusPill() {
  8572. // Maintained for backward compatibility
  8573. const pill = document.getElementById('ospf-live-status-pill');
  8574. if (!pill) return;
  8575. 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';
  8576. pill.innerText = 'OSPF ACTIVE';
  8577. }
  8578. function renderOspfInterfaces() {
  8579. renderOspfTemplates();
  8580. }
  8581. function renderOspfRoutes() {
  8582. // Routes retained in background
  8583. }
  8584. // BGP Modals & Actions
  8585. function openBgpInstanceModal() {
  8586. const inst = state.bgpInstance || { enabled: false, as: 65001, router_id: '192.168.131.56', hold_time: 180, keepalive_time: 60 };
  8587. document.getElementById('modal-bgp-enabled').checked = !!inst.enabled;
  8588. document.getElementById('modal-bgp-as').value = inst.as || 65001;
  8589. document.getElementById('modal-bgp-router-id').value = inst.router_id || '';
  8590. document.getElementById('modal-bgp-keepalive').value = inst.keepalive_time || 60;
  8591. document.getElementById('modal-bgp-holdtime').value = inst.hold_time || 180;
  8592. document.getElementById('modal-bgp-redist-conn').checked = !!inst.redistribute_connected;
  8593. document.getElementById('modal-bgp-redist-static').checked = !!inst.redistribute_static;
  8594. document.getElementById('modal-bgp-redist-ospf').checked = !!inst.redistribute_ospf;
  8595. document.getElementById('bgp-instance-modal').classList.remove('hidden');
  8596. }
  8597. function closeBgpInstanceModal() {
  8598. document.getElementById('bgp-instance-modal').classList.add('hidden');
  8599. }
  8600. async function submitBgpInstance(e) {
  8601. e.preventDefault();
  8602. const payload = {
  8603. enabled: document.getElementById('modal-bgp-enabled').checked,
  8604. as: parseInt(document.getElementById('modal-bgp-as').value, 10),
  8605. router_id: document.getElementById('modal-bgp-router-id').value.trim(),
  8606. keepalive_time: parseInt(document.getElementById('modal-bgp-keepalive').value, 10),
  8607. hold_time: parseInt(document.getElementById('modal-bgp-holdtime').value, 10),
  8608. redistribute_connected: document.getElementById('modal-bgp-redist-conn').checked,
  8609. redistribute_static: document.getElementById('modal-bgp-redist-static').checked,
  8610. redistribute_ospf: document.getElementById('modal-bgp-redist-ospf').checked
  8611. };
  8612. try {
  8613. const res = await fetch(`${API_BASE}/routing/bgp/instance`, {
  8614. method: 'POST',
  8615. headers: { 'Content-Type': 'application/json' },
  8616. body: JSON.stringify(payload)
  8617. });
  8618. if (res.ok) {
  8619. closeBgpInstanceModal();
  8620. showToast('Success', 'BGP instance configuration updated', 'success');
  8621. loadDynamicRouting();
  8622. } else {
  8623. const err = await res.json();
  8624. showToast('Error', err.error || 'Failed to update BGP instance', 'error');
  8625. }
  8626. } catch (err) {
  8627. showToast('Error', err.message, 'error');
  8628. }
  8629. }
  8630. // ----------------- BGP Peer Connection Modal (DebTik v7) -----------------
  8631. function switchBgpPeerModalTab(tab) {
  8632. const tabs = ['general', 'extra', 'attributes', 'filter'];
  8633. tabs.forEach(t => {
  8634. const pane = document.getElementById(`bgp-peer-tab-${t}`);
  8635. const btn = document.getElementById(`bgp-peer-tab-btn-${t}`);
  8636. if (t === tab) {
  8637. if (pane) pane.classList.remove('hidden');
  8638. if (btn) btn.className = 'px-4 py-2 text-xs font-bold border-b-2 border-cyan-500 text-white transition';
  8639. } else {
  8640. if (pane) pane.classList.add('hidden');
  8641. 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';
  8642. }
  8643. });
  8644. }
  8645. function addOutputNetworkRow(val = '') {
  8646. const container = document.getElementById('modal-bgp-output-networks-container');
  8647. if (!container) return;
  8648. const row = document.createElement('div');
  8649. row.className = 'flex items-center gap-2 output-net-row';
  8650. row.innerHTML = `
  8651. <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">
  8652. <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>
  8653. `;
  8654. container.appendChild(row);
  8655. }
  8656. function parseBgpTime(val) {
  8657. if (!val) return 0;
  8658. val = String(val).trim();
  8659. if (val.includes(':')) {
  8660. const parts = val.split(':').map(x => parseInt(x, 10) || 0);
  8661. if (parts.length === 3) return parts[0] * 3600 + parts[1] * 60 + parts[2];
  8662. if (parts.length === 2) return parts[0] * 60 + parts[1];
  8663. }
  8664. return parseInt(val, 10) || 0;
  8665. }
  8666. function formatBgpTime(secs) {
  8667. if (!secs || secs <= 0) return '00:00:00';
  8668. const h = Math.floor(secs / 3600);
  8669. const m = Math.floor((secs % 3600) / 60);
  8670. const s = secs % 60;
  8671. return `${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`;
  8672. }
  8673. function populateBgpRoutingTables() {
  8674. const sel = document.getElementById('modal-bgp-peer-routing-table');
  8675. if (!sel) return;
  8676. const cur = sel.value || 'main';
  8677. sel.innerHTML = '<option value="main">main</option>';
  8678. (state.routingTables || []).forEach(t => {
  8679. if (t.name !== 'main') {
  8680. const opt = document.createElement('option');
  8681. opt.value = t.name;
  8682. opt.innerText = t.name;
  8683. sel.appendChild(opt);
  8684. }
  8685. });
  8686. sel.value = cur;
  8687. }
  8688. function openAddBgpPeerModal() {
  8689. document.getElementById('bgp-peer-form').reset();
  8690. document.getElementById('modal-bgp-peer-id').value = '';
  8691. document.getElementById('bgp-peer-modal-title').innerText = 'New...';
  8692. // General Tab
  8693. document.getElementById('modal-bgp-peer-enabled').checked = true;
  8694. document.getElementById('modal-bgp-peer-comment').value = '';
  8695. document.getElementById('modal-bgp-peer-name').value = '';
  8696. if (document.getElementById('modal-bgp-peer-instance')) document.getElementById('modal-bgp-peer-instance').value = 'bgp-instance-1';
  8697. if (document.getElementById('modal-bgp-peer-template')) document.getElementById('modal-bgp-peer-template').value = '';
  8698. document.getElementById('modal-bgp-peer-local-as').value = '';
  8699. document.getElementById('modal-bgp-peer-afi-ip').checked = true;
  8700. document.getElementById('modal-bgp-peer-afi-ipv6').checked = false;
  8701. if (document.getElementById('modal-bgp-peer-afi-l2vpn')) document.getElementById('modal-bgp-peer-afi-l2vpn').checked = false;
  8702. if (document.getElementById('modal-bgp-peer-afi-vpnv4')) document.getElementById('modal-bgp-peer-afi-vpnv4').checked = false;
  8703. if (document.getElementById('modal-bgp-peer-afi-l2vpn-cisco')) document.getElementById('modal-bgp-peer-afi-l2vpn-cisco').checked = false;
  8704. document.getElementById('modal-bgp-peer-router-id').value = '';
  8705. document.getElementById('modal-bgp-peer-remote-addr').value = '';
  8706. document.getElementById('modal-bgp-peer-remote-port').value = '';
  8707. document.getElementById('modal-bgp-peer-remote-as').value = '';
  8708. if (document.getElementById('modal-bgp-peer-remote-allow-as')) document.getElementById('modal-bgp-peer-remote-allow-as').value = '';
  8709. document.getElementById('modal-bgp-peer-local-addr').value = '';
  8710. document.getElementById('modal-bgp-peer-local-port').value = '';
  8711. document.getElementById('modal-bgp-peer-local-role').value = 'ebgp';
  8712. document.getElementById('modal-bgp-peer-password').value = '';
  8713. document.getElementById('modal-bgp-peer-multihop').checked = false;
  8714. if (document.getElementById('modal-bgp-peer-tx-ttl')) document.getElementById('modal-bgp-peer-tx-ttl').value = '';
  8715. if (document.getElementById('modal-bgp-peer-rx-min-ttl')) document.getElementById('modal-bgp-peer-rx-min-ttl').value = '';
  8716. document.getElementById('modal-bgp-peer-connect').checked = true;
  8717. document.getElementById('modal-bgp-peer-listen').checked = true;
  8718. // Extra Tab
  8719. document.getElementById('modal-bgp-peer-holdtime').value = '00:00:30';
  8720. document.getElementById('modal-bgp-peer-keepalive').value = '00:00:10';
  8721. if (document.getElementById('modal-bgp-peer-use-bfd')) document.getElementById('modal-bgp-peer-use-bfd').checked = false;
  8722. if (document.getElementById('modal-bgp-peer-vrf')) document.getElementById('modal-bgp-peer-vrf').value = 'main';
  8723. if (document.getElementById('modal-bgp-peer-no-client-reflect')) document.getElementById('modal-bgp-peer-no-client-reflect').checked = true;
  8724. document.getElementById('modal-bgp-peer-redist-conn').checked = false;
  8725. document.getElementById('modal-bgp-peer-redist-static').checked = true;
  8726. if (document.getElementById('modal-bgp-peer-redist-rip')) document.getElementById('modal-bgp-peer-redist-rip').checked = false;
  8727. document.getElementById('modal-bgp-peer-redist-ospf').checked = false;
  8728. document.getElementById('modal-bgp-peer-redist-bgp').checked = false;
  8729. if (document.getElementById('modal-bgp-peer-redist-vpn')) document.getElementById('modal-bgp-peer-redist-vpn').checked = false;
  8730. if (document.getElementById('modal-bgp-peer-redist-dhcp')) document.getElementById('modal-bgp-peer-redist-dhcp').checked = false;
  8731. if (document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn')) document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn').checked = false;
  8732. if (document.getElementById('modal-bgp-peer-redist-slaac')) document.getElementById('modal-bgp-peer-redist-slaac').checked = false;
  8733. document.getElementById('modal-bgp-peer-default-orig').checked = false;
  8734. if (document.getElementById('modal-bgp-peer-network-blackhole')) document.getElementById('modal-bgp-peer-network-blackhole').checked = false;
  8735. if (document.getElementById('modal-bgp-peer-no-early-cut')) document.getElementById('modal-bgp-peer-no-early-cut').checked = false;
  8736. if (document.getElementById('modal-bgp-peer-keep-sent-attrs')) document.getElementById('modal-bgp-peer-keep-sent-attrs').checked = false;
  8737. if (document.getElementById('modal-bgp-peer-input-affinity')) document.getElementById('modal-bgp-peer-input-affinity').value = '';
  8738. if (document.getElementById('modal-bgp-peer-output-affinity')) document.getElementById('modal-bgp-peer-output-affinity').value = '';
  8739. // Attributes Tab
  8740. document.getElementById('modal-bgp-peer-nexthop-choice').value = 'force-self';
  8741. document.getElementById('modal-bgp-peer-default-prepend').value = 0;
  8742. document.getElementById('modal-bgp-peer-allow-as-in').value = 0;
  8743. if (document.getElementById('modal-bgp-peer-ignore-as-path-len')) document.getElementById('modal-bgp-peer-ignore-as-path-len').checked = false;
  8744. document.getElementById('modal-bgp-peer-remove-priv-as').checked = false;
  8745. document.getElementById('modal-bgp-peer-as-override').checked = false;
  8746. // Filter Tab
  8747. populateFilterChainsDatalist();
  8748. document.getElementById('modal-bgp-peer-in-filter').value = '';
  8749. if (document.getElementById('modal-bgp-peer-in-accept-nlri')) document.getElementById('modal-bgp-peer-in-accept-nlri').value = '';
  8750. if (document.getElementById('modal-bgp-peer-in-accept-comm')) document.getElementById('modal-bgp-peer-in-accept-comm').value = '';
  8751. if (document.getElementById('modal-bgp-peer-in-accept-ext-comm')) document.getElementById('modal-bgp-peer-in-accept-ext-comm').value = '';
  8752. if (document.getElementById('modal-bgp-peer-in-accept-large-comm')) document.getElementById('modal-bgp-peer-in-accept-large-comm').value = '';
  8753. if (document.getElementById('modal-bgp-peer-in-filter-comm')) document.getElementById('modal-bgp-peer-in-filter-comm').value = '';
  8754. if (document.getElementById('modal-bgp-peer-in-filter-ext-comm')) document.getElementById('modal-bgp-peer-in-filter-ext-comm').value = '';
  8755. if (document.getElementById('modal-bgp-peer-in-filter-large-comm')) document.getElementById('modal-bgp-peer-in-filter-large-comm').value = '';
  8756. if (document.getElementById('modal-bgp-peer-in-filter-unknown')) document.getElementById('modal-bgp-peer-in-filter-unknown').checked = false;
  8757. document.getElementById('modal-bgp-peer-out-filter').value = '';
  8758. if (document.getElementById('modal-bgp-peer-out-selection-policy')) document.getElementById('modal-bgp-peer-out-selection-policy').value = 'disabled';
  8759. if (document.getElementById('modal-bgp-peer-out-network-name')) document.getElementById('modal-bgp-peer-out-network-name').value = '';
  8760. populateBgpRoutingTables();
  8761. const container = document.getElementById('modal-bgp-output-networks-container');
  8762. if (container) {
  8763. container.innerHTML = '';
  8764. addOutputNetworkRow('');
  8765. }
  8766. const removeBtn = document.getElementById('modal-btn-remove-peer');
  8767. if (removeBtn) removeBtn.classList.add('hidden');
  8768. switchBgpPeerModalTab('general');
  8769. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  8770. }
  8771. function populateFilterChainsDatalist() {
  8772. const dl = document.getElementById('filter-chains-list');
  8773. if (!dl) return;
  8774. const chains = new Set();
  8775. (state.routingFilters || []).forEach(f => {
  8776. if (f.chain) chains.add(f.chain);
  8777. });
  8778. if (chains.size === 0) {
  8779. chains.add('awmn');
  8780. chains.add('bgp-in');
  8781. chains.add('bgp-out');
  8782. }
  8783. dl.innerHTML = '';
  8784. chains.forEach(c => {
  8785. const opt = document.createElement('option');
  8786. opt.value = c;
  8787. dl.appendChild(opt);
  8788. });
  8789. }
  8790. function openEditBgpPeerModal(id) {
  8791. const p = (state.bgpPeers || []).find(item => item.id === id);
  8792. if (!p) return;
  8793. populateBgpRoutingTables();
  8794. populateFilterChainsDatalist();
  8795. document.getElementById('modal-bgp-peer-id').value = p.id;
  8796. document.getElementById('bgp-peer-modal-title').innerText = p.name || p.id;
  8797. // General Tab
  8798. document.getElementById('modal-bgp-peer-enabled').checked = p.enabled !== false && !p.disabled;
  8799. document.getElementById('modal-bgp-peer-comment').value = p.comment || '';
  8800. document.getElementById('modal-bgp-peer-name').value = p.name || '';
  8801. if (document.getElementById('modal-bgp-peer-instance')) document.getElementById('modal-bgp-peer-instance').value = p.instance || 'bgp-instance-1';
  8802. if (document.getElementById('modal-bgp-peer-template')) document.getElementById('modal-bgp-peer-template').value = p.template || '';
  8803. document.getElementById('modal-bgp-peer-local-as').value = p.local_as || '';
  8804. document.getElementById('modal-bgp-peer-router-id').value = p.router_id || '';
  8805. document.getElementById('modal-bgp-peer-afi-ip').checked = true;
  8806. document.getElementById('modal-bgp-peer-afi-ipv6').checked = p.afi === 'ipv6';
  8807. document.getElementById('modal-bgp-peer-remote-addr').value = p.remote_address || '';
  8808. document.getElementById('modal-bgp-peer-remote-port').value = p.remote_port || '';
  8809. document.getElementById('modal-bgp-peer-remote-as').value = p.remote_as || '';
  8810. if (document.getElementById('modal-bgp-peer-remote-allow-as')) document.getElementById('modal-bgp-peer-remote-allow-as').value = p.remote_allow_as || '';
  8811. document.getElementById('modal-bgp-peer-local-addr').value = p.local_address || '';
  8812. document.getElementById('modal-bgp-peer-local-port').value = p.local_port || '';
  8813. document.getElementById('modal-bgp-peer-local-role').value = p.local_role || 'ebgp';
  8814. document.getElementById('modal-bgp-peer-password').value = p.password || '';
  8815. document.getElementById('modal-bgp-peer-multihop').checked = !!p.multihop;
  8816. if (document.getElementById('modal-bgp-peer-tx-ttl')) document.getElementById('modal-bgp-peer-tx-ttl').value = p.tx_ttl || '';
  8817. if (document.getElementById('modal-bgp-peer-rx-min-ttl')) document.getElementById('modal-bgp-peer-rx-min-ttl').value = p.rx_min_ttl || '';
  8818. document.getElementById('modal-bgp-peer-connect').checked = p.connect !== false;
  8819. document.getElementById('modal-bgp-peer-listen').checked = p.listen !== false;
  8820. // Extra Tab
  8821. document.getElementById('modal-bgp-peer-holdtime').value = p.hold_time ? formatBgpTime(p.hold_time) : '00:00:30';
  8822. document.getElementById('modal-bgp-peer-keepalive').value = p.keepalive_time ? formatBgpTime(p.keepalive_time) : '00:00:10';
  8823. if (document.getElementById('modal-bgp-peer-use-bfd')) document.getElementById('modal-bgp-peer-use-bfd').checked = !!p.use_bfd;
  8824. document.getElementById('modal-bgp-peer-routing-table').value = p.routing_table || 'main';
  8825. if (document.getElementById('modal-bgp-peer-vrf')) document.getElementById('modal-bgp-peer-vrf').value = p.vrf || 'main';
  8826. if (document.getElementById('modal-bgp-peer-no-client-reflect')) document.getElementById('modal-bgp-peer-no-client-reflect').checked = p.no_client_reflect !== false;
  8827. document.getElementById('modal-bgp-peer-redist-conn').checked = !!p.redist_connected;
  8828. document.getElementById('modal-bgp-peer-redist-static').checked = p.redist_static !== false;
  8829. if (document.getElementById('modal-bgp-peer-redist-rip')) document.getElementById('modal-bgp-peer-redist-rip').checked = !!p.redist_rip;
  8830. document.getElementById('modal-bgp-peer-redist-ospf').checked = !!p.redist_ospf;
  8831. document.getElementById('modal-bgp-peer-redist-bgp').checked = !!p.redist_bgp;
  8832. if (document.getElementById('modal-bgp-peer-redist-vpn')) document.getElementById('modal-bgp-peer-redist-vpn').checked = !!p.redist_vpn;
  8833. if (document.getElementById('modal-bgp-peer-redist-dhcp')) document.getElementById('modal-bgp-peer-redist-dhcp').checked = !!p.redist_dhcp;
  8834. 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;
  8835. if (document.getElementById('modal-bgp-peer-redist-slaac')) document.getElementById('modal-bgp-peer-redist-slaac').checked = !!p.redist_slaac;
  8836. document.getElementById('modal-bgp-peer-default-orig').checked = !!p.default_originate;
  8837. if (document.getElementById('modal-bgp-peer-network-blackhole')) document.getElementById('modal-bgp-peer-network-blackhole').checked = !!p.network_blackhole;
  8838. if (document.getElementById('modal-bgp-peer-no-early-cut')) document.getElementById('modal-bgp-peer-no-early-cut').checked = !!p.no_early_cut;
  8839. if (document.getElementById('modal-bgp-peer-keep-sent-attrs')) document.getElementById('modal-bgp-peer-keep-sent-attrs').checked = !!p.keep_sent_attrs;
  8840. if (document.getElementById('modal-bgp-peer-input-affinity')) document.getElementById('modal-bgp-peer-input-affinity').value = p.input_affinity || '';
  8841. if (document.getElementById('modal-bgp-peer-output-affinity')) document.getElementById('modal-bgp-peer-output-affinity').value = p.output_affinity || '';
  8842. // Attributes Tab
  8843. document.getElementById('modal-bgp-peer-nexthop-choice').value = p.nexthop_choice || (p.nexthop_self ? 'force-self' : 'default');
  8844. document.getElementById('modal-bgp-peer-default-prepend').value = p.default_prepend || 0;
  8845. document.getElementById('modal-bgp-peer-allow-as-in').value = p.allow_as_in || 0;
  8846. 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;
  8847. document.getElementById('modal-bgp-peer-remove-priv-as').checked = !!p.remove_private_as;
  8848. document.getElementById('modal-bgp-peer-as-override').checked = !!p.as_override;
  8849. // Filter Tab
  8850. document.getElementById('modal-bgp-peer-in-filter').value = p.in_filter || '';
  8851. if (document.getElementById('modal-bgp-peer-in-accept-nlri')) document.getElementById('modal-bgp-peer-in-accept-nlri').value = p.in_accept_nlri || '';
  8852. if (document.getElementById('modal-bgp-peer-in-accept-comm')) document.getElementById('modal-bgp-peer-in-accept-comm').value = p.in_accept_communities || '';
  8853. 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 || '';
  8854. 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 || '';
  8855. if (document.getElementById('modal-bgp-peer-in-filter-comm')) document.getElementById('modal-bgp-peer-in-filter-comm').value = p.in_filter_communities || '';
  8856. 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 || '';
  8857. 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 || '';
  8858. if (document.getElementById('modal-bgp-peer-in-filter-unknown')) document.getElementById('modal-bgp-peer-in-filter-unknown').checked = !!p.in_filter_unknown;
  8859. document.getElementById('modal-bgp-peer-out-filter').value = p.out_filter || '';
  8860. if (document.getElementById('modal-bgp-peer-out-selection-policy')) document.getElementById('modal-bgp-peer-out-selection-policy').value = p.out_selection_policy || 'disabled';
  8861. if (document.getElementById('modal-bgp-peer-out-network-name')) document.getElementById('modal-bgp-peer-out-network-name').value = p.output_network || '';
  8862. // Output Networks
  8863. const container = document.getElementById('modal-bgp-output-networks-container');
  8864. if (container) {
  8865. container.innerHTML = '';
  8866. if (p.output_networks && p.output_networks.length > 0) {
  8867. p.output_networks.forEach(net => addOutputNetworkRow(net));
  8868. } else {
  8869. addOutputNetworkRow('');
  8870. }
  8871. }
  8872. const removeBtn = document.getElementById('modal-btn-remove-peer');
  8873. if (removeBtn) removeBtn.classList.remove('hidden');
  8874. switchBgpPeerModalTab('general');
  8875. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  8876. }
  8877. function copyCurrentBgpPeer() {
  8878. document.getElementById('modal-bgp-peer-id').value = '';
  8879. const nameEl = document.getElementById('modal-bgp-peer-name');
  8880. if (nameEl) nameEl.value = (nameEl.value || 'peer') + '-copy';
  8881. document.getElementById('bgp-peer-modal-title').innerText = 'New...';
  8882. const removeBtn = document.getElementById('modal-btn-remove-peer');
  8883. if (removeBtn) removeBtn.classList.add('hidden');
  8884. showToast('Cloned', 'BGP connection copied to new draft', 'info');
  8885. }
  8886. function removeCurrentBgpPeer() {
  8887. const id = document.getElementById('modal-bgp-peer-id')?.value;
  8888. if (!id) return;
  8889. deleteBgpPeer(id);
  8890. closeBgpPeerModal();
  8891. }
  8892. function closeBgpPeerModal() {
  8893. document.getElementById('bgp-peer-modal').classList.add('hidden');
  8894. }
  8895. function getBgpPeerFormData() {
  8896. const netInputs = document.querySelectorAll('#modal-bgp-output-networks-container .output-net-row input');
  8897. const outputNetworks = [];
  8898. netInputs.forEach(inp => {
  8899. const v = inp.value.trim();
  8900. if (v) outputNetworks.push(v);
  8901. });
  8902. const enabled = document.getElementById('modal-bgp-peer-enabled').checked;
  8903. return {
  8904. id: document.getElementById('modal-bgp-peer-id').value,
  8905. name: document.getElementById('modal-bgp-peer-name').value.trim(),
  8906. enabled: enabled,
  8907. disabled: !enabled,
  8908. comment: document.getElementById('modal-bgp-peer-comment').value.trim(),
  8909. instance: document.getElementById('modal-bgp-peer-instance')?.value.trim() || 'bgp-instance-1',
  8910. template: document.getElementById('modal-bgp-peer-template')?.value.trim() || '',
  8911. local_as: parseInt(document.getElementById('modal-bgp-peer-local-as')?.value, 10) || 0,
  8912. router_id: document.getElementById('modal-bgp-peer-router-id').value.trim(),
  8913. afi: document.getElementById('modal-bgp-peer-afi-ipv6').checked ? 'ipv6' : 'ip',
  8914. remote_address: document.getElementById('modal-bgp-peer-remote-addr').value.trim(),
  8915. remote_port: parseInt(document.getElementById('modal-bgp-peer-remote-port').value, 10) || 0,
  8916. remote_as: parseInt(document.getElementById('modal-bgp-peer-remote-as').value, 10) || 0,
  8917. remote_allow_as: document.getElementById('modal-bgp-peer-remote-allow-as')?.value.trim() || '',
  8918. local_address: document.getElementById('modal-bgp-peer-local-addr').value.trim(),
  8919. local_port: parseInt(document.getElementById('modal-bgp-peer-local-port').value, 10) || 0,
  8920. local_role: document.getElementById('modal-bgp-peer-local-role').value,
  8921. password: document.getElementById('modal-bgp-peer-password').value,
  8922. multihop: document.getElementById('modal-bgp-peer-multihop').checked,
  8923. tx_ttl: parseInt(document.getElementById('modal-bgp-peer-tx-ttl')?.value, 10) || 0,
  8924. rx_min_ttl: parseInt(document.getElementById('modal-bgp-peer-rx-min-ttl')?.value, 10) || 0,
  8925. connect: document.getElementById('modal-bgp-peer-connect').checked,
  8926. listen: document.getElementById('modal-bgp-peer-listen').checked,
  8927. hold_time: parseBgpTime(document.getElementById('modal-bgp-peer-holdtime').value),
  8928. keepalive_time: parseBgpTime(document.getElementById('modal-bgp-peer-keepalive').value),
  8929. use_bfd: document.getElementById('modal-bgp-peer-use-bfd')?.checked || false,
  8930. routing_table: document.getElementById('modal-bgp-peer-routing-table').value,
  8931. vrf: document.getElementById('modal-bgp-peer-vrf')?.value.trim() || 'main',
  8932. no_client_reflect: document.getElementById('modal-bgp-peer-no-client-reflect')?.checked || false,
  8933. redist_connected: document.getElementById('modal-bgp-peer-redist-conn').checked,
  8934. redist_static: document.getElementById('modal-bgp-peer-redist-static').checked,
  8935. redist_rip: document.getElementById('modal-bgp-peer-redist-rip')?.checked || false,
  8936. redist_ospf: document.getElementById('modal-bgp-peer-redist-ospf').checked,
  8937. redist_bgp: document.getElementById('modal-bgp-peer-redist-bgp').checked,
  8938. redist_vpn: document.getElementById('modal-bgp-peer-redist-vpn')?.checked || false,
  8939. redist_dhcp: document.getElementById('modal-bgp-peer-redist-dhcp')?.checked || false,
  8940. redist_bgp_mpls_vpn: document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn')?.checked || false,
  8941. redist_slaac: document.getElementById('modal-bgp-peer-redist-slaac')?.checked || false,
  8942. default_originate: document.getElementById('modal-bgp-peer-default-orig').checked,
  8943. network_blackhole: document.getElementById('modal-bgp-peer-network-blackhole')?.checked || false,
  8944. no_early_cut: document.getElementById('modal-bgp-peer-no-early-cut')?.checked || false,
  8945. keep_sent_attrs: document.getElementById('modal-bgp-peer-keep-sent-attrs')?.checked || false,
  8946. input_affinity: (document.getElementById('modal-bgp-peer-input-affinity')?.value || '').trim(),
  8947. output_affinity: (document.getElementById('modal-bgp-peer-output-affinity')?.value || '').trim(),
  8948. nexthop_choice: document.getElementById('modal-bgp-peer-nexthop-choice').value,
  8949. nexthop_self: document.getElementById('modal-bgp-peer-nexthop-choice').value === 'force-self',
  8950. default_prepend: parseInt(document.getElementById('modal-bgp-peer-default-prepend').value, 10) || 0,
  8951. allow_as_in: parseInt(document.getElementById('modal-bgp-peer-allow-as-in').value, 10) || 0,
  8952. ignore_as_path_len: document.getElementById('modal-bgp-peer-ignore-as-path-len')?.checked || false,
  8953. remove_private_as: document.getElementById('modal-bgp-peer-remove-priv-as').checked,
  8954. as_override: document.getElementById('modal-bgp-peer-as-override').checked,
  8955. in_filter: (document.getElementById('modal-bgp-peer-in-filter')?.value || '').trim(),
  8956. in_accept_nlri: (document.getElementById('modal-bgp-peer-in-accept-nlri')?.value || '').trim(),
  8957. in_accept_communities: (document.getElementById('modal-bgp-peer-in-accept-comm')?.value || '').trim(),
  8958. in_accept_ext_communities: (document.getElementById('modal-bgp-peer-in-accept-ext-comm')?.value || '').trim(),
  8959. in_accept_large_communities: (document.getElementById('modal-bgp-peer-in-accept-large-comm')?.value || '').trim(),
  8960. in_filter_communities: (document.getElementById('modal-bgp-peer-in-filter-comm')?.value || '').trim(),
  8961. in_filter_ext_communities: (document.getElementById('modal-bgp-peer-in-filter-ext-comm')?.value || '').trim(),
  8962. in_filter_large_communities: (document.getElementById('modal-bgp-peer-in-filter-large-comm')?.value || '').trim(),
  8963. in_filter_unknown: document.getElementById('modal-bgp-peer-in-filter-unknown')?.checked || false,
  8964. out_filter: (document.getElementById('modal-bgp-peer-out-filter')?.value || '').trim(),
  8965. out_selection_policy: document.getElementById('modal-bgp-peer-out-selection-policy')?.value || 'disabled',
  8966. output_network: (document.getElementById('modal-bgp-peer-out-network-name')?.value || '').trim(),
  8967. output_networks: outputNetworks
  8968. };
  8969. }
  8970. async function submitBgpPeer(e) {
  8971. if (e) e.preventDefault();
  8972. const payload = getBgpPeerFormData();
  8973. try {
  8974. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  8975. method: 'POST',
  8976. headers: { 'Content-Type': 'application/json' },
  8977. body: JSON.stringify(payload)
  8978. });
  8979. if (res.ok) {
  8980. closeBgpPeerModal();
  8981. showToast('Success', 'BGP Connection saved', 'success');
  8982. loadDynamicRouting();
  8983. } else {
  8984. const err = await res.json();
  8985. showToast('Error', err.error || 'Failed to save peer', 'error');
  8986. }
  8987. } catch (err) {
  8988. showToast('Error', err.message, 'error');
  8989. }
  8990. }
  8991. async function applyBgpPeerModal(e) {
  8992. if (e) e.preventDefault();
  8993. const payload = getBgpPeerFormData();
  8994. try {
  8995. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  8996. method: 'POST',
  8997. headers: { 'Content-Type': 'application/json' },
  8998. body: JSON.stringify(payload)
  8999. });
  9000. if (res.ok) {
  9001. const data = await res.json();
  9002. if (data.peer && data.peer.id) {
  9003. document.getElementById('modal-bgp-peer-id').value = data.peer.id;
  9004. document.getElementById('bgp-peer-modal-title').innerText = data.peer.name || data.peer.id;
  9005. document.getElementById('modal-btn-remove-peer')?.classList.remove('hidden');
  9006. }
  9007. showToast('Applied', 'BGP Connection applied', 'success');
  9008. loadDynamicRouting();
  9009. } else {
  9010. const err = await res.json();
  9011. showToast('Error', err.error || 'Failed to apply peer', 'error');
  9012. }
  9013. } catch (err) {
  9014. showToast('Error', err.message, 'error');
  9015. }
  9016. }
  9017. async function deleteBgpPeer(id) {
  9018. if (!confirm('Are you sure you want to delete this BGP peer connection?')) return;
  9019. try {
  9020. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9021. if (res.ok) {
  9022. showToast('Deleted', 'BGP peer removed', 'success');
  9023. loadDynamicRouting();
  9024. }
  9025. } catch (err) {
  9026. showToast('Error', err.message, 'error');
  9027. }
  9028. }
  9029. async function toggleBgpPeerState(id, disabled) {
  9030. try {
  9031. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}/state`, {
  9032. method: 'POST',
  9033. headers: { 'Content-Type': 'application/json' },
  9034. body: JSON.stringify({ disabled })
  9035. });
  9036. if (res.ok) {
  9037. showToast('Updated', `Peer ${disabled ? 'disabled' : 'enabled'}`, 'success');
  9038. loadDynamicRouting();
  9039. }
  9040. } catch (err) {
  9041. showToast('Error', err.message, 'error');
  9042. }
  9043. }
  9044. function openAddBgpNetworkModal() {
  9045. document.getElementById('bgp-network-form').reset();
  9046. document.getElementById('modal-bgp-net-id').value = '';
  9047. document.getElementById('bgp-network-modal').classList.remove('hidden');
  9048. }
  9049. function closeBgpNetworkModal() {
  9050. document.getElementById('bgp-network-modal').classList.add('hidden');
  9051. }
  9052. async function submitBgpNetwork(e) {
  9053. e.preventDefault();
  9054. const payload = {
  9055. id: document.getElementById('modal-bgp-net-id').value,
  9056. network: document.getElementById('modal-bgp-net-cidr').value.trim(),
  9057. comment: document.getElementById('modal-bgp-net-comment').value.trim(),
  9058. disabled: document.getElementById('modal-bgp-net-disabled').checked
  9059. };
  9060. try {
  9061. const res = await fetch(`${API_BASE}/routing/bgp/networks`, {
  9062. method: 'POST',
  9063. headers: { 'Content-Type': 'application/json' },
  9064. body: JSON.stringify(payload)
  9065. });
  9066. if (res.ok) {
  9067. closeBgpNetworkModal();
  9068. showToast('Success', 'BGP network advertisement saved', 'success');
  9069. loadDynamicRouting();
  9070. } else {
  9071. const err = await res.json();
  9072. showToast('Error', err.error || 'Failed to save network', 'error');
  9073. }
  9074. } catch (err) {
  9075. showToast('Error', err.message, 'error');
  9076. }
  9077. }
  9078. async function deleteBgpNetwork(id) {
  9079. if (!confirm('Are you sure you want to stop announcing this network?')) return;
  9080. try {
  9081. const res = await fetch(`${API_BASE}/routing/bgp/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9082. if (res.ok) {
  9083. showToast('Deleted', 'Network advertisement removed', 'success');
  9084. loadDynamicRouting();
  9085. }
  9086. } catch (err) {
  9087. showToast('Error', err.message, 'error');
  9088. }
  9089. }
  9090. // =========================================================================
  9091. // DEBTIK v7 OSPF MODALS & ACTIONS
  9092. // =========================================================================
  9093. // --- 1. OSPF INSTANCE ---
  9094. function openOspfInstanceModal(id = null) {
  9095. const isEdit = !!id;
  9096. const inst = (state.ospfInstances || []).find(i => i.id === id) || {
  9097. id: '',
  9098. name: 'Default',
  9099. version: 2,
  9100. vrf: 'main',
  9101. router_id: '192.168.131.56',
  9102. routing_table: 'main',
  9103. enabled: true,
  9104. redistribute_connected: false,
  9105. redistribute_static: true,
  9106. redistribute_bgp: false,
  9107. comment: ''
  9108. };
  9109. document.getElementById('ospf-instance-modal-title').innerText = isEdit ? inst.name : 'New...';
  9110. document.getElementById('modal-ospf-inst-id').value = isEdit ? inst.id : '';
  9111. document.getElementById('modal-ospf-inst-enabled').checked = !inst.disabled;
  9112. document.getElementById('modal-ospf-inst-comment').value = inst.comment || '';
  9113. document.getElementById('modal-ospf-inst-name').value = inst.name || 'Default';
  9114. document.getElementById('modal-ospf-inst-version').value = inst.version || 2;
  9115. document.getElementById('modal-ospf-inst-vrf').value = inst.vrf || 'main';
  9116. document.getElementById('modal-ospf-inst-router-id').value = inst.router_id || '';
  9117. document.getElementById('modal-ospf-inst-routing-table').value = inst.routing_table || 'main';
  9118. document.getElementById('modal-ospf-inst-redist-conn').checked = !!inst.redistribute_connected;
  9119. document.getElementById('modal-ospf-inst-redist-static').checked = inst.redistribute_static !== false;
  9120. document.getElementById('modal-ospf-inst-redist-bgp').checked = !!inst.redistribute_bgp;
  9121. const btnRem = document.getElementById('btn-ospf-inst-modal-remove');
  9122. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  9123. document.getElementById('ospf-instance-modal').classList.remove('hidden');
  9124. }
  9125. function openEditOspfInstanceModal(id) {
  9126. openOspfInstanceModal(id);
  9127. }
  9128. function closeOspfInstanceModal() {
  9129. document.getElementById('ospf-instance-modal').classList.add('hidden');
  9130. }
  9131. async function submitOspfInstance(e) {
  9132. if (e) e.preventDefault();
  9133. const payload = {
  9134. id: document.getElementById('modal-ospf-inst-id').value,
  9135. name: document.getElementById('modal-ospf-inst-name').value.trim() || 'Default',
  9136. version: parseInt(document.getElementById('modal-ospf-inst-version').value, 10) || 2,
  9137. vrf: document.getElementById('modal-ospf-inst-vrf').value.trim() || 'main',
  9138. router_id: document.getElementById('modal-ospf-inst-router-id').value.trim(),
  9139. routing_table: document.getElementById('modal-ospf-inst-routing-table').value.trim() || 'main',
  9140. enabled: document.getElementById('modal-ospf-inst-enabled').checked,
  9141. disabled: !document.getElementById('modal-ospf-inst-enabled').checked,
  9142. comment: document.getElementById('modal-ospf-inst-comment').value.trim(),
  9143. redistribute_connected: document.getElementById('modal-ospf-inst-redist-conn').checked,
  9144. redistribute_static: document.getElementById('modal-ospf-inst-redist-static').checked,
  9145. redistribute_bgp: document.getElementById('modal-ospf-inst-redist-bgp').checked
  9146. };
  9147. try {
  9148. const res = await fetch(`${API_BASE}/routing/ospf/instances`, {
  9149. method: 'POST',
  9150. headers: { 'Content-Type': 'application/json' },
  9151. body: JSON.stringify(payload)
  9152. });
  9153. if (res.ok) {
  9154. closeOspfInstanceModal();
  9155. showToast('Saved', 'OSPF instance updated', 'success');
  9156. loadDynamicRouting();
  9157. } else {
  9158. const err = await res.json();
  9159. showToast('Error', err.error || 'Failed to save OSPF instance', 'error');
  9160. }
  9161. } catch (err) {
  9162. showToast('Error', err.message, 'error');
  9163. }
  9164. }
  9165. function applyOspfInstanceForm() {
  9166. submitOspfInstance(null);
  9167. }
  9168. function copyOspfInstance() {
  9169. document.getElementById('modal-ospf-inst-id').value = '';
  9170. document.getElementById('modal-ospf-inst-name').value += '-copy';
  9171. document.getElementById('ospf-instance-modal-title').innerText = 'New...';
  9172. showToast('Copied', 'Duplicated as new OSPF instance', 'info');
  9173. }
  9174. async function deleteCurrentOspfInstance() {
  9175. const id = document.getElementById('modal-ospf-inst-id').value;
  9176. if (!id) return;
  9177. if (!confirm('Are you sure you want to remove this OSPF instance?')) return;
  9178. try {
  9179. const res = await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9180. if (res.ok) {
  9181. closeOspfInstanceModal();
  9182. showToast('Removed', 'OSPF instance deleted', 'success');
  9183. loadDynamicRouting();
  9184. }
  9185. } catch (err) {
  9186. showToast('Error', err.message, 'error');
  9187. }
  9188. }
  9189. async function enableSelectedOspfInstance() {
  9190. const id = state.selectedOspfRow?.instances;
  9191. if (!id) return;
  9192. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}/state`, {
  9193. method: 'POST',
  9194. headers: { 'Content-Type': 'application/json' },
  9195. body: JSON.stringify({ disabled: false })
  9196. });
  9197. loadDynamicRouting();
  9198. }
  9199. async function disableSelectedOspfInstance() {
  9200. const id = state.selectedOspfRow?.instances;
  9201. if (!id) return;
  9202. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}/state`, {
  9203. method: 'POST',
  9204. headers: { 'Content-Type': 'application/json' },
  9205. body: JSON.stringify({ disabled: true })
  9206. });
  9207. loadDynamicRouting();
  9208. }
  9209. async function removeSelectedOspfInstance() {
  9210. const id = state.selectedOspfRow?.instances;
  9211. if (!id) return;
  9212. if (!confirm('Delete selected OSPF instance?')) return;
  9213. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9214. loadDynamicRouting();
  9215. }
  9216. async function promptCommentOspfInstance() {
  9217. const id = state.selectedOspfRow?.instances;
  9218. if (!id) return;
  9219. const inst = (state.ospfInstances || []).find(i => i.id === id);
  9220. if (!inst) return;
  9221. const comment = prompt('Enter comment for OSPF instance:', inst.comment || '');
  9222. if (comment === null) return;
  9223. inst.comment = comment;
  9224. await fetch(`${API_BASE}/routing/ospf/instances`, {
  9225. method: 'POST',
  9226. headers: { 'Content-Type': 'application/json' },
  9227. body: JSON.stringify(inst)
  9228. });
  9229. loadDynamicRouting();
  9230. }
  9231. // --- 2. OSPF AREA ---
  9232. function populateOspfAreaDropdowns() {
  9233. const instSelect = document.getElementById('modal-ospf-area-instance');
  9234. if (instSelect) {
  9235. const cur = instSelect.value;
  9236. instSelect.innerHTML = (state.ospfInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)}</option>`).join('');
  9237. if (instSelect.innerHTML === '') instSelect.innerHTML = '<option value="Default">Default</option>';
  9238. if (cur) instSelect.value = cur;
  9239. }
  9240. }
  9241. function openOspfAreaModal(id = null) {
  9242. const isEdit = !!id;
  9243. populateOspfAreaDropdowns();
  9244. const area = (state.ospfAreas || []).find(a => a.id === id) || {
  9245. id: '',
  9246. name: 'Default',
  9247. instance: 'Default',
  9248. area_id: '0.0.0.0',
  9249. area_type: 'default',
  9250. default_cost: 1,
  9251. no_summaries: false,
  9252. disabled: false,
  9253. comment: ''
  9254. };
  9255. document.getElementById('ospf-area-modal-title').innerText = isEdit ? area.name : 'New...';
  9256. document.getElementById('modal-ospf-area-id').value = isEdit ? area.id : '';
  9257. document.getElementById('modal-ospf-area-enabled').checked = !area.disabled;
  9258. document.getElementById('modal-ospf-area-comment').value = area.comment || '';
  9259. document.getElementById('modal-ospf-area-name').value = area.name || 'Default';
  9260. document.getElementById('modal-ospf-area-instance').value = area.instance || 'Default';
  9261. document.getElementById('modal-ospf-area-areaid').value = area.area_id || '0.0.0.0';
  9262. document.getElementById('modal-ospf-area-type').value = area.area_type || 'default';
  9263. document.getElementById('modal-ospf-area-default-cost').value = area.default_cost || 1;
  9264. document.getElementById('modal-ospf-area-no-summaries').checked = !!area.no_summaries;
  9265. const btnRem = document.getElementById('btn-ospf-area-modal-remove');
  9266. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  9267. document.getElementById('ospf-area-modal').classList.remove('hidden');
  9268. }
  9269. function openEditOspfAreaModal(id) {
  9270. openOspfAreaModal(id);
  9271. }
  9272. function closeOspfAreaModal() {
  9273. document.getElementById('ospf-area-modal').classList.add('hidden');
  9274. }
  9275. async function submitOspfArea(e) {
  9276. if (e) e.preventDefault();
  9277. const payload = {
  9278. id: document.getElementById('modal-ospf-area-id').value,
  9279. name: document.getElementById('modal-ospf-area-name').value.trim() || 'Default',
  9280. instance: document.getElementById('modal-ospf-area-instance').value.trim() || 'Default',
  9281. area_id: document.getElementById('modal-ospf-area-areaid').value.trim() || '0.0.0.0',
  9282. area_type: document.getElementById('modal-ospf-area-type').value,
  9283. default_cost: parseInt(document.getElementById('modal-ospf-area-default-cost').value, 10) || 1,
  9284. no_summaries: document.getElementById('modal-ospf-area-no-summaries').checked,
  9285. disabled: !document.getElementById('modal-ospf-area-enabled').checked,
  9286. comment: document.getElementById('modal-ospf-area-comment').value.trim()
  9287. };
  9288. try {
  9289. const res = await fetch(`${API_BASE}/routing/ospf/areas`, {
  9290. method: 'POST',
  9291. headers: { 'Content-Type': 'application/json' },
  9292. body: JSON.stringify(payload)
  9293. });
  9294. if (res.ok) {
  9295. closeOspfAreaModal();
  9296. showToast('Saved', 'OSPF area saved', 'success');
  9297. loadDynamicRouting();
  9298. } else {
  9299. const err = await res.json();
  9300. showToast('Error', err.error || 'Failed to save area', 'error');
  9301. }
  9302. } catch (err) {
  9303. showToast('Error', err.message, 'error');
  9304. }
  9305. }
  9306. function applyOspfAreaForm() {
  9307. submitOspfArea(null);
  9308. }
  9309. function copyOspfArea() {
  9310. document.getElementById('modal-ospf-area-id').value = '';
  9311. document.getElementById('modal-ospf-area-name').value += '-copy';
  9312. document.getElementById('ospf-area-modal-title').innerText = 'New...';
  9313. showToast('Copied', 'Duplicated as new OSPF area', 'info');
  9314. }
  9315. async function deleteCurrentOspfArea() {
  9316. const id = document.getElementById('modal-ospf-area-id').value;
  9317. if (!id) return;
  9318. if (!confirm('Are you sure you want to remove this OSPF area?')) return;
  9319. try {
  9320. const res = await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9321. if (res.ok) {
  9322. closeOspfAreaModal();
  9323. showToast('Removed', 'OSPF area deleted', 'success');
  9324. loadDynamicRouting();
  9325. }
  9326. } catch (err) {
  9327. showToast('Error', err.message, 'error');
  9328. }
  9329. }
  9330. async function enableSelectedOspfArea() {
  9331. const id = state.selectedOspfRow?.areas;
  9332. if (!id) return;
  9333. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}/state`, {
  9334. method: 'POST',
  9335. headers: { 'Content-Type': 'application/json' },
  9336. body: JSON.stringify({ disabled: false })
  9337. });
  9338. loadDynamicRouting();
  9339. }
  9340. async function disableSelectedOspfArea() {
  9341. const id = state.selectedOspfRow?.areas;
  9342. if (!id) return;
  9343. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}/state`, {
  9344. method: 'POST',
  9345. headers: { 'Content-Type': 'application/json' },
  9346. body: JSON.stringify({ disabled: true })
  9347. });
  9348. loadDynamicRouting();
  9349. }
  9350. async function removeSelectedOspfArea() {
  9351. const id = state.selectedOspfRow?.areas;
  9352. if (!id) return;
  9353. if (!confirm('Delete selected OSPF area?')) return;
  9354. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9355. loadDynamicRouting();
  9356. }
  9357. async function promptCommentOspfArea() {
  9358. const id = state.selectedOspfRow?.areas;
  9359. if (!id) return;
  9360. const area = (state.ospfAreas || []).find(a => a.id === id);
  9361. if (!area) return;
  9362. const comment = prompt('Enter comment for OSPF area:', area.comment || '');
  9363. if (comment === null) return;
  9364. area.comment = comment;
  9365. await fetch(`${API_BASE}/routing/ospf/areas`, {
  9366. method: 'POST',
  9367. headers: { 'Content-Type': 'application/json' },
  9368. body: JSON.stringify(area)
  9369. });
  9370. loadDynamicRouting();
  9371. }
  9372. // --- 3. OSPF AREA RANGE ---
  9373. function populateAreaRangeDropdowns() {
  9374. const select = document.getElementById('modal-ospf-range-area');
  9375. if (select) {
  9376. const cur = select.value;
  9377. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  9378. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  9379. if (cur) select.value = cur;
  9380. }
  9381. }
  9382. function openOspfAreaRangeModal(id = null) {
  9383. const isEdit = !!id;
  9384. populateAreaRangeDropdowns();
  9385. const r = (state.ospfAreaRanges || []).find(it => it.id === id) || {
  9386. id: '',
  9387. area: 'Default',
  9388. prefix: '',
  9389. cost: 1,
  9390. advertise: true,
  9391. disabled: false,
  9392. comment: ''
  9393. };
  9394. document.getElementById('ospf-area-range-modal-title').innerText = isEdit ? r.prefix : 'New...';
  9395. document.getElementById('modal-ospf-range-id').value = isEdit ? r.id : '';
  9396. document.getElementById('modal-ospf-range-enabled').checked = !r.disabled;
  9397. document.getElementById('modal-ospf-range-comment').value = r.comment || '';
  9398. document.getElementById('modal-ospf-range-area').value = r.area || 'Default';
  9399. document.getElementById('modal-ospf-range-prefix').value = r.prefix || '';
  9400. document.getElementById('modal-ospf-range-cost').value = r.cost || 1;
  9401. document.getElementById('modal-ospf-range-advertise').checked = r.advertise !== false;
  9402. const btnRem = document.getElementById('btn-ospf-range-modal-remove');
  9403. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  9404. document.getElementById('ospf-area-range-modal').classList.remove('hidden');
  9405. }
  9406. function openEditOspfAreaRangeModal(id) {
  9407. openOspfAreaRangeModal(id);
  9408. }
  9409. function closeOspfAreaRangeModal() {
  9410. document.getElementById('ospf-area-range-modal').classList.add('hidden');
  9411. }
  9412. async function submitOspfAreaRange(e) {
  9413. if (e) e.preventDefault();
  9414. const payload = {
  9415. id: document.getElementById('modal-ospf-range-id').value,
  9416. area: document.getElementById('modal-ospf-range-area').value,
  9417. prefix: document.getElementById('modal-ospf-range-prefix').value.trim(),
  9418. cost: parseInt(document.getElementById('modal-ospf-range-cost').value, 10) || 1,
  9419. advertise: document.getElementById('modal-ospf-range-advertise').checked,
  9420. disabled: !document.getElementById('modal-ospf-range-enabled').checked,
  9421. comment: document.getElementById('modal-ospf-range-comment').value.trim()
  9422. };
  9423. try {
  9424. const res = await fetch(`${API_BASE}/routing/ospf/area-ranges`, {
  9425. method: 'POST',
  9426. headers: { 'Content-Type': 'application/json' },
  9427. body: JSON.stringify(payload)
  9428. });
  9429. if (res.ok) {
  9430. closeOspfAreaRangeModal();
  9431. showToast('Saved', 'Area range saved', 'success');
  9432. loadDynamicRouting();
  9433. } else {
  9434. const err = await res.json();
  9435. showToast('Error', err.error || 'Failed to save area range', 'error');
  9436. }
  9437. } catch (err) {
  9438. showToast('Error', err.message, 'error');
  9439. }
  9440. }
  9441. function applyOspfAreaRangeForm() {
  9442. submitOspfAreaRange(null);
  9443. }
  9444. async function deleteCurrentOspfAreaRange() {
  9445. const id = document.getElementById('modal-ospf-range-id').value;
  9446. if (!id) return;
  9447. if (!confirm('Delete this area range?')) return;
  9448. try {
  9449. await fetch(`${API_BASE}/routing/ospf/area-ranges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9450. closeOspfAreaRangeModal();
  9451. showToast('Removed', 'Area range removed', 'success');
  9452. loadDynamicRouting();
  9453. } catch (err) {
  9454. showToast('Error', err.message, 'error');
  9455. }
  9456. }
  9457. async function enableSelectedOspfAreaRange() {
  9458. const id = state.selectedOspfRow?.['area-ranges'];
  9459. if (!id) return;
  9460. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  9461. if (!r) return;
  9462. r.disabled = false;
  9463. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  9464. loadDynamicRouting();
  9465. }
  9466. async function disableSelectedOspfAreaRange() {
  9467. const id = state.selectedOspfRow?.['area-ranges'];
  9468. if (!id) return;
  9469. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  9470. if (!r) return;
  9471. r.disabled = true;
  9472. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  9473. loadDynamicRouting();
  9474. }
  9475. async function removeSelectedOspfAreaRange() {
  9476. const id = state.selectedOspfRow?.['area-ranges'];
  9477. if (!id) return;
  9478. if (!confirm('Delete selected area range?')) return;
  9479. await fetch(`${API_BASE}/routing/ospf/area-ranges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9480. loadDynamicRouting();
  9481. }
  9482. async function promptCommentOspfAreaRange() {
  9483. const id = state.selectedOspfRow?.['area-ranges'];
  9484. if (!id) return;
  9485. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  9486. if (!r) return;
  9487. const comment = prompt('Enter comment for area range:', r.comment || '');
  9488. if (comment === null) return;
  9489. r.comment = comment;
  9490. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  9491. loadDynamicRouting();
  9492. }
  9493. // --- 4. OSPF INTERFACE TEMPLATE ---
  9494. function switchOspfTemplateTab(tab) {
  9495. const tabGen = document.getElementById('ospf-tmpl-tab-general');
  9496. const tabAuth = document.getElementById('ospf-tmpl-tab-auth');
  9497. const btnGen = document.getElementById('ospf-tmpl-tab-btn-general');
  9498. const btnAuth = document.getElementById('ospf-tmpl-tab-btn-auth');
  9499. if (tab === 'general') {
  9500. if (tabGen) tabGen.classList.remove('hidden');
  9501. if (tabAuth) tabAuth.classList.add('hidden');
  9502. if (btnGen) btnGen.className = 'px-4 py-2 text-xs font-bold border-b-2 border-sky-500 text-white transition';
  9503. 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';
  9504. } else {
  9505. if (tabGen) tabGen.classList.add('hidden');
  9506. if (tabAuth) tabAuth.classList.remove('hidden');
  9507. 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';
  9508. if (btnAuth) btnAuth.className = 'px-4 py-2 text-xs font-bold border-b-2 border-sky-500 text-white transition';
  9509. }
  9510. }
  9511. function populateTemplateAreaDropdowns() {
  9512. const select = document.getElementById('modal-ospf-tmpl-area');
  9513. if (select) {
  9514. const cur = select.value;
  9515. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  9516. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  9517. if (cur) select.value = cur;
  9518. }
  9519. }
  9520. function openOspfTemplateModal(id = null) {
  9521. const isEdit = !!id;
  9522. populateTemplateAreaDropdowns();
  9523. switchOspfTemplateTab('general');
  9524. const tmpl = (state.ospfTemplates || []).find(t => t.id === id) || {
  9525. id: '',
  9526. interfaces: '',
  9527. area: 'Default',
  9528. networks: '',
  9529. network_type: 'broadcast',
  9530. cost: 1,
  9531. priority: 128,
  9532. passive: false,
  9533. hello_interval: 10,
  9534. dead_interval: 40,
  9535. auth: 'none',
  9536. auth_key: '',
  9537. disabled: false,
  9538. comment: ''
  9539. };
  9540. document.getElementById('ospf-template-modal-title').innerText = isEdit ? (tmpl.interfaces || tmpl.networks || 'Template') : 'New...';
  9541. document.getElementById('modal-ospf-tmpl-id').value = isEdit ? tmpl.id : '';
  9542. document.getElementById('modal-ospf-tmpl-enabled').checked = !tmpl.disabled;
  9543. document.getElementById('modal-ospf-tmpl-comment').value = tmpl.comment || '';
  9544. document.getElementById('modal-ospf-tmpl-interfaces').value = tmpl.interfaces || tmpl.interface || '';
  9545. document.getElementById('modal-ospf-tmpl-area').value = tmpl.area || 'Default';
  9546. document.getElementById('modal-ospf-tmpl-networks').value = tmpl.networks || tmpl.network || '';
  9547. document.getElementById('modal-ospf-tmpl-net-type').value = tmpl.network_type || 'broadcast';
  9548. document.getElementById('modal-ospf-tmpl-cost').value = tmpl.cost || 1;
  9549. document.getElementById('modal-ospf-tmpl-priority').value = tmpl.priority || 128;
  9550. document.getElementById('modal-ospf-tmpl-passive').checked = !!tmpl.passive;
  9551. document.getElementById('modal-ospf-tmpl-hello').value = tmpl.hello_interval || 10;
  9552. document.getElementById('modal-ospf-tmpl-dead').value = tmpl.dead_interval || 40;
  9553. document.getElementById('modal-ospf-tmpl-auth').value = tmpl.auth || tmpl.auth_type || 'none';
  9554. document.getElementById('modal-ospf-tmpl-auth-key').value = tmpl.auth_key || '';
  9555. const btnRem = document.getElementById('btn-ospf-tmpl-modal-remove');
  9556. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  9557. document.getElementById('ospf-template-modal').classList.remove('hidden');
  9558. }
  9559. function openEditOspfTemplateModal(id) {
  9560. openOspfTemplateModal(id);
  9561. }
  9562. function closeOspfTemplateModal() {
  9563. document.getElementById('ospf-template-modal').classList.add('hidden');
  9564. }
  9565. async function submitOspfTemplate(e) {
  9566. if (e) e.preventDefault();
  9567. const payload = {
  9568. id: document.getElementById('modal-ospf-tmpl-id').value,
  9569. interfaces: document.getElementById('modal-ospf-tmpl-interfaces').value.trim(),
  9570. interface: document.getElementById('modal-ospf-tmpl-interfaces').value.trim(),
  9571. area: document.getElementById('modal-ospf-tmpl-area').value,
  9572. networks: document.getElementById('modal-ospf-tmpl-networks').value.trim(),
  9573. network: document.getElementById('modal-ospf-tmpl-networks').value.trim(),
  9574. network_type: document.getElementById('modal-ospf-tmpl-net-type').value,
  9575. cost: parseInt(document.getElementById('modal-ospf-tmpl-cost').value, 10) || 1,
  9576. priority: parseInt(document.getElementById('modal-ospf-tmpl-priority').value, 10) || 128,
  9577. passive: document.getElementById('modal-ospf-tmpl-passive').checked,
  9578. hello_interval: parseInt(document.getElementById('modal-ospf-tmpl-hello').value, 10) || 10,
  9579. dead_interval: parseInt(document.getElementById('modal-ospf-tmpl-dead').value, 10) || 40,
  9580. auth: document.getElementById('modal-ospf-tmpl-auth').value,
  9581. auth_type: document.getElementById('modal-ospf-tmpl-auth').value,
  9582. auth_key: document.getElementById('modal-ospf-tmpl-auth-key').value,
  9583. disabled: !document.getElementById('modal-ospf-tmpl-enabled').checked,
  9584. comment: document.getElementById('modal-ospf-tmpl-comment').value.trim()
  9585. };
  9586. try {
  9587. const res = await fetch(`${API_BASE}/routing/ospf/templates`, {
  9588. method: 'POST',
  9589. headers: { 'Content-Type': 'application/json' },
  9590. body: JSON.stringify(payload)
  9591. });
  9592. if (res.ok) {
  9593. closeOspfTemplateModal();
  9594. showToast('Saved', 'Interface template saved', 'success');
  9595. loadDynamicRouting();
  9596. } else {
  9597. const err = await res.json();
  9598. showToast('Error', err.error || 'Failed to save interface template', 'error');
  9599. }
  9600. } catch (err) {
  9601. showToast('Error', err.message, 'error');
  9602. }
  9603. }
  9604. function applyOspfTemplateForm() {
  9605. submitOspfTemplate(null);
  9606. }
  9607. function copyOspfTemplate() {
  9608. document.getElementById('modal-ospf-tmpl-id').value = '';
  9609. document.getElementById('ospf-template-modal-title').innerText = 'New...';
  9610. showToast('Copied', 'Duplicated as new template', 'info');
  9611. }
  9612. async function deleteCurrentOspfTemplate() {
  9613. const id = document.getElementById('modal-ospf-tmpl-id').value;
  9614. if (!id) return;
  9615. if (!confirm('Delete this interface template?')) return;
  9616. try {
  9617. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9618. closeOspfTemplateModal();
  9619. showToast('Removed', 'Interface template deleted', 'success');
  9620. loadDynamicRouting();
  9621. } catch (err) {
  9622. showToast('Error', err.message, 'error');
  9623. }
  9624. }
  9625. async function enableSelectedOspfTemplate() {
  9626. const id = state.selectedOspfRow?.templates;
  9627. if (!id) return;
  9628. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  9629. method: 'POST',
  9630. headers: { 'Content-Type': 'application/json' },
  9631. body: JSON.stringify({ disabled: false })
  9632. });
  9633. loadDynamicRouting();
  9634. }
  9635. async function disableSelectedOspfTemplate() {
  9636. const id = state.selectedOspfRow?.templates;
  9637. if (!id) return;
  9638. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  9639. method: 'POST',
  9640. headers: { 'Content-Type': 'application/json' },
  9641. body: JSON.stringify({ disabled: true })
  9642. });
  9643. loadDynamicRouting();
  9644. }
  9645. async function removeSelectedOspfTemplate() {
  9646. const id = state.selectedOspfRow?.templates;
  9647. if (!id) return;
  9648. if (!confirm('Delete selected interface template?')) return;
  9649. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9650. loadDynamicRouting();
  9651. }
  9652. async function promptCommentOspfTemplate() {
  9653. const id = state.selectedOspfRow?.templates;
  9654. if (!id) return;
  9655. const tmpl = (state.ospfTemplates || []).find(t => t.id === id);
  9656. if (!tmpl) return;
  9657. const comment = prompt('Enter comment for template:', tmpl.comment || '');
  9658. if (comment === null) return;
  9659. tmpl.comment = comment;
  9660. await fetch(`${API_BASE}/routing/ospf/templates`, {
  9661. method: 'POST',
  9662. headers: { 'Content-Type': 'application/json' },
  9663. body: JSON.stringify(tmpl)
  9664. });
  9665. loadDynamicRouting();
  9666. }
  9667. // --- 5. OSPF STATIC NEIGHBOR ---
  9668. function populateStaticNbrAreaDropdowns() {
  9669. const select = document.getElementById('modal-ospf-snbr-area');
  9670. if (select) {
  9671. const cur = select.value;
  9672. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  9673. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  9674. if (cur) select.value = cur;
  9675. }
  9676. }
  9677. function openOspfStaticNbrModal(id = null) {
  9678. const isEdit = !!id;
  9679. populateStaticNbrAreaDropdowns();
  9680. const nbr = (state.ospfStaticNbrs || []).find(n => n.id === id) || {
  9681. id: '',
  9682. address: '',
  9683. area: 'Default',
  9684. poll_interval: 120,
  9685. cost: 1,
  9686. disabled: false,
  9687. comment: ''
  9688. };
  9689. document.getElementById('ospf-static-nbr-modal-title').innerText = isEdit ? nbr.address : 'New...';
  9690. document.getElementById('modal-ospf-snbr-id').value = isEdit ? nbr.id : '';
  9691. document.getElementById('modal-ospf-snbr-enabled').checked = !nbr.disabled;
  9692. document.getElementById('modal-ospf-snbr-comment').value = nbr.comment || '';
  9693. document.getElementById('modal-ospf-snbr-address').value = nbr.address || '';
  9694. document.getElementById('modal-ospf-snbr-area').value = nbr.area || 'Default';
  9695. document.getElementById('modal-ospf-snbr-poll').value = nbr.poll_interval || 120;
  9696. document.getElementById('modal-ospf-snbr-cost').value = nbr.cost || 1;
  9697. const btnRem = document.getElementById('btn-ospf-snbr-modal-remove');
  9698. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  9699. document.getElementById('ospf-static-nbr-modal').classList.remove('hidden');
  9700. }
  9701. function openEditOspfStaticNbrModal(id) {
  9702. openOspfStaticNbrModal(id);
  9703. }
  9704. function closeOspfStaticNbrModal() {
  9705. document.getElementById('ospf-static-nbr-modal').classList.add('hidden');
  9706. }
  9707. async function submitOspfStaticNbr(e) {
  9708. if (e) e.preventDefault();
  9709. const payload = {
  9710. id: document.getElementById('modal-ospf-snbr-id').value,
  9711. address: document.getElementById('modal-ospf-snbr-address').value.trim(),
  9712. area: document.getElementById('modal-ospf-snbr-area').value,
  9713. poll_interval: parseInt(document.getElementById('modal-ospf-snbr-poll').value, 10) || 120,
  9714. cost: parseInt(document.getElementById('modal-ospf-snbr-cost').value, 10) || 1,
  9715. disabled: !document.getElementById('modal-ospf-snbr-enabled').checked,
  9716. comment: document.getElementById('modal-ospf-snbr-comment').value.trim()
  9717. };
  9718. try {
  9719. const res = await fetch(`${API_BASE}/routing/ospf/static-neighbors`, {
  9720. method: 'POST',
  9721. headers: { 'Content-Type': 'application/json' },
  9722. body: JSON.stringify(payload)
  9723. });
  9724. if (res.ok) {
  9725. closeOspfStaticNbrModal();
  9726. showToast('Saved', 'Static neighbor saved', 'success');
  9727. loadDynamicRouting();
  9728. } else {
  9729. const err = await res.json();
  9730. showToast('Error', err.error || 'Failed to save static neighbor', 'error');
  9731. }
  9732. } catch (err) {
  9733. showToast('Error', err.message, 'error');
  9734. }
  9735. }
  9736. function applyOspfStaticNbrForm() {
  9737. submitOspfStaticNbr(null);
  9738. }
  9739. async function deleteCurrentOspfStaticNbr() {
  9740. const id = document.getElementById('modal-ospf-snbr-id').value;
  9741. if (!id) return;
  9742. if (!confirm('Delete this static neighbor?')) return;
  9743. try {
  9744. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9745. closeOspfStaticNbrModal();
  9746. showToast('Removed', 'Static neighbor removed', 'success');
  9747. loadDynamicRouting();
  9748. } catch (err) {
  9749. showToast('Error', err.message, 'error');
  9750. }
  9751. }
  9752. async function enableSelectedOspfStaticNbr() {
  9753. const id = state.selectedOspfRow?.['static-nbrs'];
  9754. if (!id) return;
  9755. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  9756. if (!n) return;
  9757. n.disabled = false;
  9758. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  9759. loadDynamicRouting();
  9760. }
  9761. async function disableSelectedOspfStaticNbr() {
  9762. const id = state.selectedOspfRow?.['static-nbrs'];
  9763. if (!id) return;
  9764. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  9765. if (!n) return;
  9766. n.disabled = true;
  9767. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  9768. loadDynamicRouting();
  9769. }
  9770. async function removeSelectedOspfStaticNbr() {
  9771. const id = state.selectedOspfRow?.['static-nbrs'];
  9772. if (!id) return;
  9773. if (!confirm('Delete selected static neighbor?')) return;
  9774. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9775. loadDynamicRouting();
  9776. }
  9777. async function promptCommentOspfStaticNbr() {
  9778. const id = state.selectedOspfRow?.['static-nbrs'];
  9779. if (!id) return;
  9780. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  9781. if (!n) return;
  9782. const comment = prompt('Enter comment for static neighbor:', n.comment || '');
  9783. if (comment === null) return;
  9784. n.comment = comment;
  9785. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  9786. loadDynamicRouting();
  9787. }
  9788. // Backward-compat aliases
  9789. function openAddOspfInterfaceModal() { openOspfTemplateModal(); }
  9790. function openEditOspfInterfaceModal(id) { openEditOspfTemplateModal(id); }
  9791. function closeOspfInterfaceModal() { closeOspfTemplateModal(); }
  9792. function submitOspfInterface(e) { submitOspfTemplate(e); }
  9793. function deleteOspfInterface(id) {
  9794. fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' }).then(() => loadDynamicRouting());
  9795. }
  9796. function toggleOspfInterfaceState(id, disabled) {
  9797. fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  9798. method: 'POST',
  9799. headers: { 'Content-Type': 'application/json' },
  9800. body: JSON.stringify({ disabled })
  9801. }).then(() => loadDynamicRouting());
  9802. }
  9803. function openAddOspfAreaModal() { openOspfAreaModal(); }
  9804. function deleteOspfArea(id) {
  9805. fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' }).then(() => loadDynamicRouting());
  9806. }
  9807. // ============================================================================
  9808. // ==================== MIKROTIK BRIDGE SUBSYSTEM ==============================
  9809. // ============================================================================
  9810. function switchBridgeSubTab(tab) {
  9811. state.bridgeSubTab = tab;
  9812. const tabs = ['bridges', 'ports', 'vlans', 'hosts'];
  9813. tabs.forEach(t => {
  9814. const panel = document.getElementById(`bridge-subtab-${t}`);
  9815. const btn = document.getElementById(`bridge-subtab-btn-${t}`);
  9816. if (panel) {
  9817. if (t === tab) panel.classList.remove('hidden');
  9818. else panel.classList.add('hidden');
  9819. }
  9820. if (btn) {
  9821. if (t === tab) {
  9822. 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';
  9823. } else {
  9824. 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';
  9825. }
  9826. }
  9827. });
  9828. const addBtn = document.getElementById('bridge-top-action-btn');
  9829. if (addBtn) {
  9830. if (tab === 'bridges') addBtn.innerHTML = '<span>+ Add Bridge</span>';
  9831. else if (tab === 'ports') addBtn.innerHTML = '<span>+ Add Port</span>';
  9832. else if (tab === 'vlans') addBtn.innerHTML = '<span>+ Add VLAN Entry</span>';
  9833. else if (tab === 'hosts') addBtn.innerHTML = '<span>🔄 Refresh MACs</span>';
  9834. }
  9835. if (tab === 'hosts') loadBridgeHosts();
  9836. setTimeout(initTableSorting, 50);
  9837. }
  9838. function openCurrentBridgeModal() {
  9839. if (state.bridgeSubTab === 'bridges') openAddBridgeModal();
  9840. else if (state.bridgeSubTab === 'ports') openAddBridgePortModal();
  9841. else if (state.bridgeSubTab === 'vlans') openAddBridgeVLANModal();
  9842. else if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  9843. }
  9844. async function loadBridge() {
  9845. try {
  9846. const [bridgesRes, portsRes, vlansRes, summaryRes, eoipRes, vlanIfacesRes] = await Promise.all([
  9847. fetch(`${API_BASE}/bridge/bridges`),
  9848. fetch(`${API_BASE}/bridge/ports`),
  9849. fetch(`${API_BASE}/bridge/vlans`),
  9850. fetch(`${API_BASE}/bridge/summary`),
  9851. fetch(`${API_BASE}/vpn/eoip`),
  9852. fetch(`${API_BASE}/vlans`)
  9853. ]);
  9854. if (bridgesRes.ok) state.bridges = await bridgesRes.json();
  9855. if (portsRes.ok) state.bridgePorts = await portsRes.json();
  9856. if (vlansRes.ok) state.bridgeVLANs = await vlansRes.json();
  9857. if (summaryRes.ok) state.bridgeSummary = await summaryRes.json();
  9858. if (eoipRes && eoipRes.ok) state.eoipTunnels = await eoipRes.json();
  9859. if (vlanIfacesRes && vlanIfacesRes.ok) state.vlans = await vlanIfacesRes.json();
  9860. // Badges & Stats
  9861. const bBridges = document.getElementById('bridge-badge-bridges');
  9862. if (bBridges) bBridges.innerText = (state.bridges || []).length;
  9863. const bPorts = document.getElementById('bridge-badge-ports');
  9864. if (bPorts) bPorts.innerText = (state.bridgePorts || []).length;
  9865. const bVlans = document.getElementById('bridge-badge-vlans');
  9866. if (bVlans) bVlans.innerText = (state.bridgeVLANs || []).length;
  9867. const bHosts = document.getElementById('bridge-badge-hosts');
  9868. if (bHosts) bHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  9869. const sBr = document.getElementById('bridge-stat-bridges');
  9870. if (sBr) sBr.innerText = (state.bridges || []).length;
  9871. const sPorts = document.getElementById('bridge-stat-ports');
  9872. if (sPorts) sPorts.innerText = (state.bridgePorts || []).length;
  9873. const sHosts = document.getElementById('bridge-stat-hosts');
  9874. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  9875. renderBridges();
  9876. renderBridgePorts();
  9877. renderBridgeVLANs();
  9878. if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  9879. } catch (err) {
  9880. console.error('Failed to load bridge subsystem:', err);
  9881. }
  9882. }
  9883. // ----------------- Bridges -----------------
  9884. function renderBridges() {
  9885. const tbody = document.getElementById('bridge-table-body');
  9886. const empty = document.getElementById('bridge-empty-bridges');
  9887. const countBadge = document.getElementById('bridge-count-badge');
  9888. if (!tbody) return;
  9889. tbody.innerHTML = '';
  9890. const bridges = state.bridges || [];
  9891. if (countBadge) countBadge.innerText = `${bridges.length} Bridges`;
  9892. if (bridges.length === 0) {
  9893. empty?.classList.remove('hidden');
  9894. return;
  9895. }
  9896. empty?.classList.add('hidden');
  9897. bridges.forEach((b, idx) => {
  9898. const tr = document.createElement('tr');
  9899. tr.className = `hover:bg-slate-800/40 transition text-xs ${b.disabled ? 'opacity-50' : ''}`;
  9900. // Format IP addresses pill list
  9901. let ipsHtml = '<span class="text-slate-600 font-sans">None</span>';
  9902. if (b.ip_addresses && b.ip_addresses.length > 0) {
  9903. ipsHtml = b.ip_addresses.map(ip => `
  9904. <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">
  9905. <span>${ip}</span>
  9906. <button onclick="deleteBridgeIP('${b.id}', '${ip}')" class="text-slate-500 hover:text-rose-400 font-bold ml-0.5">×</button>
  9907. </span>
  9908. `).join(' ');
  9909. }
  9910. const runningFlag = b.running ? '<span class="text-emerald-400 font-bold" title="Running (R)">R</span>' : '<span class="text-slate-600">-</span>';
  9911. const disabledFlag = b.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '';
  9912. const flagDisplay = `${runningFlag}${disabledFlag ? ' ' + disabledFlag : ''}`;
  9913. tr.innerHTML = `
  9914. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  9915. <td class="py-2.5 px-3 text-center font-mono">${flagDisplay}</td>
  9916. <td class="py-2.5 px-3 font-bold text-white text-sm">
  9917. <span class="text-sky-400 mr-1.5">🌉</span>${b.name}
  9918. </td>
  9919. <td class="py-2.5 px-3 text-slate-300">${b.mtu}</td>
  9920. <td class="py-2.5 px-3 font-mono text-slate-300 text-[11px]">${b.mac_address || '-'}</td>
  9921. <td class="py-2.5 px-3">
  9922. <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>
  9923. </td>
  9924. <td class="py-2.5 px-3 text-center">
  9925. ${b.vlan_filtering ? '<span class="text-emerald-400 font-bold">yes</span>' : '<span class="text-slate-500">no</span>'}
  9926. </td>
  9927. <td class="py-2.5 px-3 font-mono">${b.pvid || 1}</td>
  9928. <td class="py-2.5 px-3">
  9929. <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>
  9930. </td>
  9931. <td class="py-2.5 px-3">
  9932. <div class="flex items-center gap-1.5 flex-wrap">
  9933. ${ipsHtml}
  9934. <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>
  9935. </div>
  9936. </td>
  9937. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  9938. <span class="text-emerald-400">↓ ${b.rx_human || '0 B'}</span> / <span class="text-cyan-400">↑ ${b.tx_human || '0 B'}</span>
  9939. </td>
  9940. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${b.comment || ''}">${b.comment || '-'}</td>
  9941. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  9942. <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>
  9943. <button onclick="openEditBridgeModal('${b.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  9944. <button onclick="deleteBridge('${b.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  9945. </td>
  9946. `;
  9947. tbody.appendChild(tr);
  9948. });
  9949. }
  9950. function openAddBridgeModal() {
  9951. document.getElementById('bridge-modal-title').innerText = 'Add Bridge Interface';
  9952. document.getElementById('bridge-modal-id').value = '';
  9953. document.getElementById('bridge-modal-name').value = 'bridge1';
  9954. document.getElementById('bridge-modal-name').disabled = false;
  9955. document.getElementById('bridge-modal-mtu').value = '1500';
  9956. document.getElementById('bridge-modal-mac').value = '';
  9957. document.getElementById('bridge-modal-stp').value = 'stp';
  9958. document.getElementById('bridge-modal-priority').value = '32768';
  9959. document.getElementById('bridge-modal-vlanfiltering').checked = false;
  9960. document.getElementById('bridge-modal-pvid').value = '1';
  9961. document.getElementById('bridge-modal-fastforward').checked = true;
  9962. document.getElementById('bridge-modal-comment').value = '';
  9963. document.getElementById('bridge-modal-disabled').checked = false;
  9964. toggleBridgeModalVlanFiltering();
  9965. document.getElementById('bridge-modal').classList.remove('hidden');
  9966. }
  9967. function openEditBridgeModal(id) {
  9968. const b = (state.bridges || []).find(x => x.id === id);
  9969. if (!b) return;
  9970. document.getElementById('bridge-modal-title').innerText = `Edit Bridge (${b.name})`;
  9971. document.getElementById('bridge-modal-id').value = b.id;
  9972. document.getElementById('bridge-modal-name').value = b.name;
  9973. document.getElementById('bridge-modal-name').disabled = true;
  9974. document.getElementById('bridge-modal-mtu').value = b.mtu || 1500;
  9975. document.getElementById('bridge-modal-mac').value = b.mac_address || '';
  9976. document.getElementById('bridge-modal-stp').value = b.stp || 'stp';
  9977. document.getElementById('bridge-modal-priority').value = b.priority || 32768;
  9978. document.getElementById('bridge-modal-vlanfiltering').checked = !!b.vlan_filtering;
  9979. document.getElementById('bridge-modal-pvid').value = b.pvid || 1;
  9980. document.getElementById('bridge-modal-fastforward').checked = b.fast_forward !== false;
  9981. document.getElementById('bridge-modal-comment').value = b.comment || '';
  9982. document.getElementById('bridge-modal-disabled').checked = !!b.disabled;
  9983. toggleBridgeModalVlanFiltering();
  9984. document.getElementById('bridge-modal').classList.remove('hidden');
  9985. }
  9986. function closeBridgeModal() {
  9987. document.getElementById('bridge-modal').classList.add('hidden');
  9988. }
  9989. function toggleBridgeModalVlanFiltering() {
  9990. const chk = document.getElementById('bridge-modal-vlanfiltering').checked;
  9991. const pvidBox = document.getElementById('bridge-modal-pvid-box');
  9992. if (pvidBox) {
  9993. if (chk) pvidBox.classList.remove('opacity-40');
  9994. else pvidBox.classList.add('opacity-40');
  9995. }
  9996. }
  9997. async function submitSaveBridge(e) {
  9998. e.preventDefault();
  9999. const id = document.getElementById('bridge-modal-id').value;
  10000. const name = document.getElementById('bridge-modal-name').value.trim();
  10001. const mtu = parseInt(document.getElementById('bridge-modal-mtu').value, 10) || 1500;
  10002. const mac = document.getElementById('bridge-modal-mac').value.trim();
  10003. const stp = document.getElementById('bridge-modal-stp').value;
  10004. const priority = parseInt(document.getElementById('bridge-modal-priority').value, 10) || 32768;
  10005. const vlanFiltering = document.getElementById('bridge-modal-vlanfiltering').checked;
  10006. const pvid = parseInt(document.getElementById('bridge-modal-pvid').value, 10) || 1;
  10007. const fastForward = document.getElementById('bridge-modal-fastforward').checked;
  10008. const comment = document.getElementById('bridge-modal-comment').value.trim();
  10009. const disabled = document.getElementById('bridge-modal-disabled').checked;
  10010. try {
  10011. const res = await fetch(`${API_BASE}/bridge/bridges`, {
  10012. method: 'POST',
  10013. headers: { 'Content-Type': 'application/json' },
  10014. body: JSON.stringify({
  10015. id,
  10016. name,
  10017. mtu,
  10018. mac_address: mac,
  10019. stp,
  10020. priority,
  10021. vlan_filtering: vlanFiltering,
  10022. pvid,
  10023. fast_forward: fastForward,
  10024. comment,
  10025. disabled
  10026. })
  10027. });
  10028. if (res.ok) {
  10029. showToast('Bridge Saved', `Bridge ${name} configured`, 'success');
  10030. closeBridgeModal();
  10031. loadBridge();
  10032. fetchData(false);
  10033. } else {
  10034. const err = await res.json();
  10035. showToast('Error', err.error || err.message || 'Failed to save bridge', 'error');
  10036. }
  10037. } catch (err) {
  10038. showToast('Error', err.message, 'error');
  10039. }
  10040. }
  10041. async function toggleBridgeState(id, disabled) {
  10042. try {
  10043. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/state`, {
  10044. method: 'POST',
  10045. headers: { 'Content-Type': 'application/json' },
  10046. body: JSON.stringify({ disabled })
  10047. });
  10048. if (res.ok) {
  10049. loadBridge();
  10050. fetchData(false);
  10051. }
  10052. } catch (err) {
  10053. showToast('Error', err.message, 'error');
  10054. }
  10055. }
  10056. async function deleteBridge(id) {
  10057. const b = (state.bridges || []).find(x => x.id === id);
  10058. const name = b ? b.name : id;
  10059. if (!confirm(`Are you sure you want to delete bridge '${name}'? All member ports will be detached.`)) return;
  10060. try {
  10061. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10062. if (res.ok) {
  10063. showToast('Deleted', `Bridge ${name} deleted`, 'success');
  10064. loadBridge();
  10065. fetchData(false);
  10066. } else {
  10067. const err = await res.json();
  10068. showToast('Error', err.error || err.message || 'Failed to delete bridge', 'error');
  10069. }
  10070. } catch (err) {
  10071. showToast('Error', err.message, 'error');
  10072. }
  10073. }
  10074. // ----------------- Bridge IP Assignments -----------------
  10075. function openAddBridgeIPModal(id, name) {
  10076. document.getElementById('bridge-ip-modal-id').value = id;
  10077. document.getElementById('bridge-ip-modal-sub').innerText = name;
  10078. document.getElementById('bridge-ip-modal-cidr').value = '';
  10079. document.getElementById('bridge-ip-modal').classList.remove('hidden');
  10080. }
  10081. function closeBridgeIPModal() {
  10082. document.getElementById('bridge-ip-modal').classList.add('hidden');
  10083. }
  10084. async function submitAddBridgeIP(e) {
  10085. e.preventDefault();
  10086. const id = document.getElementById('bridge-ip-modal-id').value;
  10087. const ip = document.getElementById('bridge-ip-modal-cidr').value.trim();
  10088. try {
  10089. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  10090. method: 'POST',
  10091. headers: { 'Content-Type': 'application/json' },
  10092. body: JSON.stringify({ ip })
  10093. });
  10094. if (res.ok) {
  10095. showToast('IP Assigned', `${ip} assigned to bridge`, 'success');
  10096. closeBridgeIPModal();
  10097. loadBridge();
  10098. fetchData(false);
  10099. } else {
  10100. const err = await res.json();
  10101. showToast('Error', err.error || err.message || 'Failed to add IP', 'error');
  10102. }
  10103. } catch (err) {
  10104. showToast('Error', err.message, 'error');
  10105. }
  10106. }
  10107. async function deleteBridgeIP(id, ip) {
  10108. if (!confirm(`Remove IP address ${ip} from bridge?`)) return;
  10109. try {
  10110. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  10111. method: 'DELETE',
  10112. headers: { 'Content-Type': 'application/json' },
  10113. body: JSON.stringify({ ip })
  10114. });
  10115. if (res.ok) {
  10116. showToast('IP Removed', `${ip} removed from bridge`, 'success');
  10117. loadBridge();
  10118. fetchData(false);
  10119. }
  10120. } catch (err) {
  10121. showToast('Error', err.message, 'error');
  10122. }
  10123. }
  10124. // ----------------- Bridge Ports -----------------
  10125. function renderBridgePorts() {
  10126. const tbody = document.getElementById('bridge-ports-table-body');
  10127. const empty = document.getElementById('bridge-empty-ports');
  10128. const countBadge = document.getElementById('bridge-ports-count-badge');
  10129. const filterBridge = document.getElementById('bridge-ports-filter-bridge')?.value || '';
  10130. if (!tbody) return;
  10131. tbody.innerHTML = '';
  10132. // Update filter select
  10133. populateBridgeSelect('bridge-ports-filter-bridge', filterBridge, true);
  10134. const ports = (state.bridgePorts || []).filter(p => !filterBridge || p.bridge === filterBridge);
  10135. if (countBadge) countBadge.innerText = `${ports.length} Ports`;
  10136. if (ports.length === 0) {
  10137. empty?.classList.remove('hidden');
  10138. return;
  10139. }
  10140. empty?.classList.add('hidden');
  10141. ports.forEach((p, idx) => {
  10142. const tr = document.createElement('tr');
  10143. tr.className = `hover:bg-slate-800/40 transition text-xs ${p.disabled ? 'opacity-50' : ''}`;
  10144. const disabledFlag = p.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  10145. tr.innerHTML = `
  10146. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  10147. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  10148. <td class="py-2.5 px-3 font-bold text-white text-sm">
  10149. <span class="text-emerald-400 mr-1.5">🔌</span>${p.interface}
  10150. </td>
  10151. <td class="py-2.5 px-3 font-semibold text-sky-400">${p.bridge}</td>
  10152. <td class="py-2.5 px-3 font-mono">${p.pvid || 1}</td>
  10153. <td class="py-2.5 px-3 text-slate-300">${p.frame_types}</td>
  10154. <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>
  10155. <td class="py-2.5 px-3">
  10156. ${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>'}
  10157. </td>
  10158. <td class="py-2.5 px-3">
  10159. <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>
  10160. </td>
  10161. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${p.comment || ''}">${p.comment || '-'}</td>
  10162. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  10163. <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>
  10164. <button onclick="openEditBridgePortModal('${p.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  10165. <button onclick="deleteBridgePort('${p.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  10166. </td>
  10167. `;
  10168. tbody.appendChild(tr);
  10169. });
  10170. }
  10171. function openAddBridgePortModal() {
  10172. document.getElementById('bridge-port-modal-title').innerText = 'Add Port to Bridge';
  10173. document.getElementById('bridge-port-modal-id').value = '';
  10174. populateBridgeSelect('bridge-port-modal-bridge');
  10175. populateBridgePortCandidateSelect('bridge-port-modal-interface');
  10176. document.getElementById('bridge-port-modal-pvid').value = '1';
  10177. document.getElementById('bridge-port-modal-frametypes').value = 'admit-all';
  10178. document.getElementById('bridge-port-modal-ingressfiltering').checked = false;
  10179. document.getElementById('bridge-port-modal-horizon').value = '0';
  10180. document.getElementById('bridge-port-modal-pathcost').value = '10';
  10181. document.getElementById('bridge-port-modal-priority').value = '128';
  10182. document.getElementById('bridge-port-modal-learn').checked = true;
  10183. document.getElementById('bridge-port-modal-comment').value = '';
  10184. document.getElementById('bridge-port-modal-disabled').checked = false;
  10185. document.getElementById('bridge-port-modal').classList.remove('hidden');
  10186. }
  10187. function openEditBridgePortModal(id) {
  10188. const p = (state.bridgePorts || []).find(x => x.id === id);
  10189. if (!p) return;
  10190. document.getElementById('bridge-port-modal-title').innerText = `Edit Bridge Port (${p.interface})`;
  10191. document.getElementById('bridge-port-modal-id').value = p.id;
  10192. populateBridgeSelect('bridge-port-modal-bridge', p.bridge);
  10193. populateBridgePortCandidateSelect('bridge-port-modal-interface', p.interface);
  10194. document.getElementById('bridge-port-modal-pvid').value = p.pvid || 1;
  10195. document.getElementById('bridge-port-modal-frametypes').value = p.frame_types || 'admit-all';
  10196. document.getElementById('bridge-port-modal-ingressfiltering').checked = !!p.ingress_filtering;
  10197. document.getElementById('bridge-port-modal-horizon').value = p.horizon || 0;
  10198. document.getElementById('bridge-port-modal-pathcost').value = p.path_cost || 10;
  10199. document.getElementById('bridge-port-modal-priority').value = p.priority || 128;
  10200. document.getElementById('bridge-port-modal-learn').checked = p.learn !== false;
  10201. document.getElementById('bridge-port-modal-comment').value = p.comment || '';
  10202. document.getElementById('bridge-port-modal-disabled').checked = !!p.disabled;
  10203. document.getElementById('bridge-port-modal').classList.remove('hidden');
  10204. }
  10205. function closeBridgePortModal() {
  10206. document.getElementById('bridge-port-modal').classList.add('hidden');
  10207. }
  10208. async function submitSaveBridgePort(e) {
  10209. e.preventDefault();
  10210. const id = document.getElementById('bridge-port-modal-id').value;
  10211. const bridge = document.getElementById('bridge-port-modal-bridge').value;
  10212. const iface = document.getElementById('bridge-port-modal-interface').value;
  10213. const pvid = parseInt(document.getElementById('bridge-port-modal-pvid').value, 10) || 1;
  10214. const frameTypes = document.getElementById('bridge-port-modal-frametypes').value;
  10215. const ingressFiltering = document.getElementById('bridge-port-modal-ingressfiltering').checked;
  10216. const horizon = parseInt(document.getElementById('bridge-port-modal-horizon').value, 10) || 0;
  10217. const pathCost = parseInt(document.getElementById('bridge-port-modal-pathcost').value, 10) || 10;
  10218. const priority = parseInt(document.getElementById('bridge-port-modal-priority').value, 10) || 128;
  10219. const learn = document.getElementById('bridge-port-modal-learn').checked;
  10220. const comment = document.getElementById('bridge-port-modal-comment').value.trim();
  10221. const disabled = document.getElementById('bridge-port-modal-disabled').checked;
  10222. try {
  10223. const res = await fetch(`${API_BASE}/bridge/ports`, {
  10224. method: 'POST',
  10225. headers: { 'Content-Type': 'application/json' },
  10226. body: JSON.stringify({
  10227. id,
  10228. bridge,
  10229. interface: iface,
  10230. pvid,
  10231. frame_types: frameTypes,
  10232. ingress_filtering: ingressFiltering,
  10233. horizon,
  10234. path_cost: pathCost,
  10235. priority,
  10236. learn,
  10237. comment,
  10238. disabled
  10239. })
  10240. });
  10241. if (res.ok) {
  10242. showToast('Port Attached', `${iface} added to ${bridge}`, 'success');
  10243. closeBridgePortModal();
  10244. loadBridge();
  10245. fetchData(false);
  10246. } else {
  10247. const err = await res.json();
  10248. showToast('Error', err.error || err.message || 'Failed to save port', 'error');
  10249. }
  10250. } catch (err) {
  10251. showToast('Error', err.message, 'error');
  10252. }
  10253. }
  10254. async function toggleBridgePortState(id, disabled) {
  10255. try {
  10256. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}/state`, {
  10257. method: 'POST',
  10258. headers: { 'Content-Type': 'application/json' },
  10259. body: JSON.stringify({ disabled })
  10260. });
  10261. if (res.ok) {
  10262. loadBridge();
  10263. fetchData(false);
  10264. }
  10265. } catch (err) {
  10266. showToast('Error', err.message, 'error');
  10267. }
  10268. }
  10269. async function deleteBridgePort(id) {
  10270. const p = (state.bridgePorts || []).find(x => x.id === id);
  10271. const iface = p ? p.interface : id;
  10272. if (!confirm(`Detach interface '${iface}' from bridge?`)) return;
  10273. try {
  10274. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10275. if (res.ok) {
  10276. showToast('Port Detached', `${iface} removed from bridge`, 'success');
  10277. loadBridge();
  10278. fetchData(false);
  10279. }
  10280. } catch (err) {
  10281. showToast('Error', err.message, 'error');
  10282. }
  10283. }
  10284. // ----------------- Bridge VLANs -----------------
  10285. function renderBridgeVLANs() {
  10286. const tbody = document.getElementById('bridge-vlans-table-body');
  10287. const empty = document.getElementById('bridge-empty-vlans');
  10288. const countBadge = document.getElementById('bridge-vlans-count-badge');
  10289. const filterBridge = document.getElementById('bridge-vlans-filter-bridge')?.value || '';
  10290. if (!tbody) return;
  10291. tbody.innerHTML = '';
  10292. populateBridgeSelect('bridge-vlans-filter-bridge', filterBridge, true);
  10293. const vlans = (state.bridgeVLANs || []).filter(v => !filterBridge || v.bridge === filterBridge);
  10294. if (countBadge) countBadge.innerText = `${vlans.length} Entries`;
  10295. if (vlans.length === 0) {
  10296. empty?.classList.remove('hidden');
  10297. return;
  10298. }
  10299. empty?.classList.add('hidden');
  10300. vlans.forEach((v, idx) => {
  10301. const tr = document.createElement('tr');
  10302. tr.className = `hover:bg-slate-800/40 transition text-xs ${v.disabled ? 'opacity-50' : ''}`;
  10303. const taggedHtml = (v.tagged && v.tagged.length > 0)
  10304. ? 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(' ')
  10305. : '<span class="text-slate-600">none</span>';
  10306. const untaggedHtml = (v.untagged && v.untagged.length > 0)
  10307. ? 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(' ')
  10308. : '<span class="text-slate-600">none</span>';
  10309. const disabledFlag = v.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  10310. tr.innerHTML = `
  10311. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  10312. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  10313. <td class="py-2.5 px-3 font-semibold text-sky-400">${v.bridge}</td>
  10314. <td class="py-2.5 px-3 font-bold text-white font-mono text-sm">${v.vlan_ids}</td>
  10315. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${taggedHtml}</div></td>
  10316. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${untaggedHtml}</div></td>
  10317. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${v.comment || ''}">${v.comment || '-'}</td>
  10318. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  10319. <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>
  10320. <button onclick="openEditBridgeVLANModal('${v.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  10321. <button onclick="deleteBridgeVLAN('${v.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  10322. </td>
  10323. `;
  10324. tbody.appendChild(tr);
  10325. });
  10326. }
  10327. function openAddBridgeVLANModal() {
  10328. document.getElementById('bridge-vlan-modal-title').innerText = 'Add Bridge VLAN Entry';
  10329. document.getElementById('bridge-vlan-modal-id').value = '';
  10330. populateBridgeSelect('bridge-vlan-modal-bridge');
  10331. document.getElementById('bridge-vlan-modal-vlanids').value = '';
  10332. document.getElementById('bridge-vlan-modal-comment').value = '';
  10333. document.getElementById('bridge-vlan-modal-disabled').checked = false;
  10334. updateBridgeVlanPortCheckboxes();
  10335. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  10336. }
  10337. function openEditBridgeVLANModal(id) {
  10338. const v = (state.bridgeVLANs || []).find(x => x.id === id);
  10339. if (!v) return;
  10340. document.getElementById('bridge-vlan-modal-title').innerText = `Edit Bridge VLAN (${v.vlan_ids})`;
  10341. document.getElementById('bridge-vlan-modal-id').value = v.id;
  10342. populateBridgeSelect('bridge-vlan-modal-bridge', v.bridge);
  10343. document.getElementById('bridge-vlan-modal-vlanids').value = v.vlan_ids;
  10344. document.getElementById('bridge-vlan-modal-comment').value = v.comment || '';
  10345. document.getElementById('bridge-vlan-modal-disabled').checked = !!v.disabled;
  10346. updateBridgeVlanPortCheckboxes(v.tagged || [], v.untagged || []);
  10347. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  10348. }
  10349. function closeBridgeVlanModal() {
  10350. document.getElementById('bridge-vlan-modal').classList.add('hidden');
  10351. }
  10352. function updateBridgeVlanPortCheckboxes(taggedSelected = [], untaggedSelected = []) {
  10353. const selBridge = document.getElementById('bridge-vlan-modal-bridge')?.value || '';
  10354. const taggedBox = document.getElementById('bridge-vlan-tagged-ports');
  10355. const untaggedBox = document.getElementById('bridge-vlan-untagged-ports');
  10356. if (!taggedBox || !untaggedBox) return;
  10357. // Ports belonging to the selected bridge
  10358. const memberPorts = (state.bridgePorts || []).filter(p => !selBridge || p.bridge === selBridge);
  10359. if (memberPorts.length === 0) {
  10360. taggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  10361. untaggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  10362. return;
  10363. }
  10364. taggedBox.innerHTML = memberPorts.map(p => `
  10365. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  10366. <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">
  10367. <span>${p.interface}</span>
  10368. </label>
  10369. `).join('');
  10370. untaggedBox.innerHTML = memberPorts.map(p => `
  10371. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  10372. <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">
  10373. <span>${p.interface}</span>
  10374. </label>
  10375. `).join('');
  10376. }
  10377. async function submitSaveBridgeVLAN(e) {
  10378. e.preventDefault();
  10379. const id = document.getElementById('bridge-vlan-modal-id').value;
  10380. const bridge = document.getElementById('bridge-vlan-modal-bridge').value;
  10381. const vlanIDs = document.getElementById('bridge-vlan-modal-vlanids').value.trim();
  10382. const comment = document.getElementById('bridge-vlan-modal-comment').value.trim();
  10383. const disabled = document.getElementById('bridge-vlan-modal-disabled').checked;
  10384. const tagged = Array.from(document.querySelectorAll('input[name="bvlan-tagged"]:checked')).map(x => x.value);
  10385. const untagged = Array.from(document.querySelectorAll('input[name="bvlan-untagged"]:checked')).map(x => x.value);
  10386. try {
  10387. const res = await fetch(`${API_BASE}/bridge/vlans`, {
  10388. method: 'POST',
  10389. headers: { 'Content-Type': 'application/json' },
  10390. body: JSON.stringify({
  10391. id,
  10392. bridge,
  10393. vlan_ids: vlanIDs,
  10394. tagged,
  10395. untagged,
  10396. comment,
  10397. disabled
  10398. })
  10399. });
  10400. if (res.ok) {
  10401. showToast('VLAN Entry Saved', `VLAN ${vlanIDs} configured on ${bridge}`, 'success');
  10402. closeBridgeVlanModal();
  10403. loadBridge();
  10404. } else {
  10405. const err = await res.json();
  10406. showToast('Error', err.error || err.message || 'Failed to save VLAN entry', 'error');
  10407. }
  10408. } catch (err) {
  10409. showToast('Error', err.message, 'error');
  10410. }
  10411. }
  10412. async function toggleBridgeVLANState(id, disabled) {
  10413. try {
  10414. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}/state`, {
  10415. method: 'POST',
  10416. headers: { 'Content-Type': 'application/json' },
  10417. body: JSON.stringify({ disabled })
  10418. });
  10419. if (res.ok) loadBridge();
  10420. } catch (err) {
  10421. showToast('Error', err.message, 'error');
  10422. }
  10423. }
  10424. async function deleteBridgeVLAN(id) {
  10425. if (!confirm('Delete this bridge VLAN entry?')) return;
  10426. try {
  10427. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10428. if (res.ok) {
  10429. showToast('Deleted', 'VLAN entry removed from bridge', 'success');
  10430. loadBridge();
  10431. }
  10432. } catch (err) {
  10433. showToast('Error', err.message, 'error');
  10434. }
  10435. }
  10436. // ----------------- Hosts / MAC Table -----------------
  10437. async function loadBridgeHosts() {
  10438. const filterBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || '';
  10439. populateBridgeSelect('bridge-hosts-filter-bridge', filterBridge, true);
  10440. try {
  10441. const url = filterBridge ? `${API_BASE}/bridge/hosts?bridge=${encodeURIComponent(filterBridge)}` : `${API_BASE}/bridge/hosts`;
  10442. const res = await fetch(url);
  10443. if (res.ok) {
  10444. state.bridgeHosts = await res.json();
  10445. renderBridgeHosts();
  10446. }
  10447. } catch (err) {
  10448. console.error('Failed to load bridge hosts:', err);
  10449. }
  10450. }
  10451. function renderBridgeHosts() {
  10452. const tbody = document.getElementById('bridge-hosts-table-body');
  10453. const empty = document.getElementById('bridge-empty-hosts');
  10454. const countBadge = document.getElementById('bridge-hosts-count-badge');
  10455. const search = (document.getElementById('bridge-hosts-search')?.value || '').toLowerCase().trim();
  10456. if (!tbody) return;
  10457. tbody.innerHTML = '';
  10458. const hosts = (state.bridgeHosts || []).filter(h => {
  10459. if (!search) return true;
  10460. return (h.mac || '').toLowerCase().includes(search) || (h.interface || '').toLowerCase().includes(search) || (h.bridge || '').toLowerCase().includes(search);
  10461. });
  10462. if (countBadge) countBadge.innerText = `${hosts.length} Hosts`;
  10463. if (hosts.length === 0) {
  10464. empty?.classList.remove('hidden');
  10465. return;
  10466. }
  10467. empty?.classList.add('hidden');
  10468. hosts.forEach(h => {
  10469. const tr = document.createElement('tr');
  10470. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  10471. let flagBadges = '';
  10472. 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>';
  10473. 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>';
  10474. 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>';
  10475. tr.innerHTML = `
  10476. <td class="py-2.5 px-3 font-mono font-bold text-white text-sm">${h.mac}</td>
  10477. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${h.interface || '-'}</td>
  10478. <td class="py-2.5 px-3 font-mono text-sky-400">${h.bridge || '-'}</td>
  10479. <td class="py-2.5 px-3 font-mono">${h.vlan_id || 1}</td>
  10480. <td class="py-2.5 px-3 font-mono text-slate-400">${h.age ? h.age.toFixed(1) + 's' : '-'}</td>
  10481. <td class="py-2.5 px-3">${flagBadges}</td>
  10482. `;
  10483. tbody.appendChild(tr);
  10484. });
  10485. }
  10486. async function flushBridgeHosts() {
  10487. const selBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || (state.bridges[0] ? state.bridges[0].name : '');
  10488. if (!selBridge) {
  10489. showToast('Notice', 'Please select a bridge to flush dynamic MACs', 'info');
  10490. return;
  10491. }
  10492. if (!confirm(`Flush all dynamic learned MAC addresses on bridge '${selBridge}'?`)) return;
  10493. try {
  10494. const res = await fetch(`${API_BASE}/bridge/hosts/flush`, {
  10495. method: 'POST',
  10496. headers: { 'Content-Type': 'application/json' },
  10497. body: JSON.stringify({ bridge: selBridge })
  10498. });
  10499. if (res.ok) {
  10500. showToast('FDB Flushed', `Dynamic MACs flushed on ${selBridge}`, 'success');
  10501. loadBridgeHosts();
  10502. }
  10503. } catch (err) {
  10504. showToast('Error', err.message, 'error');
  10505. }
  10506. }
  10507. // ----------------- Helpers -----------------
  10508. function populateBridgeSelect(selectId, currentVal = '', includeAll = false) {
  10509. const sel = document.getElementById(selectId);
  10510. if (!sel) return;
  10511. const prevVal = currentVal || sel.value;
  10512. sel.innerHTML = includeAll ? '<option value="">All Bridges</option>' : '';
  10513. (state.bridges || []).forEach(b => {
  10514. const opt = document.createElement('option');
  10515. opt.value = b.name;
  10516. opt.innerText = `${b.name} (${b.ports_count} ports)`;
  10517. if (b.name === prevVal) opt.selected = true;
  10518. sel.appendChild(opt);
  10519. });
  10520. }
  10521. function populateBridgePortCandidateSelect(selectId, currentVal = '') {
  10522. const sel = document.getElementById(selectId);
  10523. if (!sel) return;
  10524. sel.innerHTML = '<option value="">(Select Interface...)</option>';
  10525. // 1. Physical Interfaces
  10526. const grpPhys = document.createElement('optgroup');
  10527. grpPhys.label = 'Physical Interfaces';
  10528. (state.interfaces || []).filter(i => i.type !== 'bridge' && i.type !== 'vlan' && i.type !== 'loopback').forEach(i => {
  10529. const opt = document.createElement('option');
  10530. opt.value = i.name;
  10531. opt.innerText = `${i.name} (${i.role || i.type})`;
  10532. if (i.name === currentVal) opt.selected = true;
  10533. grpPhys.appendChild(opt);
  10534. });
  10535. if (grpPhys.children.length > 0) sel.appendChild(grpPhys);
  10536. // 2. VLAN Sub-interfaces
  10537. const grpVlans = document.createElement('optgroup');
  10538. grpVlans.label = 'VLAN Sub-interfaces (802.1Q)';
  10539. (state.vlans || []).forEach(v => {
  10540. const opt = document.createElement('option');
  10541. opt.value = v.name;
  10542. opt.innerText = `${v.name} (VLAN ${v.vlan_id})`;
  10543. if (v.name === currentVal) opt.selected = true;
  10544. grpVlans.appendChild(opt);
  10545. });
  10546. if (grpVlans.children.length > 0) sel.appendChild(grpVlans);
  10547. // 3. EoIP Tunnels (MikroTik EoIP bridging!)
  10548. const grpEoip = document.createElement('optgroup');
  10549. grpEoip.label = 'EoIP Tunnels (Layer 2 VPN)';
  10550. (state.eoipTunnels || []).forEach(t => {
  10551. const opt = document.createElement('option');
  10552. opt.value = t.name;
  10553. opt.innerText = `${t.name} (Tunnel ID: ${t.tunnel_id} -> ${t.remote_address})`;
  10554. if (t.name === currentVal) opt.selected = true;
  10555. grpEoip.appendChild(opt);
  10556. });
  10557. if (grpEoip.children.length > 0) sel.appendChild(grpEoip);
  10558. }
  10559. // -------------------------------------------------------------
  10560. // DebTik Routing Filters Management (/routing filter)
  10561. // -------------------------------------------------------------
  10562. if (!state.activeRoutingFilterTab) state.activeRoutingFilterTab = 'rules';
  10563. if (!state.selectedFilterRow) state.selectedFilterRow = {};
  10564. if (!state.rfSort) state.rfSort = {};
  10565. function switchRoutingFilterTab(tab) {
  10566. state.activeRoutingFilterTab = tab;
  10567. const tabs = ['rules', 'select-rules', 'community-lists', 'as-lists'];
  10568. tabs.forEach(t => {
  10569. const btn = document.getElementById(`tab-rf-${t}`);
  10570. const content = document.getElementById(`tab-content-rf-${t}`);
  10571. if (btn) {
  10572. if (t === tab) {
  10573. 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';
  10574. } else {
  10575. btn.className = 'px-3 py-1 text-xs font-semibold rounded text-slate-400 hover:text-white hover:bg-slate-800 transition';
  10576. }
  10577. }
  10578. if (content) {
  10579. if (t === tab) content.classList.remove('hidden');
  10580. else content.classList.add('hidden');
  10581. }
  10582. });
  10583. const chainContainer = document.getElementById('rf-chain-filter-container');
  10584. if (chainContainer) {
  10585. if (tab === 'rules' || tab === 'select-rules') chainContainer.classList.remove('hidden');
  10586. else chainContainer.classList.add('hidden');
  10587. }
  10588. renderRoutingFilters();
  10589. }
  10590. function selectFilterRow(tab, id) {
  10591. if (state.selectedFilterRow[tab] === id) {
  10592. delete state.selectedFilterRow[tab];
  10593. } else {
  10594. state.selectedFilterRow[tab] = id;
  10595. }
  10596. if (tab === 'rules') renderRoutingFilterRules();
  10597. else if (tab === 'select-rules') renderRoutingFilterSelectRules();
  10598. else if (tab === 'community-lists') renderRoutingFilterCommunityLists();
  10599. else if (tab === 'as-lists') renderRoutingFilterASLists();
  10600. }
  10601. function openRoutingFilterNewModal() {
  10602. const tab = state.activeRoutingFilterTab || 'rules';
  10603. if (tab === 'rules') openAddRoutingFilterModal();
  10604. else if (tab === 'select-rules') openAddSelectRuleModal();
  10605. else if (tab === 'community-lists') openAddCommunityListModal();
  10606. else if (tab === 'as-lists') openAddASListModal();
  10607. }
  10608. function toggleSelectedRoutingFilter(disabled) {
  10609. const tab = state.activeRoutingFilterTab || 'rules';
  10610. const id = state.selectedFilterRow[tab];
  10611. if (!id) {
  10612. showToast('Select Row', 'Please click on a row to select it first', 'info');
  10613. return;
  10614. }
  10615. if (tab === 'rules') toggleRoutingFilterState(id, disabled);
  10616. else if (tab === 'select-rules') toggleSelectRuleState(id, disabled);
  10617. else if (tab === 'community-lists') toggleCommunityListState(id, disabled);
  10618. else if (tab === 'as-lists') toggleASListState(id, disabled);
  10619. }
  10620. function removeSelectedRoutingFilter() {
  10621. const tab = state.activeRoutingFilterTab || 'rules';
  10622. const id = state.selectedFilterRow[tab];
  10623. if (!id) {
  10624. showToast('Select Row', 'Please click on a row to select it first', 'info');
  10625. return;
  10626. }
  10627. if (tab === 'rules') deleteRoutingFilter(id);
  10628. else if (tab === 'select-rules') deleteSelectRule(id);
  10629. else if (tab === 'community-lists') deleteCommunityList(id);
  10630. else if (tab === 'as-lists') deleteASList(id);
  10631. }
  10632. function searchRoutingFilters(q) {
  10633. state.rfSearchQuery = (q || '').trim().toLowerCase();
  10634. renderRoutingFilters();
  10635. }
  10636. function sortFilterTable(tab, col) {
  10637. if (!state.rfSort) state.rfSort = {};
  10638. if (!state.rfSort[tab]) state.rfSort[tab] = { col: col, asc: true };
  10639. if (state.rfSort[tab].col === col) {
  10640. state.rfSort[tab].asc = !state.rfSort[tab].asc;
  10641. } else {
  10642. state.rfSort[tab].col = col;
  10643. state.rfSort[tab].asc = true;
  10644. }
  10645. const asc = state.rfSort[tab].asc;
  10646. let list = [];
  10647. if (tab === 'rules') list = state.routingFilters || [];
  10648. else if (tab === 'select-rules') list = state.routingSelectRules || [];
  10649. else if (tab === 'community-lists') list = state.routingCommunityLists || [];
  10650. else if (tab === 'as-lists') list = state.routingASLists || [];
  10651. list.sort((a, b) => {
  10652. let valA = a[col] ?? '';
  10653. let valB = b[col] ?? '';
  10654. if (col === 'flags') {
  10655. valA = a.disabled ? 'X' : 'A';
  10656. valB = b.disabled ? 'X' : 'A';
  10657. }
  10658. if (typeof valA === 'number' && typeof valB === 'number') {
  10659. return asc ? valA - valB : valB - valA;
  10660. }
  10661. return asc ? String(valA).localeCompare(String(valB)) : String(valB).localeCompare(String(valA));
  10662. });
  10663. const allCols = ['flags', 'rule_order', 'chain', 'rule', 'name', 'communities', 'range', 'regexp', 'comment'];
  10664. allCols.forEach(c => {
  10665. const el = document.getElementById(`sort-icon-${tab}-${c}`);
  10666. if (el) el.innerText = (c === col) ? (asc ? '▲' : '▼') : '';
  10667. });
  10668. if (tab === 'rules') renderRoutingFilterRules();
  10669. else if (tab === 'select-rules') renderRoutingFilterSelectRules();
  10670. else if (tab === 'community-lists') renderRoutingFilterCommunityLists();
  10671. else if (tab === 'as-lists') renderRoutingFilterASLists();
  10672. }
  10673. function renderRoutingFilters() {
  10674. const navBadge = document.getElementById('badge-filters-count');
  10675. const allRules = state.routingFilters || [];
  10676. if (navBadge) navBadge.innerText = allRules.length;
  10677. // Populate chain filter select options and datalist
  10678. const chainSelect = document.getElementById('routing-filter-chain-select');
  10679. const chainDatalist = document.getElementById('dl-routing-chains');
  10680. const uniqueChains = Array.from(new Set(allRules.map(r => r.chain).filter(Boolean))).sort();
  10681. if (chainSelect) {
  10682. const currentVal = state.filterChainSelected || 'all';
  10683. chainSelect.innerHTML = `<option value="all">All Chains (${allRules.length})</option>` +
  10684. uniqueChains.map(ch => {
  10685. const count = allRules.filter(r => r.chain === ch).length;
  10686. return `<option value="${escapeHtml(ch)}"${currentVal === ch ? ' selected' : ''}>${escapeHtml(ch)} (${count})</option>`;
  10687. }).join('');
  10688. chainSelect.value = currentVal;
  10689. }
  10690. if (chainDatalist) {
  10691. chainDatalist.innerHTML = uniqueChains.map(ch => `<option value="${escapeHtml(ch)}">`).join('');
  10692. }
  10693. renderRoutingFilterRules();
  10694. renderRoutingFilterSelectRules();
  10695. renderRoutingFilterCommunityLists();
  10696. renderRoutingFilterASLists();
  10697. }
  10698. function filterRoutingFiltersByChain(chain) {
  10699. state.filterChainSelected = chain;
  10700. renderRoutingFilters();
  10701. }
  10702. // -------------------------------------------------------------
  10703. // TAB 1: RULES (/routing filter rule)
  10704. // -------------------------------------------------------------
  10705. function renderRoutingFilterRules() {
  10706. const tbody = document.getElementById('routing-filter-rules-tbody');
  10707. if (!tbody) return;
  10708. const empty = document.getElementById('rf-rules-empty');
  10709. const statusCount = document.getElementById('rf-status-count');
  10710. let list = (state.routingFilters || []).slice();
  10711. if (state.filterChainSelected && state.filterChainSelected !== 'all') {
  10712. list = list.filter(r => r.chain === state.filterChainSelected);
  10713. }
  10714. const q = state.rfSearchQuery;
  10715. if (q) {
  10716. list = list.filter(r =>
  10717. (r.chain && r.chain.toLowerCase().includes(q)) ||
  10718. (r.rule && r.rule.toLowerCase().includes(q)) ||
  10719. (r.prefix && r.prefix.toLowerCase().includes(q)) ||
  10720. (r.comment && r.comment.toLowerCase().includes(q))
  10721. );
  10722. }
  10723. if (!state.rfSort?.['rules']) {
  10724. list.sort((a, b) => {
  10725. if (a.chain !== b.chain) return (a.chain || '').localeCompare(b.chain || '');
  10726. return (a.rule_order || 0) - (b.rule_order || 0);
  10727. });
  10728. }
  10729. if (statusCount && (state.activeRoutingFilterTab === 'rules' || !state.activeRoutingFilterTab)) {
  10730. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  10731. }
  10732. if (list.length === 0) {
  10733. tbody.innerHTML = '';
  10734. if (empty) empty.classList.remove('hidden');
  10735. return;
  10736. }
  10737. if (empty) empty.classList.add('hidden');
  10738. tbody.innerHTML = list.map(r => {
  10739. const isSelected = state.selectedFilterRow?.['rules'] === r.id;
  10740. const flagA = !r.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  10741. const flagX = r.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  10742. const flagC = r.comment ? '<span class="text-amber-400 font-bold ml-1" title="Comment">C</span>' : '';
  10743. let ruleDisplay = '';
  10744. if (r.rule && r.rule.trim() !== '') {
  10745. ruleDisplay = `<span class="text-emerald-400 font-mono font-medium">${escapeHtml(r.rule)}</span>`;
  10746. } else {
  10747. let conds = [];
  10748. if (r.prefix) conds.push(`dst in ${escapeHtml(r.prefix)}`);
  10749. if (r.match_protocol && r.match_protocol !== 'any') conds.push(`protocol ${escapeHtml(r.match_protocol)}`);
  10750. let act = r.action || 'accept';
  10751. ruleDisplay = `<span class="text-slate-300 font-mono">if (${conds.length ? conds.join(' && ') : 'true'}) { ${escapeHtml(act)}; }</span>`;
  10752. }
  10753. return `
  10754. <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'}">
  10755. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}${flagC}</td>
  10756. <td class="py-2 px-2 font-mono text-slate-400 font-bold">${r.rule_order || 10}</td>
  10757. <td class="py-2 px-3">
  10758. <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>
  10759. </td>
  10760. <td class="py-2 px-3 break-all max-w-xl">${ruleDisplay}</td>
  10761. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(r.comment || '')}</td>
  10762. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  10763. <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>
  10764. <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>
  10765. <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'}">
  10766. ${r.disabled ? 'Enable' : 'Disable'}
  10767. </button>
  10768. <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">
  10769. Edit
  10770. </button>
  10771. <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">
  10772. ✕
  10773. </button>
  10774. </td>
  10775. </tr>
  10776. `;
  10777. }).join('');
  10778. }
  10779. // -------------------------------------------------------------
  10780. // TAB 2: SELECT RULES (/routing filter select-rule)
  10781. // -------------------------------------------------------------
  10782. function renderRoutingFilterSelectRules() {
  10783. const tbody = document.getElementById('routing-filter-select-rules-tbody');
  10784. if (!tbody) return;
  10785. const empty = document.getElementById('rf-select-rules-empty');
  10786. const statusCount = document.getElementById('rf-status-count');
  10787. let list = (state.routingSelectRules || []).slice();
  10788. if (state.filterChainSelected && state.filterChainSelected !== 'all') {
  10789. list = list.filter(r => r.chain === state.filterChainSelected);
  10790. }
  10791. const q = state.rfSearchQuery;
  10792. if (q) {
  10793. list = list.filter(r =>
  10794. (r.chain && r.chain.toLowerCase().includes(q)) ||
  10795. (r.rule && r.rule.toLowerCase().includes(q)) ||
  10796. (r.comment && r.comment.toLowerCase().includes(q))
  10797. );
  10798. }
  10799. if (statusCount && state.activeRoutingFilterTab === 'select-rules') {
  10800. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  10801. }
  10802. if (list.length === 0) {
  10803. tbody.innerHTML = '';
  10804. if (empty) empty.classList.remove('hidden');
  10805. return;
  10806. }
  10807. if (empty) empty.classList.add('hidden');
  10808. tbody.innerHTML = list.map(r => {
  10809. const isSelected = state.selectedFilterRow?.['select-rules'] === r.id;
  10810. const flagA = !r.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  10811. const flagX = r.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  10812. return `
  10813. <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'}">
  10814. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  10815. <td class="py-2 px-2 font-mono text-slate-400 font-bold">${r.rule_order || 10}</td>
  10816. <td class="py-2 px-3">
  10817. <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>
  10818. </td>
  10819. <td class="py-2 px-3 break-all max-w-xl font-mono text-emerald-400">${escapeHtml(r.rule || '')}</td>
  10820. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(r.comment || '')}</td>
  10821. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  10822. <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'}">
  10823. ${r.disabled ? 'Enable' : 'Disable'}
  10824. </button>
  10825. <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">
  10826. Edit
  10827. </button>
  10828. <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">
  10829. ✕
  10830. </button>
  10831. </td>
  10832. </tr>
  10833. `;
  10834. }).join('');
  10835. }
  10836. // -------------------------------------------------------------
  10837. // TAB 3: COMMUNITY LISTS (/routing filter community-list)
  10838. // -------------------------------------------------------------
  10839. function renderRoutingFilterCommunityLists() {
  10840. const tbody = document.getElementById('routing-filter-comm-lists-tbody');
  10841. if (!tbody) return;
  10842. const empty = document.getElementById('rf-comm-lists-empty');
  10843. const statusCount = document.getElementById('rf-status-count');
  10844. let list = (state.routingCommunityLists || []).slice();
  10845. const q = state.rfSearchQuery;
  10846. if (q) {
  10847. list = list.filter(cl =>
  10848. (cl.name && cl.name.toLowerCase().includes(q)) ||
  10849. (cl.comment && cl.comment.toLowerCase().includes(q)) ||
  10850. (cl.communities && cl.communities.some(c => c.toLowerCase().includes(q)))
  10851. );
  10852. }
  10853. if (statusCount && state.activeRoutingFilterTab === 'community-lists') {
  10854. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  10855. }
  10856. if (list.length === 0) {
  10857. tbody.innerHTML = '';
  10858. if (empty) empty.classList.remove('hidden');
  10859. return;
  10860. }
  10861. if (empty) empty.classList.add('hidden');
  10862. tbody.innerHTML = list.map(cl => {
  10863. const isSelected = state.selectedFilterRow?.['community-lists'] === cl.id;
  10864. const flagA = !cl.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  10865. const flagX = cl.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  10866. const commBadges = (cl.communities || []).map(c =>
  10867. `<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>`
  10868. ).join(' ');
  10869. return `
  10870. <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'}">
  10871. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  10872. <td class="py-2 px-3 font-mono font-bold text-white">${escapeHtml(cl.name)}</td>
  10873. <td class="py-2 px-3 space-x-1">${commBadges || '<span class="text-slate-600">-</span>'}</td>
  10874. <td class="py-2 px-3 font-mono text-slate-400">${escapeHtml(cl.regexp || '-')}</td>
  10875. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(cl.comment || '')}</td>
  10876. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  10877. <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'}">
  10878. ${cl.disabled ? 'Enable' : 'Disable'}
  10879. </button>
  10880. <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">
  10881. Edit
  10882. </button>
  10883. <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">
  10884. ✕
  10885. </button>
  10886. </td>
  10887. </tr>
  10888. `;
  10889. }).join('');
  10890. }
  10891. // -------------------------------------------------------------
  10892. // TAB 4: AS LISTS (/routing filter num-list)
  10893. // -------------------------------------------------------------
  10894. function renderRoutingFilterASLists() {
  10895. const tbody = document.getElementById('routing-filter-as-lists-tbody');
  10896. if (!tbody) return;
  10897. const empty = document.getElementById('rf-as-lists-empty');
  10898. const statusCount = document.getElementById('rf-status-count');
  10899. let list = (state.routingASLists || []).slice();
  10900. const q = state.rfSearchQuery;
  10901. if (q) {
  10902. list = list.filter(al =>
  10903. (al.name && al.name.toLowerCase().includes(q)) ||
  10904. (al.range && al.range.toLowerCase().includes(q)) ||
  10905. (al.comment && al.comment.toLowerCase().includes(q))
  10906. );
  10907. }
  10908. if (statusCount && state.activeRoutingFilterTab === 'as-lists') {
  10909. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  10910. }
  10911. if (list.length === 0) {
  10912. tbody.innerHTML = '';
  10913. if (empty) empty.classList.remove('hidden');
  10914. return;
  10915. }
  10916. if (empty) empty.classList.add('hidden');
  10917. tbody.innerHTML = list.map(al => {
  10918. const isSelected = state.selectedFilterRow?.['as-lists'] === al.id;
  10919. const flagA = !al.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  10920. const flagX = al.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  10921. return `
  10922. <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'}">
  10923. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  10924. <td class="py-2 px-3 font-mono font-bold text-white">${escapeHtml(al.name)}</td>
  10925. <td class="py-2 px-3 font-mono text-purple-300">${escapeHtml(al.range)}</td>
  10926. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(al.comment || '')}</td>
  10927. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  10928. <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'}">
  10929. ${al.disabled ? 'Enable' : 'Disable'}
  10930. </button>
  10931. <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">
  10932. Edit
  10933. </button>
  10934. <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">
  10935. ✕
  10936. </button>
  10937. </td>
  10938. </tr>
  10939. `;
  10940. }).join('');
  10941. }
  10942. // -------------------------------------------------------------
  10943. // SNIPPETS & WIZARD HELPERS
  10944. // -------------------------------------------------------------
  10945. function insertRuleSnippet(type) {
  10946. const textarea = document.getElementById('modal-rf-rule');
  10947. if (!textarea) return;
  10948. let snippet = '';
  10949. switch (type) {
  10950. case 'accept-default':
  10951. snippet = 'if (dst in 0.0.0.0/0) { accept; }';
  10952. break;
  10953. case 'drop-rfc1918':
  10954. snippet = 'if (dst in 10.0.0.0/8 || dst in 172.16.0.0/12 || dst in 192.168.0.0/16) { reject; }';
  10955. break;
  10956. case 'len-24':
  10957. snippet = 'if (dst-len > 24) { reject; }';
  10958. break;
  10959. case 'local-pref-150':
  10960. snippet = 'if (dst in 10.0.0.0/8) { set bgp-local-pref 150; accept; }';
  10961. break;
  10962. case 'as-prepend-2':
  10963. snippet = 'set bgp-path-prepend 2; accept;';
  10964. break;
  10965. case 'set-comm':
  10966. snippet = 'set bgp-communities.add 65000:100; accept;';
  10967. break;
  10968. case 'match-comm':
  10969. snippet = 'if (bgp-communities includes 65000:100) { accept; }';
  10970. break;
  10971. case 'reject-all':
  10972. snippet = 'reject;';
  10973. break;
  10974. }
  10975. if (!snippet) return;
  10976. if (!textarea.value.trim()) {
  10977. textarea.value = snippet;
  10978. } else {
  10979. textarea.value = textarea.value.trim() + '\n' + snippet;
  10980. }
  10981. }
  10982. function generateScriptFromWizard() {
  10983. const pfx = (document.getElementById('modal-rf-prefix')?.value || '').trim();
  10984. const pfxLen = (document.getElementById('modal-rf-prefix-len')?.value || '').trim();
  10985. const proto = document.getElementById('modal-rf-protocol')?.value || 'any';
  10986. const asp = (document.getElementById('modal-rf-as-path')?.value || '').trim();
  10987. const comm = (document.getElementById('modal-rf-community')?.value || '').trim();
  10988. const act = document.getElementById('modal-rf-action')?.value || 'accept';
  10989. const lp = parseInt(document.getElementById('modal-rf-set-local-pref')?.value, 10) || 0;
  10990. const prep = parseInt(document.getElementById('modal-rf-set-as-prepend')?.value, 10) || 0;
  10991. const conds = [];
  10992. if (pfx) {
  10993. if (pfxLen) {
  10994. if (pfxLen.includes('-')) {
  10995. const parts = pfxLen.split('-');
  10996. conds.push(`dst in ${pfx}{${parts[0].trim()},${parts[1].trim()}}`);
  10997. } else {
  10998. conds.push(`dst in ${pfx} && dst-len >= ${pfxLen}`);
  10999. }
  11000. } else {
  11001. conds.push(`dst in ${pfx}`);
  11002. }
  11003. }
  11004. if (proto && proto !== 'any') {
  11005. conds.push(`protocol ${proto}`);
  11006. }
  11007. if (asp) {
  11008. conds.push(`bgp-as-path "${asp}"`);
  11009. }
  11010. if (comm) {
  11011. conds.push(`bgp-communities includes ${comm}`);
  11012. }
  11013. const actions = [];
  11014. if (lp > 0) actions.push(`set bgp-local-pref ${lp};`);
  11015. if (prep > 0) actions.push(`set bgp-path-prepend ${prep};`);
  11016. actions.push(`${act};`);
  11017. let code = '';
  11018. if (conds.length > 0) {
  11019. code = `if (${conds.join(' && ')}) {\n ${actions.join(' ')}\n}`;
  11020. } else {
  11021. code = actions.join(' ');
  11022. }
  11023. const textarea = document.getElementById('modal-rf-rule');
  11024. if (textarea) textarea.value = code;
  11025. }
  11026. // -------------------------------------------------------------
  11027. // MODAL CRUD: RULES (/routing filter rule)
  11028. // -------------------------------------------------------------
  11029. function openAddRoutingFilterModal(defaultChain = '') {
  11030. const form = document.getElementById('routing-filter-form');
  11031. if (form) form.reset();
  11032. const idEl = document.getElementById('modal-rf-id');
  11033. if (idEl) idEl.value = '';
  11034. const titleEl = document.getElementById('modal-rf-title');
  11035. if (titleEl) titleEl.innerText = 'Add Routing Filter Rule';
  11036. const chainEl = document.getElementById('modal-rf-chain');
  11037. if (chainEl) chainEl.value = defaultChain || (state.filterChainSelected && state.filterChainSelected !== 'all' ? state.filterChainSelected : 'bgp-in');
  11038. const orderEl = document.getElementById('modal-rf-order');
  11039. if (orderEl) orderEl.value = ((state.routingFilters || []).length + 1) * 10;
  11040. const ruleEl = document.getElementById('modal-rf-rule');
  11041. if (ruleEl) ruleEl.value = 'if (dst in 10.0.0.0/8) { set bgp-local-pref 150; accept; }';
  11042. const disEl = document.getElementById('modal-rf-disabled');
  11043. if (disEl) disEl.checked = false;
  11044. const modal = document.getElementById('modal-routing-filter');
  11045. if (modal) modal.classList.remove('hidden');
  11046. }
  11047. function openEditRoutingFilterModal(id) {
  11048. const r = (state.routingFilters || []).find(item => item.id === id);
  11049. if (!r) return;
  11050. const idEl = document.getElementById('modal-rf-id');
  11051. if (idEl) idEl.value = r.id;
  11052. const titleEl = document.getElementById('modal-rf-title');
  11053. if (titleEl) titleEl.innerText = 'Edit Routing Filter Rule';
  11054. const chainEl = document.getElementById('modal-rf-chain');
  11055. if (chainEl) chainEl.value = r.chain || '';
  11056. const orderEl = document.getElementById('modal-rf-order');
  11057. if (orderEl) orderEl.value = r.rule_order || 10;
  11058. const ruleEl = document.getElementById('modal-rf-rule');
  11059. if (ruleEl) {
  11060. if (r.rule) {
  11061. ruleEl.value = r.rule;
  11062. } else {
  11063. let conds = [];
  11064. if (r.prefix) conds.push(`dst in ${r.prefix}`);
  11065. if (r.match_protocol && r.match_protocol !== 'any') conds.push(`protocol ${r.match_protocol}`);
  11066. let act = r.action || 'accept';
  11067. ruleEl.value = `if (${conds.length ? conds.join(' && ') : 'true'}) { ${act}; }`;
  11068. }
  11069. }
  11070. const comEl = document.getElementById('modal-rf-comment');
  11071. if (comEl) comEl.value = r.comment || '';
  11072. const disEl = document.getElementById('modal-rf-disabled');
  11073. if (disEl) disEl.checked = !!r.disabled;
  11074. const modal = document.getElementById('modal-routing-filter');
  11075. if (modal) modal.classList.remove('hidden');
  11076. }
  11077. function closeRoutingFilterModal() {
  11078. const modal = document.getElementById('modal-routing-filter');
  11079. if (modal) modal.classList.add('hidden');
  11080. }
  11081. async function submitRoutingFilter(e) {
  11082. if (e) e.preventDefault();
  11083. const payload = {
  11084. id: document.getElementById('modal-rf-id').value,
  11085. chain: document.getElementById('modal-rf-chain').value.trim(),
  11086. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  11087. rule: document.getElementById('modal-rf-rule').value.trim(),
  11088. comment: document.getElementById('modal-rf-comment').value.trim(),
  11089. disabled: document.getElementById('modal-rf-disabled').checked
  11090. };
  11091. try {
  11092. const res = await fetch(`${API_BASE}/routing/filters`, {
  11093. method: 'POST',
  11094. headers: { 'Content-Type': 'application/json' },
  11095. body: JSON.stringify(payload)
  11096. });
  11097. if (res.ok) {
  11098. closeRoutingFilterModal();
  11099. showToast('Success', 'Routing filter rule saved', 'success');
  11100. loadDynamicRouting();
  11101. } else {
  11102. const err = await res.json();
  11103. showToast('Error', err.error || 'Failed to save filter rule', 'error');
  11104. }
  11105. } catch (err) {
  11106. showToast('Error', err.message, 'error');
  11107. }
  11108. }
  11109. async function applyRoutingFilterForm() {
  11110. const payload = {
  11111. id: document.getElementById('modal-rf-id').value,
  11112. chain: document.getElementById('modal-rf-chain').value.trim(),
  11113. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  11114. rule: document.getElementById('modal-rf-rule').value.trim(),
  11115. comment: document.getElementById('modal-rf-comment').value.trim(),
  11116. disabled: document.getElementById('modal-rf-disabled').checked
  11117. };
  11118. try {
  11119. const res = await fetch(`${API_BASE}/routing/filters`, {
  11120. method: 'POST',
  11121. headers: { 'Content-Type': 'application/json' },
  11122. body: JSON.stringify(payload)
  11123. });
  11124. if (res.ok) {
  11125. const data = await res.json();
  11126. if (data.id) document.getElementById('modal-rf-id').value = data.id;
  11127. showToast('Applied', 'Routing filter configuration applied', 'success');
  11128. loadDynamicRouting();
  11129. } else {
  11130. const err = await res.json();
  11131. showToast('Error', err.error || 'Failed to apply filter rule', 'error');
  11132. }
  11133. } catch (err) {
  11134. showToast('Error', err.message, 'error');
  11135. }
  11136. }
  11137. async function moveRoutingFilterOrder(id, delta) {
  11138. const list = state.routingFilters || [];
  11139. const idx = list.findIndex(r => r.id === id);
  11140. if (idx < 0) return;
  11141. const targetIdx = idx + delta;
  11142. if (targetIdx < 0 || targetIdx >= list.length) return;
  11143. const currentOrder = list[idx].rule_order || 10;
  11144. const targetOrder = list[targetIdx].rule_order || 20;
  11145. list[idx].rule_order = targetOrder;
  11146. list[targetIdx].rule_order = currentOrder;
  11147. try {
  11148. await fetch(`${API_BASE}/routing/filters`, {
  11149. method: 'POST',
  11150. headers: { 'Content-Type': 'application/json' },
  11151. body: JSON.stringify(list[idx])
  11152. });
  11153. await fetch(`${API_BASE}/routing/filters`, {
  11154. method: 'POST',
  11155. headers: { 'Content-Type': 'application/json' },
  11156. body: JSON.stringify(list[targetIdx])
  11157. });
  11158. loadDynamicRouting();
  11159. } catch (e) {
  11160. console.error('Reorder error:', e);
  11161. }
  11162. }
  11163. async function deleteRoutingFilter(id) {
  11164. if (!confirm('Are you sure you want to delete this routing filter rule?')) return;
  11165. try {
  11166. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11167. if (res.ok) {
  11168. showToast('Deleted', 'Routing filter rule removed', 'info');
  11169. loadDynamicRouting();
  11170. } else {
  11171. const err = await res.json();
  11172. showToast('Error', err.error || 'Failed to delete rule', 'error');
  11173. }
  11174. } catch (err) {
  11175. showToast('Error', err.message, 'error');
  11176. }
  11177. }
  11178. async function toggleRoutingFilterState(id, disabled) {
  11179. try {
  11180. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}/state`, {
  11181. method: 'POST',
  11182. headers: { 'Content-Type': 'application/json' },
  11183. body: JSON.stringify({ disabled })
  11184. });
  11185. if (res.ok) {
  11186. showToast('Status Updated', `Rule ${disabled ? 'disabled' : 'enabled'}`, 'info');
  11187. loadDynamicRouting();
  11188. } else {
  11189. const err = await res.json();
  11190. showToast('Error', err.error || 'Failed to toggle rule state', 'error');
  11191. }
  11192. } catch (err) {
  11193. showToast('Error', err.message, 'error');
  11194. }
  11195. }
  11196. // -------------------------------------------------------------
  11197. // MODAL CRUD: SELECT RULES (/routing filter select-rule)
  11198. // -------------------------------------------------------------
  11199. function openAddSelectRuleModal() {
  11200. document.getElementById('modal-rf-sr-id').value = '';
  11201. document.getElementById('modal-rf-sr-title').innerText = 'Add Routing Select Rule';
  11202. document.getElementById('modal-rf-sr-chain').value = state.filterChainSelected && state.filterChainSelected !== 'all' ? state.filterChainSelected : 'bgp-out';
  11203. document.getElementById('modal-rf-sr-order').value = ((state.routingSelectRules || []).length + 1) * 10;
  11204. document.getElementById('modal-rf-sr-rule').value = 'if (protocol bgp && dst in 10.0.0.0/8) { accept; }';
  11205. document.getElementById('modal-rf-sr-comment').value = '';
  11206. document.getElementById('modal-rf-sr-disabled').checked = false;
  11207. document.getElementById('modal-rf-select-rule').classList.remove('hidden');
  11208. }
  11209. function openEditSelectRuleModal(id) {
  11210. const r = (state.routingSelectRules || []).find(item => item.id === id);
  11211. if (!r) return;
  11212. document.getElementById('modal-rf-sr-id').value = r.id;
  11213. document.getElementById('modal-rf-sr-title').innerText = 'Edit Routing Select Rule';
  11214. document.getElementById('modal-rf-sr-chain').value = r.chain || '';
  11215. document.getElementById('modal-rf-sr-order').value = r.rule_order || 10;
  11216. document.getElementById('modal-rf-sr-rule').value = r.rule || '';
  11217. document.getElementById('modal-rf-sr-comment').value = r.comment || '';
  11218. document.getElementById('modal-rf-sr-disabled').checked = !!r.disabled;
  11219. document.getElementById('modal-rf-select-rule').classList.remove('hidden');
  11220. }
  11221. function closeSelectRuleModal() {
  11222. document.getElementById('modal-rf-select-rule').classList.add('hidden');
  11223. }
  11224. async function submitSelectRule(e) {
  11225. e.preventDefault();
  11226. const payload = {
  11227. id: document.getElementById('modal-rf-sr-id').value,
  11228. chain: document.getElementById('modal-rf-sr-chain').value.trim(),
  11229. rule_order: parseInt(document.getElementById('modal-rf-sr-order').value, 10) || 10,
  11230. rule: document.getElementById('modal-rf-sr-rule').value.trim(),
  11231. comment: document.getElementById('modal-rf-sr-comment').value.trim(),
  11232. disabled: document.getElementById('modal-rf-sr-disabled').checked
  11233. };
  11234. try {
  11235. const res = await fetch(`${API_BASE}/routing/filters/select-rules`, {
  11236. method: 'POST',
  11237. headers: { 'Content-Type': 'application/json' },
  11238. body: JSON.stringify(payload)
  11239. });
  11240. if (res.ok) {
  11241. closeSelectRuleModal();
  11242. showToast('Success', 'Select rule saved', 'success');
  11243. loadDynamicRouting();
  11244. } else {
  11245. const err = await res.json();
  11246. showToast('Error', err.error || 'Failed to save select rule', 'error');
  11247. }
  11248. } catch (err) {
  11249. showToast('Error', err.message, 'error');
  11250. }
  11251. }
  11252. async function deleteSelectRule(id) {
  11253. if (!confirm('Are you sure you want to delete this select rule?')) return;
  11254. try {
  11255. const res = await fetch(`${API_BASE}/routing/filters/select-rules/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11256. if (res.ok) {
  11257. showToast('Deleted', 'Select rule removed', 'info');
  11258. loadDynamicRouting();
  11259. } else {
  11260. const err = await res.json();
  11261. showToast('Error', err.error || 'Failed to delete select rule', 'error');
  11262. }
  11263. } catch (err) {
  11264. showToast('Error', err.message, 'error');
  11265. }
  11266. }
  11267. async function toggleSelectRuleState(id, disabled) {
  11268. try {
  11269. const res = await fetch(`${API_BASE}/routing/filters/select-rules/${encodeURIComponent(id)}/state`, {
  11270. method: 'POST',
  11271. headers: { 'Content-Type': 'application/json' },
  11272. body: JSON.stringify({ disabled })
  11273. });
  11274. if (res.ok) {
  11275. showToast('Status Updated', `Select rule ${disabled ? 'disabled' : 'enabled'}`, 'info');
  11276. loadDynamicRouting();
  11277. } else {
  11278. const err = await res.json();
  11279. showToast('Error', err.error || 'Failed to update select rule state', 'error');
  11280. }
  11281. } catch (err) {
  11282. showToast('Error', err.message, 'error');
  11283. }
  11284. }
  11285. // -------------------------------------------------------------
  11286. // MODAL CRUD: COMMUNITY LISTS (/routing filter community-list)
  11287. // -------------------------------------------------------------
  11288. function openAddCommunityListModal() {
  11289. document.getElementById('modal-rf-cl-id').value = '';
  11290. document.getElementById('modal-rf-cl-title').innerText = 'Add BGP Community List';
  11291. document.getElementById('modal-rf-cl-name').value = '';
  11292. document.getElementById('modal-rf-cl-communities').value = '';
  11293. document.getElementById('modal-rf-cl-regexp').value = '';
  11294. document.getElementById('modal-rf-cl-comment').value = '';
  11295. document.getElementById('modal-rf-cl-disabled').checked = false;
  11296. document.getElementById('modal-rf-community-list').classList.remove('hidden');
  11297. }
  11298. function openEditCommunityListModal(id) {
  11299. const cl = (state.routingCommunityLists || []).find(item => item.id === id);
  11300. if (!cl) return;
  11301. document.getElementById('modal-rf-cl-id').value = cl.id;
  11302. document.getElementById('modal-rf-cl-title').innerText = 'Edit BGP Community List';
  11303. document.getElementById('modal-rf-cl-name').value = cl.name || '';
  11304. document.getElementById('modal-rf-cl-communities').value = (cl.communities || []).join(', ');
  11305. document.getElementById('modal-rf-cl-regexp').value = cl.regexp || '';
  11306. document.getElementById('modal-rf-cl-comment').value = cl.comment || '';
  11307. document.getElementById('modal-rf-cl-disabled').checked = !!cl.disabled;
  11308. document.getElementById('modal-rf-community-list').classList.remove('hidden');
  11309. }
  11310. function closeCommunityListModal() {
  11311. document.getElementById('modal-rf-community-list').classList.add('hidden');
  11312. }
  11313. async function submitCommunityList(e) {
  11314. e.preventDefault();
  11315. const rawComms = document.getElementById('modal-rf-cl-communities').value;
  11316. const comms = rawComms.split(',').map(c => c.trim()).filter(Boolean);
  11317. const payload = {
  11318. id: document.getElementById('modal-rf-cl-id').value,
  11319. name: document.getElementById('modal-rf-cl-name').value.trim(),
  11320. communities: comms,
  11321. regexp: document.getElementById('modal-rf-cl-regexp').value.trim(),
  11322. comment: document.getElementById('modal-rf-cl-comment').value.trim(),
  11323. disabled: document.getElementById('modal-rf-cl-disabled').checked
  11324. };
  11325. try {
  11326. const res = await fetch(`${API_BASE}/routing/filters/community-lists`, {
  11327. method: 'POST',
  11328. headers: { 'Content-Type': 'application/json' },
  11329. body: JSON.stringify(payload)
  11330. });
  11331. if (res.ok) {
  11332. closeCommunityListModal();
  11333. showToast('Success', 'Community list saved', 'success');
  11334. loadDynamicRouting();
  11335. } else {
  11336. const err = await res.json();
  11337. showToast('Error', err.error || 'Failed to save community list', 'error');
  11338. }
  11339. } catch (err) {
  11340. showToast('Error', err.message, 'error');
  11341. }
  11342. }
  11343. async function deleteCommunityList(id) {
  11344. if (!confirm('Are you sure you want to delete this community list?')) return;
  11345. try {
  11346. const res = await fetch(`${API_BASE}/routing/filters/community-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11347. if (res.ok) {
  11348. showToast('Deleted', 'Community list removed', 'info');
  11349. loadDynamicRouting();
  11350. } else {
  11351. const err = await res.json();
  11352. showToast('Error', err.error || 'Failed to delete community list', 'error');
  11353. }
  11354. } catch (err) {
  11355. showToast('Error', err.message, 'error');
  11356. }
  11357. }
  11358. async function toggleCommunityListState(id, disabled) {
  11359. try {
  11360. const res = await fetch(`${API_BASE}/routing/filters/community-lists/${encodeURIComponent(id)}/state`, {
  11361. method: 'POST',
  11362. headers: { 'Content-Type': 'application/json' },
  11363. body: JSON.stringify({ disabled })
  11364. });
  11365. if (res.ok) {
  11366. showToast('Status Updated', `Community list ${disabled ? 'disabled' : 'enabled'}`, 'info');
  11367. loadDynamicRouting();
  11368. } else {
  11369. const err = await res.json();
  11370. showToast('Error', err.error || 'Failed to update community list state', 'error');
  11371. }
  11372. } catch (err) {
  11373. showToast('Error', err.message, 'error');
  11374. }
  11375. }
  11376. // -------------------------------------------------------------
  11377. // MODAL CRUD: AS LISTS (/routing filter num-list)
  11378. // -------------------------------------------------------------
  11379. function openAddASListModal() {
  11380. document.getElementById('modal-rf-al-id').value = '';
  11381. document.getElementById('modal-rf-al-title').innerText = 'Add AS Number List';
  11382. document.getElementById('modal-rf-al-name').value = '';
  11383. document.getElementById('modal-rf-al-range').value = '';
  11384. document.getElementById('modal-rf-al-comment').value = '';
  11385. document.getElementById('modal-rf-al-disabled').checked = false;
  11386. document.getElementById('modal-rf-as-list').classList.remove('hidden');
  11387. }
  11388. function openEditASListModal(id) {
  11389. const al = (state.routingASLists || []).find(item => item.id === id);
  11390. if (!al) return;
  11391. document.getElementById('modal-rf-al-id').value = al.id;
  11392. document.getElementById('modal-rf-al-title').innerText = 'Edit AS Number List';
  11393. document.getElementById('modal-rf-al-name').value = al.name || '';
  11394. document.getElementById('modal-rf-al-range').value = al.range || '';
  11395. document.getElementById('modal-rf-al-comment').value = al.comment || '';
  11396. document.getElementById('modal-rf-al-disabled').checked = !!al.disabled;
  11397. document.getElementById('modal-rf-as-list').classList.remove('hidden');
  11398. }
  11399. function closeASListModal() {
  11400. document.getElementById('modal-rf-as-list').classList.add('hidden');
  11401. }
  11402. async function submitASList(e) {
  11403. e.preventDefault();
  11404. const payload = {
  11405. id: document.getElementById('modal-rf-al-id').value,
  11406. name: document.getElementById('modal-rf-al-name').value.trim(),
  11407. range: document.getElementById('modal-rf-al-range').value.trim(),
  11408. comment: document.getElementById('modal-rf-al-comment').value.trim(),
  11409. disabled: document.getElementById('modal-rf-al-disabled').checked
  11410. };
  11411. try {
  11412. const res = await fetch(`${API_BASE}/routing/filters/as-lists`, {
  11413. method: 'POST',
  11414. headers: { 'Content-Type': 'application/json' },
  11415. body: JSON.stringify(payload)
  11416. });
  11417. if (res.ok) {
  11418. closeASListModal();
  11419. showToast('Success', 'AS number list saved', 'success');
  11420. loadDynamicRouting();
  11421. } else {
  11422. const err = await res.json();
  11423. showToast('Error', err.error || 'Failed to save AS list', 'error');
  11424. }
  11425. } catch (err) {
  11426. showToast('Error', err.message, 'error');
  11427. }
  11428. }
  11429. async function deleteASList(id) {
  11430. if (!confirm('Are you sure you want to delete this AS list?')) return;
  11431. try {
  11432. const res = await fetch(`${API_BASE}/routing/filters/as-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11433. if (res.ok) {
  11434. showToast('Deleted', 'AS list removed', 'info');
  11435. loadDynamicRouting();
  11436. } else {
  11437. const err = await res.json();
  11438. showToast('Error', err.error || 'Failed to delete AS list', 'error');
  11439. }
  11440. } catch (err) {
  11441. showToast('Error', err.message, 'error');
  11442. }
  11443. }
  11444. async function toggleASListState(id, disabled) {
  11445. try {
  11446. const res = await fetch(`${API_BASE}/routing/filters/as-lists/${encodeURIComponent(id)}/state`, {
  11447. method: 'POST',
  11448. headers: { 'Content-Type': 'application/json' },
  11449. body: JSON.stringify({ disabled })
  11450. });
  11451. if (res.ok) {
  11452. showToast('Status Updated', `AS list ${disabled ? 'disabled' : 'enabled'}`, 'info');
  11453. loadDynamicRouting();
  11454. } else {
  11455. const err = await res.json();
  11456. showToast('Error', err.error || 'Failed to update AS list state', 'error');
  11457. }
  11458. } catch (err) {
  11459. showToast('Error', err.message, 'error');
  11460. }
  11461. }
  11462. // ==========================================
  11463. // TROUBLESHOOT & DIAGNOSTIC TOOLS (/tool)
  11464. // ==========================================
  11465. function loadToolsView() {
  11466. populateToolsInterfaces();
  11467. switchToolsSubTab(state.activeToolsSubTab || 'ping');
  11468. }
  11469. function populateToolsInterfaces() {
  11470. const pingSel = document.getElementById('tools-ping-iface');
  11471. const traceSel = document.getElementById('tools-tr-iface');
  11472. let opts = '<option value="">Auto (Default Route)</option>';
  11473. if (Array.isArray(state.interfaces)) {
  11474. state.interfaces.forEach(iface => {
  11475. if (iface.name) {
  11476. opts += `<option value="${escapeHtml(iface.name)}">${escapeHtml(iface.name)}${iface.ip_address ? ' (' + escapeHtml(iface.ip_address) + ')' : ''}</option>`;
  11477. }
  11478. });
  11479. }
  11480. if (pingSel) {
  11481. const cur = pingSel.value;
  11482. pingSel.innerHTML = opts;
  11483. if (cur) pingSel.value = cur;
  11484. }
  11485. if (traceSel) {
  11486. const cur = traceSel.value;
  11487. traceSel.innerHTML = opts;
  11488. if (cur) traceSel.value = cur;
  11489. }
  11490. }
  11491. function switchToolsSubTab(subTab) {
  11492. state.activeToolsSubTab = subTab;
  11493. const tabs = ['ping', 'traceroute', 'mtr', 'dns', 'port'];
  11494. tabs.forEach(t => {
  11495. const btn = document.getElementById(`tools-subtab-btn-${t}`);
  11496. const view = document.getElementById(`tools-view-${t}`);
  11497. if (btn) {
  11498. if (t === subTab) {
  11499. 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';
  11500. } else {
  11501. 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';
  11502. }
  11503. }
  11504. if (view) {
  11505. if (t === subTab) {
  11506. view.classList.remove('hidden');
  11507. } else {
  11508. view.classList.add('hidden');
  11509. }
  11510. }
  11511. });
  11512. }
  11513. function setPortPreset(port) {
  11514. const input = document.getElementById('tools-port-num');
  11515. if (input) input.value = port;
  11516. }
  11517. let pingAbortController = null;
  11518. let tracerouteAbortController = null;
  11519. function clearPingTable() {
  11520. const tbody = document.getElementById('tools-ping-tbody');
  11521. if (tbody) tbody.innerHTML = '';
  11522. const rawEl = document.getElementById('tools-ping-raw');
  11523. if (rawEl) rawEl.innerText = '';
  11524. const sentEl = document.getElementById('tools-ping-stat-sent');
  11525. if (sentEl) sentEl.innerText = '0';
  11526. const recvEl = document.getElementById('tools-ping-stat-recv');
  11527. if (recvEl) recvEl.innerText = '0';
  11528. const lossEl = document.getElementById('tools-ping-stat-loss');
  11529. if (lossEl) lossEl.innerText = '0%';
  11530. const avgEl = document.getElementById('tools-ping-stat-avg');
  11531. if (avgEl) avgEl.innerText = '0 ms';
  11532. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  11533. if (minMaxEl) minMaxEl.innerText = '-';
  11534. const badge = document.getElementById('tools-ping-status-badge');
  11535. if (badge) {
  11536. badge.className = '';
  11537. badge.innerText = '';
  11538. }
  11539. }
  11540. function clearTracerouteTable() {
  11541. const tbody = document.getElementById('tools-tr-tbody');
  11542. if (tbody) tbody.innerHTML = '';
  11543. const rawEl = document.getElementById('tools-tr-raw');
  11544. if (rawEl) rawEl.innerText = '';
  11545. const statHops = document.getElementById('tools-tr-hops-count');
  11546. if (statHops) statHops.innerText = '0 Hops';
  11547. }
  11548. function resetPingButton() {
  11549. const btn = document.getElementById('tools-ping-btn');
  11550. const btnText = document.getElementById('tools-ping-btn-text');
  11551. const spinner = document.getElementById('tools-ping-spinner');
  11552. if (btn) {
  11553. btn.disabled = false;
  11554. 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';
  11555. }
  11556. if (btnText) btnText.innerText = 'Start Ping';
  11557. if (spinner) spinner.classList.add('hidden');
  11558. }
  11559. function setPingRunningButton() {
  11560. const btn = document.getElementById('tools-ping-btn');
  11561. const btnText = document.getElementById('tools-ping-btn-text');
  11562. const spinner = document.getElementById('tools-ping-spinner');
  11563. if (btn) {
  11564. btn.disabled = false;
  11565. 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';
  11566. }
  11567. if (btnText) btnText.innerText = 'Stop Ping';
  11568. if (spinner) spinner.classList.remove('hidden');
  11569. }
  11570. function resetTracerouteButton() {
  11571. const btn = document.getElementById('tools-tr-btn');
  11572. const btnText = document.getElementById('tools-tr-btn-text');
  11573. const spinner = document.getElementById('tools-tr-spinner');
  11574. if (btn) {
  11575. btn.disabled = false;
  11576. 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';
  11577. }
  11578. if (btnText) btnText.innerText = 'Start Traceroute';
  11579. if (spinner) spinner.classList.add('hidden');
  11580. }
  11581. function setTracerouteRunningButton() {
  11582. const btn = document.getElementById('tools-tr-btn');
  11583. const btnText = document.getElementById('tools-tr-btn-text');
  11584. const spinner = document.getElementById('tools-tr-spinner');
  11585. if (btn) {
  11586. btn.disabled = false;
  11587. 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';
  11588. }
  11589. if (btnText) btnText.innerText = 'Stop Traceroute';
  11590. if (spinner) spinner.classList.remove('hidden');
  11591. }
  11592. async function executePing(e) {
  11593. if (e) e.preventDefault();
  11594. // If already running, clicking the button stops the stream!
  11595. if (pingAbortController) {
  11596. pingAbortController.abort();
  11597. pingAbortController = null;
  11598. resetPingButton();
  11599. showToast('Ping Stopped', 'Live ping stopped by user', 'info');
  11600. return;
  11601. }
  11602. const target = document.getElementById('tools-ping-target')?.value?.trim();
  11603. const count = parseInt(document.getElementById('tools-ping-count')?.value || '4', 10);
  11604. const size = parseInt(document.getElementById('tools-ping-size')?.value || '56', 10);
  11605. const timeout = parseInt(document.getElementById('tools-ping-timeout')?.value || '3', 10);
  11606. const iface = document.getElementById('tools-ping-iface')?.value || '';
  11607. const dontFrag = document.getElementById('tools-ping-df')?.checked || false;
  11608. if (!target) {
  11609. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  11610. return;
  11611. }
  11612. clearPingTable();
  11613. const resCard = document.getElementById('tools-ping-results');
  11614. if (resCard) resCard.classList.remove('hidden');
  11615. pingAbortController = new AbortController();
  11616. setPingRunningButton();
  11617. try {
  11618. const res = await fetch(`${API_BASE}/tools/ping/stream`, {
  11619. method: 'POST',
  11620. headers: { 'Content-Type': 'application/json' },
  11621. body: JSON.stringify({
  11622. target,
  11623. count,
  11624. size,
  11625. timeout,
  11626. interface: iface,
  11627. dont_frag: dontFrag
  11628. }),
  11629. signal: pingAbortController.signal
  11630. });
  11631. if (!res.ok) {
  11632. const errText = await res.text();
  11633. showToast('Ping Error', errText || 'Failed to start live ping', 'error');
  11634. resetPingButton();
  11635. pingAbortController = null;
  11636. return;
  11637. }
  11638. const reader = res.body.getReader();
  11639. const decoder = new TextDecoder('utf-8');
  11640. let buffer = '';
  11641. while (true) {
  11642. const { done, value } = await reader.read();
  11643. if (done) break;
  11644. buffer += decoder.decode(value, { stream: true });
  11645. const blocks = buffer.split('\n\n');
  11646. buffer = blocks.pop() || '';
  11647. for (const block of blocks) {
  11648. const trimmed = block.trim();
  11649. if (!trimmed) continue;
  11650. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  11651. try {
  11652. const evt = JSON.parse(line);
  11653. handleLivePingEvent(evt);
  11654. } catch (parseErr) {
  11655. console.warn('Ping SSE parse error:', parseErr, line);
  11656. }
  11657. }
  11658. }
  11659. } catch (err) {
  11660. if (err.name === 'AbortError') {
  11661. // User aborted normally
  11662. } else {
  11663. showToast('Ping Error', err.message, 'error');
  11664. }
  11665. } finally {
  11666. pingAbortController = null;
  11667. resetPingButton();
  11668. }
  11669. }
  11670. function handleLivePingEvent(evt) {
  11671. const sentEl = document.getElementById('tools-ping-stat-sent');
  11672. const recvEl = document.getElementById('tools-ping-stat-recv');
  11673. const lossEl = document.getElementById('tools-ping-stat-loss');
  11674. const avgEl = document.getElementById('tools-ping-stat-avg');
  11675. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  11676. const badge = document.getElementById('tools-ping-status-badge');
  11677. const tbody = document.getElementById('tools-ping-tbody');
  11678. const rawEl = document.getElementById('tools-ping-raw');
  11679. if (evt.raw && rawEl) {
  11680. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  11681. rawEl.scrollTop = rawEl.scrollHeight;
  11682. }
  11683. if (evt.type === 'reply') {
  11684. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  11685. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  11686. if (lossEl && evt.packet_loss_pct !== undefined) {
  11687. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  11688. lossEl.className = evt.packet_loss_pct === 0
  11689. ? 'text-base font-bold font-mono text-emerald-400 mt-1'
  11690. : (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');
  11691. }
  11692. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  11693. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  11694. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  11695. }
  11696. if (badge) {
  11697. if (evt.packet_loss_pct === 0) {
  11698. 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';
  11699. badge.innerText = '100% OK';
  11700. } else {
  11701. 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';
  11702. badge.innerText = `${evt.packet_loss_pct.toFixed(0)}% LOSS`;
  11703. }
  11704. }
  11705. if (tbody) {
  11706. const tr = document.createElement('tr');
  11707. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  11708. tr.innerHTML = `
  11709. <td class="py-2 px-3 text-slate-300">#${evt.seq}</td>
  11710. <td class="py-2 px-3 font-semibold text-white">${escapeHtml(evt.from)}</td>
  11711. <td class="py-2 px-3 text-slate-400">${evt.bytes} bytes</td>
  11712. <td class="py-2 px-3 text-slate-300">${evt.ttl}</td>
  11713. <td class="py-2 px-3 font-bold text-amber-300">${evt.time_ms.toFixed(2)} ms</td>
  11714. <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>
  11715. `;
  11716. tbody.appendChild(tr);
  11717. }
  11718. } else if (evt.type === 'timeout') {
  11719. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  11720. if (lossEl && evt.packet_loss_pct !== undefined) {
  11721. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  11722. 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';
  11723. }
  11724. if (badge) {
  11725. 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';
  11726. badge.innerText = `${evt.packet_loss_pct?.toFixed(0) || 100}% LOSS`;
  11727. }
  11728. if (tbody) {
  11729. const tr = document.createElement('tr');
  11730. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs opacity-75';
  11731. tr.innerHTML = `
  11732. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  11733. <td class="py-2 px-3 font-semibold text-slate-500 italic">Request timed out</td>
  11734. <td class="py-2 px-3 text-slate-600">--</td>
  11735. <td class="py-2 px-3 text-slate-600">--</td>
  11736. <td class="py-2 px-3 font-bold text-slate-500">* * *</td>
  11737. <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>
  11738. `;
  11739. tbody.appendChild(tr);
  11740. }
  11741. } else if (evt.type === 'unreach') {
  11742. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  11743. if (lossEl && evt.packet_loss_pct !== undefined) {
  11744. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  11745. lossEl.className = 'text-base font-bold font-mono text-rose-400 mt-1';
  11746. }
  11747. if (badge) {
  11748. 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';
  11749. badge.innerText = 'UNREACHABLE';
  11750. }
  11751. if (tbody) {
  11752. const tr = document.createElement('tr');
  11753. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  11754. tr.innerHTML = `
  11755. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  11756. <td class="py-2 px-3 font-semibold text-rose-400">${escapeHtml(evt.from || 'Gateway')}</td>
  11757. <td class="py-2 px-3 text-slate-600">--</td>
  11758. <td class="py-2 px-3 text-slate-600">--</td>
  11759. <td class="py-2 px-3 font-bold text-rose-400 text-xs">${escapeHtml(evt.message || 'Unreachable')}</td>
  11760. <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>
  11761. `;
  11762. tbody.appendChild(tr);
  11763. }
  11764. } else if (evt.type === 'stats') {
  11765. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  11766. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  11767. if (lossEl && evt.packet_loss_pct !== undefined) lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  11768. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  11769. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  11770. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  11771. }
  11772. } else if (evt.type === 'done') {
  11773. 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');
  11774. }
  11775. }
  11776. async function executeTraceroute(e) {
  11777. if (e) e.preventDefault();
  11778. if (tracerouteAbortController) {
  11779. tracerouteAbortController.abort();
  11780. tracerouteAbortController = null;
  11781. resetTracerouteButton();
  11782. showToast('Traceroute Stopped', 'Traceroute stopped by user', 'info');
  11783. return;
  11784. }
  11785. const target = document.getElementById('tools-tr-target')?.value?.trim();
  11786. const maxHops = parseInt(document.getElementById('tools-tr-maxhops')?.value || '15', 10);
  11787. const protocol = document.getElementById('tools-tr-proto')?.value || 'icmp';
  11788. const iface = document.getElementById('tools-tr-iface')?.value || '';
  11789. const resolve = document.getElementById('tools-tr-resolve')?.checked || false;
  11790. if (!target) {
  11791. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  11792. return;
  11793. }
  11794. clearTracerouteTable();
  11795. const resCard = document.getElementById('tools-tr-results');
  11796. if (resCard) resCard.classList.remove('hidden');
  11797. tracerouteAbortController = new AbortController();
  11798. setTracerouteRunningButton();
  11799. try {
  11800. const res = await fetch(`${API_BASE}/tools/traceroute/stream`, {
  11801. method: 'POST',
  11802. headers: { 'Content-Type': 'application/json' },
  11803. body: JSON.stringify({
  11804. target,
  11805. max_hops: maxHops,
  11806. protocol,
  11807. interface: iface,
  11808. resolve
  11809. }),
  11810. signal: tracerouteAbortController.signal
  11811. });
  11812. if (!res.ok) {
  11813. const errText = await res.text();
  11814. showToast('Traceroute Error', errText || 'Failed to start traceroute', 'error');
  11815. resetTracerouteButton();
  11816. tracerouteAbortController = null;
  11817. return;
  11818. }
  11819. const reader = res.body.getReader();
  11820. const decoder = new TextDecoder('utf-8');
  11821. let buffer = '';
  11822. while (true) {
  11823. const { done, value } = await reader.read();
  11824. if (done) break;
  11825. buffer += decoder.decode(value, { stream: true });
  11826. const blocks = buffer.split('\n\n');
  11827. buffer = blocks.pop() || '';
  11828. for (const block of blocks) {
  11829. const trimmed = block.trim();
  11830. if (!trimmed) continue;
  11831. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  11832. try {
  11833. const evt = JSON.parse(line);
  11834. handleLiveTracerouteEvent(evt);
  11835. } catch (parseErr) {
  11836. console.warn('Traceroute SSE parse error:', parseErr, line);
  11837. }
  11838. }
  11839. }
  11840. } catch (err) {
  11841. if (err.name === 'AbortError') {
  11842. // User aborted normally
  11843. } else {
  11844. showToast('Traceroute Error', err.message, 'error');
  11845. }
  11846. } finally {
  11847. tracerouteAbortController = null;
  11848. resetTracerouteButton();
  11849. }
  11850. }
  11851. function handleLiveTracerouteEvent(evt) {
  11852. const statHops = document.getElementById('tools-tr-hops-count');
  11853. const tbody = document.getElementById('tools-tr-tbody');
  11854. const rawEl = document.getElementById('tools-tr-raw');
  11855. if (evt.raw && rawEl) {
  11856. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  11857. rawEl.scrollTop = rawEl.scrollHeight;
  11858. }
  11859. if (evt.hops_count !== undefined && statHops) {
  11860. statHops.innerText = `${evt.hops_count} Hops`;
  11861. }
  11862. if (evt.type === 'hop' && evt.hop && tbody) {
  11863. const h = evt.hop;
  11864. const isTimeout = h.status === 'timeout' || (!h.ip && !h.host);
  11865. const rtt1 = Array.isArray(h.times_ms) && h.times_ms[0] ? `${h.times_ms[0]} ms` : (isTimeout ? '*' : '--');
  11866. const rtt2 = Array.isArray(h.times_ms) && h.times_ms[1] ? `${h.times_ms[1]} ms` : (isTimeout ? '*' : '--');
  11867. const displayHost = h.host && h.host !== h.ip ? `${escapeHtml(h.host)} (${escapeHtml(h.ip || '')})` : escapeHtml(h.ip || (isTimeout ? 'Request timed out' : '--'));
  11868. const tr = document.createElement('tr');
  11869. tr.className = `hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs ${isTimeout ? 'opacity-60' : ''}`;
  11870. tr.innerHTML = `
  11871. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  11872. <td class="py-2.5 px-3 font-semibold ${isTimeout ? 'text-slate-500 italic' : 'text-cyan-300'}">${displayHost}</td>
  11873. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt1)}</td>
  11874. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt2)}</td>
  11875. <td class="py-2.5 px-3 text-right">
  11876. ${isTimeout
  11877. ? '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-slate-800 text-slate-400 border border-slate-700">TIMEOUT</span>'
  11878. : '<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>'}
  11879. </td>
  11880. `;
  11881. tbody.appendChild(tr);
  11882. } else if (evt.type === 'done') {
  11883. showToast('Traceroute Finished', `Traced ${evt.hops_count || 0} hops`, 'info');
  11884. }
  11885. }
  11886. async function executeMTR(e) {
  11887. if (e) e.preventDefault();
  11888. const target = document.getElementById('tools-mtr-target')?.value?.trim();
  11889. const cycles = parseInt(document.getElementById('tools-mtr-count')?.value || '3', 10);
  11890. if (!target) {
  11891. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  11892. return;
  11893. }
  11894. const btn = document.getElementById('tools-mtr-btn');
  11895. const spinner = document.getElementById('tools-mtr-spinner');
  11896. if (btn) btn.disabled = true;
  11897. if (spinner) spinner.classList.remove('hidden');
  11898. try {
  11899. const res = await fetch(`${API_BASE}/tools/mtr`, {
  11900. method: 'POST',
  11901. headers: { 'Content-Type': 'application/json' },
  11902. body: JSON.stringify({ target, count: cycles })
  11903. });
  11904. const data = await res.json();
  11905. if (!res.ok) {
  11906. showToast('MTR Error', data.error || 'Failed to execute MTR', 'error');
  11907. return;
  11908. }
  11909. const resCard = document.getElementById('tools-mtr-results');
  11910. if (resCard) resCard.classList.remove('hidden');
  11911. const hopsCount = Array.isArray(data.hops) ? data.hops.length : 0;
  11912. const statHops = document.getElementById('tools-mtr-hops-count');
  11913. if (statHops) statHops.innerText = `${hopsCount} Hops`;
  11914. const tbody = document.getElementById('tools-mtr-tbody');
  11915. if (tbody) {
  11916. if (hopsCount > 0) {
  11917. tbody.innerHTML = data.hops.map(h => {
  11918. 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');
  11919. return `
  11920. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  11921. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  11922. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(h.host || '--')}</td>
  11923. <td class="py-2.5 px-3 ${lossClass}">${h.loss_pct.toFixed(1)}%</td>
  11924. <td class="py-2.5 px-3 text-slate-300">${h.sent}</td>
  11925. <td class="py-2.5 px-3 text-slate-300">${h.last_ms.toFixed(1)}</td>
  11926. <td class="py-2.5 px-3 font-bold text-amber-300">${h.avg_ms.toFixed(1)}</td>
  11927. <td class="py-2.5 px-3 text-emerald-400">${h.best_ms.toFixed(1)}</td>
  11928. <td class="py-2.5 px-3 text-rose-400">${h.wrst_ms.toFixed(1)}</td>
  11929. <td class="py-2.5 px-3 text-slate-400">${h.stdev_ms.toFixed(1)}</td>
  11930. </tr>
  11931. `;
  11932. }).join('');
  11933. } else {
  11934. tbody.innerHTML = `<tr><td colspan="9" class="p-4 text-center text-xs text-rose-400 font-mono">No MTR data collected</td></tr>`;
  11935. }
  11936. }
  11937. const rawEl = document.getElementById('tools-mtr-raw');
  11938. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  11939. showToast('MTR Finished', `Report completed (${hopsCount} hops discovered)`, 'info');
  11940. } catch (err) {
  11941. showToast('MTR Error', err.message, 'error');
  11942. } finally {
  11943. if (btn) btn.disabled = false;
  11944. if (spinner) spinner.classList.add('hidden');
  11945. }
  11946. }
  11947. async function executeDNS(e) {
  11948. if (e) e.preventDefault();
  11949. const domain = document.getElementById('tools-dns-domain')?.value?.trim();
  11950. const type = document.getElementById('tools-dns-type')?.value || 'A';
  11951. const server = document.getElementById('tools-dns-server')?.value?.trim() || '';
  11952. if (!domain) {
  11953. showToast('Input Required', 'Please enter a hostname or domain', 'warning');
  11954. return;
  11955. }
  11956. const btn = document.getElementById('tools-dns-btn');
  11957. const spinner = document.getElementById('tools-dns-spinner');
  11958. if (btn) btn.disabled = true;
  11959. if (spinner) spinner.classList.remove('hidden');
  11960. try {
  11961. const res = await fetch(`${API_BASE}/tools/dns`, {
  11962. method: 'POST',
  11963. headers: { 'Content-Type': 'application/json' },
  11964. body: JSON.stringify({ domain, type, server })
  11965. });
  11966. const data = await res.json();
  11967. if (!res.ok) {
  11968. showToast('DNS Error', data.error || 'Failed to resolve DNS query', 'error');
  11969. return;
  11970. }
  11971. const resCard = document.getElementById('tools-dns-results');
  11972. if (resCard) resCard.classList.remove('hidden');
  11973. const metaEl = document.getElementById('tools-dns-meta');
  11974. if (metaEl) metaEl.innerText = `Resolved in ${data.query_time_ms ?? 0} ms via ${escapeHtml(data.server || 'System DNS')}`;
  11975. const tbody = document.getElementById('tools-dns-tbody');
  11976. if (tbody) {
  11977. if (Array.isArray(data.records) && data.records.length > 0) {
  11978. tbody.innerHTML = data.records.map(r => `
  11979. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  11980. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.name)}</td>
  11981. <td class="py-2.5 px-3 text-slate-400">${r.ttl}s</td>
  11982. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.class || 'IN')}</td>
  11983. <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>
  11984. <td class="py-2.5 px-3 font-bold text-amber-300 break-all">${escapeHtml(r.value)}</td>
  11985. </tr>
  11986. `).join('');
  11987. } else {
  11988. 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>`;
  11989. }
  11990. }
  11991. const rawEl = document.getElementById('tools-dns-raw');
  11992. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  11993. showToast('DNS Lookup Done', `Resolved ${domain} in ${data.query_time_ms} ms`, 'success');
  11994. } catch (err) {
  11995. showToast('DNS Error', err.message, 'error');
  11996. } finally {
  11997. if (btn) btn.disabled = false;
  11998. if (spinner) spinner.classList.add('hidden');
  11999. }
  12000. }
  12001. async function executePortProbe(e) {
  12002. if (e) e.preventDefault();
  12003. const target = document.getElementById('tools-port-target')?.value?.trim();
  12004. const port = parseInt(document.getElementById('tools-port-num')?.value || '80', 10);
  12005. const timeout = parseInt(document.getElementById('tools-port-timeout')?.value || '3', 10);
  12006. if (!target || !port) {
  12007. showToast('Input Required', 'Please enter a target host and TCP port', 'warning');
  12008. return;
  12009. }
  12010. const btn = document.getElementById('tools-port-btn');
  12011. const spinner = document.getElementById('tools-port-spinner');
  12012. if (btn) btn.disabled = true;
  12013. if (spinner) spinner.classList.remove('hidden');
  12014. try {
  12015. const res = await fetch(`${API_BASE}/tools/port-probe`, {
  12016. method: 'POST',
  12017. headers: { 'Content-Type': 'application/json' },
  12018. body: JSON.stringify({ target, port, timeout })
  12019. });
  12020. const data = await res.json();
  12021. if (!res.ok) {
  12022. showToast('Probe Error', data.error || 'Failed to probe TCP port', 'error');
  12023. return;
  12024. }
  12025. const resCard = document.getElementById('tools-port-results');
  12026. if (resCard) resCard.classList.remove('hidden');
  12027. const banner = document.getElementById('tools-port-banner');
  12028. const icon = document.getElementById('tools-port-icon');
  12029. const title = document.getElementById('tools-port-title');
  12030. const sub = document.getElementById('tools-port-sub');
  12031. const latency = document.getElementById('tools-port-latency');
  12032. if (data.open) {
  12033. if (banner) banner.className = 'rounded-xl p-5 border bg-emerald-950/30 border-emerald-800/50 flex items-center justify-between';
  12034. if (icon) {
  12035. 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';
  12036. icon.innerText = '✓';
  12037. }
  12038. if (title) {
  12039. title.className = 'text-sm font-bold text-emerald-300';
  12040. title.innerText = `PORT ${port} OPEN / LISTENING`;
  12041. }
  12042. if (sub) {
  12043. sub.className = 'text-xs mt-0.5 font-mono text-emerald-400/80';
  12044. sub.innerText = `TCP 3-way handshake established with ${escapeHtml(target)}:${port}${data.service ? ' (' + escapeHtml(data.service) + ')' : ''}`;
  12045. }
  12046. if (latency) {
  12047. latency.className = 'text-base font-bold font-mono text-emerald-300';
  12048. latency.innerText = `${data.latency_ms.toFixed(2)} ms`;
  12049. }
  12050. } else {
  12051. if (banner) banner.className = 'rounded-xl p-5 border bg-rose-950/30 border-rose-800/50 flex items-center justify-between';
  12052. if (icon) {
  12053. 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';
  12054. icon.innerText = '✕';
  12055. }
  12056. if (title) {
  12057. title.className = 'text-sm font-bold text-rose-300';
  12058. title.innerText = `PORT ${port} CLOSED / FILTERED`;
  12059. }
  12060. if (sub) {
  12061. sub.className = 'text-xs mt-0.5 font-mono text-rose-400/80';
  12062. sub.innerText = `Connection failed or timed out to ${escapeHtml(target)}:${port}`;
  12063. }
  12064. if (latency) {
  12065. latency.className = 'text-base font-bold font-mono text-slate-500';
  12066. latency.innerText = '--';
  12067. }
  12068. }
  12069. const rawEl = document.getElementById('tools-port-raw');
  12070. 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'}`);
  12071. showToast('Probe Complete', `Port ${port} is ${data.open ? 'OPEN' : 'CLOSED'}`, data.open ? 'success' : 'warning');
  12072. } catch (err) {
  12073. showToast('Probe Error', err.message, 'error');
  12074. } finally {
  12075. if (btn) btn.disabled = false;
  12076. if (spinner) spinner.classList.add('hidden');
  12077. }
  12078. }
  12079. // ==========================================
  12080. // DHCP CLIENT (/ip dhcp-client) CONTROLLER
  12081. // ==========================================
  12082. async function loadDHCPClients(showToastMsg = false) {
  12083. try {
  12084. const [clientsRes, sumRes] = await Promise.all([
  12085. fetch(`${API_BASE}/dhcp/clients`),
  12086. fetch(`${API_BASE}/dhcp/clients/summary`)
  12087. ]);
  12088. if (clientsRes.ok) {
  12089. state.dhcpClients = await clientsRes.json();
  12090. }
  12091. if (sumRes.ok) {
  12092. state.dhcpSummary = await sumRes.json();
  12093. }
  12094. renderDHCPClients();
  12095. updateDHCPSummaryCards();
  12096. const bDhcp = document.getElementById('badge-dhcp-client-count');
  12097. if (bDhcp && state.dhcpSummary) {
  12098. bDhcp.innerText = state.dhcpSummary.total_clients || 0;
  12099. }
  12100. if (showToastMsg) {
  12101. showToast('Refreshed', 'DHCP Client telemetry updated', 'info');
  12102. }
  12103. } catch (err) {
  12104. console.error('Failed to load DHCP clients:', err);
  12105. if (showToastMsg) {
  12106. showToast('Notice', 'Unable to fetch DHCP client status', 'warning');
  12107. }
  12108. }
  12109. }
  12110. function updateDHCPSummaryCards() {
  12111. const sum = state.dhcpSummary || {
  12112. total_clients: (state.dhcpClients || []).length,
  12113. bound_clients: (state.dhcpClients || []).filter(c => c.status === 'bound').length,
  12114. searching_clients: (state.dhcpClients || []).filter(c => c.status === 'searching').length,
  12115. disabled_clients: (state.dhcpClients || []).filter(c => !c.enabled).length
  12116. };
  12117. const totalEl = document.getElementById('dhcp-stat-total');
  12118. const boundEl = document.getElementById('dhcp-stat-bound');
  12119. const searchEl = document.getElementById('dhcp-stat-searching');
  12120. const disEl = document.getElementById('dhcp-stat-disabled');
  12121. if (totalEl) totalEl.innerText = sum.total_clients ?? 0;
  12122. if (boundEl) boundEl.innerText = sum.bound_clients ?? 0;
  12123. if (searchEl) searchEl.innerText = sum.searching_clients ?? 0;
  12124. if (disEl) disEl.innerText = sum.disabled_clients ?? 0;
  12125. }
  12126. function renderDHCPClients() {
  12127. const tbody = document.getElementById('dhcp-clients-tbody');
  12128. const emptyState = document.getElementById('dhcp-clients-empty');
  12129. if (!tbody) return;
  12130. const clients = Array.isArray(state.dhcpClients) ? state.dhcpClients : [];
  12131. if (clients.length === 0) {
  12132. tbody.innerHTML = '';
  12133. if (emptyState) emptyState.classList.remove('hidden');
  12134. return;
  12135. }
  12136. if (emptyState) emptyState.classList.add('hidden');
  12137. const sig = clients.map(c => `${c.id}:${c.status}:${c.ip_address}:${c.gateway}:${c.enabled}`).join(';');
  12138. if (tbody.dataset.sig === sig) return;
  12139. tbody.dataset.sig = sig;
  12140. tbody.innerHTML = clients.map(c => {
  12141. let statusBadge = '';
  12142. if (!c.enabled) {
  12143. 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>';
  12144. } else if (c.status === 'bound') {
  12145. 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>';
  12146. } else if (c.status === 'searching') {
  12147. 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>';
  12148. } else if (c.status === 'stopped') {
  12149. 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>';
  12150. } else {
  12151. 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>`;
  12152. }
  12153. 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>';
  12154. const gwDisplay = c.gateway ? `<span class="text-slate-300">${escapeHtml(c.gateway)}</span>` : '<span class="text-slate-600">--</span>';
  12155. const srvDisplay = c.dhcp_server ? `<span class="text-slate-300">${escapeHtml(c.dhcp_server)}</span>` : '<span class="text-slate-600">--</span>';
  12156. 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>';
  12157. const expDisplay = c.expires_in ? `<span class="text-purple-300">${escapeHtml(c.expires_in)}</span>` : '<span class="text-slate-600">--</span>';
  12158. // Option flags
  12159. const flags = [];
  12160. 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>');
  12161. 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>');
  12162. 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>');
  12163. 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>`);
  12164. return `
  12165. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 text-xs transition">
  12166. <td class="py-3 px-4">
  12167. <div class="flex items-center gap-2">
  12168. <span class="font-bold text-white text-sm">${escapeHtml(c.interface)}</span>
  12169. ${c.comment ? `<span class="text-[11px] text-slate-400 font-sans italic">(${escapeHtml(c.comment)})</span>` : ''}
  12170. </div>
  12171. </td>
  12172. <td class="py-3 px-4">${statusBadge}</td>
  12173. <td class="py-3 px-4 font-mono">${ipDisplay}</td>
  12174. <td class="py-3 px-4 font-mono">${gwDisplay}</td>
  12175. <td class="py-3 px-4 font-mono">${srvDisplay}</td>
  12176. <td class="py-3 px-4 font-mono text-[11px]">${dnsDisplay}</td>
  12177. <td class="py-3 px-4 font-mono text-[11px]">${expDisplay}</td>
  12178. <td class="py-3 px-4">
  12179. <div class="flex flex-wrap gap-1 font-mono">${flags.join('')}</div>
  12180. </td>
  12181. <td class="py-3 px-4 text-right space-x-1.5 font-sans whitespace-nowrap">
  12182. ${c.enabled ? `
  12183. <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>
  12184. <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>
  12185. <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>
  12186. ` : `
  12187. <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>
  12188. `}
  12189. <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>
  12190. <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>
  12191. </td>
  12192. </tr>
  12193. `;
  12194. }).join('');
  12195. }
  12196. function openDHCPClientModal(clientId = null) {
  12197. const modal = document.getElementById('modal-dhcp-client');
  12198. if (!modal) return;
  12199. const title = document.getElementById('modal-dhcp-title');
  12200. const idInput = document.getElementById('modal-dhcp-id');
  12201. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  12202. const distInput = document.getElementById('modal-dhcp-distance');
  12203. const commentInput = document.getElementById('modal-dhcp-comment');
  12204. const defRouteCheck = document.getElementById('modal-dhcp-def-route');
  12205. const peerDnsCheck = document.getElementById('modal-dhcp-peer-dns');
  12206. const peerNtpCheck = document.getElementById('modal-dhcp-peer-ntp');
  12207. const enabledCheck = document.getElementById('modal-dhcp-enabled');
  12208. // Populate interfaces
  12209. if (ifaceSelect) {
  12210. let opts = '<option value="">Select interface...</option>';
  12211. const allIfaces = state.interfaces || [];
  12212. const allVlans = state.vlans || [];
  12213. const usedIfaces = new Set((state.dhcpClients || []).map(c => c.interface));
  12214. // Group 1: Physical & Bridge Interfaces
  12215. opts += '<optgroup label="Physical & Bridge Interfaces">';
  12216. allIfaces.filter(i => supportsDHCPClient(i)).forEach(i => {
  12217. const isConfigured = usedIfaces.has(i.name) ? ' (Configured)' : '';
  12218. opts += `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)} [${escapeHtml(i.role || i.type)}]${isConfigured}</option>`;
  12219. });
  12220. opts += '</optgroup>';
  12221. // Group 2: VLAN Interfaces
  12222. if (allVlans.length > 0) {
  12223. opts += '<optgroup label="802.1Q VLAN Sub-interfaces">';
  12224. allVlans.forEach(v => {
  12225. const isConfigured = usedIfaces.has(v.name) ? ' (Configured)' : '';
  12226. opts += `<option value="${escapeHtml(v.name)}">${escapeHtml(v.name)} (VLAN ${v.vlan_id})${isConfigured}</option>`;
  12227. });
  12228. opts += '</optgroup>';
  12229. }
  12230. ifaceSelect.innerHTML = opts;
  12231. }
  12232. if (clientId) {
  12233. const client = (state.dhcpClients || []).find(c => c.id === clientId);
  12234. if (client) {
  12235. if (title) title.innerText = `Edit DHCP Client: ${client.interface}`;
  12236. if (idInput) idInput.value = client.id;
  12237. if (ifaceSelect) {
  12238. ifaceSelect.value = client.interface;
  12239. ifaceSelect.disabled = true; // interface cannot be changed on edit
  12240. }
  12241. if (distInput) distInput.value = client.default_route_distance || 1;
  12242. if (commentInput) commentInput.value = client.comment || '';
  12243. if (defRouteCheck) defRouteCheck.checked = client.add_default_route !== false;
  12244. if (peerDnsCheck) peerDnsCheck.checked = client.use_peer_dns !== false;
  12245. if (peerNtpCheck) peerNtpCheck.checked = client.use_peer_ntp !== false;
  12246. if (enabledCheck) enabledCheck.checked = client.enabled !== false;
  12247. }
  12248. } else {
  12249. if (title) title.innerText = 'Add DHCP Client';
  12250. if (idInput) idInput.value = '';
  12251. if (ifaceSelect) {
  12252. ifaceSelect.value = '';
  12253. ifaceSelect.disabled = false;
  12254. }
  12255. if (distInput) distInput.value = 1;
  12256. if (commentInput) commentInput.value = '';
  12257. if (defRouteCheck) defRouteCheck.checked = true;
  12258. if (peerDnsCheck) peerDnsCheck.checked = true;
  12259. if (peerNtpCheck) peerNtpCheck.checked = true;
  12260. if (enabledCheck) enabledCheck.checked = true;
  12261. }
  12262. modal.classList.remove('hidden');
  12263. }
  12264. function openDHCPClientModalForIface(ifaceName) {
  12265. openDHCPClientModal();
  12266. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  12267. if (ifaceSelect && ifaceName) {
  12268. ifaceSelect.value = ifaceName;
  12269. }
  12270. }
  12271. function closeDHCPClientModal() {
  12272. const modal = document.getElementById('modal-dhcp-client');
  12273. if (modal) modal.classList.add('hidden');
  12274. }
  12275. async function submitSaveDHCPClient(e) {
  12276. if (e) e.preventDefault();
  12277. const id = document.getElementById('modal-dhcp-id')?.value;
  12278. const iface = document.getElementById('modal-dhcp-iface')?.value?.trim();
  12279. const distance = parseInt(document.getElementById('modal-dhcp-distance')?.value || '1', 10);
  12280. const comment = document.getElementById('modal-dhcp-comment')?.value?.trim() || '';
  12281. const defRoute = document.getElementById('modal-dhcp-def-route')?.checked ?? true;
  12282. const peerDns = document.getElementById('modal-dhcp-peer-dns')?.checked ?? true;
  12283. const peerNtp = document.getElementById('modal-dhcp-peer-ntp')?.checked ?? true;
  12284. const enabled = document.getElementById('modal-dhcp-enabled')?.checked ?? true;
  12285. if (!id && !iface) {
  12286. showToast('Input Required', 'Please select an interface for the DHCP client', 'warning');
  12287. return;
  12288. }
  12289. try {
  12290. let res;
  12291. if (id) {
  12292. // PUT update
  12293. res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  12294. method: 'PUT',
  12295. headers: { 'Content-Type': 'application/json' },
  12296. body: JSON.stringify({
  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. } else {
  12306. // POST create
  12307. res = await fetch(`${API_BASE}/dhcp/clients`, {
  12308. method: 'POST',
  12309. headers: { 'Content-Type': 'application/json' },
  12310. body: JSON.stringify({
  12311. interface: iface,
  12312. enabled,
  12313. add_default_route: defRoute,
  12314. default_route_distance: distance,
  12315. use_peer_dns: peerDns,
  12316. use_peer_ntp: peerNtp,
  12317. comment
  12318. })
  12319. });
  12320. }
  12321. const data = await res.json();
  12322. if (!res.ok) {
  12323. showToast('Error', data.error || 'Failed to save DHCP client', 'error');
  12324. return;
  12325. }
  12326. closeDHCPClientModal();
  12327. showToast('Success', id ? 'DHCP Client updated successfully' : `DHCP Client activated on ${iface}`, 'success');
  12328. await loadDHCPClients();
  12329. fetchData(); // refresh interfaces list with new lease/status
  12330. } catch (err) {
  12331. showToast('Error', err.message, 'error');
  12332. }
  12333. }
  12334. async function toggleDHCPClientState(id, enabled) {
  12335. try {
  12336. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/state`, {
  12337. method: 'POST',
  12338. headers: { 'Content-Type': 'application/json' },
  12339. body: JSON.stringify({ enabled })
  12340. });
  12341. const data = await res.json();
  12342. if (!res.ok) {
  12343. showToast('Error', data.error || 'Failed to toggle client state', 'error');
  12344. return;
  12345. }
  12346. showToast('Updated', `DHCP client ${enabled ? 'enabled' : 'disabled'}`, 'info');
  12347. await loadDHCPClients();
  12348. fetchData();
  12349. } catch (err) {
  12350. showToast('Error', err.message, 'error');
  12351. }
  12352. }
  12353. async function renewDHCPClient(id) {
  12354. try {
  12355. showToast('Renewing...', 'Requesting DHCP lease renewal from upstream server', 'info');
  12356. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/renew`, {
  12357. method: 'POST'
  12358. });
  12359. const data = await res.json();
  12360. if (!res.ok) {
  12361. showToast('Error', data.error || 'Failed to renew lease', 'error');
  12362. return;
  12363. }
  12364. showToast('Lease Renewed', 'DHCP renewal signal sent successfully', 'success');
  12365. setTimeout(() => {
  12366. loadDHCPClients();
  12367. fetchData();
  12368. }, 1500);
  12369. } catch (err) {
  12370. showToast('Error', err.message, 'error');
  12371. }
  12372. }
  12373. async function releaseDHCPClient(id) {
  12374. try {
  12375. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/release`, {
  12376. method: 'POST'
  12377. });
  12378. const data = await res.json();
  12379. if (!res.ok) {
  12380. showToast('Error', data.error || 'Failed to release lease', 'error');
  12381. return;
  12382. }
  12383. showToast('Lease Released', 'DHCP lease released from upstream server', 'info');
  12384. await loadDHCPClients();
  12385. fetchData();
  12386. } catch (err) {
  12387. showToast('Error', err.message, 'error');
  12388. }
  12389. }
  12390. async function deleteDHCPClient(id, ifaceName) {
  12391. if (!confirm(`Are you sure you want to remove the DHCP Client on ${ifaceName}? The interface will release its dynamic IP.`)) {
  12392. return;
  12393. }
  12394. try {
  12395. const res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  12396. method: 'DELETE'
  12397. });
  12398. const data = await res.json();
  12399. if (!res.ok) {
  12400. showToast('Error', data.error || 'Failed to delete DHCP client', 'error');
  12401. return;
  12402. }
  12403. showToast('Deleted', `DHCP client removed from ${ifaceName}`, 'info');
  12404. await loadDHCPClients();
  12405. fetchData();
  12406. } catch (err) {
  12407. showToast('Error', err.message, 'error');
  12408. }
  12409. }
  12410. // ==================== DHCP SERVER (/ip dhcp-server) ====================
  12411. async function loadDHCPServer(populate = true) {
  12412. try {
  12413. const [sumRes, srvRes, netRes, leaseRes, optRes] = await Promise.all([
  12414. fetch(`${API_BASE}/dhcp-server/summary`),
  12415. fetch(`${API_BASE}/dhcp-server/servers`),
  12416. fetch(`${API_BASE}/dhcp-server/networks`),
  12417. fetch(`${API_BASE}/dhcp-server/leases`),
  12418. fetch(`${API_BASE}/dhcp-server/options`)
  12419. ]);
  12420. if (sumRes.ok) state.dhcpServerSummary = await sumRes.json();
  12421. if (srvRes.ok) state.dhcpServers = await srvRes.json();
  12422. if (netRes.ok) state.dhcpNetworks = await netRes.json();
  12423. if (leaseRes.ok) state.dhcpLeases = await leaseRes.json();
  12424. if (optRes.ok) state.dhcpOptions = await optRes.json();
  12425. const sum = state.dhcpServerSummary || {};
  12426. const srvs = state.dhcpServers || [];
  12427. const nets = state.dhcpNetworks || [];
  12428. const leases = state.dhcpLeases || [];
  12429. const opts = state.dhcpOptions || [];
  12430. // KPI Cards
  12431. const statActive = document.getElementById('dhcp-server-stat-active');
  12432. if (statActive) {
  12433. const activeCount = srvs.filter(s => s.running).length;
  12434. statActive.innerText = `${activeCount} / ${srvs.length}`;
  12435. }
  12436. const statLeases = document.getElementById('dhcp-server-stat-leases');
  12437. if (statLeases) {
  12438. statLeases.innerText = leases.length;
  12439. }
  12440. const statLeasesSub = document.getElementById('dhcp-server-stat-leases-sub');
  12441. if (statLeasesSub) {
  12442. const dyn = leases.filter(l => l.dynamic).length;
  12443. const st = leases.filter(l => !l.dynamic).length;
  12444. statLeasesSub.innerText = `${dyn} dynamic, ${st} static`;
  12445. }
  12446. const statNetworks = document.getElementById('dhcp-server-stat-networks');
  12447. if (statNetworks) {
  12448. statNetworks.innerText = nets.length;
  12449. }
  12450. // Subtab Badges
  12451. const bSrv = document.getElementById('dhcp-server-tab-badge-servers');
  12452. if (bSrv) bSrv.innerText = srvs.length;
  12453. const bNet = document.getElementById('dhcp-server-tab-badge-networks');
  12454. if (bNet) bNet.innerText = nets.length;
  12455. const bLease = document.getElementById('dhcp-server-tab-badge-leases');
  12456. if (bLease) bLease.innerText = leases.length;
  12457. const bOpt = document.getElementById('dhcp-server-tab-badge-options');
  12458. if (bOpt) bOpt.innerText = opts.length;
  12459. // Sidebar Badge
  12460. const sideBadge = document.getElementById('badge-dhcp-server-count');
  12461. if (sideBadge) sideBadge.innerText = leases.length || srvs.length;
  12462. renderCurrentDHCPServerTab();
  12463. } catch (err) {
  12464. console.error('Failed to load DHCP Server:', err);
  12465. }
  12466. }
  12467. function switchDHCPServerTab(tab) {
  12468. state.dhcpServerTab = tab;
  12469. const tabs = ['servers', 'networks', 'leases', 'options'];
  12470. tabs.forEach(t => {
  12471. const panel = document.getElementById(`dhcp-server-subtab-${t}`);
  12472. const btn = document.getElementById(`dhcp-server-tab-btn-${t}`);
  12473. if (panel) {
  12474. if (t === tab) panel.classList.remove('hidden');
  12475. else panel.classList.add('hidden');
  12476. }
  12477. if (btn) {
  12478. if (t === tab) {
  12479. 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';
  12480. } else {
  12481. 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';
  12482. }
  12483. }
  12484. });
  12485. const addBtn = document.getElementById('dhcp-server-primary-add-btn');
  12486. if (addBtn) {
  12487. if (tab === 'servers') addBtn.innerHTML = '<span>+ Add Server</span>';
  12488. else if (tab === 'networks') addBtn.innerHTML = '<span>+ Add Network</span>';
  12489. else if (tab === 'leases') addBtn.innerHTML = '<span>+ Add Static Lease</span>';
  12490. else if (tab === 'options') addBtn.innerHTML = '<span>+ Add Option</span>';
  12491. }
  12492. renderCurrentDHCPServerTab();
  12493. }
  12494. function handleDHCPServerPrimaryAdd() {
  12495. const tab = state.dhcpServerTab || 'servers';
  12496. if (tab === 'servers') openAddDHCPServerModal();
  12497. else if (tab === 'networks') openAddDHCPNetworkModal();
  12498. else if (tab === 'leases') openAddDHCPStaticLeaseModal();
  12499. else if (tab === 'options') openAddDHCPOptionModal();
  12500. }
  12501. function renderCurrentDHCPServerTab() {
  12502. const tab = state.dhcpServerTab || 'servers';
  12503. if (tab === 'servers') renderDHCPServers();
  12504. else if (tab === 'networks') renderDHCPNetworks();
  12505. else if (tab === 'leases') renderDHCPLeases();
  12506. else if (tab === 'options') renderDHCPOptions();
  12507. }
  12508. function renderDHCPServers() {
  12509. const tbody = document.getElementById('dhcp-server-tbody');
  12510. const empty = document.getElementById('dhcp-server-empty');
  12511. if (!tbody) return;
  12512. const servers = state.dhcpServers || [];
  12513. if (servers.length === 0) {
  12514. tbody.innerHTML = '';
  12515. empty?.classList.remove('hidden');
  12516. return;
  12517. }
  12518. empty?.classList.add('hidden');
  12519. const sig = servers.map(s => `${s.id}:${s.running}:${s.disabled}:${s.active_leases}:${s.interface}`).join(';');
  12520. if (tbody.dataset.sig === sig) return;
  12521. tbody.dataset.sig = sig;
  12522. tbody.innerHTML = '';
  12523. servers.forEach(s => {
  12524. const tr = document.createElement('tr');
  12525. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  12526. tr.innerHTML = `
  12527. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(s.running, s.disabled)}</td>
  12528. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(s.name)}</td>
  12529. <td class="py-2.5 px-3 font-mono text-cyan-400 font-semibold">${escapeHtml(s.interface)}</td>
  12530. <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>
  12531. <td class="py-2.5 px-3 font-mono text-emerald-400">${escapeHtml(s.address_pool)}</td>
  12532. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(s.lease_time || '12h')}</td>
  12533. <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>
  12534. <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>
  12535. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]" title="${escapeHtml(s.comment || '')}">${escapeHtml(s.comment || '-')}</td>
  12536. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  12537. <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>
  12538. <button onclick="openEditDHCPServerModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  12539. <button onclick="deleteDHCPServer('${s.id}', '${escapeHtml(s.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  12540. </td>
  12541. `;
  12542. tbody.appendChild(tr);
  12543. });
  12544. }
  12545. function renderDHCPNetworks() {
  12546. const tbody = document.getElementById('dhcp-networks-tbody');
  12547. const empty = document.getElementById('dhcp-networks-empty');
  12548. if (!tbody) return;
  12549. tbody.innerHTML = '';
  12550. const networks = state.dhcpNetworks || [];
  12551. if (networks.length === 0) {
  12552. empty?.classList.remove('hidden');
  12553. return;
  12554. }
  12555. empty?.classList.add('hidden');
  12556. networks.forEach(n => {
  12557. const tr = document.createElement('tr');
  12558. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  12559. const dnsStr = (n.dns_servers || []).join(', ') || '-';
  12560. const optionsChips = (n.dhcp_options || []).map(optId => {
  12561. const opt = (state.dhcpOptions || []).find(o => o.id === optId);
  12562. if (!opt) return '';
  12563. 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>`;
  12564. }).filter(Boolean).join('');
  12565. tr.innerHTML = `
  12566. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${escapeHtml(n.address)}</td>
  12567. <td class="py-2.5 px-3 font-mono text-cyan-300 font-semibold">${escapeHtml(n.gateway || '-')}</td>
  12568. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(n.netmask || '-')}</td>
  12569. <td class="py-2.5 px-3 font-mono text-slate-300 truncate max-w-[140px]" title="${escapeHtml(dnsStr)}">${escapeHtml(dnsStr)}</td>
  12570. <td class="py-2.5 px-3 font-mono text-slate-400">${escapeHtml(n.domain || '-')}</td>
  12571. <td class="py-2.5 px-3 font-mono">${optionsChips || '<span class="text-slate-600 font-sans">-</span>'}</td>
  12572. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(n.comment || '')}">${escapeHtml(n.comment || '-')}</td>
  12573. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  12574. <button onclick="openEditDHCPNetworkModal('${n.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  12575. <button onclick="deleteDHCPNetwork('${n.id}', '${escapeHtml(n.address)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  12576. </td>
  12577. `;
  12578. tbody.appendChild(tr);
  12579. });
  12580. }
  12581. function renderDHCPLeases() {
  12582. const tbody = document.getElementById('dhcp-leases-tbody');
  12583. const empty = document.getElementById('dhcp-leases-empty');
  12584. if (!tbody) return;
  12585. tbody.innerHTML = '';
  12586. const leases = state.dhcpLeases || [];
  12587. if (leases.length === 0) {
  12588. empty?.classList.remove('hidden');
  12589. return;
  12590. }
  12591. empty?.classList.add('hidden');
  12592. leases.forEach(l => {
  12593. const tr = document.createElement('tr');
  12594. tr.className = `hover:bg-slate-800/40 transition text-xs ${l.disabled ? 'opacity-50' : ''}`;
  12595. 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>';
  12596. const statusBadge = l.status === 'bound'
  12597. ? '<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>'
  12598. : l.status === 'static'
  12599. ? '<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>'
  12600. : '<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>';
  12601. const makeStaticBtn = l.dynamic
  12602. ? `<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>`
  12603. : `<button onclick="deleteDHCPStaticLease('${l.id}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Remove</button>`;
  12604. tr.innerHTML = `
  12605. <td class="py-2.5 px-3 text-center">${flag}</td>
  12606. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(l.address)}</td>
  12607. <td class="py-2.5 px-3 font-mono text-cyan-300">${escapeHtml(l.mac_address)}</td>
  12608. <td class="py-2.5 px-3 font-sans text-slate-200 font-medium">${escapeHtml(l.hostname || '*')}</td>
  12609. <td class="py-2.5 px-3 font-mono text-slate-400">${escapeHtml(l.server || 'all')}</td>
  12610. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(l.expires_in || 'never')}</td>
  12611. <td class="py-2.5 px-3">${statusBadge}</td>
  12612. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(l.comment || '')}">${escapeHtml(l.comment || '-')}</td>
  12613. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  12614. ${makeStaticBtn}
  12615. </td>
  12616. `;
  12617. tbody.appendChild(tr);
  12618. });
  12619. }
  12620. function renderDHCPOptions() {
  12621. const tbody = document.getElementById('dhcp-options-tbody');
  12622. const empty = document.getElementById('dhcp-options-empty');
  12623. if (!tbody) return;
  12624. tbody.innerHTML = '';
  12625. const options = state.dhcpOptions || [];
  12626. if (options.length === 0) {
  12627. empty?.classList.remove('hidden');
  12628. return;
  12629. }
  12630. empty?.classList.add('hidden');
  12631. options.forEach(o => {
  12632. const tr = document.createElement('tr');
  12633. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  12634. tr.innerHTML = `
  12635. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(o.name)}</td>
  12636. <td class="py-2.5 px-3 font-bold text-cyan-400 font-mono">${o.code}</td>
  12637. <td class="py-2.5 px-3 font-mono text-emerald-400 break-all max-w-xs">${escapeHtml(o.value)}</td>
  12638. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-xs" title="${escapeHtml(o.comment || '')}">${escapeHtml(o.comment || '-')}</td>
  12639. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  12640. <button onclick="openEditDHCPOptionModal('${o.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  12641. <button onclick="deleteDHCPOption('${o.id}', '${escapeHtml(o.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  12642. </td>
  12643. `;
  12644. tbody.appendChild(tr);
  12645. });
  12646. }
  12647. // ==================== MODALS & ACTIONS: SERVER ====================
  12648. function populateDHCPNetworkSelect(elemId, selectedVal) {
  12649. const sel = document.getElementById(elemId);
  12650. if (!sel) return;
  12651. sel.innerHTML = '<option value="">Select network subnet...</option>';
  12652. const networks = state.dhcpNetworks || [];
  12653. networks.forEach(n => {
  12654. const opt = document.createElement('option');
  12655. opt.value = n.address;
  12656. opt.innerText = `${n.address} (Gateway: ${n.gateway || 'None'}${n.comment ? ' - ' + n.comment : ''})`;
  12657. if (selectedVal && (selectedVal === n.address || selectedVal === n.id)) {
  12658. opt.selected = true;
  12659. }
  12660. sel.appendChild(opt);
  12661. });
  12662. }
  12663. function onDHCPServerNetworkChange() {
  12664. const netSel = document.getElementById('dhcp-server-modal-network');
  12665. if (!netSel) return;
  12666. const netVal = netSel.value;
  12667. if (!netVal) return;
  12668. const poolInput = document.getElementById('dhcp-server-modal-pool');
  12669. if (!poolInput) return;
  12670. // Auto-calculate suggested address pool based on subnet CIDR
  12671. const parts = netVal.split('/');
  12672. const ip = parts[0];
  12673. const cidr = parseInt(parts[1] || '24', 10);
  12674. if (cidr === 24) {
  12675. const octets = ip.split('.');
  12676. if (octets.length === 4) {
  12677. const base = `${octets[0]}.${octets[1]}.${octets[2]}`;
  12678. poolInput.value = `${base}.10-${base}.254`;
  12679. }
  12680. }
  12681. }
  12682. function openAddDHCPServerModal() {
  12683. document.getElementById('dhcp-server-modal-title').innerText = 'Add DHCP Server';
  12684. document.getElementById('dhcp-server-modal-id').value = '';
  12685. document.getElementById('dhcp-server-modal-name').value = `dhcp${(state.dhcpServers || []).length + 1}`;
  12686. document.getElementById('dhcp-server-modal-pool').value = '192.168.88.10-192.168.88.254';
  12687. document.getElementById('dhcp-server-modal-leasetime').value = '12h';
  12688. document.getElementById('dhcp-server-modal-comment').value = '';
  12689. document.getElementById('dhcp-server-modal-authoritative').checked = true;
  12690. document.getElementById('dhcp-server-modal-disabled').checked = false;
  12691. populateDHCPIfaceSelect('dhcp-server-modal-iface', '');
  12692. const networks = state.dhcpNetworks || [];
  12693. const defaultNet = networks.length > 0 ? networks[0].address : '';
  12694. populateDHCPNetworkSelect('dhcp-server-modal-network', defaultNet);
  12695. if (defaultNet) {
  12696. onDHCPServerNetworkChange();
  12697. }
  12698. document.getElementById('dhcp-server-instance-modal').classList.remove('hidden');
  12699. }
  12700. function openEditDHCPServerModal(id) {
  12701. const s = (state.dhcpServers || []).find(item => item.id === id);
  12702. if (!s) return;
  12703. document.getElementById('dhcp-server-modal-title').innerText = `Edit DHCP Server (${s.name})`;
  12704. document.getElementById('dhcp-server-modal-id').value = s.id;
  12705. document.getElementById('dhcp-server-modal-name').value = s.name;
  12706. document.getElementById('dhcp-server-modal-pool').value = s.address_pool;
  12707. document.getElementById('dhcp-server-modal-leasetime').value = s.lease_time || '12h';
  12708. document.getElementById('dhcp-server-modal-comment').value = s.comment || '';
  12709. document.getElementById('dhcp-server-modal-authoritative').checked = s.authoritative !== false;
  12710. document.getElementById('dhcp-server-modal-disabled').checked = !!s.disabled;
  12711. populateDHCPIfaceSelect('dhcp-server-modal-iface', s.interface);
  12712. populateDHCPNetworkSelect('dhcp-server-modal-network', s.network || '');
  12713. document.getElementById('dhcp-server-instance-modal').classList.remove('hidden');
  12714. }
  12715. function closeDHCPServerModal() {
  12716. document.getElementById('dhcp-server-instance-modal').classList.add('hidden');
  12717. }
  12718. async function submitSaveDHCPServer(e) {
  12719. e.preventDefault();
  12720. const id = document.getElementById('dhcp-server-modal-id').value;
  12721. const name = document.getElementById('dhcp-server-modal-name').value.trim();
  12722. const iface = document.getElementById('dhcp-server-modal-iface').value;
  12723. const network = document.getElementById('dhcp-server-modal-network').value.trim();
  12724. const pool = document.getElementById('dhcp-server-modal-pool').value.trim();
  12725. const leaseTime = document.getElementById('dhcp-server-modal-leasetime').value.trim() || '12h';
  12726. const comment = document.getElementById('dhcp-server-modal-comment').value.trim();
  12727. const authoritative = document.getElementById('dhcp-server-modal-authoritative').checked;
  12728. const disabled = document.getElementById('dhcp-server-modal-disabled').checked;
  12729. try {
  12730. const res = await fetch(`${API_BASE}/dhcp-server/servers`, {
  12731. method: 'POST',
  12732. headers: { 'Content-Type': 'application/json' },
  12733. body: JSON.stringify({
  12734. id,
  12735. name,
  12736. interface: iface,
  12737. network,
  12738. address_pool: pool,
  12739. lease_time: leaseTime,
  12740. authoritative,
  12741. disabled,
  12742. comment
  12743. })
  12744. });
  12745. if (res.ok) {
  12746. showToast('DHCP Server Saved', `Server ${name} configured successfully`, 'success');
  12747. closeDHCPServerModal();
  12748. loadDHCPServer(false);
  12749. fetchData(false);
  12750. } else {
  12751. const err = await res.text();
  12752. showToast('Error', err, 'error');
  12753. }
  12754. } catch (err) {
  12755. showToast('Error', err.message, 'error');
  12756. }
  12757. }
  12758. async function toggleDHCPServerState(id, disabled) {
  12759. try {
  12760. const res = await fetch(`${API_BASE}/dhcp-server/servers/${encodeURIComponent(id)}/state`, {
  12761. method: 'POST',
  12762. headers: { 'Content-Type': 'application/json' },
  12763. body: JSON.stringify({ disabled })
  12764. });
  12765. if (res.ok) {
  12766. showToast('State Updated', disabled ? 'Server disabled' : 'Server enabled', 'info');
  12767. loadDHCPServer(false);
  12768. fetchData(false);
  12769. }
  12770. } catch (err) {
  12771. showToast('Error', err.message, 'error');
  12772. }
  12773. }
  12774. async function deleteDHCPServer(id, name) {
  12775. if (!confirm(`Are you sure you want to delete DHCP Server "${name}"?`)) return;
  12776. try {
  12777. const res = await fetch(`${API_BASE}/dhcp-server/servers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12778. if (res.ok) {
  12779. showToast('Deleted', `DHCP Server ${name} removed`, 'success');
  12780. loadDHCPServer(false);
  12781. fetchData(false);
  12782. }
  12783. } catch (err) {
  12784. showToast('Error', err.message, 'error');
  12785. }
  12786. }
  12787. // ==================== MODALS & ACTIONS: NETWORKS ====================
  12788. function openAddDHCPNetworkModal() {
  12789. document.getElementById('dhcp-network-modal-title').innerText = 'Add DHCP Network';
  12790. document.getElementById('dhcp-network-modal-id').value = '';
  12791. document.getElementById('dhcp-network-modal-address').value = '192.168.88.0/24';
  12792. document.getElementById('dhcp-network-modal-gateway').value = '192.168.88.1';
  12793. document.getElementById('dhcp-network-modal-dns').value = '192.168.88.1, 1.1.1.1, 8.8.8.8';
  12794. document.getElementById('dhcp-network-modal-domain').value = 'lan';
  12795. document.getElementById('dhcp-network-modal-netmask').value = '';
  12796. document.getElementById('dhcp-network-modal-comment').value = '';
  12797. renderDHCPNetworkOptionsCheckboxes([]);
  12798. document.getElementById('dhcp-network-modal').classList.remove('hidden');
  12799. }
  12800. function openEditDHCPNetworkModal(id) {
  12801. const n = (state.dhcpNetworks || []).find(item => item.id === id);
  12802. if (!n) return;
  12803. document.getElementById('dhcp-network-modal-title').innerText = `Edit DHCP Network (${n.address})`;
  12804. document.getElementById('dhcp-network-modal-id').value = n.id;
  12805. document.getElementById('dhcp-network-modal-address').value = n.address;
  12806. document.getElementById('dhcp-network-modal-gateway').value = n.gateway || '';
  12807. document.getElementById('dhcp-network-modal-dns').value = (n.dns_servers || []).join(', ');
  12808. document.getElementById('dhcp-network-modal-domain').value = n.domain || '';
  12809. document.getElementById('dhcp-network-modal-netmask').value = n.netmask || '';
  12810. document.getElementById('dhcp-network-modal-comment').value = n.comment || '';
  12811. renderDHCPNetworkOptionsCheckboxes(n.dhcp_options || []);
  12812. document.getElementById('dhcp-network-modal').classList.remove('hidden');
  12813. }
  12814. function renderDHCPNetworkOptionsCheckboxes(selectedIds) {
  12815. const container = document.getElementById('dhcp-network-modal-options-list');
  12816. if (!container) return;
  12817. container.innerHTML = '';
  12818. const opts = state.dhcpOptions || [];
  12819. if (opts.length === 0) {
  12820. container.innerHTML = '<span class="text-slate-500 text-[11px] col-span-2">No custom options configured. Add some in the "Options" tab.</span>';
  12821. return;
  12822. }
  12823. opts.forEach(o => {
  12824. const isChecked = selectedIds.includes(o.id);
  12825. const label = document.createElement('label');
  12826. label.className = 'flex items-center space-x-2 text-slate-300 hover:text-white cursor-pointer';
  12827. label.innerHTML = `
  12828. <input type="checkbox" name="dhcp-net-opt" value="${o.id}" ${isChecked ? 'checked' : ''} class="rounded bg-slate-800 border-slate-700 text-emerald-600">
  12829. <span class="truncate" title="${escapeHtml(o.name)} (Code ${o.code})">${escapeHtml(o.name)} <span class="text-cyan-400">#${o.code}</span></span>
  12830. `;
  12831. container.appendChild(label);
  12832. });
  12833. }
  12834. function closeDHCPNetworkModal() {
  12835. document.getElementById('dhcp-network-modal').classList.add('hidden');
  12836. }
  12837. async function submitSaveDHCPNetwork(e) {
  12838. e.preventDefault();
  12839. const id = document.getElementById('dhcp-network-modal-id').value;
  12840. const address = document.getElementById('dhcp-network-modal-address').value.trim();
  12841. const gateway = document.getElementById('dhcp-network-modal-gateway').value.trim();
  12842. const dnsStr = document.getElementById('dhcp-network-modal-dns').value.trim();
  12843. const domain = document.getElementById('dhcp-network-modal-domain').value.trim();
  12844. const netmask = document.getElementById('dhcp-network-modal-netmask').value.trim();
  12845. const comment = document.getElementById('dhcp-network-modal-comment').value.trim();
  12846. const selectedOpts = [];
  12847. document.querySelectorAll('input[name="dhcp-net-opt"]:checked').forEach(cb => selectedOpts.push(cb.value));
  12848. const dnsServers = dnsStr ? dnsStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  12849. try {
  12850. const res = await fetch(`${API_BASE}/dhcp-server/networks`, {
  12851. method: 'POST',
  12852. headers: { 'Content-Type': 'application/json' },
  12853. body: JSON.stringify({
  12854. id,
  12855. address,
  12856. gateway,
  12857. netmask,
  12858. dns_servers: dnsServers,
  12859. domain,
  12860. dhcp_options: selectedOpts,
  12861. comment
  12862. })
  12863. });
  12864. if (res.ok) {
  12865. showToast('Network Saved', `Subnet ${address} configured successfully`, 'success');
  12866. closeDHCPNetworkModal();
  12867. loadDHCPServer(false);
  12868. fetchData(false);
  12869. } else {
  12870. const err = await res.text();
  12871. showToast('Error', err, 'error');
  12872. }
  12873. } catch (err) {
  12874. showToast('Error', err.message, 'error');
  12875. }
  12876. }
  12877. async function deleteDHCPNetwork(id, addr) {
  12878. if (!confirm(`Are you sure you want to delete DHCP Network "${addr}"?`)) return;
  12879. try {
  12880. const res = await fetch(`${API_BASE}/dhcp-server/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12881. if (res.ok) {
  12882. showToast('Deleted', `Network ${addr} removed`, 'success');
  12883. loadDHCPServer(false);
  12884. fetchData(false);
  12885. }
  12886. } catch (err) {
  12887. showToast('Error', err.message, 'error');
  12888. }
  12889. }
  12890. // ==================== MODALS & ACTIONS: LEASES ====================
  12891. function openAddDHCPStaticLeaseModal() {
  12892. document.getElementById('dhcp-static-lease-modal-title').innerText = 'Add Static Lease Reservation';
  12893. document.getElementById('dhcp-static-lease-modal-id').value = '';
  12894. document.getElementById('dhcp-static-lease-modal-mac').value = '';
  12895. document.getElementById('dhcp-static-lease-modal-ip').value = '';
  12896. document.getElementById('dhcp-static-lease-modal-hostname').value = '';
  12897. document.getElementById('dhcp-static-lease-modal-server').value = 'all';
  12898. document.getElementById('dhcp-static-lease-modal-comment').value = '';
  12899. document.getElementById('dhcp-static-lease-modal-disabled').checked = false;
  12900. document.getElementById('dhcp-static-lease-modal').classList.remove('hidden');
  12901. }
  12902. function closeDHCPStaticLeaseModal() {
  12903. document.getElementById('dhcp-static-lease-modal').classList.add('hidden');
  12904. }
  12905. async function submitSaveDHCPStaticLease(e) {
  12906. e.preventDefault();
  12907. const id = document.getElementById('dhcp-static-lease-modal-id').value;
  12908. const mac = document.getElementById('dhcp-static-lease-modal-mac').value.trim();
  12909. const ip = document.getElementById('dhcp-static-lease-modal-ip').value.trim();
  12910. const hostname = document.getElementById('dhcp-static-lease-modal-hostname').value.trim();
  12911. const server = document.getElementById('dhcp-static-lease-modal-server').value.trim() || 'all';
  12912. const comment = document.getElementById('dhcp-static-lease-modal-comment').value.trim();
  12913. const disabled = document.getElementById('dhcp-static-lease-modal-disabled').checked;
  12914. try {
  12915. const res = await fetch(`${API_BASE}/dhcp-server/leases/static`, {
  12916. method: 'POST',
  12917. headers: { 'Content-Type': 'application/json' },
  12918. body: JSON.stringify({
  12919. id,
  12920. mac_address: mac,
  12921. address: ip,
  12922. hostname,
  12923. server,
  12924. comment,
  12925. disabled
  12926. })
  12927. });
  12928. if (res.ok) {
  12929. showToast('Static Lease Saved', `IP ${ip} reserved for ${mac}`, 'success');
  12930. closeDHCPStaticLeaseModal();
  12931. loadDHCPServer(false);
  12932. fetchData(false);
  12933. } else {
  12934. const err = await res.text();
  12935. showToast('Error', err, 'error');
  12936. }
  12937. } catch (err) {
  12938. showToast('Error', err.message, 'error');
  12939. }
  12940. }
  12941. async function deleteDHCPStaticLease(id) {
  12942. if (!confirm('Are you sure you want to remove this static reservation?')) return;
  12943. try {
  12944. const res = await fetch(`${API_BASE}/dhcp-server/leases/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12945. if (res.ok) {
  12946. showToast('Deleted', 'Static lease removed', 'success');
  12947. loadDHCPServer(false);
  12948. fetchData(false);
  12949. }
  12950. } catch (err) {
  12951. showToast('Error', err.message, 'error');
  12952. }
  12953. }
  12954. async function makeDHCPLeaseStatic(mac, ip, hostname, comment) {
  12955. try {
  12956. const res = await fetch(`${API_BASE}/dhcp-server/leases/make-static`, {
  12957. method: 'POST',
  12958. headers: { 'Content-Type': 'application/json' },
  12959. body: JSON.stringify({
  12960. mac_address: mac,
  12961. address: ip,
  12962. hostname,
  12963. comment: comment || 'Converted to static'
  12964. })
  12965. });
  12966. if (res.ok) {
  12967. showToast('Lease Made Static', `IP ${ip} permanently reserved for ${mac}`, 'success');
  12968. loadDHCPServer(false);
  12969. fetchData(false);
  12970. } else {
  12971. const err = await res.text();
  12972. showToast('Error', err, 'error');
  12973. }
  12974. } catch (err) {
  12975. showToast('Error', err.message, 'error');
  12976. }
  12977. }
  12978. // ==================== MODALS & ACTIONS: OPTIONS ====================
  12979. function openAddDHCPOptionModal() {
  12980. document.getElementById('dhcp-option-modal-title').innerText = 'Add DHCP Option';
  12981. document.getElementById('dhcp-option-modal-id').value = '';
  12982. document.getElementById('dhcp-option-modal-name').value = '';
  12983. document.getElementById('dhcp-option-modal-code').value = '';
  12984. document.getElementById('dhcp-option-modal-value').value = '';
  12985. document.getElementById('dhcp-option-modal-comment').value = '';
  12986. document.getElementById('dhcp-option-modal').classList.remove('hidden');
  12987. }
  12988. function openEditDHCPOptionModal(id) {
  12989. const o = (state.dhcpOptions || []).find(item => item.id === id);
  12990. if (!o) return;
  12991. document.getElementById('dhcp-option-modal-title').innerText = `Edit DHCP Option (${o.name})`;
  12992. document.getElementById('dhcp-option-modal-id').value = o.id;
  12993. document.getElementById('dhcp-option-modal-name').value = o.name;
  12994. document.getElementById('dhcp-option-modal-code').value = o.code;
  12995. document.getElementById('dhcp-option-modal-value').value = o.value;
  12996. document.getElementById('dhcp-option-modal-comment').value = o.comment || '';
  12997. document.getElementById('dhcp-option-modal').classList.remove('hidden');
  12998. }
  12999. function closeDHCPOptionModal() {
  13000. document.getElementById('dhcp-option-modal').classList.add('hidden');
  13001. }
  13002. async function submitSaveDHCPOption(e) {
  13003. e.preventDefault();
  13004. const id = document.getElementById('dhcp-option-modal-id').value;
  13005. const name = document.getElementById('dhcp-option-modal-name').value.trim();
  13006. const code = parseInt(document.getElementById('dhcp-option-modal-code').value);
  13007. const value = document.getElementById('dhcp-option-modal-value').value.trim();
  13008. const comment = document.getElementById('dhcp-option-modal-comment').value.trim();
  13009. try {
  13010. const res = await fetch(`${API_BASE}/dhcp-server/options`, {
  13011. method: 'POST',
  13012. headers: { 'Content-Type': 'application/json' },
  13013. body: JSON.stringify({ id, name, code, value, comment })
  13014. });
  13015. if (res.ok) {
  13016. showToast('Option Saved', `DHCP option ${name} (#${code}) configured`, 'success');
  13017. closeDHCPOptionModal();
  13018. loadDHCPServer(false);
  13019. fetchData(false);
  13020. } else {
  13021. const err = await res.text();
  13022. showToast('Error', err, 'error');
  13023. }
  13024. } catch (err) {
  13025. showToast('Error', err.message, 'error');
  13026. }
  13027. }
  13028. async function deleteDHCPOption(id, name) {
  13029. if (!confirm(`Are you sure you want to delete DHCP Option "${name}"?`)) return;
  13030. try {
  13031. const res = await fetch(`${API_BASE}/dhcp-server/options/${encodeURIComponent(id)}`, { method: 'DELETE' });
  13032. if (res.ok) {
  13033. showToast('Deleted', `Option ${name} removed`, 'success');
  13034. loadDHCPServer(false);
  13035. fetchData(false);
  13036. }
  13037. } catch (err) {
  13038. showToast('Error', err.message, 'error');
  13039. }
  13040. }
  13041. // ==================== WIZARD: DHCP SETUP (MikroTik style) ====================
  13042. function openDHCPServerSetupModal() {
  13043. populateDHCPIfaceSelect('dhcp-wizard-iface', '');
  13044. onDHCPWizardIfaceChange();
  13045. document.getElementById('dhcp-setup-wizard-modal').classList.remove('hidden');
  13046. }
  13047. function closeDHCPServerSetupModal() {
  13048. document.getElementById('dhcp-setup-wizard-modal').classList.add('hidden');
  13049. }
  13050. function onDHCPWizardIfaceChange() {
  13051. const ifaceName = document.getElementById('dhcp-wizard-iface').value;
  13052. const iface = (state.interfaces || []).find(i => i.name === ifaceName);
  13053. let ip = '192.168.88.1';
  13054. let prefix = '24';
  13055. if (iface && iface.ip_address) {
  13056. const parts = iface.ip_address.split('/');
  13057. ip = parts[0];
  13058. if (parts.length > 1) prefix = parts[1];
  13059. }
  13060. // Calculate subnet base (e.g. 192.168.88.0/24)
  13061. const ipParts = ip.split('.');
  13062. if (ipParts.length === 4) {
  13063. const baseSpace = `${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.0/${prefix}`;
  13064. const pool = `${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.10-${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.254`;
  13065. document.getElementById('dhcp-wizard-space').value = baseSpace;
  13066. document.getElementById('dhcp-wizard-gateway').value = ip;
  13067. document.getElementById('dhcp-wizard-pool').value = pool;
  13068. document.getElementById('dhcp-wizard-dns').value = `${ip}, 1.1.1.1, 8.8.8.8`;
  13069. document.getElementById('dhcp-wizard-ntp').value = `${ip}`;
  13070. }
  13071. }
  13072. async function submitDHCPServerSetupWizard(e) {
  13073. e.preventDefault();
  13074. const iface = document.getElementById('dhcp-wizard-iface').value;
  13075. const space = document.getElementById('dhcp-wizard-space').value.trim();
  13076. const gw = document.getElementById('dhcp-wizard-gateway').value.trim();
  13077. const pool = document.getElementById('dhcp-wizard-pool').value.trim();
  13078. const dnsStr = document.getElementById('dhcp-wizard-dns').value.trim();
  13079. const leaseTime = document.getElementById('dhcp-wizard-leasetime').value.trim() || '12h';
  13080. const ntpStr = document.getElementById('dhcp-wizard-ntp').value.trim();
  13081. const tftp = document.getElementById('dhcp-wizard-tftp').value.trim();
  13082. const dnsServers = dnsStr ? dnsStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  13083. const ntpServers = ntpStr ? ntpStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  13084. try {
  13085. const res = await fetch(`${API_BASE}/dhcp-server/setup`, {
  13086. method: 'POST',
  13087. headers: { 'Content-Type': 'application/json' },
  13088. body: JSON.stringify({
  13089. interface: iface,
  13090. address_space: space,
  13091. gateway: gw,
  13092. address_pool: pool,
  13093. dns_servers: dnsServers,
  13094. lease_time: leaseTime,
  13095. ntp_servers: ntpServers,
  13096. next_server: tftp
  13097. })
  13098. });
  13099. if (res.ok) {
  13100. showToast('DHCP Setup Complete', `DHCP Server setup finished on ${iface}`, 'success');
  13101. closeDHCPServerSetupModal();
  13102. loadDHCPServer(false);
  13103. fetchData(false);
  13104. } else {
  13105. const err = await res.text();
  13106. showToast('Error', err, 'error');
  13107. }
  13108. } catch (err) {
  13109. showToast('Error', err.message, 'error');
  13110. }
  13111. }
  13112. function populateDHCPIfaceSelect(elemId, selectedVal) {
  13113. const sel = document.getElementById(elemId);
  13114. if (!sel) return;
  13115. sel.innerHTML = '<option value="">Select interface...</option>';
  13116. const ifaces = state.interfaces || [];
  13117. ifaces.forEach(i => {
  13118. if (i.name === 'lo') return;
  13119. const opt = document.createElement('option');
  13120. opt.value = i.name;
  13121. const ipStr = i.ip_address ? ` (${i.ip_address})` : '';
  13122. opt.textContent = `${i.name}${ipStr} [${i.role || i.type || 'interface'}]`;
  13123. if (i.name === selectedVal) opt.selected = true;
  13124. sel.appendChild(opt);
  13125. });
  13126. }
  13127. // ==================== UNIVERSAL TABLE ORDERING / SORTING (WINBOX / WEBFIG STYLE) ====================
  13128. function initTableSorting() {
  13129. document.querySelectorAll('table').forEach(setupSortableTable);
  13130. }
  13131. function setupSortableTable(table) {
  13132. const thead = table.querySelector('thead');
  13133. const tbody = table.querySelector('tbody');
  13134. if (!thead || !tbody) return;
  13135. const headerRows = thead.querySelectorAll('tr');
  13136. if (headerRows.length === 0) return;
  13137. const ths = headerRows[headerRows.length - 1].querySelectorAll('th');
  13138. ths.forEach((th, colIdx) => {
  13139. if (th._sortBound) return;
  13140. th._sortBound = true;
  13141. const rawText = th.innerText.trim().toLowerCase();
  13142. const isActionsCol = rawText === 'actions' || (rawText === 'action' && th.classList.contains('text-right'));
  13143. const isCheckboxCol = !!th.querySelector('input[type="checkbox"]');
  13144. const isExpandCol = (th.classList.contains('w-8') || th.classList.contains('w-6')) && !rawText;
  13145. const isExplicitNoSort = th.classList.contains('no-sort') || th.getAttribute('data-sortable') === 'false';
  13146. if (isActionsCol || isCheckboxCol || isExpandCol || isExplicitNoSort) {
  13147. return;
  13148. }
  13149. th.classList.add('table-sortable', 'group');
  13150. if (!th.title) th.title = 'Click to sort (Ascending / Descending / Default)';
  13151. let icon = th.querySelector('.table-sort-icon');
  13152. if (!icon) {
  13153. icon = document.createElement('span');
  13154. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  13155. icon.innerHTML = '⇅';
  13156. th.appendChild(icon);
  13157. }
  13158. th.addEventListener('click', (e) => {
  13159. if (e.target.tagName === 'INPUT' || e.target.tagName === 'BUTTON' || e.target.closest('button, input')) return;
  13160. handleHeaderClick(table, th, colIdx);
  13161. });
  13162. });
  13163. if (!tbody._sortObserved) {
  13164. tbody._sortObserved = true;
  13165. let sortDebounceTimer = null;
  13166. const observer = new MutationObserver((mutations) => {
  13167. if (tbody._isSorting) return;
  13168. const hasChildChanges = mutations.some(m => m.type === 'childList' && m.addedNodes.length > 0);
  13169. if (!hasChildChanges) return;
  13170. clearTimeout(sortDebounceTimer);
  13171. sortDebounceTimer = setTimeout(() => {
  13172. if (tbody._isSorting) return;
  13173. if (table._activeSort && table._activeSort.dir !== 'none') {
  13174. applyTableSort(table, table._activeSort.colIdx, table._activeSort.dir, false);
  13175. } else {
  13176. tagOriginalRowOrder(tbody);
  13177. }
  13178. }, 50);
  13179. });
  13180. tbody._sortObserver = observer;
  13181. observer.observe(tbody, { childList: true });
  13182. }
  13183. tagOriginalRowOrder(tbody);
  13184. }
  13185. function tagOriginalRowOrder(tbody) {
  13186. let idx = 0;
  13187. Array.from(tbody.children).forEach(tr => {
  13188. if (!tr.querySelector('td[colspan]')) {
  13189. if (!tr.hasAttribute('data-orig-idx')) {
  13190. tr.setAttribute('data-orig-idx', idx++);
  13191. }
  13192. }
  13193. });
  13194. }
  13195. function handleHeaderClick(table, th, colIdx) {
  13196. const currentSort = table._activeSort || { colIdx: -1, dir: 'none' };
  13197. let newDir = 'asc';
  13198. if (currentSort.colIdx === colIdx) {
  13199. if (currentSort.dir === 'asc') newDir = 'desc';
  13200. else if (currentSort.dir === 'desc') newDir = 'none';
  13201. else newDir = 'asc';
  13202. } else {
  13203. newDir = 'asc';
  13204. }
  13205. table._activeSort = { colIdx, dir: newDir };
  13206. updateHeaderIcons(table, colIdx, newDir);
  13207. applyTableSort(table, colIdx, newDir, true);
  13208. }
  13209. function updateHeaderIcons(table, activeColIdx, dir) {
  13210. const thead = table.querySelector('thead');
  13211. if (!thead) return;
  13212. const ths = thead.querySelectorAll('th');
  13213. ths.forEach((th, idx) => {
  13214. const icon = th.querySelector('.table-sort-icon');
  13215. if (!icon) return;
  13216. if (idx === activeColIdx && dir !== 'none') {
  13217. icon.innerHTML = dir === 'asc' ? '▲' : '▼';
  13218. icon.className = 'table-sort-icon text-cyan-400 font-bold opacity-100';
  13219. th.classList.add('table-sorted-active');
  13220. } else {
  13221. icon.innerHTML = '⇅';
  13222. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  13223. th.classList.remove('table-sorted-active');
  13224. }
  13225. });
  13226. }
  13227. function applyTableSort(table, colIdx, dir, userInitiated) {
  13228. const tbody = table.querySelector('tbody');
  13229. if (!tbody || tbody.children.length <= 1) return;
  13230. tbody._isSorting = true;
  13231. tagOriginalRowOrder(tbody);
  13232. // Group parent rows and any attached drawer/sub-rows
  13233. const groups = [];
  13234. let currentGroup = null;
  13235. Array.from(tbody.children).forEach(tr => {
  13236. if (tr.querySelector('td[colspan]')) {
  13237. if (currentGroup) {
  13238. currentGroup.subRows.push(tr);
  13239. } else {
  13240. groups.push({ mainRow: tr, subRows: [] });
  13241. }
  13242. } else {
  13243. currentGroup = { mainRow: tr, subRows: [] };
  13244. groups.push(currentGroup);
  13245. }
  13246. });
  13247. if (dir === 'none') {
  13248. groups.sort((a, b) => {
  13249. const idxA = parseInt(a.mainRow.getAttribute('data-orig-idx') || '0', 10);
  13250. const idxB = parseInt(b.mainRow.getAttribute('data-orig-idx') || '0', 10);
  13251. return idxA - idxB;
  13252. });
  13253. } else {
  13254. groups.sort((a, b) => {
  13255. const cellA = a.mainRow.children[colIdx];
  13256. const cellB = b.mainRow.children[colIdx];
  13257. const res = compareTableCells(cellA, cellB);
  13258. return dir === 'asc' ? res : -res;
  13259. });
  13260. }
  13261. // Check if rows are already in correct order to avoid modifying DOM
  13262. let alreadyOrdered = true;
  13263. let childIdx = 0;
  13264. for (const g of groups) {
  13265. if (tbody.children[childIdx] !== g.mainRow) {
  13266. alreadyOrdered = false;
  13267. break;
  13268. }
  13269. childIdx++;
  13270. for (const sub of g.subRows) {
  13271. if (tbody.children[childIdx] !== sub) {
  13272. alreadyOrdered = false;
  13273. break;
  13274. }
  13275. childIdx++;
  13276. }
  13277. }
  13278. if (alreadyOrdered) {
  13279. tbody._isSorting = false;
  13280. return;
  13281. }
  13282. // Disconnect observer while re-ordering to prevent recursion and thrashing
  13283. if (tbody._sortObserver) {
  13284. tbody._sortObserver.disconnect();
  13285. }
  13286. // Re-append rows in sorted order
  13287. groups.forEach(g => {
  13288. tbody.appendChild(g.mainRow);
  13289. g.subRows.forEach(sub => tbody.appendChild(sub));
  13290. });
  13291. // Drain any queued mutations and re-connect observer
  13292. if (tbody._sortObserver) {
  13293. tbody._sortObserver.takeRecords();
  13294. tbody._sortObserver.observe(tbody, { childList: true });
  13295. }
  13296. tbody._isSorting = false;
  13297. }
  13298. function getCellRawText(cell) {
  13299. if (!cell) return '';
  13300. if (cell.hasAttribute('data-sort-value')) return cell.getAttribute('data-sort-value');
  13301. const input = cell.querySelector('input, select');
  13302. if (input) {
  13303. if (input.type === 'checkbox') return input.checked ? '1' : '0';
  13304. return input.value;
  13305. }
  13306. return cell.innerText.trim();
  13307. }
  13308. function parseTrafficToNumber(str) {
  13309. const m = str.match(/^([\d.,]+)\s*([KMGTkmgt]?[iI]?[Bb](?:ps|\/s)?)/);
  13310. if (!m) return null;
  13311. const num = parseFloat(m[1].replace(/,/g, ''));
  13312. if (isNaN(num)) return null;
  13313. const unit = m[2].toUpperCase();
  13314. let mult = 1;
  13315. if (unit.startsWith('K')) mult = 1024;
  13316. else if (unit.startsWith('M')) mult = 1024 * 1024;
  13317. else if (unit.startsWith('G')) mult = 1024 * 1024 * 1024;
  13318. else if (unit.startsWith('T')) mult = 1024 * 1024 * 1024 * 1024;
  13319. return num * mult;
  13320. }
  13321. function parseIpToNumber(str) {
  13322. const clean = str.replace(/^[!~]/, '').trim();
  13323. const m = clean.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(?:\/(\d{1,2}))?/);
  13324. if (!m) return null;
  13325. const o1 = parseInt(m[1], 10);
  13326. const o2 = parseInt(m[2], 10);
  13327. const o3 = parseInt(m[3], 10);
  13328. const o4 = parseInt(m[4], 10);
  13329. if (o1 > 255 || o2 > 255 || o3 > 255 || o4 > 255) return null;
  13330. return ((o1 * 256 + o2) * 256 + o3) * 256 + o4;
  13331. }
  13332. function parseCompoundPackets(str) {
  13333. const m = str.match(/^([\d,]+)p/);
  13334. if (!m) return null;
  13335. return parseInt(m[1].replace(/,/g, ''), 10);
  13336. }
  13337. function compareTableCells(cellA, cellB) {
  13338. const a = getCellRawText(cellA);
  13339. const b = getCellRawText(cellB);
  13340. if (a === '' && b !== '') return 1;
  13341. if (b === '' && a !== '') return -1;
  13342. if (a === b) return 0;
  13343. // 1. IP Addresses / CIDR
  13344. const ipA = parseIpToNumber(a);
  13345. const ipB = parseIpToNumber(b);
  13346. if (ipA !== null && ipB !== null) return ipA - ipB;
  13347. // 2. Packet counts (e.g. "1,250p / 45 KB")
  13348. const pktA = parseCompoundPackets(a);
  13349. const pktB = parseCompoundPackets(b);
  13350. if (pktA !== null && pktB !== null) return pktA - pktB;
  13351. // 3. Traffic / Throughput / Bytes (e.g. "1.2 MB", "500 KiB", "10 Gbps")
  13352. const trafA = parseTrafficToNumber(a);
  13353. const trafB = parseTrafficToNumber(b);
  13354. if (trafA !== null && trafB !== null) return trafA - trafB;
  13355. // 4. Numbers with '#' or formatted with commas (e.g. "#1", "24", "1,200")
  13356. const cleanNumA = a.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  13357. const cleanNumB = b.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  13358. const numA = Number(cleanNumA);
  13359. const numB = Number(cleanNumB);
  13360. if (!isNaN(numA) && !isNaN(numB) && cleanNumA !== '' && cleanNumB !== '') {
  13361. return numA - numB;
  13362. }
  13363. // 5. Natural case-insensitive string compare
  13364. return a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' });
  13365. }
  13366. // ==================== VRRP HIGH AVAILABILITY CONTROLLER ====================
  13367. async function loadVRRP(showToastNotification = false) {
  13368. try {
  13369. const [instRes, sumRes] = await Promise.all([
  13370. fetch(`${API_BASE}/vrrp/instances`),
  13371. fetch(`${API_BASE}/vrrp/summary`)
  13372. ]);
  13373. if (instRes.ok) {
  13374. state.vrrpInstances = await instRes.json();
  13375. renderVRRP();
  13376. }
  13377. if (sumRes.ok) {
  13378. state.vrrpSummary = await sumRes.json();
  13379. renderVRRPSummary();
  13380. }
  13381. if (showToastNotification) {
  13382. showToast('Refreshed', 'VRRP telemetry refreshed', 'info');
  13383. }
  13384. } catch (err) {
  13385. console.error('Failed to load VRRP:', err);
  13386. }
  13387. }
  13388. function renderVRRPSummary() {
  13389. const s = state.vrrpSummary || { total_instances: 0, master_instances: 0, backup_instances: 0 };
  13390. const elTotal = document.getElementById('vrrp-stat-total');
  13391. if (elTotal) elTotal.innerText = s.total_instances || 0;
  13392. const elMaster = document.getElementById('vrrp-stat-master');
  13393. if (elMaster) elMaster.innerText = s.master_instances || 0;
  13394. const elBackup = document.getElementById('vrrp-stat-backup');
  13395. if (elBackup) elBackup.innerText = s.backup_instances || 0;
  13396. const bCount = document.getElementById('badge-vrrp-count');
  13397. if (bCount) bCount.innerText = s.total_instances || 0;
  13398. const dot = document.getElementById('badge-vrrp-dot');
  13399. if (dot) {
  13400. if (s.master_instances > 0) {
  13401. dot.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  13402. } else if (s.backup_instances > 0) {
  13403. dot.className = 'w-2 h-2 rounded-full bg-sky-400';
  13404. } else {
  13405. dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  13406. }
  13407. }
  13408. }
  13409. function renderVRRP() {
  13410. const tbody = document.getElementById('vrrp-table-tbody');
  13411. const empty = document.getElementById('vrrp-table-empty');
  13412. if (!tbody) return;
  13413. tbody.innerHTML = '';
  13414. const instances = state.vrrpInstances || [];
  13415. if (instances.length === 0) {
  13416. empty?.classList.remove('hidden');
  13417. return;
  13418. }
  13419. empty?.classList.add('hidden');
  13420. instances.forEach(inst => {
  13421. const tr = document.createElement('tr');
  13422. tr.className = `hover:bg-slate-800/40 transition text-xs ${inst.disabled ? 'opacity-50' : ''}`;
  13423. // Render Flag: M (Master), B (Backup), F (Fault), X (Disabled)
  13424. 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>`;
  13425. if (inst.disabled) {
  13426. 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>`;
  13427. } else if (inst.state === 'MASTER') {
  13428. 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>`;
  13429. } else if (inst.state === 'BACKUP') {
  13430. 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>`;
  13431. } else if (inst.state === 'FAULT') {
  13432. 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>`;
  13433. }
  13434. // Render State Badge
  13435. let stateBadge = `<span class="px-2 py-0.5 rounded text-[10px] bg-slate-800 text-slate-400 border border-slate-700">DISABLED</span>`;
  13436. if (!inst.disabled) {
  13437. if (inst.state === 'MASTER') {
  13438. 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>`;
  13439. } else if (inst.state === 'BACKUP') {
  13440. 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>`;
  13441. } else if (inst.state === 'FAULT') {
  13442. 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>`;
  13443. }
  13444. }
  13445. const vipsStr = (inst.virtual_ips || []).join(', ') || '-';
  13446. tr.innerHTML = `
  13447. <td class="py-2.5 px-3 text-center">${flagHtml}</td>
  13448. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(inst.name)}</td>
  13449. <td class="py-2.5 px-3 font-mono text-cyan-400 font-semibold">${escapeHtml(inst.interface)}</td>
  13450. <td class="py-2.5 px-3 font-mono font-bold text-center text-white">${inst.vrid}</td>
  13451. <td class="py-2.5 px-3 font-mono text-center text-slate-300 font-semibold">${inst.priority}</td>
  13452. <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>
  13453. <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>
  13454. <td class="py-2.5 px-3 font-mono text-slate-400 text-[11px]">${escapeHtml(inst.virtual_mac || '-')}</td>
  13455. <td class="py-2.5 px-3 text-center">${stateBadge}</td>
  13456. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]" title="${escapeHtml(inst.comment || '')}">${escapeHtml(inst.comment || '-')}</td>
  13457. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  13458. <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>
  13459. <button onclick="openEditVRRPModal('${inst.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  13460. <button onclick="deleteVRRP('${inst.id}', '${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  13461. </td>
  13462. `;
  13463. tbody.appendChild(tr);
  13464. });
  13465. }
  13466. function populateVRRPIfaceSelect(elemId, selectedIface) {
  13467. const sel = document.getElementById(elemId);
  13468. if (!sel) return;
  13469. sel.innerHTML = '<option value="">Select interface...</option>';
  13470. const ifaces = state.interfaces || [];
  13471. ifaces.forEach(i => {
  13472. const opt = document.createElement('option');
  13473. opt.value = i.name;
  13474. opt.innerText = `${i.name} (${i.type || 'net'}${i.ip ? ' - ' + i.ip : ''})`;
  13475. if (selectedIface && selectedIface === i.name) opt.selected = true;
  13476. sel.appendChild(opt);
  13477. });
  13478. }
  13479. function openAddVRRPModal() {
  13480. document.getElementById('modal-vrrp-title').innerText = 'Add VRRP Instance';
  13481. document.getElementById('modal-vrrp-id').value = '';
  13482. document.getElementById('modal-vrrp-name').value = `vrrp${(state.vrrpInstances || []).length + 1}`;
  13483. document.getElementById('modal-vrrp-vrid').value = 10 + (state.vrrpInstances || []).length;
  13484. document.getElementById('modal-vrrp-priority').value = 100;
  13485. document.getElementById('modal-vrrp-vip').value = '192.168.88.254/24';
  13486. document.getElementById('modal-vrrp-version').value = '3';
  13487. document.getElementById('modal-vrrp-interval').value = 1;
  13488. document.getElementById('modal-vrrp-authtype').value = 'none';
  13489. document.getElementById('modal-vrrp-authpass').value = '';
  13490. document.getElementById('modal-vrrp-comment').value = '';
  13491. document.getElementById('modal-vrrp-preempt').checked = true;
  13492. document.getElementById('modal-vrrp-disabled').checked = false;
  13493. populateVRRPIfaceSelect('modal-vrrp-iface', '');
  13494. document.getElementById('modal-vrrp-instance').classList.remove('hidden');
  13495. }
  13496. function openEditVRRPModal(id) {
  13497. const inst = (state.vrrpInstances || []).find(item => item.id === id);
  13498. if (!inst) return;
  13499. document.getElementById('modal-vrrp-title').innerText = `Edit VRRP Instance (${inst.name})`;
  13500. document.getElementById('modal-vrrp-id').value = inst.id;
  13501. document.getElementById('modal-vrrp-name').value = inst.name;
  13502. document.getElementById('modal-vrrp-vrid').value = inst.vrid;
  13503. document.getElementById('modal-vrrp-priority').value = inst.priority;
  13504. document.getElementById('modal-vrrp-vip').value = (inst.virtual_ips || []).join(', ');
  13505. document.getElementById('modal-vrrp-version').value = String(inst.version || 3);
  13506. document.getElementById('modal-vrrp-interval').value = inst.interval || 1;
  13507. document.getElementById('modal-vrrp-authtype').value = inst.auth_type || 'none';
  13508. document.getElementById('modal-vrrp-authpass').value = inst.auth_password || '';
  13509. document.getElementById('modal-vrrp-comment').value = inst.comment || '';
  13510. document.getElementById('modal-vrrp-preempt').checked = inst.preempt !== false;
  13511. document.getElementById('modal-vrrp-disabled').checked = !!inst.disabled;
  13512. populateVRRPIfaceSelect('modal-vrrp-iface', inst.interface);
  13513. document.getElementById('modal-vrrp-instance').classList.remove('hidden');
  13514. }
  13515. function closeVRRPModal() {
  13516. document.getElementById('modal-vrrp-instance').classList.add('hidden');
  13517. }
  13518. async function submitSaveVRRP(e) {
  13519. e.preventDefault();
  13520. const id = document.getElementById('modal-vrrp-id').value;
  13521. const name = document.getElementById('modal-vrrp-name').value.trim();
  13522. const iface = document.getElementById('modal-vrrp-iface').value;
  13523. const vrid = parseInt(document.getElementById('modal-vrrp-vrid').value, 10) || 1;
  13524. const priority = parseInt(document.getElementById('modal-vrrp-priority').value, 10) || 100;
  13525. const vipRaw = document.getElementById('modal-vrrp-vip').value.trim();
  13526. const version = parseInt(document.getElementById('modal-vrrp-version').value, 10) || 3;
  13527. const interval = parseInt(document.getElementById('modal-vrrp-interval').value, 10) || 1;
  13528. const authType = document.getElementById('modal-vrrp-authtype').value;
  13529. const authPass = document.getElementById('modal-vrrp-authpass').value.trim();
  13530. const comment = document.getElementById('modal-vrrp-comment').value.trim();
  13531. const preempt = document.getElementById('modal-vrrp-preempt').checked;
  13532. const disabled = document.getElementById('modal-vrrp-disabled').checked;
  13533. const vips = vipRaw.split(',').map(s => s.trim()).filter(Boolean);
  13534. try {
  13535. const res = await fetch(`${API_BASE}/vrrp/instances`, {
  13536. method: 'POST',
  13537. headers: { 'Content-Type': 'application/json' },
  13538. body: JSON.stringify({
  13539. id,
  13540. name,
  13541. interface: iface,
  13542. vrid,
  13543. priority,
  13544. virtual_ips: vips,
  13545. version,
  13546. interval,
  13547. auth_type: authType,
  13548. auth_password: authPass,
  13549. comment,
  13550. preempt,
  13551. disabled
  13552. })
  13553. });
  13554. if (res.ok) {
  13555. showToast('VRRP Saved', `VRRP instance ${name} configured`, 'success');
  13556. closeVRRPModal();
  13557. loadVRRP(false);
  13558. fetchData(false);
  13559. } else {
  13560. const err = await res.text();
  13561. showToast('Error', err, 'error');
  13562. }
  13563. } catch (err) {
  13564. showToast('Error', err.message, 'error');
  13565. }
  13566. }
  13567. async function deleteVRRP(id, name) {
  13568. if (!confirm(`Delete VRRP instance "${name}"?`)) return;
  13569. try {
  13570. const res = await fetch(`${API_BASE}/vrrp/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  13571. if (res.ok) {
  13572. showToast('Deleted', `VRRP instance ${name} removed`, 'info');
  13573. loadVRRP(false);
  13574. fetchData(false);
  13575. } else {
  13576. const err = await res.text();
  13577. showToast('Error', err, 'error');
  13578. }
  13579. } catch (err) {
  13580. showToast('Error', err.message, 'error');
  13581. }
  13582. }
  13583. async function toggleVRRPState(id, disabled) {
  13584. try {
  13585. const res = await fetch(`${API_BASE}/vrrp/instances/${encodeURIComponent(id)}/state`, {
  13586. method: 'POST',
  13587. headers: { 'Content-Type': 'application/json' },
  13588. body: JSON.stringify({ disabled })
  13589. });
  13590. if (res.ok) {
  13591. showToast('State Updated', disabled ? 'VRRP disabled' : 'VRRP enabled', 'info');
  13592. loadVRRP(false);
  13593. fetchData(false);
  13594. } else {
  13595. const err = await res.text();
  13596. showToast('Error', err, 'error');
  13597. }
  13598. } catch (err) {
  13599. showToast('Error', err.message, 'error');
  13600. }
  13601. }
  13602. // Global observer for dynamically injected tables (e.g. inside modals or drawers)
  13603. if (typeof MutationObserver !== 'undefined' && typeof document !== 'undefined') {
  13604. let docSortDebounce = null;
  13605. const docTableObserver = new MutationObserver((mutations) => {
  13606. let needsInit = false;
  13607. for (const m of mutations) {
  13608. for (const node of m.addedNodes) {
  13609. if (node.nodeType === 1) {
  13610. if (node.tagName === 'TABLE' && !node.closest('tbody, thead')) {
  13611. needsInit = true;
  13612. break;
  13613. } else if (node.querySelector && !node.closest('table') && node.querySelector('table')) {
  13614. needsInit = true;
  13615. break;
  13616. }
  13617. }
  13618. }
  13619. if (needsInit) break;
  13620. }
  13621. if (needsInit) {
  13622. clearTimeout(docSortDebounce);
  13623. docSortDebounce = setTimeout(initTableSorting, 100);
  13624. }
  13625. });
  13626. docTableObserver.observe(document.body || document.documentElement, { childList: true, subtree: true });
  13627. }
  13628. // =========================================================================
  13629. // BANDWIDTH TEST (BwTest) BENCHMARK ENGINE
  13630. // =========================================================================
  13631. const bwtestState = {
  13632. running: false,
  13633. pollTimer: null,
  13634. eventSource: null,
  13635. chartPoints: [],
  13636. maxChartPoints: 60,
  13637. serverConfig: null,
  13638. peakTx: 0,
  13639. peakRx: 0,
  13640. targetDuration: 10,
  13641. lastSampleElapsed: -1,
  13642. sessionID: null
  13643. };
  13644. async function loadBwTestView() {
  13645. resizeBwTestCanvas();
  13646. await Promise.all([fetchBwTestServerStatus(), loadBwTestHistory(), checkActiveBwTest()]);
  13647. }
  13648. async function fetchBwTestServerStatus() {
  13649. try {
  13650. const res = await fetch(`${API_BASE}/tools/bwtest/server`);
  13651. if (!res.ok) return;
  13652. const s = await res.json();
  13653. bwtestState.serverConfig = s;
  13654. // Update indicator and badges
  13655. const indicator = document.getElementById('bwtest-server-indicator');
  13656. const badge = document.getElementById('bwtest-server-badge');
  13657. const sideBadge = document.getElementById('badge-bwtest-server');
  13658. if (s.enabled && s.running) {
  13659. if (indicator) indicator.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  13660. if (badge) {
  13661. badge.innerText = `Port ${s.port} (Active)`;
  13662. badge.className = 'text-emerald-400 font-bold';
  13663. }
  13664. if (sideBadge) {
  13665. sideBadge.innerText = s.port;
  13666. 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';
  13667. }
  13668. } else {
  13669. if (indicator) indicator.className = 'w-2 h-2 rounded-full bg-slate-600';
  13670. if (badge) {
  13671. badge.innerText = `Disabled`;
  13672. badge.className = 'text-slate-500 font-bold';
  13673. }
  13674. if (sideBadge) {
  13675. sideBadge.innerText = 'Off';
  13676. sideBadge.className = 'text-[10px] bg-slate-800 text-slate-500 border border-slate-700 px-1.5 py-0.2 rounded-full font-mono';
  13677. }
  13678. }
  13679. // Modal fields
  13680. const toggle = document.getElementById('bwtest-server-enable-toggle');
  13681. const serverModal = document.getElementById('modal-bwtest-server');
  13682. const editing = serverModal && !serverModal.classList.contains('hidden');
  13683. if (toggle && !editing) toggle.checked = !!s.enabled;
  13684. const portInp = document.getElementById('bwtest-server-port-input');
  13685. if (portInp && !editing) portInp.value = s.port || 2000;
  13686. const actSess = document.getElementById('bwtest-modal-active-sessions');
  13687. if (actSess) actSess.innerText = s.active_sessions || 0;
  13688. const totServ = document.getElementById('bwtest-modal-total-served');
  13689. if (totServ) totServ.innerText = s.total_sessions_served || 0;
  13690. const totBytes = document.getElementById('bwtest-modal-total-bytes');
  13691. if (totBytes) totBytes.innerText = formatBytes(s.total_bytes_processed || 0);
  13692. } catch (err) {
  13693. console.error('Failed to fetch BwTest server status:', err);
  13694. }
  13695. }
  13696. function openBwTestServerModal() {
  13697. const cfg = bwtestState.serverConfig;
  13698. if (cfg) {
  13699. document.getElementById('bwtest-server-enable-toggle').checked = !!cfg.enabled;
  13700. document.getElementById('bwtest-server-port-input').value = cfg.port || 2000;
  13701. }
  13702. fetchBwTestServerStatus();
  13703. document.getElementById('modal-bwtest-server')?.classList.remove('hidden');
  13704. }
  13705. function closeBwTestServerModal() {
  13706. document.getElementById('modal-bwtest-server')?.classList.add('hidden');
  13707. }
  13708. async function submitBwTestServerSettings(e) {
  13709. e.preventDefault();
  13710. const enabled = document.getElementById('bwtest-server-enable-toggle').checked;
  13711. const port = parseInt(document.getElementById('bwtest-server-port-input').value, 10) || 2000;
  13712. try {
  13713. const res = await fetch(`${API_BASE}/tools/bwtest/server`, {
  13714. method: 'POST',
  13715. headers: { 'Content-Type': 'application/json' },
  13716. body: JSON.stringify({ enabled, port, listen_addr: '0.0.0.0', allow_anonymous: true })
  13717. });
  13718. if (!res.ok) {
  13719. const err = await res.json();
  13720. throw new Error(err.error || 'Failed to update server configuration');
  13721. }
  13722. showToast('BwTest Server', `Bandwidth Test server updated (Port ${port})`, 'success');
  13723. closeBwTestServerModal();
  13724. fetchBwTestServerStatus();
  13725. } catch (err) {
  13726. showToast('Server Configuration Error', err.message, 'error');
  13727. }
  13728. }
  13729. function setBwTestTarget(target) {
  13730. const inp = document.getElementById('bwtest-input-target');
  13731. if (inp) inp.value = target;
  13732. }
  13733. function setBwTestProtocol(proto) {
  13734. const hiddenInp = document.getElementById('bwtest-input-protocol');
  13735. if (hiddenInp) hiddenInp.value = proto;
  13736. const btnUdp = document.getElementById('bwtest-proto-udp');
  13737. const btnTcp = document.getElementById('bwtest-proto-tcp');
  13738. const badge = document.getElementById('bwtest-proto-badge');
  13739. const pktField = document.getElementById('bwtest-field-pktsize');
  13740. 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';
  13741. 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';
  13742. 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';
  13743. if (proto === 'udp') {
  13744. if (btnUdp) {
  13745. btnUdp.className = activeUdpCls;
  13746. const dot = btnUdp.querySelector('span');
  13747. if (dot) dot.className = 'w-2 h-2 rounded-full bg-emerald-400';
  13748. }
  13749. if (btnTcp) {
  13750. btnTcp.className = inactiveCls;
  13751. const dot = btnTcp.querySelector('span');
  13752. if (dot) dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  13753. }
  13754. if (badge) {
  13755. badge.innerText = 'UDP Mode (RFC 3550 Jitter + Loss %)';
  13756. badge.className = 'text-[10px] font-mono text-emerald-400 bg-emerald-500/10 px-2 py-0.5 rounded border border-emerald-500/20';
  13757. }
  13758. if (pktField) pktField.classList.remove('opacity-40');
  13759. } else {
  13760. if (btnUdp) {
  13761. btnUdp.className = inactiveCls;
  13762. const dot = btnUdp.querySelector('span');
  13763. if (dot) dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  13764. }
  13765. if (btnTcp) {
  13766. btnTcp.className = activeTcpCls;
  13767. const dot = btnTcp.querySelector('span');
  13768. if (dot) dot.className = 'w-2 h-2 rounded-full bg-blue-400';
  13769. }
  13770. if (badge) {
  13771. badge.innerText = 'TCP Mode (Sliding Window Throughput)';
  13772. badge.className = 'text-[10px] font-mono text-blue-400 bg-blue-500/10 px-2 py-0.5 rounded border border-blue-500/20';
  13773. }
  13774. if (pktField) pktField.classList.add('opacity-40');
  13775. }
  13776. }
  13777. function setBwTestDirection(dir) {
  13778. const hiddenInp = document.getElementById('bwtest-input-direction');
  13779. if (hiddenInp) hiddenInp.value = dir;
  13780. const btnBoth = document.getElementById('bwtest-dir-both');
  13781. const btnTx = document.getElementById('bwtest-dir-tx');
  13782. const btnRx = document.getElementById('bwtest-dir-rx');
  13783. 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';
  13784. 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';
  13785. if (btnBoth) btnBoth.className = dir === 'both' ? activeCls : inactiveCls;
  13786. if (btnTx) btnTx.className = dir === 'tx' ? activeCls : inactiveCls;
  13787. if (btnRx) btnRx.className = dir === 'rx' ? activeCls : inactiveCls;
  13788. }
  13789. function setBwTestLimit(bps) {
  13790. const sel = document.getElementById('bwtest-input-limit');
  13791. if (sel) sel.value = String(bps);
  13792. }
  13793. async function checkActiveBwTest() {
  13794. try {
  13795. const res = await fetch(`${API_BASE}/tools/bwtest/status`);
  13796. if (!res.ok) return;
  13797. const st = await res.json();
  13798. if (st.running) {
  13799. setBwTestRunningUI(true);
  13800. processBwTestStatus(st);
  13801. startBwTestTelemetry();
  13802. }
  13803. } catch (err) {
  13804. console.error('Failed to check active BwTest:', err);
  13805. }
  13806. }
  13807. async function startBwTest(e) {
  13808. if (e && e.preventDefault) e.preventDefault();
  13809. const target = document.getElementById('bwtest-input-target').value.trim() || '127.0.0.1';
  13810. const port = parseInt(document.getElementById('bwtest-input-port').value, 10) || 2000;
  13811. const direction = document.getElementById('bwtest-input-direction').value || 'both';
  13812. const protocol = document.getElementById('bwtest-input-protocol').value || 'udp';
  13813. const bandwidth_limit = parseInt(document.getElementById('bwtest-input-limit').value, 10) || 0;
  13814. const packet_size = parseInt(document.getElementById('bwtest-input-pktsize').value, 10) || 1472;
  13815. const streams = parseInt(document.getElementById('bwtest-input-streams').value, 10) || 1;
  13816. const duration = parseInt(document.getElementById('bwtest-input-duration').value, 10);
  13817. bwtestState.targetDuration = duration;
  13818. bwtestState.chartPoints = [];
  13819. bwtestState.peakTx = 0;
  13820. bwtestState.peakRx = 0;
  13821. bwtestState.lastSampleElapsed = -1;
  13822. bwtestState.sessionID = null;
  13823. // Clear UI elements
  13824. document.getElementById('bwtest-stat-tx-mbps').innerText = '0.00';
  13825. document.getElementById('bwtest-stat-tx-peak').innerText = '0.00 Mbps';
  13826. document.getElementById('bwtest-stat-tx-pkts').innerText = '0';
  13827. document.getElementById('bwtest-stat-rx-mbps').innerText = '0.00';
  13828. document.getElementById('bwtest-stat-rx-peak').innerText = '0.00 Mbps';
  13829. document.getElementById('bwtest-stat-rx-pkts').innerText = '0';
  13830. document.getElementById('bwtest-stat-loss').innerText = '0.0%';
  13831. document.getElementById('bwtest-stat-jitter').innerText = '0.00 ms';
  13832. document.getElementById('bwtest-stat-time').innerText = '0.0s';
  13833. document.getElementById('bwtest-stat-data').innerText = '0.0 MB';
  13834. document.getElementById('bwtest-stat-target-dur').innerText = duration > 0 ? `/ ${duration}s` : '/ ∞';
  13835. const tbody = document.getElementById('bwtest-samples-tbody');
  13836. if (tbody) tbody.innerHTML = '';
  13837. document.getElementById('bwtest-sample-count').innerText = '0 samples';
  13838. setBwTestRunningUI(true);
  13839. try {
  13840. const res = await fetch(`${API_BASE}/tools/bwtest/start`, {
  13841. method: 'POST',
  13842. headers: { 'Content-Type': 'application/json' },
  13843. body: JSON.stringify({
  13844. target,
  13845. port,
  13846. direction,
  13847. protocol,
  13848. bandwidth_limit,
  13849. packet_size,
  13850. streams,
  13851. duration
  13852. })
  13853. });
  13854. if (!res.ok) {
  13855. const err = await res.json();
  13856. throw new Error(err.error || 'Failed to start bandwidth test');
  13857. }
  13858. showToast('Benchmark Started', `Target: ${target}:${port} (${direction.toUpperCase()}, ${protocol.toUpperCase()})`, 'info');
  13859. startBwTestTelemetry();
  13860. } catch (err) {
  13861. setBwTestRunningUI(false);
  13862. showToast('Start Failed', err.message, 'error');
  13863. }
  13864. }
  13865. function setBwTestRunningUI(running) {
  13866. bwtestState.running = running;
  13867. const startBtn = document.getElementById('bwtest-btn-start');
  13868. const stopBtn = document.getElementById('bwtest-btn-stop');
  13869. const badge = document.getElementById('bwtest-run-status-badge');
  13870. const ph = document.getElementById('bwtest-chart-placeholder');
  13871. if (running) {
  13872. if (startBtn) {
  13873. startBtn.disabled = true;
  13874. startBtn.classList.add('opacity-50', 'cursor-not-allowed');
  13875. }
  13876. if (stopBtn) {
  13877. stopBtn.disabled = false;
  13878. stopBtn.classList.remove('opacity-40');
  13879. }
  13880. if (badge) {
  13881. badge.innerText = 'TESTING...';
  13882. 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';
  13883. }
  13884. if (ph) ph.style.display = 'none';
  13885. } else {
  13886. if (startBtn) {
  13887. startBtn.disabled = false;
  13888. startBtn.classList.remove('opacity-50', 'cursor-not-allowed');
  13889. }
  13890. if (stopBtn) {
  13891. stopBtn.disabled = true;
  13892. stopBtn.classList.add('opacity-40');
  13893. }
  13894. if (badge) {
  13895. badge.innerText = 'IDLE';
  13896. badge.className = 'px-2 py-0.5 rounded text-[10px] font-mono bg-slate-800 text-slate-400 border border-slate-700 font-semibold';
  13897. }
  13898. }
  13899. }
  13900. async function stopBwTest() {
  13901. try {
  13902. const res = await fetch(`${API_BASE}/tools/bwtest/stop`, { method: 'POST' });
  13903. if (!res.ok) throw new Error(await responseError(res));
  13904. showToast('Stop Requested', 'Waiting for the bandwidth test to finish', 'info');
  13905. if (!bwtestState.pollTimer) startBwTestTelemetry();
  13906. } catch (err) {
  13907. showToast('Stop Failed', err.message, 'error');
  13908. }
  13909. }
  13910. async function responseError(res) {
  13911. const text = await res.text();
  13912. try { const data = JSON.parse(text); return data.message || (typeof data.error === 'string' ? data.error : null) || `HTTP ${res.status}`; }
  13913. catch { return text || `HTTP ${res.status}`; }
  13914. }
  13915. function processBwTestStatus(st) {
  13916. if (st.session_id && bwtestState.sessionID !== st.session_id) {
  13917. bwtestState.sessionID = st.session_id;
  13918. bwtestState.lastSampleElapsed = -1;
  13919. }
  13920. for (const sample of st.recent_samples || []) {
  13921. if (sample.elapsed_sec > (bwtestState.lastSampleElapsed ?? -1)) {
  13922. handleBwTestSample(sample);
  13923. bwtestState.lastSampleElapsed = sample.elapsed_sec;
  13924. }
  13925. }
  13926. if (!st.running) {
  13927. if (bwtestState.pollTimer) clearInterval(bwtestState.pollTimer);
  13928. bwtestState.pollTimer = null;
  13929. setBwTestRunningUI(false);
  13930. handleBwTestFinish(st.summary, st.error);
  13931. }
  13932. }
  13933. function startBwTestTelemetry() {
  13934. if (!state.currentUser) return;
  13935. if (bwtestState.pollTimer) clearInterval(bwtestState.pollTimer);
  13936. let busy = false;
  13937. const poll = async () => {
  13938. if (busy || !state.currentUser || document.hidden) return;
  13939. busy = true;
  13940. try {
  13941. const res = await fetch(`${API_BASE}/tools/bwtest/status`);
  13942. if (!res.ok) throw new Error(await responseError(res));
  13943. processBwTestStatus(await res.json());
  13944. } catch (err) {
  13945. console.error('BwTest polling error:', err);
  13946. } finally { busy = false; }
  13947. };
  13948. bwtestState.pollTimer = setInterval(poll, 400);
  13949. poll();
  13950. }
  13951. function handleBwTestSample(s) {
  13952. if (!s) return;
  13953. const payloadHint = document.getElementById('bwtest-effective-payload');
  13954. if (payloadHint && s.packet_size) payloadHint.innerText = `Effective datagram: ${s.packet_size} bytes`;
  13955. const txMbps = s.tx_mbps || 0;
  13956. const rxMbps = s.rx_mbps || 0;
  13957. if (txMbps > bwtestState.peakTx) bwtestState.peakTx = txMbps;
  13958. if (rxMbps > bwtestState.peakRx) bwtestState.peakRx = rxMbps;
  13959. // KPI updates
  13960. const elTx = document.getElementById('bwtest-stat-tx-mbps');
  13961. if (elTx) {
  13962. elTx.innerText = txMbps.toFixed(2);
  13963. elTx.title = `Confirmed by peer; locally offered: ${(s.offered_tx_mbps || 0).toFixed(2)} Mbps`;
  13964. }
  13965. const elTxPeak = document.getElementById('bwtest-stat-tx-peak');
  13966. if (elTxPeak) elTxPeak.innerText = `${bwtestState.peakTx.toFixed(2)} Mbps`;
  13967. const elTxPkts = document.getElementById('bwtest-stat-tx-pkts');
  13968. if (elTxPkts) elTxPkts.innerText = s.tx_packets || 0;
  13969. const elRx = document.getElementById('bwtest-stat-rx-mbps');
  13970. if (elRx) elRx.innerText = rxMbps.toFixed(2);
  13971. const elRxPeak = document.getElementById('bwtest-stat-rx-peak');
  13972. if (elRxPeak) elRxPeak.innerText = `${bwtestState.peakRx.toFixed(2)} Mbps`;
  13973. const elRxPkts = document.getElementById('bwtest-stat-rx-pkts');
  13974. if (elRxPkts) elRxPkts.innerText = s.rx_packets || 0;
  13975. const elLoss = document.getElementById('bwtest-stat-loss');
  13976. if (elLoss) {
  13977. elLoss.innerText = `${(s.loss_pct || 0).toFixed(1)}%`;
  13978. elLoss.className = (s.loss_pct > 1.0) ? 'text-2xl font-bold text-rose-400' : 'text-2xl font-bold text-emerald-400';
  13979. }
  13980. const elLostPkts = document.getElementById('bwtest-stat-lost-pkts');
  13981. if (elLostPkts) elLostPkts.innerText = s.lost_packets || 0;
  13982. const elJitter = document.getElementById('bwtest-stat-jitter');
  13983. if (elJitter) elJitter.innerText = `${(s.jitter_ms || 0).toFixed(2)} ms`;
  13984. const elTime = document.getElementById('bwtest-stat-time');
  13985. if (elTime) elTime.innerText = `${(s.elapsed_sec || 0).toFixed(1)}s`;
  13986. const elData = document.getElementById('bwtest-stat-data');
  13987. if (elData) elData.innerText = formatBytes((s.tx_bytes || 0) + (s.rx_bytes || 0));
  13988. const elGraphRate = document.getElementById('bwtest-graph-rate');
  13989. if (elGraphRate) elGraphRate.innerText = `TX: ${txMbps.toFixed(1)} Mbps • RX: ${rxMbps.toFixed(1)} Mbps`;
  13990. // Append point to chart buffer
  13991. bwtestState.chartPoints.push({
  13992. elapsed: s.elapsed_sec || 0,
  13993. tx: txMbps,
  13994. rx: rxMbps
  13995. });
  13996. if (bwtestState.chartPoints.length > bwtestState.maxChartPoints) {
  13997. bwtestState.chartPoints.shift();
  13998. }
  13999. drawBwTestChart();
  14000. // Add row to breakdown table
  14001. const tbody = document.getElementById('bwtest-samples-tbody');
  14002. if (tbody) {
  14003. const tr = document.createElement('tr');
  14004. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  14005. tr.innerHTML = `
  14006. <td class="py-1.5 px-3 font-semibold text-white">${(s.elapsed_sec || 0).toFixed(1)}s</td>
  14007. <td class="py-1.5 px-3 font-bold text-cyan-400">${txMbps.toFixed(2)} Mbps</td>
  14008. <td class="py-1.5 px-3 font-bold text-purple-400">${rxMbps.toFixed(2)} Mbps</td>
  14009. <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>
  14010. <td class="py-1.5 px-3 text-slate-300">${(s.jitter_ms || 0).toFixed(2)} ms</td>
  14011. <td class="py-1.5 px-3 text-slate-400">${formatBytes((s.tx_bytes || 0) + (s.rx_bytes || 0))}</td>
  14012. `;
  14013. tbody.insertBefore(tr, tbody.firstChild);
  14014. const countEl = document.getElementById('bwtest-sample-count');
  14015. if (countEl) countEl.innerText = `${tbody.children.length} samples`;
  14016. }
  14017. }
  14018. function handleBwTestFinish(summary, error) {
  14019. const badge = document.getElementById('bwtest-run-status-badge');
  14020. if (error) {
  14021. showToast('Benchmark Error', error, 'error');
  14022. if (badge) {
  14023. badge.innerText = 'ERROR';
  14024. 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';
  14025. }
  14026. } else if (summary) {
  14027. const avgTx = summary.avg_tx_mbps.toFixed(1);
  14028. const avgRx = summary.avg_rx_mbps.toFixed(1);
  14029. showToast('Benchmark Complete', `Average TX: ${avgTx} Mbps | RX: ${avgRx} Mbps (Loss: ${summary.avg_loss_pct.toFixed(1)}%)`, 'success');
  14030. if (badge) {
  14031. badge.innerText = 'COMPLETED';
  14032. 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';
  14033. }
  14034. }
  14035. loadBwTestHistory();
  14036. fetchBwTestServerStatus();
  14037. }
  14038. function resizeBwTestCanvas() {
  14039. const canvas = document.getElementById('bwtest-chart');
  14040. if (!canvas || !canvas.parentElement) return;
  14041. const rect = canvas.parentElement.getBoundingClientRect();
  14042. const dpr = window.devicePixelRatio || 1;
  14043. canvas.width = rect.width * dpr;
  14044. canvas.height = rect.height * dpr;
  14045. const ctx = canvas.getContext('2d');
  14046. ctx.scale(dpr, dpr);
  14047. drawBwTestChart();
  14048. }
  14049. window.addEventListener('resize', () => {
  14050. if (state.activeTab === 'bwtest') resizeBwTestCanvas();
  14051. });
  14052. function drawBwTestChart() {
  14053. const canvas = document.getElementById('bwtest-chart');
  14054. if (!canvas) return;
  14055. const ctx = canvas.getContext('2d');
  14056. const dpr = window.devicePixelRatio || 1;
  14057. const width = canvas.width / dpr;
  14058. const height = canvas.height / dpr;
  14059. ctx.clearRect(0, 0, width, height);
  14060. const points = bwtestState.chartPoints;
  14061. if (!points || points.length === 0) return;
  14062. // Determine scale ceiling
  14063. let maxRate = 10;
  14064. for (const p of points) {
  14065. if (p.tx > maxRate) maxRate = p.tx;
  14066. if (p.rx > maxRate) maxRate = p.rx;
  14067. }
  14068. maxRate = Math.ceil(maxRate * 1.25); // 25% headroom
  14069. const paddingLeft = 55;
  14070. const paddingBottom = 24;
  14071. const paddingTop = 12;
  14072. const paddingRight = 16;
  14073. const chartW = width - paddingLeft - paddingRight;
  14074. const chartH = height - paddingTop - paddingBottom;
  14075. // Grid Lines and Y-Axis labels
  14076. ctx.strokeStyle = 'rgba(51, 65, 85, 0.4)';
  14077. ctx.lineWidth = 1;
  14078. ctx.fillStyle = '#94a3b8';
  14079. ctx.font = '10px monospace';
  14080. ctx.textAlign = 'right';
  14081. const gridSteps = 4;
  14082. for (let i = 0; i <= gridSteps; i++) {
  14083. const val = (maxRate / gridSteps) * i;
  14084. const y = paddingTop + chartH - (i / gridSteps) * chartH;
  14085. ctx.beginPath();
  14086. ctx.moveTo(paddingLeft, y);
  14087. ctx.lineTo(width - paddingRight, y);
  14088. ctx.stroke();
  14089. ctx.fillText(`${Math.round(val)}M`, paddingLeft - 8, y + 3);
  14090. }
  14091. // Draw TX Line (Cyan #22d3ee)
  14092. drawSeries(ctx, points, p => p.tx, maxRate, paddingLeft, paddingTop, chartW, chartH, '#22d3ee', 'rgba(34, 211, 238, 0.15)');
  14093. // Draw RX Line (Purple #a855f7)
  14094. drawSeries(ctx, points, p => p.rx, maxRate, paddingLeft, paddingTop, chartW, chartH, '#a855f7', 'rgba(168, 85, 247, 0.15)');
  14095. }
  14096. function drawSeries(ctx, points, valFn, maxVal, left, top, w, h, strokeColor, fillColor) {
  14097. if (points.length < 2) return;
  14098. const stepX = w / Math.max(points.length - 1, 1);
  14099. // Gradient area fill
  14100. const grad = ctx.createLinearGradient(0, top, 0, top + h);
  14101. grad.addColorStop(0, fillColor);
  14102. grad.addColorStop(1, 'rgba(0, 0, 0, 0)');
  14103. ctx.beginPath();
  14104. points.forEach((p, idx) => {
  14105. const x = left + idx * stepX;
  14106. const val = valFn(p);
  14107. const y = top + h - (val / maxVal) * h;
  14108. if (idx === 0) {
  14109. ctx.moveTo(x, y);
  14110. } else {
  14111. ctx.lineTo(x, y);
  14112. }
  14113. });
  14114. // Complete path for fill
  14115. ctx.lineTo(left + (points.length - 1) * stepX, top + h);
  14116. ctx.lineTo(left, top + h);
  14117. ctx.closePath();
  14118. ctx.fillStyle = grad;
  14119. ctx.fill();
  14120. // Draw line stroke
  14121. ctx.beginPath();
  14122. ctx.lineWidth = 2.5;
  14123. ctx.strokeStyle = strokeColor;
  14124. points.forEach((p, idx) => {
  14125. const x = left + idx * stepX;
  14126. const val = valFn(p);
  14127. const y = top + h - (val / maxVal) * h;
  14128. if (idx === 0) {
  14129. ctx.moveTo(x, y);
  14130. } else {
  14131. ctx.lineTo(x, y);
  14132. }
  14133. });
  14134. ctx.stroke();
  14135. // Draw end point halo
  14136. const lastP = points[points.length - 1];
  14137. const lastX = left + (points.length - 1) * stepX;
  14138. const lastY = top + h - (valFn(lastP) / maxVal) * h;
  14139. ctx.fillStyle = strokeColor;
  14140. ctx.beginPath();
  14141. ctx.arc(lastX, lastY, 4, 0, 2 * Math.PI);
  14142. ctx.fill();
  14143. }
  14144. async function loadBwTestHistory() {
  14145. try {
  14146. const res = await fetch(`${API_BASE}/tools/bwtest/history`);
  14147. if (!res.ok) return;
  14148. const list = await res.json();
  14149. renderBwTestHistory(Array.isArray(list) ? list : []);
  14150. } catch (err) {
  14151. console.error('Failed to load BwTest history:', err);
  14152. }
  14153. }
  14154. function renderBwTestHistory(list) {
  14155. const tbody = document.getElementById('bwtest-history-tbody');
  14156. if (!tbody) return;
  14157. if (list.length === 0) {
  14158. 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>`;
  14159. return;
  14160. }
  14161. tbody.innerHTML = '';
  14162. list.forEach(item => {
  14163. const s = item.summary || {};
  14164. const tr = document.createElement('tr');
  14165. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  14166. const dirBadge = item.direction === 'both'
  14167. ? `<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>`
  14168. : item.direction === 'tx'
  14169. ? `<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>`
  14170. : `<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>`;
  14171. const protoBadge = item.protocol === 'tcp'
  14172. ? `<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>`
  14173. : `<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>`;
  14174. const dateStr = item.timestamp ? new Date(item.timestamp).toLocaleString() : '-';
  14175. tr.innerHTML = `
  14176. <td class="py-2.5 px-4 font-bold text-white font-mono text-[11px]">${escapeHtml(item.id || '-')}</td>
  14177. <td class="py-2.5 px-4 text-emerald-400 font-mono font-medium">${escapeHtml(item.target || '-')}</td>
  14178. <td class="py-2.5 px-4">${protoBadge}</td>
  14179. <td class="py-2.5 px-4">${dirBadge}</td>
  14180. <td class="py-2.5 px-4 text-slate-300">${(s.duration_sec || 0).toFixed(1)}s</td>
  14181. <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>
  14182. <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>
  14183. <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>
  14184. <td class="py-2.5 px-4 text-slate-300 font-mono">${(s.avg_jitter_ms || 0).toFixed(2)} ms</td>
  14185. <td class="py-2.5 px-4 text-slate-400 text-[11px] font-sans">${escapeHtml(dateStr)}</td>
  14186. `;
  14187. tbody.appendChild(tr);
  14188. });
  14189. }
  14190. // ======================== SETTINGS & ROUTER DNS ========================
  14191. state.settingsSubTab = 'dns';
  14192. state.dnsSettings = null;
  14193. state.dnsStaticRecords = [];
  14194. state.dnsStatus = null;
  14195. function switchSettingsSubTab(sub) {
  14196. state.settingsSubTab = sub;
  14197. const btnDns = document.getElementById('btn-settings-subtab-dns');
  14198. const btnSys = document.getElementById('btn-settings-subtab-system');
  14199. const tabDns = document.getElementById('settings-subtab-dns');
  14200. const tabSys = document.getElementById('settings-subtab-system');
  14201. if (sub === 'dns') {
  14202. if (btnDns) {
  14203. 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';
  14204. }
  14205. if (btnSys) {
  14206. 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';
  14207. }
  14208. tabDns?.classList.remove('hidden');
  14209. tabSys?.classList.add('hidden');
  14210. loadDNSSettings();
  14211. } else {
  14212. if (btnSys) {
  14213. 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';
  14214. }
  14215. if (btnDns) {
  14216. 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';
  14217. }
  14218. tabSys?.classList.remove('hidden');
  14219. tabDns?.classList.add('hidden');
  14220. loadSystemSettings();
  14221. }
  14222. }
  14223. async function loadSettingsData(showLoading = false) {
  14224. if (state.settingsSubTab === 'system') {
  14225. await loadSystemSettings();
  14226. } else {
  14227. await loadDNSSettings();
  14228. }
  14229. }
  14230. async function loadDNSSettings() {
  14231. try {
  14232. const [settingsRes, staticRes, statusRes] = await Promise.all([
  14233. fetch(`${API_BASE}/dns/settings`),
  14234. fetch(`${API_BASE}/dns/static`),
  14235. fetch(`${API_BASE}/dns/status`)
  14236. ]);
  14237. if (settingsRes.ok) {
  14238. state.dnsSettings = await settingsRes.json();
  14239. populateDNSSettingsForm(state.dnsSettings);
  14240. }
  14241. if (staticRes.ok) {
  14242. state.dnsStaticRecords = await staticRes.json();
  14243. renderStaticDNSList();
  14244. }
  14245. if (statusRes.ok) {
  14246. state.dnsStatus = await statusRes.json();
  14247. updateDNSStatusView(state.dnsStatus);
  14248. }
  14249. } catch (err) {
  14250. console.error('Failed to load DNS settings:', err);
  14251. }
  14252. }
  14253. function populateDNSSettingsForm(s) {
  14254. if (!s) return;
  14255. const dnsForm = document.getElementById('form-dns-settings');
  14256. const isEditing = dnsForm && (dnsForm.contains(document.activeElement) || dnsForm.dataset.dirty === 'true');
  14257. const dynamicEl = document.getElementById('dns-dynamic-servers-list');
  14258. if (dynamicEl) {
  14259. if (Array.isArray(s.dynamic_servers) && s.dynamic_servers.length > 0) {
  14260. 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(' ');
  14261. } else {
  14262. dynamicEl.innerText = 'None';
  14263. }
  14264. }
  14265. // If user is actively typing or editing in the form, do not overwrite their inputs!
  14266. if (isEditing) return;
  14267. const serversInput = document.getElementById('dns-servers-input');
  14268. if (serversInput) serversInput.value = (s.servers || []).join(', ');
  14269. const cacheSizeInput = document.getElementById('dns-cache-size-input');
  14270. if (cacheSizeInput) cacheSizeInput.value = s.cache_size || 2048;
  14271. const domainInput = document.getElementById('dns-domain-input');
  14272. if (domainInput) domainInput.value = s.domain || '';
  14273. const allowRemoteInput = document.getElementById('dns-allow-remote-input');
  14274. if (allowRemoteInput) allowRemoteInput.checked = s.allow_remote_requests !== false;
  14275. }
  14276. function updateDNSStatusView(st) {
  14277. if (!st) return;
  14278. const preview = document.getElementById('dns-resolv-preview');
  14279. if (preview) preview.innerText = st.resolv_conf_content || '(empty)';
  14280. const pillText = document.getElementById('dns-live-status-text');
  14281. const pill = document.getElementById('dns-live-status-pill');
  14282. if (pill && pillText) {
  14283. if (st.service_running) {
  14284. 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';
  14285. pillText.innerText = 'DNS Service Active';
  14286. } else {
  14287. 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';
  14288. pillText.innerText = 'DNS Service Inactive';
  14289. }
  14290. }
  14291. }
  14292. function appendDNSPreset(preset) {
  14293. const input = document.getElementById('dns-servers-input');
  14294. if (!input) return;
  14295. const dnsForm = document.getElementById('form-dns-settings');
  14296. if (dnsForm) dnsForm.dataset.dirty = 'true';
  14297. const current = input.value.trim();
  14298. if (!current) {
  14299. input.value = preset;
  14300. } else {
  14301. const existing = current.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  14302. const toAdd = preset.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  14303. toAdd.forEach(ip => {
  14304. if (!existing.includes(ip)) existing.push(ip);
  14305. });
  14306. input.value = existing.join(', ');
  14307. }
  14308. }
  14309. async function saveDNSSettings(e) {
  14310. e.preventDefault();
  14311. const rawServers = document.getElementById('dns-servers-input')?.value || '';
  14312. const servers = rawServers.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  14313. if (servers.length === 0) {
  14314. showToast('Validation Error', 'Please enter at least one upstream DNS server IP', 'error');
  14315. return;
  14316. }
  14317. const cacheSize = parseInt(document.getElementById('dns-cache-size-input')?.value || '2048', 10);
  14318. const domain = (document.getElementById('dns-domain-input')?.value || '').trim();
  14319. const allowRemote = document.getElementById('dns-allow-remote-input')?.checked ?? true;
  14320. try {
  14321. const res = await fetch(`${API_BASE}/dns/settings`, {
  14322. method: 'POST',
  14323. headers: { 'Content-Type': 'application/json' },
  14324. body: JSON.stringify({
  14325. servers: servers,
  14326. cache_size: cacheSize,
  14327. domain: domain,
  14328. allow_remote_requests: allowRemote
  14329. })
  14330. });
  14331. const data = await res.json();
  14332. if (res.ok) {
  14333. const dnsForm = document.getElementById('form-dns-settings');
  14334. if (dnsForm) dnsForm.dataset.dirty = 'false';
  14335. showToast('DNS Applied', 'Router DNS forwarders and resolver settings updated successfully', 'success');
  14336. loadDNSSettings();
  14337. } else {
  14338. showToast('Error', data.error || data.message || 'Failed to save DNS settings', 'error');
  14339. }
  14340. } catch (err) {
  14341. showToast('Error', err.message, 'error');
  14342. }
  14343. }
  14344. async function flushDNSCache() {
  14345. try {
  14346. const res = await fetch(`${API_BASE}/dns/flush`, { method: 'POST' });
  14347. if (res.ok) {
  14348. showToast('Cache Flushed', 'Router DNS cache cleared and static hosts reloaded', 'success');
  14349. loadDNSSettings();
  14350. } else {
  14351. const err = await res.json();
  14352. showToast('Error', err.error || 'Failed to flush cache', 'error');
  14353. }
  14354. } catch (err) {
  14355. showToast('Error', err.message, 'error');
  14356. }
  14357. }
  14358. function renderStaticDNSList() {
  14359. const tbody = document.getElementById('dns-static-tbody');
  14360. const empty = document.getElementById('dns-static-empty');
  14361. const badge = document.getElementById('dns-static-count-badge');
  14362. if (!tbody) return;
  14363. tbody.innerHTML = '';
  14364. const records = state.dnsStaticRecords || [];
  14365. if (badge) badge.innerText = `${records.length} Records`;
  14366. if (records.length === 0) {
  14367. empty?.classList.remove('hidden');
  14368. return;
  14369. }
  14370. empty?.classList.add('hidden');
  14371. records.forEach(rec => {
  14372. const tr = document.createElement('tr');
  14373. tr.className = `hover:bg-slate-800/40 transition text-xs ${rec.disabled ? 'opacity-50' : ''}`;
  14374. tr.innerHTML = `
  14375. <td class="py-2.5 px-4 font-bold text-white">${escapeHtml(rec.name)}</td>
  14376. <td class="py-2.5 px-4">
  14377. <span class="px-2 py-0.5 rounded text-[10px] font-bold ${
  14378. rec.type === 'CNAME' ? 'bg-purple-950 text-purple-300 border border-purple-800' :
  14379. (rec.type === 'AAAA' ? 'bg-blue-950 text-blue-300 border border-blue-800' : 'bg-cyan-950 text-cyan-300 border border-cyan-800')
  14380. }">
  14381. ${rec.type || 'A'}
  14382. </span>
  14383. </td>
  14384. <td class="py-2.5 px-4 text-emerald-400 font-mono">${escapeHtml(rec.address)}</td>
  14385. <td class="py-2.5 px-4 text-slate-400 font-mono">${rec.ttl || 3600}s</td>
  14386. <td class="py-2.5 px-4 text-slate-400 italic truncate max-w-[140px]">${escapeHtml(rec.comment || '-')}</td>
  14387. <td class="py-2.5 px-4">
  14388. <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'}">
  14389. ${rec.disabled ? 'Disabled' : 'Active'}
  14390. </span>
  14391. </td>
  14392. <td class="py-2.5 px-4 text-right space-x-2 font-sans whitespace-nowrap">
  14393. <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>
  14394. <button onclick="openStaticDNSModal('${rec.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold">Edit</button>
  14395. <button onclick="deleteStaticDNS('${rec.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  14396. </td>
  14397. `;
  14398. tbody.appendChild(tr);
  14399. });
  14400. }
  14401. function openStaticDNSModal(id = null) {
  14402. const modal = document.getElementById('modal-static-dns');
  14403. const title = document.getElementById('modal-static-dns-title');
  14404. const form = document.getElementById('form-static-dns');
  14405. if (!modal || !form) return;
  14406. form.reset();
  14407. document.getElementById('modal-static-dns-id').value = '';
  14408. if (id) {
  14409. const rec = (state.dnsStaticRecords || []).find(r => r.id === id);
  14410. if (rec) {
  14411. if (title) title.innerText = 'Edit Static DNS Record';
  14412. document.getElementById('modal-static-dns-id').value = rec.id;
  14413. document.getElementById('modal-static-dns-name').value = rec.name;
  14414. document.getElementById('modal-static-dns-type').value = rec.type || 'A';
  14415. document.getElementById('modal-static-dns-addr').value = rec.address;
  14416. document.getElementById('modal-static-dns-ttl').value = rec.ttl || 3600;
  14417. document.getElementById('modal-static-dns-comment').value = rec.comment || '';
  14418. document.getElementById('modal-static-dns-disabled').checked = !!rec.disabled;
  14419. }
  14420. } else {
  14421. if (title) title.innerText = 'Add Static DNS Record';
  14422. }
  14423. modal.classList.remove('hidden');
  14424. }
  14425. function closeStaticDNSModal() {
  14426. document.getElementById('modal-static-dns')?.classList.add('hidden');
  14427. }
  14428. async function submitSaveStaticDNS(e) {
  14429. e.preventDefault();
  14430. const id = document.getElementById('modal-static-dns-id')?.value || '';
  14431. const name = (document.getElementById('modal-static-dns-name')?.value || '').trim();
  14432. const type = document.getElementById('modal-static-dns-type')?.value || 'A';
  14433. const address = (document.getElementById('modal-static-dns-addr')?.value || '').trim();
  14434. const ttl = parseInt(document.getElementById('modal-static-dns-ttl')?.value || '3600', 10);
  14435. const comment = (document.getElementById('modal-static-dns-comment')?.value || '').trim();
  14436. const disabled = document.getElementById('modal-static-dns-disabled')?.checked ?? false;
  14437. if (!name || !address) {
  14438. showToast('Validation Error', 'Name and Target Address are required', 'error');
  14439. return;
  14440. }
  14441. try {
  14442. const res = await fetch(`${API_BASE}/dns/static`, {
  14443. method: 'POST',
  14444. headers: { 'Content-Type': 'application/json' },
  14445. body: JSON.stringify({ id, name, type, address, ttl, comment, disabled })
  14446. });
  14447. const data = await res.json();
  14448. if (res.ok) {
  14449. showToast('Static DNS Saved', `Saved record ${name} -> ${address}`, 'success');
  14450. closeStaticDNSModal();
  14451. loadDNSSettings();
  14452. } else {
  14453. showToast('Error', data.error || data.message || 'Failed to save record', 'error');
  14454. }
  14455. } catch (err) {
  14456. showToast('Error', err.message, 'error');
  14457. }
  14458. }
  14459. async function deleteStaticDNS(id) {
  14460. if (!confirm('Are you sure you want to delete this static DNS entry?')) return;
  14461. try {
  14462. const res = await fetch(`${API_BASE}/dns/static/${encodeURIComponent(id)}`, { method: 'DELETE' });
  14463. if (res.ok) {
  14464. showToast('Deleted', 'Static DNS record deleted', 'success');
  14465. loadDNSSettings();
  14466. }
  14467. } catch (err) {
  14468. showToast('Error', err.message, 'error');
  14469. }
  14470. }
  14471. async function toggleStaticDNS(id, disabled) {
  14472. try {
  14473. const res = await fetch(`${API_BASE}/dns/static/${encodeURIComponent(id)}/state`, {
  14474. method: 'POST',
  14475. headers: { 'Content-Type': 'application/json' },
  14476. body: JSON.stringify({ disabled })
  14477. });
  14478. if (res.ok) {
  14479. showToast('Updated', `Record ${disabled ? 'disabled' : 'enabled'}`, 'success');
  14480. loadDNSSettings();
  14481. }
  14482. } catch (err) {
  14483. showToast('Error', err.message, 'error');
  14484. }
  14485. }
  14486. async function loadSystemSettings() {
  14487. try {
  14488. const sysForm = document.getElementById('form-system-settings');
  14489. const isEditing = sysForm && (sysForm.contains(document.activeElement) || sysForm.dataset.dirty === 'true');
  14490. const res = await fetch(`${API_BASE}/system/settings`);
  14491. if (res.ok) {
  14492. const data = await res.json();
  14493. if (!isEditing) {
  14494. const hostInput = document.getElementById('system-hostname-input');
  14495. if (hostInput) hostInput.value = data.hostname || '';
  14496. const tzInput = document.getElementById('system-timezone-input');
  14497. if (tzInput && data.timezone) tzInput.value = data.timezone;
  14498. }
  14499. }
  14500. } catch (err) {
  14501. console.error('Failed to load system settings:', err);
  14502. }
  14503. }
  14504. async function saveSystemSettings(e) {
  14505. e.preventDefault();
  14506. const hostname = (document.getElementById('system-hostname-input')?.value || '').trim();
  14507. const timezone = document.getElementById('system-timezone-input')?.value || 'UTC';
  14508. try {
  14509. const res = await fetch(`${API_BASE}/system/settings`, {
  14510. method: 'POST',
  14511. headers: { 'Content-Type': 'application/json' },
  14512. body: JSON.stringify({ hostname, timezone })
  14513. });
  14514. const data = await res.json();
  14515. if (res.ok) {
  14516. const sysForm = document.getElementById('form-system-settings');
  14517. if (sysForm) sysForm.dataset.dirty = 'false';
  14518. showToast('System Updated', 'Hostname and timezone saved successfully', 'success');
  14519. const sideH = document.getElementById('side-hostname');
  14520. if (sideH) sideH.innerText = data.hostname;
  14521. } else {
  14522. showToast('Error', data.error || 'Failed to save system settings', 'error');
  14523. }
  14524. } catch (err) {
  14525. showToast('Error', err.message, 'error');
  14526. }
  14527. }
  14528. // =============================================================================
  14529. // AUTHENTICATION & USER MANAGER
  14530. // =============================================================================
  14531. async function checkAuthStatus() {
  14532. try {
  14533. const res = await originalFetch(`${API_BASE}/auth/me`, {
  14534. headers: {
  14535. 'Authorization': `Bearer ${localStorage.getItem('debtik_token') || ''}`
  14536. }
  14537. });
  14538. if (res.ok) {
  14539. const user = await res.json();
  14540. state.currentUser = user;
  14541. updateUserProfileHeader(user);
  14542. hideLoginScreen();
  14543. state.isPolling = true;
  14544. fetchData();
  14545. initLiveTrafficStream();
  14546. return true;
  14547. } else {
  14548. showLoginScreen(false);
  14549. return false;
  14550. }
  14551. } catch (err) {
  14552. showLoginScreen(false);
  14553. return false;
  14554. }
  14555. }
  14556. function showLoginScreen(isExpired = false) {
  14557. const el = document.getElementById('login-screen');
  14558. if (el) el.classList.remove('hidden');
  14559. const errEl = document.getElementById('login-error');
  14560. const errTxt = document.getElementById('login-error-text');
  14561. if (isExpired && errEl && errTxt) {
  14562. errTxt.innerText = 'Session expired. Please sign in again.';
  14563. errEl.classList.remove('hidden');
  14564. } else if (errEl) {
  14565. errEl.classList.add('hidden');
  14566. }
  14567. const pwInput = document.getElementById('login-password');
  14568. if (pwInput) pwInput.value = '';
  14569. const userInput = document.getElementById('login-username');
  14570. if (userInput && !userInput.value) userInput.focus();
  14571. else if (pwInput) pwInput.focus();
  14572. }
  14573. function hideLoginScreen() {
  14574. const el = document.getElementById('login-screen');
  14575. if (el) el.classList.add('hidden');
  14576. const errEl = document.getElementById('login-error');
  14577. if (errEl) errEl.classList.add('hidden');
  14578. }
  14579. async function handleLoginSubmit(event) {
  14580. event.preventDefault();
  14581. const username = (document.getElementById('login-username')?.value || '').trim();
  14582. const password = document.getElementById('login-password')?.value || '';
  14583. const errEl = document.getElementById('login-error');
  14584. const errTxt = document.getElementById('login-error-text');
  14585. const btn = document.getElementById('login-submit-btn');
  14586. const btnText = document.getElementById('login-btn-text');
  14587. const spinner = document.getElementById('login-btn-spinner');
  14588. if (!username || !password) {
  14589. if (errTxt) errTxt.innerText = 'Username and password are required.';
  14590. if (errEl) errEl.classList.remove('hidden');
  14591. return;
  14592. }
  14593. if (errEl) errEl.classList.add('hidden');
  14594. if (btn) btn.disabled = true;
  14595. if (btnText) btnText.innerText = 'Authenticating...';
  14596. if (spinner) spinner.classList.remove('hidden');
  14597. try {
  14598. const res = await originalFetch(`${API_BASE}/auth/login`, {
  14599. method: 'POST',
  14600. headers: { 'Content-Type': 'application/json' },
  14601. body: JSON.stringify({ username, password })
  14602. });
  14603. const data = await res.json();
  14604. if (res.ok && data.success) {
  14605. localStorage.setItem('debtik_token', data.token);
  14606. state.currentUser = data.user;
  14607. updateUserProfileHeader(data.user);
  14608. hideLoginScreen();
  14609. state.isPolling = true;
  14610. showToast('Authenticated', `Signed in as ${data.user.username}`, 'success');
  14611. const hash = window.location.hash.replace('#', '') || 'dashboard';
  14612. navigate(hash);
  14613. fetchData();
  14614. initLiveTrafficStream();
  14615. // Ensure background telemetry polling is active
  14616. if (!window._telemetryInterval) {
  14617. window._telemetryInterval = setInterval(() => {
  14618. if (state.isPolling && state.currentUser && !document.hidden) {
  14619. fetchData(false);
  14620. }
  14621. }, 5000);
  14622. }
  14623. } else {
  14624. if (errTxt) errTxt.innerText = data.message || 'Invalid username or password';
  14625. if (errEl) errEl.classList.remove('hidden');
  14626. }
  14627. } catch (err) {
  14628. if (errTxt) errTxt.innerText = err.message || 'Failed to connect to router';
  14629. if (errEl) errEl.classList.remove('hidden');
  14630. } finally {
  14631. if (btn) btn.disabled = false;
  14632. if (btnText) btnText.innerText = 'Sign In to Controller';
  14633. if (spinner) spinner.classList.add('hidden');
  14634. }
  14635. }
  14636. async function handleLogoutClick() {
  14637. try {
  14638. await originalFetch(`${API_BASE}/auth/logout`, {
  14639. method: 'POST',
  14640. headers: {
  14641. 'Authorization': `Bearer ${localStorage.getItem('debtik_token') || ''}`
  14642. }
  14643. });
  14644. } catch (e) {}
  14645. stopSessionPolling();
  14646. localStorage.removeItem('debtik_token');
  14647. state.currentUser = null;
  14648. state.isPolling = false;
  14649. if (window._telemetryInterval) {
  14650. clearInterval(window._telemetryInterval);
  14651. window._telemetryInterval = null;
  14652. }
  14653. if (trafficEventSource) {
  14654. trafficEventSource.close();
  14655. trafficEventSource = null;
  14656. }
  14657. if (trafficPollFallback) {
  14658. clearInterval(trafficPollFallback);
  14659. trafficPollFallback = null;
  14660. }
  14661. showLoginScreen(false);
  14662. showToast('Signed Out', 'You have been signed out successfully', 'info');
  14663. }
  14664. function togglePasswordVisibility(id) {
  14665. const input = document.getElementById(id);
  14666. if (!input) return;
  14667. input.type = input.type === 'password' ? 'text' : 'password';
  14668. }
  14669. function toggleUserMenu() {
  14670. const menu = document.getElementById('user-menu-dropdown');
  14671. if (menu) menu.classList.toggle('hidden');
  14672. }
  14673. function closeUserMenu() {
  14674. const menu = document.getElementById('user-menu-dropdown');
  14675. if (menu) menu.classList.add('hidden');
  14676. }
  14677. // Close user menu on outside click
  14678. document.addEventListener('click', (e) => {
  14679. const menu = document.getElementById('user-menu-dropdown');
  14680. if (!menu || menu.classList.contains('hidden')) return;
  14681. if (!e.target.closest('#user-menu-dropdown') && !e.target.closest('button[onclick*="toggleUserMenu"]')) {
  14682. menu.classList.add('hidden');
  14683. }
  14684. });
  14685. function updateUserProfileHeader(user) {
  14686. if (!user) return;
  14687. const navName = document.getElementById('nav-user-name');
  14688. if (navName) navName.innerText = user.username;
  14689. const dropName = document.getElementById('dropdown-user-name');
  14690. if (dropName) dropName.innerText = user.username;
  14691. const navRole = document.getElementById('nav-user-role');
  14692. if (navRole) navRole.innerText = (user.role || 'read').toUpperCase();
  14693. const navAvatar = document.getElementById('nav-user-avatar');
  14694. if (navAvatar) {
  14695. const initials = (user.username || 'AD').slice(0, 2).toUpperCase();
  14696. navAvatar.innerText = initials;
  14697. }
  14698. const statCurUser = document.getElementById('stat-current-user');
  14699. if (statCurUser) statCurUser.innerText = user.username;
  14700. const statCurRole = document.getElementById('stat-current-role');
  14701. if (statCurRole) statCurRole.innerText = (user.role || 'read').toUpperCase();
  14702. // Role permissions UI visibility: hide user management for non-admins
  14703. const isFullAdmin = user.role === 'full';
  14704. const navUsers = document.getElementById('nav-users');
  14705. if (navUsers) {
  14706. if (isFullAdmin) navUsers.classList.remove('hidden');
  14707. else navUsers.classList.add('hidden');
  14708. }
  14709. const dropdownUsers = document.getElementById('dropdown-item-users');
  14710. if (dropdownUsers) {
  14711. if (isFullAdmin) dropdownUsers.classList.remove('hidden');
  14712. else dropdownUsers.classList.add('hidden');
  14713. }
  14714. }
  14715. // ================= User Management CRUD =================
  14716. async function loadUsers(isManual = false) {
  14717. try {
  14718. const res = await fetch(`${API_BASE}/users`);
  14719. if (res.status === 403) {
  14720. const tbody = document.getElementById('users-table-tbody');
  14721. if (tbody) {
  14722. tbody.innerHTML = `
  14723. <tr>
  14724. <td colspan="6" class="p-6 text-center text-amber-400 font-sans">
  14725. <div class="inline-flex items-center gap-2">
  14726. <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>
  14727. <span>Viewing and managing users requires Super Administrator (full) permissions.</span>
  14728. </div>
  14729. </td>
  14730. </tr>
  14731. `;
  14732. }
  14733. return;
  14734. }
  14735. if (res.ok) {
  14736. state.users = await res.json();
  14737. renderUsersTable();
  14738. const totalUsers = document.getElementById('stat-total-users');
  14739. if (totalUsers) totalUsers.innerText = state.users.length;
  14740. const adminCount = state.users.filter(u => u.role === 'full' && !u.disabled).length;
  14741. const adminUsers = document.getElementById('stat-admin-users');
  14742. if (adminUsers) adminUsers.innerText = adminCount;
  14743. const badgeCount = document.getElementById('badge-users-count');
  14744. if (badgeCount) badgeCount.innerText = state.users.length;
  14745. if (isManual) showToast('Refreshed', 'User list updated', 'info');
  14746. }
  14747. } catch (err) {
  14748. console.error('Failed to load users:', err);
  14749. }
  14750. }
  14751. function renderUsersTable() {
  14752. const tbody = document.getElementById('users-table-tbody');
  14753. const emptyState = document.getElementById('users-empty-state');
  14754. if (!tbody) return;
  14755. tbody.innerHTML = '';
  14756. const query = (document.getElementById('users-search-input')?.value || '').trim().toLowerCase();
  14757. const filtered = (state.users || []).filter(u => {
  14758. if (!query) return true;
  14759. return u.username.toLowerCase().includes(query) ||
  14760. (u.role || '').toLowerCase().includes(query) ||
  14761. (u.comment || '').toLowerCase().includes(query);
  14762. });
  14763. if (filtered.length === 0) {
  14764. if (emptyState) emptyState.classList.remove('hidden');
  14765. return;
  14766. }
  14767. if (emptyState) emptyState.classList.add('hidden');
  14768. const currentAuthUser = state.currentUser?.username || '';
  14769. filtered.forEach(u => {
  14770. const isSelf = u.username === currentAuthUser;
  14771. const isFull = u.role === 'full';
  14772. const isWrite = u.role === 'write';
  14773. 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>`;
  14774. if (isFull) {
  14775. 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>`;
  14776. } else if (isWrite) {
  14777. 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>`;
  14778. }
  14779. const statusBadge = u.disabled
  14780. ? `<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>`
  14781. : `<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>`;
  14782. let lastLoginText = 'Never';
  14783. if (u.last_login_at && !u.last_login_at.startsWith('0001-01-01')) {
  14784. const dt = new Date(u.last_login_at);
  14785. lastLoginText = dt.toLocaleString();
  14786. }
  14787. const initials = u.username.slice(0, 2).toUpperCase();
  14788. const tr = document.createElement('tr');
  14789. tr.className = 'hover:bg-slate-800/40 transition group';
  14790. tr.innerHTML = `
  14791. <td class="py-3 px-4">
  14792. <div class="flex items-center gap-3">
  14793. <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">
  14794. ${initials}
  14795. </div>
  14796. <div>
  14797. <div class="font-bold text-white text-xs flex items-center gap-2">
  14798. <span>${escapeHtml(u.username)}</span>
  14799. ${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>' : ''}
  14800. </div>
  14801. <div class="text-[10px] text-slate-500 font-sans">Created: ${u.created_at ? new Date(u.created_at).toLocaleDateString() : '-'}</div>
  14802. </div>
  14803. </div>
  14804. </td>
  14805. <td class="py-3 px-4 font-sans">
  14806. ${roleBadge}
  14807. </td>
  14808. <td class="py-3 px-4 font-sans">
  14809. ${statusBadge}
  14810. </td>
  14811. <td class="py-3 px-4 text-slate-300 font-sans text-xs">
  14812. ${escapeHtml(u.comment) || '<span class="text-slate-600">-</span>'}
  14813. </td>
  14814. <td class="py-3 px-4 text-slate-400 text-xs">
  14815. ${lastLoginText}
  14816. </td>
  14817. <td class="py-3 px-4 text-right space-x-1.5 font-sans">
  14818. <button onclick="openAdminResetPasswordModal('${escapeHtml(u.username)}')"
  14819. class="p-1.5 rounded-lg text-slate-400 hover:text-amber-400 hover:bg-slate-800 transition" title="Reset User Password">
  14820. <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>
  14821. </button>
  14822. <button onclick="openEditUserModal('${escapeHtml(u.username)}')"
  14823. class="p-1.5 rounded-lg text-slate-400 hover:text-cyan-400 hover:bg-slate-800 transition" title="Edit User">
  14824. <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>
  14825. </button>
  14826. ${!isSelf ? `
  14827. <button onclick="deleteUser('${escapeHtml(u.username)}')"
  14828. class="p-1.5 rounded-lg text-slate-400 hover:text-rose-400 hover:bg-slate-800 transition" title="Delete User">
  14829. <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>
  14830. </button>
  14831. ` : ''}
  14832. </td>
  14833. `;
  14834. tbody.appendChild(tr);
  14835. });
  14836. }
  14837. function openAddUserModal() {
  14838. document.getElementById('user-add-username').value = '';
  14839. document.getElementById('user-add-password').value = '';
  14840. document.getElementById('user-add-confirm').value = '';
  14841. document.getElementById('user-add-role').value = 'full';
  14842. document.getElementById('user-add-comment').value = '';
  14843. document.getElementById('modal-add-user')?.classList.remove('hidden');
  14844. document.getElementById('user-add-username')?.focus();
  14845. }
  14846. function closeAddUserModal() {
  14847. document.getElementById('modal-add-user')?.classList.add('hidden');
  14848. }
  14849. async function submitAddUser(event) {
  14850. event.preventDefault();
  14851. const username = (document.getElementById('user-add-username')?.value || '').trim();
  14852. const password = document.getElementById('user-add-password')?.value || '';
  14853. const confirm = document.getElementById('user-add-confirm')?.value || '';
  14854. const role = document.getElementById('user-add-role')?.value || 'full';
  14855. const comment = (document.getElementById('user-add-comment')?.value || '').trim();
  14856. if (password !== confirm) {
  14857. showToast('Validation Error', 'Passwords do not match', 'warning');
  14858. return;
  14859. }
  14860. if (password.length < 4) {
  14861. showToast('Validation Error', 'Password must be at least 4 characters', 'warning');
  14862. return;
  14863. }
  14864. try {
  14865. const res = await fetch(`${API_BASE}/users`, {
  14866. method: 'POST',
  14867. headers: { 'Content-Type': 'application/json' },
  14868. body: JSON.stringify({ username, password, role, comment })
  14869. });
  14870. const data = await res.json();
  14871. if (res.ok) {
  14872. showToast('User Created', `Created user ${username} with ${role.toUpperCase()} permissions`, 'success');
  14873. closeAddUserModal();
  14874. loadUsers(false);
  14875. } else {
  14876. showToast('Error', data.message || 'Failed to create user', 'error');
  14877. }
  14878. } catch (err) {
  14879. showToast('Error', err.message, 'error');
  14880. }
  14881. }
  14882. function openEditUserModal(username) {
  14883. const user = (state.users || []).find(u => u.username === username);
  14884. if (!user) return;
  14885. document.getElementById('user-edit-username').value = user.username;
  14886. document.getElementById('user-edit-username-title').innerText = `@${user.username}`;
  14887. document.getElementById('user-edit-role').value = user.role || 'read';
  14888. document.getElementById('user-edit-comment').value = user.comment || '';
  14889. document.getElementById('user-edit-disabled').checked = !!user.disabled;
  14890. document.getElementById('modal-edit-user')?.classList.remove('hidden');
  14891. }
  14892. function closeEditUserModal() {
  14893. document.getElementById('modal-edit-user')?.classList.add('hidden');
  14894. }
  14895. async function submitEditUser(event) {
  14896. event.preventDefault();
  14897. const username = document.getElementById('user-edit-username')?.value;
  14898. const role = document.getElementById('user-edit-role')?.value || 'read';
  14899. const comment = (document.getElementById('user-edit-comment')?.value || '').trim();
  14900. const disabled = document.getElementById('user-edit-disabled')?.checked || false;
  14901. try {
  14902. const res = await fetch(`${API_BASE}/users/${encodeURIComponent(username)}`, {
  14903. method: 'PUT',
  14904. headers: { 'Content-Type': 'application/json' },
  14905. body: JSON.stringify({ role, comment, disabled })
  14906. });
  14907. const data = await res.json();
  14908. if (res.ok) {
  14909. showToast('User Updated', `Updated settings for ${username}`, 'success');
  14910. closeEditUserModal();
  14911. loadUsers(false);
  14912. // If updated own role/disabled status, refresh self profile
  14913. if (username === state.currentUser?.username) {
  14914. checkAuthStatus();
  14915. }
  14916. } else {
  14917. showToast('Error', data.message || 'Failed to update user', 'error');
  14918. }
  14919. } catch (err) {
  14920. showToast('Error', err.message, 'error');
  14921. }
  14922. }
  14923. function openAdminResetPasswordModal(username) {
  14924. document.getElementById('admin-reset-username').value = username;
  14925. document.getElementById('admin-reset-username-title').innerText = `@${username}`;
  14926. document.getElementById('admin-reset-new-pw').value = '';
  14927. document.getElementById('admin-reset-confirm-pw').value = '';
  14928. document.getElementById('modal-admin-reset-pw')?.classList.remove('hidden');
  14929. document.getElementById('admin-reset-new-pw')?.focus();
  14930. }
  14931. function closeAdminResetPasswordModal() {
  14932. document.getElementById('modal-admin-reset-pw')?.classList.add('hidden');
  14933. }
  14934. async function submitAdminResetPassword(event) {
  14935. event.preventDefault();
  14936. const username = document.getElementById('admin-reset-username')?.value;
  14937. const newPassword = document.getElementById('admin-reset-new-pw')?.value || '';
  14938. const confirm = document.getElementById('admin-reset-confirm-pw')?.value || '';
  14939. if (newPassword !== confirm) {
  14940. showToast('Validation Error', 'Passwords do not match', 'warning');
  14941. return;
  14942. }
  14943. if (newPassword.length < 4) {
  14944. showToast('Validation Error', 'Password must be at least 4 characters', 'warning');
  14945. return;
  14946. }
  14947. try {
  14948. const res = await fetch(`${API_BASE}/users/${encodeURIComponent(username)}/password`, {
  14949. method: 'POST',
  14950. headers: { 'Content-Type': 'application/json' },
  14951. body: JSON.stringify({ new_password: newPassword })
  14952. });
  14953. const data = await res.json();
  14954. if (res.ok) {
  14955. showToast('Password Reset', `Password for user ${username} updated successfully`, 'success');
  14956. closeAdminResetPasswordModal();
  14957. } else {
  14958. showToast('Error', data.message || 'Failed to reset password', 'error');
  14959. }
  14960. } catch (err) {
  14961. showToast('Error', err.message, 'error');
  14962. }
  14963. }
  14964. async function deleteUser(username) {
  14965. if (username === state.currentUser?.username) {
  14966. showToast('Action Forbidden', 'You cannot delete your own account', 'warning');
  14967. return;
  14968. }
  14969. if (!confirm(`Are you sure you want to completely remove user "${username}"?`)) {
  14970. return;
  14971. }
  14972. try {
  14973. const res = await fetch(`${API_BASE}/users/${encodeURIComponent(username)}`, {
  14974. method: 'DELETE'
  14975. });
  14976. const data = await res.json();
  14977. if (res.ok) {
  14978. showToast('User Deleted', `User ${username} has been removed`, 'success');
  14979. loadUsers(false);
  14980. } else {
  14981. showToast('Error', data.message || 'Failed to delete user', 'error');
  14982. }
  14983. } catch (err) {
  14984. showToast('Error', err.message, 'error');
  14985. }
  14986. }
  14987. function openSelfPasswordModal() {
  14988. document.getElementById('self-current-password').value = '';
  14989. document.getElementById('self-new-password').value = '';
  14990. document.getElementById('self-confirm-password').value = '';
  14991. document.getElementById('modal-self-password')?.classList.remove('hidden');
  14992. document.getElementById('self-current-password')?.focus();
  14993. }
  14994. function closeSelfPasswordModal() {
  14995. document.getElementById('modal-self-password')?.classList.add('hidden');
  14996. }
  14997. async function submitSelfPassword(event) {
  14998. event.preventDefault();
  14999. const oldPassword = document.getElementById('self-current-password')?.value || '';
  15000. const newPassword = document.getElementById('self-new-password')?.value || '';
  15001. const confirm = document.getElementById('self-confirm-password')?.value || '';
  15002. if (newPassword !== confirm) {
  15003. showToast('Validation Error', 'New passwords do not match', 'warning');
  15004. return;
  15005. }
  15006. if (newPassword.length < 4) {
  15007. showToast('Validation Error', 'Password must be at least 4 characters', 'warning');
  15008. return;
  15009. }
  15010. try {
  15011. const res = await fetch(`${API_BASE}/auth/change-password`, {
  15012. method: 'POST',
  15013. headers: { 'Content-Type': 'application/json' },
  15014. body: JSON.stringify({ old_password: oldPassword, new_password: newPassword })
  15015. });
  15016. const data = await res.json();
  15017. if (res.ok) {
  15018. showToast('Password Changed', 'Your password has been changed successfully', 'success');
  15019. closeSelfPasswordModal();
  15020. } else {
  15021. showToast('Error', data.message || 'Failed to change password', 'error');
  15022. }
  15023. } catch (err) {
  15024. showToast('Error', err.message, 'error');
  15025. }
  15026. }
  15027. // ==================== MANAGEMENT SERVICES (/ip service) ====================
  15028. state.services = [];
  15029. async function loadServices(manual = false) {
  15030. try {
  15031. const res = await fetch(`${API_BASE}/system/services`);
  15032. if (!res.ok) throw new Error('Failed to load services');
  15033. const data = await res.json();
  15034. state.services = data || [];
  15035. renderServicesTable();
  15036. updateCertificatesBadges();
  15037. if (manual) showToast('Services Updated', 'Service status synchronized', 'success');
  15038. } catch (err) {
  15039. if (manual) showToast('Error', err.message, 'error');
  15040. }
  15041. }
  15042. function renderServicesTable() {
  15043. const tbody = document.getElementById('services-table-body');
  15044. if (!tbody) return;
  15045. if (!state.services || state.services.length === 0) {
  15046. tbody.innerHTML = '<tr><td colspan="5" class="py-6 text-center text-slate-500 text-xs">No services configured.</td></tr>';
  15047. return;
  15048. }
  15049. tbody.innerHTML = state.services.map(s => {
  15050. const isOff = s.disabled;
  15051. const statusBadge = isOff
  15052. ? '<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>'
  15053. : '<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>';
  15054. const toggleBtn = isOff
  15055. ? `<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>`
  15056. : `<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>`;
  15057. let certBadge = '';
  15058. if (s.name === 'www-ssl') {
  15059. if (s.certificate) {
  15060. 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>`;
  15061. } else {
  15062. 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>`;
  15063. }
  15064. }
  15065. const certArg = s.certificate ? `'${escapeHtml(s.certificate)}'` : "''";
  15066. return `
  15067. <tr class="hover:bg-slate-800/40 transition">
  15068. <td class="py-3 px-4 font-bold text-white uppercase">${s.name} ${certBadge}</td>
  15069. <td class="py-3 px-4">
  15070. <div class="flex items-center gap-2">
  15071. <span class="text-cyan-400 font-mono font-bold">${s.port}</span>
  15072. <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">
  15073. <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>
  15074. </button>
  15075. </div>
  15076. </td>
  15077. <td class="py-3 px-4">${statusBadge}</td>
  15078. <td class="py-3 px-4 text-slate-400 text-xs font-sans">${s.comment || '-'}</td>
  15079. <td class="py-3 px-4 text-right">
  15080. <div class="flex items-center justify-end gap-2">
  15081. <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">
  15082. <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>
  15083. <span>Edit</span>
  15084. </button>
  15085. ${toggleBtn}
  15086. </div>
  15087. </td>
  15088. </tr>
  15089. `;
  15090. }).join('');
  15091. }
  15092. function openEditServiceModal(serviceName, currentPort, isDisabled, currentCert = '') {
  15093. document.getElementById('modal-service-name').value = serviceName;
  15094. document.getElementById('modal-service-disabled').value = String(isDisabled);
  15095. document.getElementById('modal-service-display-name').textContent = serviceName.toUpperCase();
  15096. document.getElementById('modal-service-port').value = currentPort;
  15097. const hintEl = document.getElementById('modal-service-port-hint');
  15098. const warnEl = document.getElementById('modal-service-warning');
  15099. const certGroup = document.getElementById('modal-service-cert-group');
  15100. const certSelect = document.getElementById('modal-service-cert-select');
  15101. if (serviceName === 'www') {
  15102. hintEl.textContent = 'Default HTTP web port: 80';
  15103. warnEl.classList.remove('hidden');
  15104. certGroup.classList.add('hidden');
  15105. } else if (serviceName === 'www-ssl') {
  15106. hintEl.textContent = 'Default HTTPS web port: 443';
  15107. warnEl.classList.remove('hidden');
  15108. certGroup.classList.remove('hidden');
  15109. const populateCertOptions = (certs) => {
  15110. certSelect.innerHTML = '<option value="">-- No Certificate Selected --</option>';
  15111. (certs || []).forEach(c => {
  15112. const opt = document.createElement('option');
  15113. opt.value = c.name;
  15114. opt.textContent = `${c.name} (${c.common_name})${c.is_ca ? ' [CA]' : ''}`;
  15115. if (c.name === currentCert) opt.selected = true;
  15116. certSelect.appendChild(opt);
  15117. });
  15118. };
  15119. if (state.certificates && state.certificates.length > 0) {
  15120. populateCertOptions(state.certificates);
  15121. } else {
  15122. loadCertificates(false).then(() => {
  15123. populateCertOptions(state.certificates);
  15124. });
  15125. }
  15126. } else if (serviceName === 'telnet') {
  15127. hintEl.textContent = 'Default Telnet console port: 8282';
  15128. warnEl.classList.add('hidden');
  15129. certGroup.classList.add('hidden');
  15130. } else if (serviceName === 'ssh') {
  15131. hintEl.textContent = 'Default SSH port: 2222';
  15132. warnEl.classList.add('hidden');
  15133. certGroup.classList.add('hidden');
  15134. } else {
  15135. hintEl.textContent = '';
  15136. warnEl.classList.add('hidden');
  15137. certGroup.classList.add('hidden');
  15138. }
  15139. const modal = document.getElementById('modal-service-edit');
  15140. modal.classList.remove('hidden');
  15141. setTimeout(() => document.getElementById('modal-service-port').focus(), 50);
  15142. }
  15143. function closeEditServiceModal() {
  15144. const modal = document.getElementById('modal-service-edit');
  15145. if (modal) modal.classList.add('hidden');
  15146. }
  15147. async function submitSaveServicePort(event) {
  15148. event.preventDefault();
  15149. const name = document.getElementById('modal-service-name').value;
  15150. const disabled = document.getElementById('modal-service-disabled').value === 'true';
  15151. const port = parseInt(document.getElementById('modal-service-port').value, 10);
  15152. if (isNaN(port) || port < 1 || port > 65535) {
  15153. showToast('Invalid Port', 'Port must be a valid number between 1 and 65535', 'error');
  15154. return;
  15155. }
  15156. const certSelect = document.getElementById('modal-service-cert-select');
  15157. const certVal = (name === 'www-ssl' && certSelect) ? certSelect.value : '';
  15158. try {
  15159. const res = await fetch(`${API_BASE}/system/services/${name}`, {
  15160. method: 'POST',
  15161. headers: { 'Content-Type': 'application/json' },
  15162. body: JSON.stringify({ port: port, disabled: disabled, certificate: certVal })
  15163. });
  15164. if (!res.ok) {
  15165. const errData = await res.json();
  15166. throw new Error(errData.message || 'Failed to update service settings');
  15167. }
  15168. closeEditServiceModal();
  15169. showToast('Service Updated', `Service ${name.toUpperCase()} settings saved`, 'success');
  15170. await loadServices();
  15171. } catch (err) {
  15172. showToast('Error', err.message, 'error');
  15173. }
  15174. }
  15175. async function toggleServiceState(serviceName, newDisabled) {
  15176. if (serviceName === 'www' && newDisabled) {
  15177. 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?")) {
  15178. return;
  15179. }
  15180. }
  15181. if (serviceName === 'www-ssl' && !newDisabled) {
  15182. const sslSvc = (state.services || []).find(s => s.name === 'www-ssl');
  15183. if (!sslSvc || !sslSvc.certificate) {
  15184. showToast('Certificate Required', 'Please assign an SSL/TLS certificate to www-ssl before enabling HTTPS.', 'warning');
  15185. openEditServiceModal('www-ssl', sslSvc ? sslSvc.port : 443, false, '');
  15186. return;
  15187. }
  15188. }
  15189. try {
  15190. const res = await fetch(`${API_BASE}/system/services/${serviceName}/state`, {
  15191. method: 'POST',
  15192. headers: { 'Content-Type': 'application/json' },
  15193. body: JSON.stringify({ disabled: newDisabled })
  15194. });
  15195. if (!res.ok) {
  15196. const errData = await res.json();
  15197. throw new Error(errData.message || 'Failed to update service');
  15198. }
  15199. showToast('Service Updated', `Service ${serviceName} is now ${newDisabled ? 'disabled' : 'enabled'}`, 'success');
  15200. await loadServices();
  15201. } catch (err) {
  15202. showToast('Error', err.message, 'error');
  15203. }
  15204. }
  15205. // ==================== SYSTEM LOGS (/log) ====================
  15206. state.logs = [];
  15207. let logsTimer = null;
  15208. async function loadLogs(manual = false) {
  15209. const limitEl = document.getElementById('logs-limit-select');
  15210. const limit = limitEl ? limitEl.value : '100';
  15211. try {
  15212. const res = await fetch(`${API_BASE}/system/logs?limit=${limit}`);
  15213. if (!res.ok) throw new Error('Failed to load logs');
  15214. const data = await res.json();
  15215. state.logs = data.logs || [];
  15216. renderLogsTable();
  15217. if (manual) showToast('Logs Refreshed', `Fetched ${state.logs.length} log records`, 'success');
  15218. } catch (err) {
  15219. if (manual) showToast('Error', err.message, 'error');
  15220. }
  15221. // Setup auto-refresh if enabled and on logs tab
  15222. if (!logsTimer && state.currentUser) {
  15223. logsTimer = setInterval(() => {
  15224. if (state.currentUser && !document.hidden && state.activeTab === 'logs') {
  15225. const auto = document.getElementById('logs-auto-refresh');
  15226. if (auto && auto.checked) {
  15227. loadLogs(false);
  15228. }
  15229. }
  15230. }, 3000);
  15231. }
  15232. }
  15233. function renderLogsTable() {
  15234. const tbody = document.getElementById('logs-table-body');
  15235. if (!tbody) return;
  15236. const search = (document.getElementById('logs-search-input')?.value || '').toLowerCase();
  15237. const topicFilter = (document.getElementById('logs-topic-filter')?.value || '').toLowerCase();
  15238. const filtered = state.logs.filter(entry => {
  15239. if (topicFilter && !entry.topics.toLowerCase().includes(topicFilter)) {
  15240. return false;
  15241. }
  15242. if (search && !entry.message.toLowerCase().includes(search) && !entry.topics.toLowerCase().includes(search)) {
  15243. return false;
  15244. }
  15245. return true;
  15246. });
  15247. if (filtered.length === 0) {
  15248. tbody.innerHTML = '<tr><td colspan="4" class="py-8 text-center text-slate-500 text-xs">No matching log entries found.</td></tr>';
  15249. return;
  15250. }
  15251. tbody.innerHTML = filtered.map(l => {
  15252. let topicColor = 'bg-slate-800 text-slate-300 border-slate-700';
  15253. const topLower = l.topics.toLowerCase();
  15254. if (topLower.includes('auth')) {
  15255. topicColor = 'bg-amber-500/20 text-amber-300 border-amber-500/30';
  15256. } else if (topLower.includes('dhcp')) {
  15257. topicColor = 'bg-cyan-500/20 text-cyan-300 border-cyan-500/30';
  15258. } else if (topLower.includes('route')) {
  15259. topicColor = 'bg-blue-500/20 text-blue-300 border-blue-500/30';
  15260. } else if (topLower.includes('firewall')) {
  15261. topicColor = 'bg-rose-500/20 text-rose-300 border-rose-500/30';
  15262. } else if (topLower.includes('error')) {
  15263. topicColor = 'bg-red-500/20 text-red-300 border-red-500/30';
  15264. } else if (topLower.includes('system')) {
  15265. topicColor = 'bg-emerald-500/20 text-emerald-300 border-emerald-500/30';
  15266. }
  15267. const d = new Date(l.time);
  15268. const timeStr = d.toLocaleDateString('en-US', { month: 'short', day: '2-digit' }) + ' ' + d.toLocaleTimeString('en-US', { hour12: false });
  15269. return `
  15270. <tr class="hover:bg-slate-800/40 transition">
  15271. <td class="py-2 px-3 text-slate-500 font-mono">${l.id}</td>
  15272. <td class="py-2 px-3 text-slate-400 font-mono whitespace-nowrap">${timeStr}</td>
  15273. <td class="py-2 px-3 whitespace-nowrap">
  15274. <span class="px-2 py-0.5 rounded text-[10px] font-bold border ${topicColor}">${l.topics}</span>
  15275. </td>
  15276. <td class="py-2 px-3 text-slate-200 font-mono break-all">${escapeHtml(l.message)}</td>
  15277. </tr>
  15278. `;
  15279. }).join('');
  15280. }
  15281. // ==================== CERTIFICATES & SSL/TLS (/certificate) ====================
  15282. state.certificates = [];
  15283. async function loadCertificates(manual = false) {
  15284. try {
  15285. const res = await fetch(`${API_BASE}/certificates`);
  15286. if (!res.ok) throw new Error('Failed to load certificates');
  15287. state.certificates = await res.json() || [];
  15288. updateCertificatesBadges();
  15289. renderCertificatesTable();
  15290. if (manual) showToast('Certificates Updated', `Loaded ${state.certificates.length} certificates`, 'success');
  15291. } catch (err) {
  15292. if (manual) showToast('Error', err.message, 'error');
  15293. }
  15294. }
  15295. function updateCertificatesBadges() {
  15296. const total = (state.certificates || []).length;
  15297. const caCount = (state.certificates || []).filter(c => c.is_ca).length;
  15298. const bCount = document.getElementById('badge-certs-count');
  15299. if (bCount) bCount.innerText = total;
  15300. const kpiTotal = document.getElementById('kpi-certs-total');
  15301. if (kpiTotal) kpiTotal.innerText = total;
  15302. const kpiCA = document.getElementById('kpi-certs-ca');
  15303. if (kpiCA) kpiCA.innerText = caCount;
  15304. const kpiHttps = document.getElementById('kpi-https-status');
  15305. if (kpiHttps) {
  15306. const sslSvc = (state.services || []).find(s => s.name === 'www-ssl');
  15307. if (sslSvc) {
  15308. if (!sslSvc.disabled) {
  15309. 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>`;
  15310. } else {
  15311. 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>`;
  15312. }
  15313. }
  15314. }
  15315. }
  15316. function renderCertificatesTable() {
  15317. const tbody = document.getElementById('certs-table-body');
  15318. if (!tbody) return;
  15319. if (!state.certificates || state.certificates.length === 0) {
  15320. 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>';
  15321. return;
  15322. }
  15323. tbody.innerHTML = state.certificates.map(c => {
  15324. let typeBadge = '';
  15325. if (c.is_ca) {
  15326. 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>';
  15327. } else if (c.type === 'acme') {
  15328. 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>';
  15329. } else if (c.issuer && c.issuer !== c.common_name) {
  15330. 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>';
  15331. } else {
  15332. 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>';
  15333. }
  15334. const sansHtml = (c.sans && c.sans.length > 0)
  15335. ? 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('')
  15336. : '<span class="text-slate-500">-</span>';
  15337. const validTo = c.valid_to ? new Date(c.valid_to) : null;
  15338. let validStr = '-';
  15339. let validBadge = '';
  15340. if (validTo && !isNaN(validTo.getTime())) {
  15341. const now = new Date();
  15342. const daysLeft = Math.round((validTo - now) / (1000 * 60 * 60 * 24));
  15343. validStr = validTo.toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' });
  15344. if (daysLeft < 0) {
  15345. validBadge = '<span class="ml-1 text-[10px] text-rose-400 font-bold">(Expired)</span>';
  15346. } else if (daysLeft < 30) {
  15347. validBadge = `<span class="ml-1 text-[10px] text-amber-400 font-bold">(${daysLeft}d left)</span>`;
  15348. } else {
  15349. validBadge = `<span class="ml-1 text-[10px] text-slate-400">(${daysLeft}d left)</span>`;
  15350. }
  15351. }
  15352. return `
  15353. <tr class="hover:bg-slate-800/40 transition">
  15354. <td class="py-3 px-4">${typeBadge}</td>
  15355. <td class="py-3 px-4">
  15356. <div class="font-bold text-white">${escapeHtml(c.name)}</div>
  15357. <div class="text-[10px] text-slate-400 font-sans truncate max-w-xs" title="${escapeHtml(c.common_name)}">${escapeHtml(c.common_name)}</div>
  15358. </td>
  15359. <td class="py-3 px-4 text-slate-300 text-xs truncate max-w-xs" title="${escapeHtml(c.issuer || '-')}">${escapeHtml(c.issuer || '-')}</td>
  15360. <td class="py-3 px-4 max-w-xs">${sansHtml}</td>
  15361. <td class="py-3 px-4 whitespace-nowrap text-xs text-slate-300">
  15362. <span>${validStr}</span> ${validBadge}
  15363. ${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>` : ''}
  15364. <div class="text-[10px] text-slate-500">${c.key_type || ''}</div>
  15365. </td>
  15366. <td class="py-3 px-4 text-right whitespace-nowrap">
  15367. <div class="flex items-center justify-end gap-1.5">
  15368. <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">
  15369. <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>
  15370. <span>View</span>
  15371. </button>
  15372. <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">
  15373. <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>
  15374. </button>
  15375. </div>
  15376. </td>
  15377. </tr>
  15378. `;
  15379. }).join('');
  15380. }
  15381. // Create CA
  15382. function openCreateCAModal() {
  15383. document.getElementById('form-create-ca').reset();
  15384. document.getElementById('ca-days').value = '3650';
  15385. document.getElementById('ca-org').value = 'DebTik Network Appliance';
  15386. document.getElementById('ca-country').value = 'GR';
  15387. document.getElementById('ca-key-type').value = 'RSA-2048';
  15388. document.getElementById('modal-create-ca').classList.remove('hidden');
  15389. setTimeout(() => document.getElementById('ca-name').focus(), 50);
  15390. }
  15391. function closeCreateCAModal() {
  15392. document.getElementById('modal-create-ca').classList.add('hidden');
  15393. }
  15394. async function submitCreateCA(event) {
  15395. event.preventDefault();
  15396. const payload = {
  15397. name: document.getElementById('ca-name').value.trim(),
  15398. common_name: document.getElementById('ca-cn').value.trim(),
  15399. organization: document.getElementById('ca-org').value.trim(),
  15400. country: document.getElementById('ca-country').value.trim(),
  15401. days: parseInt(document.getElementById('ca-days').value, 10) || 3650,
  15402. key_type: document.getElementById('ca-key-type').value
  15403. };
  15404. try {
  15405. const res = await fetch(`${API_BASE}/certificates/ca`, {
  15406. method: 'POST',
  15407. headers: { 'Content-Type': 'application/json' },
  15408. body: JSON.stringify(payload)
  15409. });
  15410. if (!res.ok) {
  15411. const errData = await res.json();
  15412. throw new Error(errData.message || 'Failed to create CA');
  15413. }
  15414. closeCreateCAModal();
  15415. showToast('CA Created', `Root CA ${payload.name} generated successfully`, 'success');
  15416. await loadCertificates();
  15417. } catch (err) {
  15418. showToast('Error', err.message, 'error');
  15419. }
  15420. }
  15421. // Create Cert
  15422. function openCreateCertModal() {
  15423. document.getElementById('form-create-cert').reset();
  15424. document.getElementById('cert-days').value = '730';
  15425. document.getElementById('cert-key-type').value = 'RSA-2048';
  15426. const caSelect = document.getElementById('cert-ca-select');
  15427. caSelect.innerHTML = '<option value="">[ Self-Signed Certificate ]</option>';
  15428. (state.certificates || []).filter(c => c.is_ca).forEach(ca => {
  15429. const opt = document.createElement('option');
  15430. opt.value = ca.name;
  15431. opt.textContent = `${ca.name} (${ca.common_name})`;
  15432. caSelect.appendChild(opt);
  15433. });
  15434. document.getElementById('modal-create-cert').classList.remove('hidden');
  15435. setTimeout(() => document.getElementById('cert-name').focus(), 50);
  15436. }
  15437. function closeCreateCertModal() {
  15438. document.getElementById('modal-create-cert').classList.add('hidden');
  15439. }
  15440. async function submitCreateCert(event) {
  15441. event.preventDefault();
  15442. const rawSans = document.getElementById('cert-sans').value;
  15443. const sansList = rawSans ? rawSans.split(',').map(s => s.trim()).filter(Boolean) : [];
  15444. const caName = document.getElementById('cert-ca-select').value;
  15445. const payload = {
  15446. name: document.getElementById('cert-name').value.trim(),
  15447. common_name: document.getElementById('cert-cn').value.trim(),
  15448. ca_name: caName,
  15449. sans: sansList,
  15450. days: parseInt(document.getElementById('cert-days').value, 10) || 730,
  15451. key_type: document.getElementById('cert-key-type').value,
  15452. is_server: true
  15453. };
  15454. try {
  15455. const res = await fetch(`${API_BASE}/certificates/generate`, {
  15456. method: 'POST',
  15457. headers: { 'Content-Type': 'application/json' },
  15458. body: JSON.stringify(payload)
  15459. });
  15460. if (!res.ok) {
  15461. const errData = await res.json();
  15462. throw new Error(errData.message || 'Failed to issue certificate');
  15463. }
  15464. closeCreateCertModal();
  15465. showToast('Certificate Issued', `Certificate ${payload.name} generated successfully`, 'success');
  15466. await loadCertificates();
  15467. } catch (err) {
  15468. showToast('Error', err.message, 'error');
  15469. }
  15470. }
  15471. // Let's Encrypt
  15472. function openLetsEncryptModal() {
  15473. document.getElementById('form-letsencrypt').reset();
  15474. document.getElementById('modal-letsencrypt').classList.remove('hidden');
  15475. setTimeout(() => document.getElementById('le-domain').focus(), 50);
  15476. }
  15477. function closeLetsEncryptModal() {
  15478. document.getElementById('modal-letsencrypt').classList.add('hidden');
  15479. }
  15480. async function submitLetsEncrypt(event) {
  15481. event.preventDefault();
  15482. const domain = document.getElementById('le-domain').value.trim();
  15483. const email = document.getElementById('le-email').value.trim();
  15484. let name = document.getElementById('le-name').value.trim();
  15485. if (!name) name = domain.replace(/[^a-zA-Z0-9_-]/g, '-');
  15486. const staging = document.getElementById('le-staging').checked;
  15487. const btn = document.getElementById('btn-submit-letsencrypt');
  15488. const origBtnHtml = btn.innerHTML;
  15489. btn.disabled = true;
  15490. 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>`;
  15491. try {
  15492. const res = await fetch(`${API_BASE}/certificates/letsencrypt`, {
  15493. method: 'POST',
  15494. headers: { 'Content-Type': 'application/json' },
  15495. body: JSON.stringify({
  15496. name: name,
  15497. domain: domain,
  15498. email: email,
  15499. staging: staging
  15500. })
  15501. });
  15502. if (!res.ok) {
  15503. const errData = await res.json();
  15504. throw new Error(errData.message || 'Let\'s Encrypt challenge failed');
  15505. }
  15506. closeLetsEncryptModal();
  15507. showToast('Let\'s Encrypt Issued', `Successfully issued trusted certificate for ${domain}`, 'success');
  15508. await loadCertificates();
  15509. } catch (err) {
  15510. showToast('Let\'s Encrypt Error', err.message, 'error');
  15511. } finally {
  15512. btn.disabled = false;
  15513. btn.innerHTML = origBtnHtml;
  15514. }
  15515. }
  15516. // Import Cert
  15517. function openImportCertModal() {
  15518. document.getElementById('form-import-cert').reset();
  15519. document.getElementById('modal-import-cert').classList.remove('hidden');
  15520. setTimeout(() => document.getElementById('import-cert-name').focus(), 50);
  15521. }
  15522. function closeImportCertModal() {
  15523. document.getElementById('modal-import-cert').classList.add('hidden');
  15524. }
  15525. async function submitImportCert(event) {
  15526. event.preventDefault();
  15527. const payload = {
  15528. name: document.getElementById('import-cert-name').value.trim(),
  15529. cert_pem: document.getElementById('import-cert-pem').value.trim(),
  15530. key_pem: document.getElementById('import-key-pem').value.trim()
  15531. };
  15532. try {
  15533. const res = await fetch(`${API_BASE}/certificates/import`, {
  15534. method: 'POST',
  15535. headers: { 'Content-Type': 'application/json' },
  15536. body: JSON.stringify(payload)
  15537. });
  15538. if (!res.ok) {
  15539. const errData = await res.json();
  15540. throw new Error(errData.message || 'Failed to import certificate');
  15541. }
  15542. closeImportCertModal();
  15543. showToast('Certificate Imported', `Imported ${payload.name} successfully`, 'success');
  15544. await loadCertificates();
  15545. } catch (err) {
  15546. showToast('Error', err.message, 'error');
  15547. }
  15548. }
  15549. // View / Export Modal
  15550. async function openViewCertModal(name) {
  15551. const c = (state.certificates || []).find(x => x.name === name);
  15552. if (!c) return;
  15553. document.getElementById('view-cert-modal-title').textContent = `Certificate: ${c.name}`;
  15554. document.getElementById('view-cert-cn').textContent = c.common_name || '-';
  15555. document.getElementById('view-cert-issuer').textContent = c.issuer || '-';
  15556. document.getElementById('view-cert-type').textContent = `${c.is_ca ? 'CA' : 'Server/Client'} (${c.key_type || 'Unknown'})`;
  15557. document.getElementById('view-cert-validto').textContent = c.valid_to ? new Date(c.valid_to).toLocaleString() : '-';
  15558. document.getElementById('view-cert-sans').textContent = (c.sans && c.sans.length > 0) ? c.sans.join(', ') : 'None';
  15559. document.getElementById('view-cert-fp').textContent = c.fingerprint || '-';
  15560. document.getElementById('view-cert-pem-text').value = 'Loading PEM...';
  15561. document.getElementById('view-key-pem-text').value = 'Loading Key...';
  15562. document.getElementById('modal-view-cert').classList.remove('hidden');
  15563. try {
  15564. const res = await fetch(`${API_BASE}/certificates/${encodeURIComponent(name)}/export`);
  15565. if (!res.ok) throw new Error('Failed to export certificate PEM');
  15566. const data = await res.json();
  15567. document.getElementById('view-cert-pem-text').value = data.cert_pem || '';
  15568. document.getElementById('view-key-pem-text').value = data.key_pem || '(Private key not available)';
  15569. } catch (err) {
  15570. document.getElementById('view-cert-pem-text').value = 'Error loading certificate PEM: ' + err.message;
  15571. document.getElementById('view-key-pem-text').value = '';
  15572. }
  15573. }
  15574. function closeViewCertModal() {
  15575. document.getElementById('modal-view-cert').classList.add('hidden');
  15576. }
  15577. function copyCertPEM() {
  15578. const text = document.getElementById('view-cert-pem-text').value;
  15579. if (!text) return;
  15580. navigator.clipboard.writeText(text).then(() => {
  15581. showToast('Copied', 'Certificate PEM copied to clipboard', 'info');
  15582. }).catch(() => {
  15583. showToast('Error', 'Failed to copy to clipboard', 'error');
  15584. });
  15585. }
  15586. function copyKeyPEM() {
  15587. const text = document.getElementById('view-key-pem-text').value;
  15588. if (!text) return;
  15589. navigator.clipboard.writeText(text).then(() => {
  15590. showToast('Copied', 'Private Key PEM copied to clipboard', 'info');
  15591. }).catch(() => {
  15592. showToast('Error', 'Failed to copy to clipboard', 'error');
  15593. });
  15594. }
  15595. async function deleteCertificate(name) {
  15596. if (!confirm(`Are you sure you want to delete certificate "${name}"? This action cannot be undone.`)) {
  15597. return;
  15598. }
  15599. try {
  15600. const res = await fetch(`${API_BASE}/certificates/${encodeURIComponent(name)}`, {
  15601. method: 'DELETE'
  15602. });
  15603. if (!res.ok) {
  15604. const errData = await res.json();
  15605. throw new Error(errData.message || 'Failed to delete certificate');
  15606. }
  15607. showToast('Certificate Deleted', `Certificate "${name}" removed`, 'success');
  15608. await loadCertificates();
  15609. } catch (err) {
  15610. showToast('Error', err.message, 'error');
  15611. }
  15612. }
  15613. // Refresh immediately when returning to a backgrounded controller tab.
  15614. document.addEventListener('visibilitychange', () => {
  15615. if (!state.currentUser) return;
  15616. if (document.hidden) {
  15617. if (trafficEventSource) trafficEventSource.close();
  15618. trafficEventSource = null;
  15619. if (trafficPollFallback) clearInterval(trafficPollFallback);
  15620. trafficPollFallback = null;
  15621. } else {
  15622. fetchData(false);
  15623. initLiveTrafficStream();
  15624. if (state.activeTab === 'bwtest') loadBwTestView();
  15625. }
  15626. });
  15627. async function loadUpdateStatus(populate = true) {
  15628. try {
  15629. const res = await fetch(`${API_BASE}/update/status`);
  15630. if (!res.ok) throw new Error(await responseError(res));
  15631. const data = await res.json();
  15632. if (populate && document.activeElement?.id !== 'update-repository') document.getElementById('update-repository').value = data.repository || '';
  15633. if (populate && document.activeElement?.id !== 'update-tls-pin') document.getElementById('update-tls-pin').value = data.tls_key_pin || '';
  15634. document.getElementById('update-installed').textContent = data.installed_version || 'unknown';
  15635. document.getElementById('update-state').textContent = data.state || 'idle';
  15636. document.getElementById('update-log').textContent = data.log || '';
  15637. } catch (err) { showToast('Update Status', err.message, 'error'); }
  15638. }
  15639. async function saveUpdateConfig() {
  15640. try {
  15641. const repository = document.getElementById('update-repository').value.trim();
  15642. const branch = 'master';
  15643. const tls_key_pin = document.getElementById('update-tls-pin').value.trim();
  15644. const res = await fetch(`${API_BASE}/update/config`, {method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({repository,branch,tls_key_pin})});
  15645. if (!res.ok) throw new Error(await responseError(res));
  15646. document.getElementById('update-install-button').disabled = true;
  15647. document.getElementById('update-available').textContent = '—';
  15648. showToast('Update Source Saved', 'Repository and branch saved', 'success');
  15649. await loadUpdateStatus(false);
  15650. } catch (err) { showToast('Update Source', err.message, 'error'); }
  15651. }
  15652. async function checkUpdate() {
  15653. try {
  15654. const res = await fetch(`${API_BASE}/update/check`, {method:'POST'});
  15655. if (!res.ok) throw new Error(await responseError(res));
  15656. const data = await res.json();
  15657. document.getElementById('update-available').textContent = data.available_version;
  15658. document.getElementById('update-install-button').disabled = !data.update_available;
  15659. showToast('Git Check', data.update_available ? 'An update is available' : 'No newer version available', 'info');
  15660. } catch (err) { showToast('Git Check Failed', err.message, 'error'); }
  15661. }
  15662. async function startUpdate(action) {
  15663. if (!confirm(action === 'rollback' ? 'Restore the previous version and restart DebTik?' : 'Install the newer release version and restart DebTik?')) return;
  15664. try {
  15665. const res = await fetch(`${API_BASE}/update/${action}`, {method:'POST'});
  15666. if (!res.ok) throw new Error(await responseError(res));
  15667. showToast('Update Started', 'The service will restart; reconnect after a few seconds', 'info');
  15668. await loadUpdateStatus(false);
  15669. } catch (err) { showToast('Update Failed', err.message, 'error'); }
  15670. }
  15671. async function resetCurrentRuleCounters() { return resetFirewallRuleCounter('filter', resetRuleCounterDisplay); }
  15672. async function resetCurrentNATRuleCounters() { return resetFirewallRuleCounter('nat', resetNATCounterDisplay); }
  15673. async function resetCurrentMangleRuleCounters() { return resetFirewallRuleCounter('mangle', resetMangleCounterDisplay); }
  15674. function safeFirewallRow(row) {
  15675. const result = {...row};
  15676. for (const [key,value] of Object.entries(result)) if (typeof value === 'string') result[key] = escapeHtml(value);
  15677. result.id = encodeURIComponent(String(row.id || '')).replace(/'/g, '%27').replace(/\(/g, '%28').replace(/\)/g, '%29');
  15678. return result;
  15679. }
  15680. function setFirewallDays(prefix, days) {
  15681. const selected = days ? days.toLowerCase().split(',') : ['sun','mon','tue','wed','thu','fri','sat'];
  15682. 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); }
  15683. }
  15684. function getFirewallDays(prefix) {
  15685. if (document.getElementById(prefix+'-field-days')?.classList.contains('hidden')) return '';
  15686. const selected = ['sun','mon','tue','wed','thu','fri','sat'].filter(d => document.getElementById(prefix+'-day-'+d)?.checked);
  15687. if (!selected.length) throw new Error('Select at least one weekday, or remove the Days condition.');
  15688. return selected.join(',');
  15689. }
  15690. async function resetFirewallRuleCounter(kind, resetDisplay) {
  15691. const id = document.getElementById(kind+'-modal-id')?.value;
  15692. if (!id) { resetDisplay(); return; }
  15693. try {
  15694. const response = await fetch(`${API_BASE}/firewall/${kind}/${encodeURIComponent(id)}/reset-counters`, {method:'POST'});
  15695. if (!response.ok) { const error = await response.json(); throw new Error(error.message || 'Counter reset failed'); }
  15696. resetDisplay(); await loadFirewall(false);
  15697. } catch(error) { showToast('Error', error.message, 'error'); }
  15698. }
  15699. function reviewLegacyFirewallSettings(kind, id) {
  15700. if (!id) return true;
  15701. const rows = kind === 'filter' ? state.filterRules : kind === 'nat' ? state.natRules : state.mangleRules;
  15702. const rule = (rows || []).find(r => r.id === id);
  15703. if (!rule) return true;
  15704. 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'];
  15705. const present = unsupported.filter(key => rule[key]);
  15706. if (!present.length) return true;
  15707. return confirm('This saved rule contains unsupported settings: '+present.join(', ')+'. Saving removes them. Review the remaining match conditions before continuing.');
  15708. }
  15709. function refreshFirewallRejectTypes() {
  15710. const select=document.getElementById('filter-modal-rejectwith'); if(!select) return;
  15711. const old=select.value;
  15712. const ipv6=document.getElementById('filter-modal-family')?.value==='6';
  15713. 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'];
  15714. select.replaceChildren(...types.map(value=>{const option=document.createElement('option');option.value=value;option.textContent=value;return option}));
  15715. if(types.includes(old))select.value=old;
  15716. }
  15717. function setFirewallActionSelection(kind, value) {
  15718. const select=document.getElementById(kind+'-modal-action'); if(!select)return;
  15719. if(!Array.from(select.options).some(option=>option.value===value)) {
  15720. const option=document.createElement('option');option.value=value;option.textContent='Unsupported saved action: '+value;option.disabled=true;select.appendChild(option);
  15721. }
  15722. select.value=value;
  15723. }