app.js 728 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285
  1. // DebTik - Debian Linux Router Frontend Application Logic
  2. // ================= Interceptor: Automatic Auth Bearer & 401 Handling =================
  3. const originalFetch = window.fetch.bind(window);
  4. const pendingAPIReads = new Map();
  5. const telemetryHealth = { lastSuccess: 0, failures: new Map() };
  6. let coreRefreshPromise = null;
  7. let lastSummaryRefresh = 0;
  8. function renderTelemetryHealth() {
  9. const el = document.getElementById('telemetry-health');
  10. if (!el) return;
  11. const failures = [...telemetryHealth.failures.entries()];
  12. const seconds = telemetryHealth.lastSuccess ? Math.floor((Date.now() - telemetryHealth.lastSuccess) / 1000) : null;
  13. const stale = seconds === null || seconds > 15;
  14. el.textContent = failures.length ? `Data unavailable / incomplete${seconds === null ? '' : ` · updated ${seconds}s ago`}` : stale ? 'Waiting for fresh data' : `Updated ${seconds}s ago`;
  15. el.className = `text-[10px] font-mono ${failures.length || stale ? 'text-amber-400' : 'text-emerald-400'}`;
  16. el.title = failures.length ? failures.map(([path, error]) => `${path}: ${error}`).join('\n') : telemetryHealth.lastSuccess ? `Last successful update: ${new Date(telemetryHealth.lastSuccess).toLocaleTimeString()}` : 'No successful update yet';
  17. }
  18. function stopSessionPolling() {
  19. if (window._telemetryInterval) clearInterval(window._telemetryInterval);
  20. window._telemetryInterval = null;
  21. if (trafficEventSource) trafficEventSource.close();
  22. trafficEventSource = null;
  23. if (trafficPollFallback) clearInterval(trafficPollFallback);
  24. trafficPollFallback = null;
  25. if (bwtestState.pollTimer) clearInterval(bwtestState.pollTimer);
  26. bwtestState.pollTimer = null;
  27. if (logsTimer) clearInterval(logsTimer);
  28. logsTimer = null;
  29. stopFwStatPolling();
  30. stopNATStatPolling();
  31. stopMangleStatPolling();
  32. telemetryHealth.failures.clear();
  33. telemetryHealth.lastSuccess = 0;
  34. lastSummaryRefresh = 0;
  35. }
  36. window.fetch = async function(resource, options = {}) {
  37. const url = new URL(resource instanceof Request ? resource.url : resource, window.location.href);
  38. const isAPI = url.origin === window.location.origin && url.pathname.startsWith('/api/');
  39. if (!isAPI) return originalFetch(resource, options);
  40. const config = { ...options, headers: new Headers(options.headers || (resource instanceof Request ? resource.headers : undefined)) };
  41. const token = localStorage.getItem('debtik_token');
  42. if (token && !config.headers.has('Authorization')) config.headers.set('Authorization', `Bearer ${token}`);
  43. const method = (config.method || (resource instanceof Request ? resource.method : 'GET')).toUpperCase();
  44. const isRead = method === 'GET' && !url.pathname.includes('/stream') && !url.pathname.startsWith('/api/auth/');
  45. const key = `${url.href}|${JSON.stringify([...config.headers])}`;
  46. if (isRead && pendingAPIReads.has(key)) return (await pendingAPIReads.get(key)).clone();
  47. const perform = async () => {
  48. let timeout;
  49. if (isRead && !config.signal) {
  50. const controller = new AbortController();
  51. config.signal = controller.signal;
  52. timeout = setTimeout(() => controller.abort(), 15000);
  53. }
  54. try {
  55. const response = await originalFetch(resource, config);
  56. if (isRead) {
  57. if (response.ok) {
  58. telemetryHealth.lastSuccess = Date.now();
  59. telemetryHealth.failures.delete(url.pathname);
  60. } else {
  61. telemetryHealth.failures.set(url.pathname, `HTTP ${response.status}; displayed values may be old`);
  62. }
  63. renderTelemetryHealth();
  64. }
  65. if (response.status === 401 && url.pathname !== '/api/auth/login' && state.currentUser && token === localStorage.getItem('debtik_token')) {
  66. stopSessionPolling();
  67. state.isPolling = false;
  68. state.currentUser = null;
  69. localStorage.removeItem('debtik_token');
  70. showLoginScreen(true);
  71. }
  72. return response;
  73. } catch (err) {
  74. if (isRead) {
  75. telemetryHealth.failures.set(url.pathname, err.name === 'AbortError' ? 'Request timed out' : 'Connection failed; displayed values may be old');
  76. renderTelemetryHealth();
  77. }
  78. throw err;
  79. } finally {
  80. if (timeout) clearTimeout(timeout);
  81. }
  82. };
  83. if (!isRead) return perform();
  84. const request = perform();
  85. pendingAPIReads.set(key, request);
  86. try { return (await request).clone(); }
  87. finally { if (pendingAPIReads.get(key) === request) pendingAPIReads.delete(key); }
  88. };
  89. let state = {
  90. currentUser: null,
  91. users: [],
  92. interfaces: [],
  93. vlans: [],
  94. systemStatus: null,
  95. vpnStatus: null,
  96. routes: [],
  97. activeTab: 'dashboard',
  98. fwSubTab: 'filter',
  99. bridgeSubTab: 'bridges',
  100. bridges: [],
  101. bridgePorts: [],
  102. bridgeVLANs: [],
  103. bridgeHosts: [],
  104. bridgeSummary: null,
  105. routesSubTab: 'routes',
  106. pppSubTab: 'secrets',
  107. eoipTunnels: [],
  108. pppSecrets: [],
  109. pppProfiles: [],
  110. pppActiveSessions: [],
  111. pppoeServer: null,
  112. pptpServer: null,
  113. l2tpServer: null,
  114. ipsecServer: null,
  115. ifaceFilter: 'all',
  116. currentModalIface: null,
  117. isPolling: false,
  118. expandedParents: new Set(['eth0']),
  119. pppoeData: null,
  120. wgData: null,
  121. ipsecData: null,
  122. l2tpData: null,
  123. pptpData: null,
  124. fwSummary: null,
  125. filterRules: [],
  126. natRules: [],
  127. mangleRules: [],
  128. addressLists: [],
  129. connections: [],
  130. policyRules: [],
  131. routingTables: [],
  132. routingFilters: [],
  133. filterChainSelected: 'all',
  134. activeToolsSubTab: 'ping',
  135. dhcpClients: [],
  136. dhcpSummary: null,
  137. dhcpServerTab: 'servers',
  138. dhcpServers: [],
  139. dhcpNetworks: [],
  140. dhcpLeases: [],
  141. dhcpOptions: [],
  142. dhcpServerSummary: null
  143. };
  144. const API_BASE = '/api';
  145. function escapeHtml(str) {
  146. if (str === null || str === undefined) return '';
  147. return String(str)
  148. .replace(/&/g, '&')
  149. .replace(/</g, '&lt;')
  150. .replace(/>/g, '&gt;')
  151. .replace(/"/g, '&quot;')
  152. .replace(/'/g, '&#039;');
  153. }
  154. function formatBytes(bytes) {
  155. if (bytes === undefined || bytes === null || isNaN(bytes) || bytes === 0) return '0 B';
  156. const k = 1024;
  157. const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
  158. const i = Math.floor(Math.log(bytes) / Math.log(k));
  159. if (i < 0 || i >= sizes.length) return `${bytes} B`;
  160. return `${parseFloat((bytes / Math.pow(k, i)).toFixed(2))} ${sizes[i]}`;
  161. }
  162. // Initialize on page load
  163. document.addEventListener('DOMContentLoaded', async () => {
  164. initTableSorting();
  165. // Verify authentication before bootstrapping telemetry and views
  166. const isAuthenticated = await checkAuthStatus();
  167. if (isAuthenticated) {
  168. const hash = window.location.hash.replace('#', '') || 'dashboard';
  169. navigate(hash);
  170. // Full state telemetry polling every 5 seconds (smooth & flicker-free)
  171. if (!window._telemetryInterval) {
  172. window._telemetryInterval = setInterval(() => {
  173. if (state.isPolling && state.currentUser && !document.hidden) {
  174. fetchData(false);
  175. }
  176. }, 5000);
  177. }
  178. }
  179. });
  180. let trafficEventSource = null;
  181. let trafficPollFallback = null;
  182. function initLiveTrafficStream() {
  183. if (trafficEventSource) {
  184. try { trafficEventSource.close(); } catch(e) {}
  185. trafficEventSource = null;
  186. }
  187. if (trafficPollFallback) {
  188. clearInterval(trafficPollFallback);
  189. trafficPollFallback = null;
  190. }
  191. if (window.EventSource) {
  192. try {
  193. trafficEventSource = new EventSource(`${API_BASE}/interfaces/traffic/stream`);
  194. trafficEventSource.onmessage = (event) => {
  195. try {
  196. const data = JSON.parse(event.data);
  197. updateLiveInterfaceTraffic(data);
  198. } catch (e) {
  199. console.error('Error parsing live traffic event:', e);
  200. }
  201. };
  202. trafficEventSource.onerror = () => {
  203. // Fallback polling if SSE disconnects
  204. if (!trafficPollFallback) {
  205. trafficPollFallback = setInterval(pollLiveTrafficSnapshot, 1000);
  206. }
  207. };
  208. trafficEventSource.onopen = () => {
  209. if (trafficPollFallback) {
  210. clearInterval(trafficPollFallback);
  211. trafficPollFallback = null;
  212. }
  213. };
  214. return;
  215. } catch (e) {
  216. console.warn('EventSource failed, using 1s polling fallback:', e);
  217. }
  218. }
  219. // Fallback if EventSource is unavailable
  220. trafficPollFallback = setInterval(pollLiveTrafficSnapshot, 1000);
  221. }
  222. async function pollLiveTrafficSnapshot() {
  223. try {
  224. const res = await fetch(`${API_BASE}/interfaces/traffic/rates`);
  225. if (res.ok) {
  226. const data = await res.json();
  227. updateLiveInterfaceTraffic(data);
  228. }
  229. } catch (e) {}
  230. }
  231. function updateLiveInterfaceTraffic(data) {
  232. if (!data || !data.interfaces) return;
  233. state.latestTraffic = data;
  234. // 1. Update Top & Dashboard Total Bandwidth Indicators
  235. const rxHuman = data.total_rx_human || '0 B/s';
  236. const txHuman = data.total_tx_human || '0 B/s';
  237. const statRx = document.getElementById('stat-traffic-rx');
  238. if (statRx && statRx.innerText !== rxHuman) statRx.innerText = rxHuman;
  239. const statTx = document.getElementById('stat-traffic-tx');
  240. if (statTx && statTx.innerText !== txHuman) statTx.innerText = txHuman;
  241. // 2. Update state.interfaces rates in-memory
  242. if (Array.isArray(state.interfaces)) {
  243. state.interfaces.forEach(i => {
  244. const live = data.interfaces[i.name];
  245. if (live) {
  246. i.rate = {
  247. rx_bytes_sec: live.rx_bytes_sec,
  248. tx_bytes_sec: live.tx_bytes_sec,
  249. rx_human: live.rx_human,
  250. tx_human: live.tx_human
  251. };
  252. i.stats = {
  253. rx_bytes: live.rx_bytes,
  254. tx_bytes: live.tx_bytes,
  255. rx_packets: live.rx_packets,
  256. tx_packets: live.tx_packets,
  257. rx_errors: live.rx_errors,
  258. tx_errors: live.tx_errors,
  259. rx_dropped: live.rx_dropped,
  260. tx_dropped: live.tx_dropped
  261. };
  262. }
  263. });
  264. }
  265. // 3. Update all live UI rate spans in-place (ZERO flicker)
  266. Object.keys(data.interfaces).forEach(name => {
  267. const live = data.interfaces[name];
  268. // Dashboard Port Matrix Card
  269. const cardRate = document.getElementById(`port-card-rate-${name}`);
  270. if (cardRate && cardRate.innerText !== live.rx_human) {
  271. cardRate.innerText = live.rx_human;
  272. }
  273. // Dashboard Quick Interfaces Table
  274. const quickRx = document.getElementById(`quick-rx-${name}`);
  275. if (quickRx) quickRx.innerText = `↓ ${live.rx_human}`;
  276. const quickTx = document.getElementById(`quick-tx-${name}`);
  277. if (quickTx) quickTx.innerText = `↑ ${live.tx_human}`;
  278. // Main Interfaces Tree Table
  279. const ifaceRx = document.getElementById(`iface-rate-rx-${name}`);
  280. if (ifaceRx) ifaceRx.innerText = `↓ ${live.rx_human}`;
  281. const ifaceTx = document.getElementById(`iface-rate-tx-${name}`);
  282. if (ifaceTx) ifaceTx.innerText = `↑ ${live.tx_human}`;
  283. // VLAN Sub-interfaces Table
  284. const vlanRx = document.getElementById(`vlan-rate-rx-${name}`);
  285. if (vlanRx) vlanRx.innerText = `↓ ${live.rx_human}`;
  286. const vlanTx = document.getElementById(`vlan-rate-tx-${name}`);
  287. if (vlanTx) vlanTx.innerText = `↑ ${live.tx_human}`;
  288. // VLAN Page Table
  289. const vlanPageRx = document.getElementById(`vlan-page-rate-rx-${name}`);
  290. if (vlanPageRx) vlanPageRx.innerText = `↓ ${live.rx_human}`;
  291. const vlanPageTx = document.getElementById(`vlan-page-rate-tx-${name}`);
  292. if (vlanPageTx) vlanPageTx.innerText = `↑ ${live.tx_human}`;
  293. });
  294. }
  295. // Navigation Handler
  296. function navigate(tabName) {
  297. if (tabName === 'dynamic-routing' || tabName === 'routing') {
  298. navigate('bgp');
  299. return;
  300. }
  301. if (tabName === 'vlans') {
  302. navigate('interfaces');
  303. return;
  304. }
  305. if (tabName === 'persistence') {
  306. navigate('dashboard');
  307. return;
  308. }
  309. stopFwStatPolling();
  310. stopNATStatPolling();
  311. stopMangleStatPolling();
  312. state.activeTab = tabName;
  313. window.location.hash = tabName;
  314. // Update nav links styling
  315. document.querySelectorAll('.nav-link').forEach(link => {
  316. link.className = 'nav-link flex items-center justify-between px-3 py-2 rounded-lg text-xs font-medium transition-all group text-slate-300 hover:bg-slate-800/80 hover:text-white';
  317. });
  318. const activeNav = document.getElementById(`nav-${tabName}`);
  319. if (activeNav) {
  320. activeNav.className = 'nav-link flex items-center justify-between px-3 py-2 rounded-lg text-xs font-medium transition-all group bg-brand-500/10 text-brand-400 border border-brand-500/20';
  321. }
  322. // Update page headers
  323. const titles = {
  324. dashboard: { title: 'Dashboard Overview', sub: 'Live router performance and network telemetry' },
  325. interfaces: { title: 'Network Interfaces', sub: 'Interface Table View' },
  326. 'dhcp-client': { title: 'DHCP Client', sub: 'DHCP Client List' },
  327. 'dhcp-server': { title: 'DHCP Server & Subnets', sub: 'DHCP Server instances, subnet networks (NTP, TFTP, DNS), dynamic leases & static reservations' },
  328. bridge: { title: 'Bridge Interfaces', sub: 'IEEE 802.1D / 802.1Q VLAN-aware Layer 2 switching, RSTP & hardware forwarding (FDB)' },
  329. vlans: { title: 'VLAN Virtual Networks', sub: 'IEEE 802.1Q sub-interface segmentation and routing' },
  330. firewall: { title: 'Network Firewall', sub: 'Stateful packet inspection, NAT, traffic mangle, address lists & connection tracking' },
  331. routes: { title: 'Routing & Policy', sub: 'Routing tables, static routes (DAS/DAC), and policy routing rules' },
  332. bgp: { title: 'BGP Dynamic Routing', sub: 'BGP multi-instance peering sessions, advertised networks, and routing table (RIB)' },
  333. ospf: { title: 'OSPF Dynamic Routing', sub: 'OSPFv2 link-state routing, dynamic neighbor adjacencies, and multi-area topology' },
  334. 'routing-filters': { title: 'Routing Policy Filters', sub: 'Route filter chains, prefix matching, BGP community maps & policy-based path control' },
  335. 'dynamic-routing': { title: 'BGP Dynamic Routing', sub: 'Dynamic routing engine and peering sessions' },
  336. ppp: { title: 'PPP Servers & Secrets', sub: 'Subscriber authentication, dynamic IP pools and VPN access concentrators' },
  337. eoip: { title: 'EoIP Tunnels', sub: 'Ethernet over IP (EoIP / GRETAP) Layer 2 encapsulation & transparent network bridging' },
  338. aerotun: { title: 'AeroTUN High-Speed VPN', sub: 'Layer 3 encrypted tunnel with XChaCha20-Poly1305 and adaptive LZ4 compression' },
  339. pppoe: { title: 'PPPoE Client WAN', sub: 'Point-to-Point Protocol over Ethernet WAN access' },
  340. wireguard: { title: 'WireGuard VPN', sub: 'High-performance cryptographic Layer 3 tunnels with ChaCha20-Poly1305 key exchange' },
  341. ipsec: { title: 'IPSec (IKEv2) strongSwan', sub: 'Enterprise Site-to-Site & Roadwarrior IPSec controller' },
  342. l2tp: { title: 'L2TP VPN Client', sub: 'Layer 2 Tunneling Protocol via xl2tpd' },
  343. pptp: { title: 'PPTP VPN Client', sub: 'Point-to-Point Tunneling Protocol with MPPE-128 encryption' },
  344. vrrp: { title: 'VRRP High Availability', sub: 'Virtual Router Redundancy Protocol, active-backup gateway failover & Virtual IP (VIP) routing' },
  345. bwtest: { title: 'Bandwidth Test Benchmark', sub: 'High-speed line-rate throughput benchmark, token-bucket rate limiting, loss & jitter telemetry' },
  346. tools: { title: 'Diagnostic & Troubleshooting Tools', sub: 'Network latency analysis, ICMP/MTR telemetry, path tracing, DNS resolution and TCP probing' },
  347. settings: { title: 'Router Settings & DNS', sub: 'System DNS forwarder, upstream resolvers, static host mappings, and appliance identity' },
  348. users: { title: 'Local User Manager', sub: 'Manage local system administrator credentials and access permissions' },
  349. certificates: { title: 'Certificates & SSL/TLS', sub: 'Root Certificate Authorities (CA), Server/Client certificates and automated Let\'s Encrypt' },
  350. services: { title: 'Management Services', sub: 'Enable or disable Web, SSH, and Telnet management listeners and listening ports' },
  351. updates: { title: 'Git Updates', sub: 'Check, install and restore appliance software' },
  352. logs: { title: 'System Activity Logs', sub: 'Real-time circular buffer log viewer and topic-based event monitoring' }
  353. };
  354. const header = titles[tabName] || titles.dashboard;
  355. const pTitle = document.getElementById('page-title');
  356. if (pTitle) pTitle.innerText = header.title;
  357. const pSub = document.getElementById('page-subtitle');
  358. if (pSub) pSub.innerText = header.sub;
  359. // Toggle sections dynamically for all section elements
  360. document.querySelectorAll('main section[id^="section-"]').forEach(el => {
  361. if (el.id === `section-${tabName}`) {
  362. el.classList.remove('hidden');
  363. } else {
  364. el.classList.add('hidden');
  365. }
  366. });
  367. if (tabName === 'interfaces') {
  368. loadRoles();
  369. if (state.activeIfaceSubTab === 'roles') switchIfaceSubTab('roles');
  370. else switchIfaceSubTab('tree');
  371. }
  372. if (tabName === 'bridge') loadBridge();
  373. if (tabName === 'firewall') loadFirewall();
  374. if (tabName === 'routes') loadRoutes();
  375. if (tabName === 'bgp') {
  376. loadDynamicRouting();
  377. switchBgpSubTab(state.activeBgpSubTab || 'bgp-peers');
  378. }
  379. if (tabName === 'ospf') {
  380. loadDynamicRouting();
  381. switchOspfTab(state.activeOspfTab || 'instances');
  382. }
  383. if (tabName === 'routing-filters') loadDynamicRouting();
  384. if (tabName === 'dynamic-routing') loadDynamicRouting();
  385. if (tabName === 'ppp') loadPPP();
  386. if (tabName === 'eoip') loadEoIP();
  387. if (tabName === 'aerotun') loadAeroTUN();
  388. if (tabName === 'pppoe') loadPPPoE();
  389. if (tabName === 'wireguard') loadWireGuard();
  390. if (tabName === 'ipsec') loadIPSec();
  391. if (tabName === 'l2tp') loadL2TP();
  392. if (tabName === 'pptp') loadPPTP();
  393. if (tabName === 'tools') loadToolsView();
  394. if (tabName === 'dhcp-client') loadDHCPClients();
  395. if (tabName === 'dhcp-server') loadDHCPServer();
  396. if (tabName === 'vrrp') loadVRRP();
  397. if (tabName === 'bwtest') loadBwTestView();
  398. if (tabName === 'settings') loadSettingsData();
  399. if (tabName === 'users') loadUsers();
  400. if (tabName === 'certificates') loadCertificates();
  401. if (tabName === 'services') loadServices();
  402. if (tabName === 'updates') loadUpdateStatus();
  403. if (tabName === 'logs') loadLogs();
  404. setTimeout(initTableSorting, 50);
  405. }
  406. // Fetch all core system, network and VPN telemetry
  407. function fetchData(isManual = false) {
  408. if (coreRefreshPromise) return coreRefreshPromise;
  409. coreRefreshPromise = refreshCoreData(isManual).finally(() => { coreRefreshPromise = null; });
  410. return coreRefreshPromise;
  411. }
  412. async function refreshCoreData(isManual = false) {
  413. const spinner = document.getElementById('refresh-spinner');
  414. if (isManual && spinner) spinner.classList.add('animate-spin');
  415. try {
  416. const refreshSummaries = isManual || Date.now() - lastSummaryRefresh > 30000;
  417. const summaryFetch = path => (refreshSummaries || (state.activeTab === 'interfaces' && ['/vlans', '/roles'].includes(path))) ? fetch(`${API_BASE}${path}`).catch(() => ({ ok: false })) : Promise.resolve({ ok: false });
  418. const [statusRes, ifacesRes, vlansRes, vpnRes, fwRes, dynRes, brSummaryRes, dhcpSumRes, dhcpClientsRes, vrrpSumRes, rolesRes] = await Promise.all([
  419. fetch(`${API_BASE}/system/status`).catch(() => ({ ok: false })),
  420. fetch(`${API_BASE}/interfaces`).catch(() => ({ ok: false })),
  421. summaryFetch('/vlans'),
  422. summaryFetch('/vpn/status'),
  423. summaryFetch('/firewall/summary'),
  424. summaryFetch('/routing/dynamic/summary'),
  425. summaryFetch('/bridge/summary'),
  426. summaryFetch('/dhcp/clients/summary'),
  427. summaryFetch('/dhcp/clients'),
  428. summaryFetch('/vrrp/summary').catch(() => null),
  429. summaryFetch('/roles').catch(() => null)
  430. ]);
  431. if (refreshSummaries && [vlansRes, vpnRes, fwRes, dynRes, brSummaryRes, dhcpSumRes, dhcpClientsRes, vrrpSumRes, rolesRes].every(r => r && r.ok)) lastSummaryRefresh = Date.now();
  432. if (rolesRes && rolesRes.ok) {
  433. state.roles = await rolesRes.json();
  434. const countEl = document.getElementById('badge-roles-count');
  435. if (countEl) countEl.innerText = (state.roles || []).length;
  436. }
  437. if (vrrpSumRes && vrrpSumRes.ok) {
  438. state.vrrpSummary = await vrrpSumRes.json();
  439. renderVRRPSummary();
  440. }
  441. if (dhcpSumRes && dhcpSumRes.ok) {
  442. state.dhcpSummary = await dhcpSumRes.json();
  443. const bDhcp = document.getElementById('badge-dhcp-client-count');
  444. if (bDhcp) bDhcp.innerText = state.dhcpSummary?.total_clients || 0;
  445. }
  446. if (dhcpClientsRes && dhcpClientsRes.ok) {
  447. state.dhcpClients = await dhcpClientsRes.json();
  448. }
  449. if (brSummaryRes.ok) {
  450. state.bridgeSummary = await brSummaryRes.json();
  451. const bBridge = document.getElementById('badge-bridge-count');
  452. if (bBridge) bBridge.innerText = state.bridgeSummary?.bridges_count || 0;
  453. const sBr = document.getElementById('bridge-stat-bridges');
  454. if (sBr) sBr.innerText = state.bridgeSummary?.bridges_count || 0;
  455. const sPorts = document.getElementById('bridge-stat-ports');
  456. if (sPorts) sPorts.innerText = state.bridgeSummary?.ports_count || 0;
  457. const sHosts = document.getElementById('bridge-stat-hosts');
  458. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  459. }
  460. if (statusRes.ok) state.systemStatus = await statusRes.json();
  461. if (ifacesRes.ok) {
  462. const ifacesData = await ifacesRes.json();
  463. const rawIfaces = Array.isArray(ifacesData) ? ifacesData : [];
  464. state.interfaces = rawIfaces.filter(i => {
  465. if (!i.name) return false;
  466. if (i.name.startsWith('ep_')) return false;
  467. return !['gre0', 'gretap0', 'erspan0', 'sit0', 'tunl0', 'ip6tnl0', 'ip6gre0', 'ip6erspan0'].includes(i.name);
  468. });
  469. try { populateToolsInterfaces(); } catch (e) {}
  470. }
  471. if (vlansRes.ok) {
  472. const vlansData = await vlansRes.json();
  473. state.vlans = Array.isArray(vlansData) ? vlansData : [];
  474. }
  475. if (vpnRes.ok) state.vpnStatus = await vpnRes.json();
  476. if (fwRes && fwRes.ok) state.fwSummary = await fwRes.json();
  477. if (dynRes && dynRes.ok) state.dynSummary = await dynRes.json();
  478. updateSystemMetrics();
  479. updateBadges();
  480. if (state.activeTab === 'dashboard') renderDashboard();
  481. if (state.activeTab === 'interfaces') {
  482. if (state.activeIfaceSubTab === 'roles') renderRolesTable();
  483. else renderInterfacesList();
  484. }
  485. if (state.activeTab === 'vlans') renderVlansList();
  486. if (state.activeTab === 'firewall') await loadFirewall(false);
  487. if (state.activeTab === 'routes') await loadRoutes(false);
  488. if (state.activeTab === 'dynamic-routing' || state.activeTab === 'bgp' || state.activeTab === 'ospf') await loadDynamicRouting(false);
  489. if (state.activeTab === 'ppp') await loadPPP(false);
  490. if (state.activeTab === 'eoip') await loadEoIP(false);
  491. if (state.activeTab === 'aerotun') await loadAeroTUN(false);
  492. if (state.activeTab === 'pppoe') await loadPPPoE(false);
  493. if (state.activeTab === 'wireguard') await loadWireGuard(false);
  494. if (state.activeTab === 'ipsec') await loadIPSec(false);
  495. if (state.activeTab === 'l2tp') await loadL2TP(false);
  496. if (state.activeTab === 'pptp') await loadPPTP(false);
  497. if (state.activeTab === 'dhcp-client') await loadDHCPClients(false);
  498. if (state.activeTab === 'dhcp-server') await loadDHCPServer(false);
  499. if (state.activeTab === 'vrrp') await loadVRRP(false);
  500. if (state.activeTab === 'settings') await loadSettingsData(false);
  501. if (state.activeTab === 'users') await loadUsers(false);
  502. if (state.activeTab === 'certificates') await loadCertificates(false);
  503. if (state.activeTab === 'services') await loadServices(false);
  504. if (state.activeTab === 'updates') await loadUpdateStatus(false);
  505. if (state.activeTab === 'bwtest') await fetchBwTestServerStatus();
  506. } catch (err) {
  507. console.error('Failed to fetch router state:', err);
  508. } finally {
  509. if (isManual && spinner) {
  510. setTimeout(() => spinner.classList.remove('animate-spin'), 300);
  511. }
  512. }
  513. }
  514. // Update Top KPI and Sidebar Telemetry
  515. function updateSystemMetrics() {
  516. const s = state.systemStatus;
  517. const v = state.vpnStatus;
  518. if (!s) return;
  519. // Sidebar Host & Uptime
  520. const sideHost = document.getElementById('side-hostname');
  521. if (sideHost) sideHost.innerText = s.hostname || 'debian-lxc';
  522. const sideUp = document.getElementById('side-uptime');
  523. if (sideUp) sideUp.innerText = s.uptime_human || '0m';
  524. const sideGw = document.getElementById('side-gateway-ip');
  525. if (sideGw) sideGw.innerText = s.default_gateway ? `GW: ${s.default_gateway}` : 'GW: Isolated';
  526. // Compute CPU Metrics
  527. let cpuPct = 0;
  528. if (s.cpu_pct !== undefined) {
  529. cpuPct = s.cpu_pct;
  530. } else if (s.cpu_load && s.cpu_load.length > 0) {
  531. const cores = s.cpu_cores || 1;
  532. cpuPct = Math.min(100, Math.round((parseFloat(s.cpu_load[0]) / cores) * 100));
  533. }
  534. const cpuPctStr = `${cpuPct.toFixed(1)}%`;
  535. const cpuWidth = `${Math.max(3, Math.min(100, cpuPct))}%`;
  536. const loadStr = s.cpu_load ? s.cpu_load.join(', ') : '-';
  537. // Sidebar CPU
  538. const sideCpuVal = document.getElementById('side-cpu-val');
  539. if (sideCpuVal) sideCpuVal.innerText = cpuPctStr;
  540. const sideCpuBar = document.getElementById('side-cpu-bar');
  541. if (sideCpuBar) {
  542. sideCpuBar.style.width = cpuWidth;
  543. sideCpuBar.title = `Container: ${cpuPctStr} | Host Loadavg: ${loadStr} (${s.cpu_cores || 1} cores)`;
  544. }
  545. // Dashboard CPU Card
  546. const dashCpuVal = document.getElementById('dash-cpu-val');
  547. if (dashCpuVal) dashCpuVal.innerText = cpuPctStr;
  548. const dashCpuBar = document.getElementById('dash-cpu-bar');
  549. if (dashCpuBar) {
  550. dashCpuBar.style.width = cpuWidth;
  551. if (cpuPct > 85) {
  552. dashCpuBar.className = 'h-full rounded-full bg-rose-500 transition-all duration-500';
  553. } else if (cpuPct > 65) {
  554. dashCpuBar.className = 'h-full rounded-full bg-amber-500 transition-all duration-500';
  555. } else {
  556. dashCpuBar.className = 'h-full rounded-full bg-emerald-500 transition-all duration-500';
  557. }
  558. }
  559. const dashCpuCores = document.getElementById('dash-cpu-cores');
  560. if (dashCpuCores) dashCpuCores.innerText = `${s.cpu_cores || 1} Cores`;
  561. const dashCpuLoad = document.getElementById('dash-cpu-load');
  562. if (dashCpuLoad) dashCpuLoad.innerText = loadStr;
  563. const dashCpuStatus = document.getElementById('dash-cpu-status');
  564. if (dashCpuStatus) {
  565. if (cpuPct > 85) {
  566. dashCpuStatus.innerText = 'High';
  567. dashCpuStatus.className = 'text-[11px] font-semibold text-rose-400 uppercase px-2 py-0.5 rounded bg-rose-500/10';
  568. } else if (cpuPct > 65) {
  569. dashCpuStatus.innerText = 'Heavy';
  570. dashCpuStatus.className = 'text-[11px] font-semibold text-amber-400 uppercase px-2 py-0.5 rounded bg-amber-500/10';
  571. } else {
  572. dashCpuStatus.innerText = 'Normal';
  573. dashCpuStatus.className = 'text-[11px] font-semibold text-emerald-400 uppercase px-2 py-0.5 rounded bg-emerald-500/10';
  574. }
  575. }
  576. // Compute RAM Metrics
  577. const memPct = Math.round(s.mem_usage_pct || 0);
  578. const memPctStr = `${memPct}%`;
  579. const memWidth = `${Math.max(3, Math.min(100, memPct))}%`;
  580. const usedMB = s.mem_used_mb || 0;
  581. const totalMB = s.mem_total_mb || 0;
  582. const freeMB = totalMB > usedMB ? totalMB - usedMB : 0;
  583. function fmtMemMB(mb) {
  584. if (mb >= 1024) {
  585. return `${(mb / 1024).toFixed(1)} GB`;
  586. }
  587. return `${mb} MB`;
  588. }
  589. // Sidebar RAM
  590. const sideRamVal = document.getElementById('side-ram-val');
  591. if (sideRamVal) sideRamVal.innerText = memPctStr;
  592. const sideRamBar = document.getElementById('side-ram-bar');
  593. if (sideRamBar) sideRamBar.style.width = memWidth;
  594. // Dashboard RAM Card
  595. const dashRamVal = document.getElementById('dash-ram-val');
  596. if (dashRamVal) dashRamVal.innerText = memPctStr;
  597. const dashRamBar = document.getElementById('dash-ram-bar');
  598. if (dashRamBar) {
  599. dashRamBar.style.width = memWidth;
  600. if (memPct > 85) {
  601. dashRamBar.className = 'h-full rounded-full bg-rose-500 transition-all duration-500';
  602. } else if (memPct > 70) {
  603. dashRamBar.className = 'h-full rounded-full bg-amber-500 transition-all duration-500';
  604. } else {
  605. dashRamBar.className = 'h-full rounded-full bg-indigo-500 transition-all duration-500';
  606. }
  607. }
  608. const dashRamUsedTotal = document.getElementById('dash-ram-used-total');
  609. if (dashRamUsedTotal) {
  610. dashRamUsedTotal.innerText = `${fmtMemMB(usedMB)} / ${fmtMemMB(totalMB)}`;
  611. }
  612. const dashRamFree = document.getElementById('dash-ram-free');
  613. if (dashRamFree) {
  614. dashRamFree.innerText = fmtMemMB(freeMB);
  615. }
  616. const dashRamStatus = document.getElementById('dash-ram-status');
  617. if (dashRamStatus) {
  618. if (memPct > 85) {
  619. dashRamStatus.innerText = 'High';
  620. dashRamStatus.className = 'text-[11px] font-semibold text-rose-400 uppercase px-2 py-0.5 rounded bg-rose-500/10';
  621. } else {
  622. dashRamStatus.innerText = 'Active';
  623. dashRamStatus.className = 'text-[11px] font-semibold text-indigo-400 uppercase px-2 py-0.5 rounded bg-indigo-500/10';
  624. }
  625. }
  626. // Legacy Dashboard Stats (Safe checks)
  627. const elIfacesUp = document.getElementById('stat-ifaces-up');
  628. if (elIfacesUp) elIfacesUp.innerText = s.up_ifaces || 0;
  629. const elIfacesTot = document.getElementById('stat-ifaces-total');
  630. if (elIfacesTot) elIfacesTot.innerText = `${s.total_ifaces || 0} Total`;
  631. const elIfacesDown = document.getElementById('stat-ifaces-down');
  632. if (elIfacesDown) elIfacesDown.innerText = `${s.down_ifaces || 0} DOWN`;
  633. const elVlans = document.getElementById('stat-vlans-count');
  634. if (elVlans) elVlans.innerText = s.vlan_ifaces || 0;
  635. // VPN Status Indicators
  636. if (v) {
  637. const totalActive = v.total_active_tunnels || 0;
  638. const statVpnActive = document.getElementById('stat-vpn-active');
  639. if (statVpnActive) statVpnActive.innerText = totalActive;
  640. const tunnelsDot = document.getElementById('tunnels-dot');
  641. const tunnelsLabel = document.getElementById('tunnels-label');
  642. if (tunnelsDot && tunnelsLabel) {
  643. if (totalActive > 0) {
  644. tunnelsDot.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  645. tunnelsLabel.innerText = `${totalActive} Active VPN Tunnel${totalActive > 1 ? 's' : ''}`;
  646. } else {
  647. tunnelsDot.className = 'w-2 h-2 rounded-full bg-slate-500';
  648. tunnelsLabel.innerText = '0 Active VPN Tunnels';
  649. }
  650. }
  651. setDotBadge('badge-pppoe-status', (v.active_pppoe || 0) > 0 || v.pppoe_connected);
  652. setDotBadge('badge-wg-status', (v.active_wireguard || 0) > 0 || v.wireguard_active);
  653. setDotBadge('badge-ipsec-status', (v.active_ipsec || 0) > 0 || v.ipsec_active);
  654. setDotBadge('badge-l2tp-status', (v.active_l2tp || 0) > 0 || v.l2tp_connected);
  655. setDotBadge('badge-pptp-status', (v.active_pptp || 0) > 0 || v.pptp_connected);
  656. }
  657. // Total Live Bandwidth Rate
  658. let totalRx = 0;
  659. let totalTx = 0;
  660. (state.interfaces || []).forEach(i => {
  661. if (i.rate) {
  662. totalRx += i.rate.rx_bytes_sec || 0;
  663. totalTx += i.rate.tx_bytes_sec || 0;
  664. }
  665. });
  666. document.getElementById('stat-traffic-rx').innerText = formatTraffic(totalRx);
  667. document.getElementById('stat-traffic-tx').innerText = formatTraffic(totalTx);
  668. }
  669. function setDotBadge(id, active) {
  670. const el = document.getElementById(id);
  671. if (!el) return;
  672. if (active) {
  673. el.className = 'w-2 h-2 rounded-full bg-emerald-400 shadow-sm shadow-emerald-400/80';
  674. } else {
  675. el.className = 'w-2 h-2 rounded-full bg-slate-600';
  676. }
  677. }
  678. function updateBadges() {
  679. const bIfaces = document.getElementById('badge-ifaces-count');
  680. if (bIfaces) bIfaces.innerText = (state.interfaces || []).length;
  681. const bVlans = document.getElementById('badge-vlans-count');
  682. if (bVlans) bVlans.innerText = (state.vlans || []).length;
  683. if (state.fwSummary) {
  684. const totalFwRules = (state.fwSummary.filter_rules_count || 0) + (state.fwSummary.nat_rules_count || 0) + (state.fwSummary.mangle_rules_count || 0);
  685. const badgeFw = document.getElementById('badge-firewall-count');
  686. if (badgeFw) badgeFw.innerText = totalFwRules;
  687. }
  688. if (state.vpnStatus) {
  689. const v = state.vpnStatus;
  690. const bEoIP = document.getElementById('badge-eoip-count');
  691. if (bEoIP) bEoIP.innerText = v.total_eoip || 0;
  692. const bAero = document.getElementById('badge-aerotun-count');
  693. if (bAero) bAero.innerText = v.total_aerotun || 0;
  694. const bPPPSess = document.getElementById('badge-ppp-sessions');
  695. if (bPPPSess) bPPPSess.innerText = v.total_ppp_sessions || 0;
  696. setDotBadge('badge-pppoe-status', v.active_pppoe > 0 || v.pppoe_server_running);
  697. setDotBadge('badge-wg-status', v.active_wireguard > 0);
  698. setDotBadge('badge-ipsec-status', v.active_ipsec > 0 || v.ipsec_server_running);
  699. setDotBadge('badge-l2tp-status', v.active_l2tp > 0 || v.l2tp_server_running);
  700. setDotBadge('badge-pptp-status', v.active_pptp > 0 || v.pptp_server_running);
  701. }
  702. if (state.dynSummary) {
  703. const d = state.dynSummary;
  704. setDotBadge('badge-bgp-dot', d.bgp_running);
  705. setDotBadge('badge-ospf-dot', d.ospf_running);
  706. const bBgp = document.getElementById('badge-bgp-count');
  707. if (bBgp) bBgp.innerText = (state.bgpPeers || []).length;
  708. const bOspf = document.getElementById('badge-ospf-count');
  709. if (bOspf) bOspf.innerText = (state.ospfInterfaces || []).length;
  710. const bFilters = document.getElementById('badge-filters-count');
  711. if (bFilters) bFilters.innerText = (state.routingFilters || []).length;
  712. }
  713. const bDhcpServer = document.getElementById('badge-dhcp-server-count');
  714. if (bDhcpServer) {
  715. bDhcpServer.innerText = state.dhcpServerSummary ? (state.dhcpServerSummary.active_leases || state.dhcpServerSummary.total_servers || 0) : (state.dhcpServers || []).length;
  716. }
  717. }
  718. // Render Dashboard View
  719. function renderDashboard() {
  720. const matrix = document.getElementById('port-matrix');
  721. if (!matrix) return;
  722. const ifaces = state.interfaces || [];
  723. const sig = ifaces.map(i => `${i.name}:${i.state}:${(i.ipv4 || []).join(',')}:${i.type}:${i.is_vlan}`).join(';');
  724. if (matrix.dataset.sig === sig) {
  725. return; // Structure & link states haven't changed! Do not rebuild or flicker!
  726. }
  727. matrix.dataset.sig = sig;
  728. matrix.innerHTML = '';
  729. (state.interfaces || []).forEach(iface => {
  730. const isUp = iface.state === 'UP';
  731. const isVlan = iface.is_vlan;
  732. const portCard = document.createElement('div');
  733. portCard.className = `p-3 rounded-xl border transition-all cursor-pointer select-none group ${
  734. isUp
  735. ? (isVlan ? 'bg-cyan-950/20 border-cyan-800/60 hover:border-cyan-500' : 'bg-slate-800/80 border-slate-700/80 hover:border-brand-500')
  736. : 'bg-slate-900/40 border-slate-800/60 opacity-60 hover:opacity-100 hover:border-slate-700'
  737. }`;
  738. portCard.onclick = () => openIfaceModal(iface.name);
  739. let statusPillClass = isUp ? 'bg-emerald-500 shadow-sm shadow-emerald-500/50' : 'bg-rose-500';
  740. if (isVlan) statusPillClass = isUp ? 'bg-cyan-400 shadow-sm shadow-cyan-400/50' : 'bg-rose-500';
  741. portCard.innerHTML = `
  742. <div class="flex items-center justify-between mb-2">
  743. <span class="font-bold text-xs font-mono text-white group-hover:text-brand-400 transition truncate">${iface.name}</span>
  744. <span class="w-2 h-2 rounded-full ${statusPillClass}"></span>
  745. </div>
  746. <div class="text-[11px] font-mono text-slate-300 truncate">${iface.ipv4 && iface.ipv4.length > 0 ? iface.ipv4[0] : (iface.mac || 'No IP')}</div>
  747. <div class="mt-2 flex items-center justify-between text-[10px] text-slate-400">
  748. <span class="uppercase tracking-wider font-semibold">${isVlan ? `VLAN ${iface.vlan_id}` : iface.type}</span>
  749. <span id="port-card-rate-${iface.name}">${iface.rate?.rx_human || '0 B/s'}</span>
  750. </div>
  751. `;
  752. matrix.appendChild(portCard);
  753. });
  754. const ifaceTbody = document.getElementById('quick-interfaces-table');
  755. if (ifaceTbody) {
  756. ifaceTbody.innerHTML = '';
  757. (state.interfaces || []).forEach(i => {
  758. const isUp = i.state === 'UP';
  759. const tr = document.createElement('tr');
  760. tr.className = 'hover:bg-slate-800/40 transition cursor-pointer';
  761. tr.onclick = () => openIfaceModal(i.name);
  762. const rxStr = i.rate?.rx_human || '0 B/s';
  763. const txStr = i.rate?.tx_human || '0 B/s';
  764. tr.innerHTML = `
  765. <td class="py-2.5 font-bold text-white flex items-center gap-2">
  766. <span class="w-2 h-2 rounded-full ${isUp ? 'bg-emerald-400 shadow-sm shadow-emerald-400/50' : 'bg-rose-400'}"></span>
  767. <span>${i.name}</span>
  768. </td>
  769. <td class="py-2.5 text-slate-300 font-sans">
  770. ${getRoleBadge(i.role || 'LAN')}
  771. </td>
  772. <td class="py-2.5 text-slate-400 text-[11px] font-mono">${i.mac || '-'}</td>
  773. <td class="py-2.5 text-slate-200 font-semibold">${i.ipv4 && i.ipv4.length > 0 ? i.ipv4.join(', ') : '<span class="text-slate-600 font-normal">Unassigned</span>'}</td>
  774. <td class="py-2.5 text-slate-300 text-[11px] font-mono">
  775. <span id="quick-rx-${i.name}" class="text-emerald-400">↓ ${rxStr}</span> <span class="text-slate-600">•</span> <span id="quick-tx-${i.name}" class="text-cyan-400">↑ ${txStr}</span>
  776. </td>
  777. <td class="py-2.5 text-right font-sans font-semibold">
  778. <span class="px-2 py-0.5 rounded text-[10px] ${isUp ? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/20' : 'bg-rose-500/10 text-rose-400 border border-rose-500/20'}">${i.state}</span>
  779. </td>
  780. `;
  781. ifaceTbody.appendChild(tr);
  782. });
  783. }
  784. const vlanTbody = document.getElementById('quick-vlans-table');
  785. if (vlanTbody) {
  786. vlanTbody.innerHTML = '';
  787. }
  788. }
  789. // Expand / Collapse Handlers
  790. function toggleExpand(parentName) {
  791. if (state.expandedParents.has(parentName)) {
  792. state.expandedParents.delete(parentName);
  793. } else {
  794. state.expandedParents.add(parentName);
  795. }
  796. renderInterfacesList();
  797. }
  798. // VLAN Support Checker: 802.1Q sub-interfaces are only supported on physical ethernet, veth, bridge, bond
  799. function supportsVLAN(iface) {
  800. if (!iface) return false;
  801. if (iface.is_vlan) return false;
  802. const name = (iface.name || '').toLowerCase();
  803. const type = (iface.type || '').toLowerCase();
  804. const role = (iface.role || '').toLowerCase();
  805. // Exclude loopback
  806. if (name === 'lo' || type === 'loopback' || role === 'loopback') return false;
  807. // Exclude WireGuard (Layer 3 tunnel, no 802.1Q support)
  808. if (type === 'wireguard' || name.startsWith('wg')) return false;
  809. // Exclude PPP / PPPoE
  810. if (type === 'ppp' || name.startsWith('ppp')) return false;
  811. // Exclude other Layer 3 tunnels and dummy devices
  812. if (type === 'dummy' || type === 'gre' || type === 'sit' || type === 'tun' || type === 'tap' ||
  813. name.startsWith('gre') || name.startsWith('sit') || name.startsWith('ipsec') || name.startsWith('xfrm') || name.startsWith('dummy')) {
  814. return false;
  815. }
  816. // If name already contains a dot, it's already a sub-interface
  817. if (name.includes('.')) return false;
  818. return true;
  819. }
  820. // DHCP Client Support Checker: Only broadcast-capable layer-2 interfaces (Ethernet, veth, VLAN, bridge, bond)
  821. function supportsDHCPClient(iface) {
  822. if (!iface) return false;
  823. const name = (iface.name || '').toLowerCase();
  824. const type = (iface.type || '').toLowerCase();
  825. const role = (iface.role || '').toLowerCase();
  826. // Exclude loopback
  827. if (name === 'lo' || type === 'loopback' || role === 'loopback') return false;
  828. // Exclude WireGuard (Layer 3 point-to-point tunnel, no broadcast/DHCP)
  829. if (type === 'wireguard' || name.startsWith('wg')) return false;
  830. // Exclude PPP / PPPoE / L2TP / PPTP tunnels
  831. if (type === 'ppp' || name.startsWith('ppp') || name.startsWith('l2tp') || name.startsWith('pptp')) return false;
  832. // Exclude other Layer 3 tunnels and dummy devices
  833. if (type === 'dummy' || type === 'gre' || type === 'sit' || type === 'tun' || type === 'tap' ||
  834. name.startsWith('gre') || name.startsWith('sit') || name.startsWith('ipsec') || name.startsWith('xfrm') || name.startsWith('dummy')) {
  835. return false;
  836. }
  837. // Exclude bridge member/slave ports (bridge itself handles IP / DHCP)
  838. const isBridgePort = (state.bridgePorts || []).some(bp => bp.interface === iface.name);
  839. if (isBridgePort) return false;
  840. return true;
  841. }
  842. // Expand / Collapse Handlers
  843. function toggleExpand(parentName) {
  844. const childVlans = (state.vlans || []).filter(v => v.parent_name === parentName || v.name.startsWith(parentName + '.'));
  845. if (childVlans.length === 0) {
  846. // Cannot expand an interface with no VLANs
  847. state.expandedParents.delete(parentName);
  848. return;
  849. }
  850. if (state.expandedParents.has(parentName)) {
  851. state.expandedParents.delete(parentName);
  852. } else {
  853. state.expandedParents.add(parentName);
  854. }
  855. renderInterfacesList();
  856. }
  857. function expandAllIfaces(expand) {
  858. if (expand) {
  859. (state.interfaces || []).forEach(i => {
  860. const hasVlans = (state.vlans || []).some(v => v.parent_name === i.name || v.name.startsWith(i.name + '.'));
  861. if (!i.is_vlan && hasVlans) state.expandedParents.add(i.name);
  862. });
  863. } else {
  864. state.expandedParents.clear();
  865. }
  866. renderInterfacesList();
  867. }
  868. // =========================================================================
  869. // INTERFACE ROLE TAGS MANAGEMENT
  870. // =========================================================================
  871. const ROLE_COLORS = {
  872. amber: { bg: 'bg-amber-500/20', text: 'text-amber-300', border: 'border-amber-500/30' },
  873. blue: { bg: 'bg-blue-500/20', text: 'text-blue-300', border: 'border-blue-500/30' },
  874. cyan: { bg: 'bg-cyan-500/20', text: 'text-cyan-300', border: 'border-cyan-500/30' },
  875. emerald: { bg: 'bg-emerald-500/20', text: 'text-emerald-300', border: 'border-emerald-500/30' },
  876. purple: { bg: 'bg-purple-500/20', text: 'text-purple-300', border: 'border-purple-500/30' },
  877. rose: { bg: 'bg-rose-500/20', text: 'text-rose-300', border: 'border-rose-500/30' },
  878. indigo: { bg: 'bg-indigo-500/20', text: 'text-indigo-300', border: 'border-indigo-500/30' },
  879. sky: { bg: 'bg-sky-500/20', text: 'text-sky-300', border: 'border-sky-500/30' },
  880. slate: { bg: 'bg-slate-800', text: 'text-slate-300', border: 'border-slate-700' }
  881. };
  882. function getRoleBadge(roleName) {
  883. const name = roleName || 'LAN';
  884. const role = (state.roles || []).find(r => r.name.toLowerCase() === name.toLowerCase() || r.id.toLowerCase() === name.toLowerCase());
  885. const colorKey = (role?.color || 'blue').toLowerCase();
  886. const theme = ROLE_COLORS[colorKey] || ROLE_COLORS.blue;
  887. return `<span class="px-2 py-0.5 rounded text-[10px] font-semibold ${theme.bg} ${theme.text} border ${theme.border}" title="Role Tag: ${escapeHtml(name)}">${escapeHtml(name)}</span>`;
  888. }
  889. function switchIfaceSubTab(subTab) {
  890. state.activeIfaceSubTab = subTab;
  891. const treeTab = document.getElementById('ifaces-subtab-tree');
  892. const rolesTab = document.getElementById('ifaces-subtab-roles');
  893. const btnTree = document.getElementById('ifaces-subtab-btn-tree');
  894. const btnRoles = document.getElementById('ifaces-subtab-btn-roles');
  895. if (subTab === 'roles') {
  896. treeTab?.classList.add('hidden');
  897. rolesTab?.classList.remove('hidden');
  898. if (btnRoles) {
  899. btnRoles.className = 'px-3.5 py-1.5 rounded-lg text-xs font-semibold bg-brand-500/10 text-brand-400 border border-brand-500/20 transition flex items-center gap-1.5';
  900. }
  901. if (btnTree) {
  902. btnTree.className = 'px-3.5 py-1.5 rounded-lg text-xs font-medium text-slate-400 hover:text-white hover:bg-slate-800 transition flex items-center gap-1.5';
  903. }
  904. loadRoles();
  905. } else {
  906. rolesTab?.classList.add('hidden');
  907. treeTab?.classList.remove('hidden');
  908. if (btnTree) {
  909. btnTree.className = 'px-3.5 py-1.5 rounded-lg text-xs font-semibold bg-brand-500/10 text-brand-400 border border-brand-500/20 transition flex items-center gap-1.5';
  910. }
  911. if (btnRoles) {
  912. btnRoles.className = 'px-3.5 py-1.5 rounded-lg text-xs font-medium text-slate-400 hover:text-white hover:bg-slate-800 transition flex items-center gap-1.5';
  913. }
  914. renderInterfacesList();
  915. }
  916. }
  917. async function loadRoles() {
  918. try {
  919. const res = await fetch(`${API_BASE}/roles`);
  920. if (res.ok) {
  921. state.roles = await res.json();
  922. const countEl = document.getElementById('badge-roles-count');
  923. if (countEl) countEl.innerText = (state.roles || []).length;
  924. renderRolesTable();
  925. populateRoleSelects();
  926. }
  927. } catch (err) {
  928. console.error('Failed to load role tags:', err);
  929. }
  930. }
  931. function renderRolesTable() {
  932. const tbody = document.getElementById('roles-table-body');
  933. const empty = document.getElementById('roles-empty-state');
  934. if (!tbody) return;
  935. const roles = state.roles || [];
  936. if (roles.length === 0) {
  937. tbody.innerHTML = '';
  938. empty?.classList.remove('hidden');
  939. return;
  940. }
  941. empty?.classList.add('hidden');
  942. const sig = roles.map(r => `${r.id}:${r.name}:${r.color}:${r.description}:${(r.interfaces||[]).join(',')}`).join(';');
  943. if (tbody.dataset.sig === sig) return;
  944. tbody.dataset.sig = sig;
  945. tbody.innerHTML = roles.map(r => {
  946. const colorKey = (r.color || 'blue').toLowerCase();
  947. const theme = ROLE_COLORS[colorKey] || ROLE_COLORS.blue;
  948. const ifaces = Array.isArray(r.interfaces) ? r.interfaces : [];
  949. const ifacesChips = ifaces.length > 0
  950. ? ifaces.map(name => `<span onclick="openIfaceModal('${escapeHtml(name)}')" class="cursor-pointer px-2 py-0.5 rounded text-[10px] font-mono bg-slate-800 text-slate-200 border border-slate-700 hover:border-cyan-500 transition mr-1 mb-1 inline-block" title="Click to view/edit ${escapeHtml(name)}">${escapeHtml(name)}</span>`).join('')
  951. : '<span class="text-slate-600 font-sans text-xs italic">Unassigned (0)</span>';
  952. return `
  953. <tr class="hover:bg-slate-800/40 transition">
  954. <td class="py-3 px-4">
  955. <span class="px-2.5 py-1 rounded text-xs font-semibold ${theme.bg} ${theme.text} border ${theme.border}">
  956. ${escapeHtml(r.name)}
  957. </span>
  958. </td>
  959. <td class="py-3 px-4 font-bold text-white font-mono flex items-center gap-2">
  960. <span>${escapeHtml(r.name)}</span>
  961. ${r.builtin ? '<span class="text-[9px] px-1.5 py-0.2 rounded bg-slate-800 text-slate-400 border border-slate-700 uppercase font-sans">Builtin</span>' : ''}
  962. </td>
  963. <td class="py-3 px-4 font-sans capitalize text-slate-300">
  964. <span class="inline-flex items-center gap-1.5">
  965. <span class="w-2 h-2 rounded-full ${theme.bg.replace('/20', '')}"></span>
  966. <span>${escapeHtml(r.color || 'blue')}</span>
  967. </span>
  968. </td>
  969. <td class="py-3 px-4 font-sans text-slate-400 text-xs">${escapeHtml(r.description || '-')}</td>
  970. <td class="py-3 px-4 font-sans">
  971. <div class="flex flex-wrap items-center">
  972. ${ifacesChips}
  973. </div>
  974. </td>
  975. <td class="py-3 px-4 text-right space-x-2 font-sans whitespace-nowrap">
  976. <button onclick="openRoleModal('${escapeHtml(r.id)}')"
  977. class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold px-2 py-1 rounded hover:bg-slate-800 transition">
  978. Edit
  979. </button>
  980. <button onclick="deleteRoleTag('${escapeHtml(r.id)}', '${escapeHtml(r.name)}')"
  981. class="text-xs text-rose-400 hover:text-rose-300 font-semibold px-2 py-1 rounded hover:bg-slate-800 transition">
  982. Delete
  983. </button>
  984. </td>
  985. </tr>
  986. `;
  987. }).join('');
  988. }
  989. function openRoleModal(id = null) {
  990. const modal = document.getElementById('role-modal');
  991. if (!modal) return;
  992. const idInput = document.getElementById('role-modal-id');
  993. const nameInput = document.getElementById('role-modal-name');
  994. const colorSelect = document.getElementById('role-modal-color');
  995. const descInput = document.getElementById('role-modal-desc');
  996. const title = document.getElementById('role-modal-title');
  997. if (id) {
  998. const role = (state.roles || []).find(r => r.id === id);
  999. if (role) {
  1000. if (title) title.innerText = `Edit Role Tag: ${role.name}`;
  1001. if (idInput) idInput.value = role.id;
  1002. if (nameInput) nameInput.value = role.name;
  1003. if (colorSelect) colorSelect.value = role.color || 'blue';
  1004. if (descInput) descInput.value = role.description || '';
  1005. }
  1006. } else {
  1007. if (title) title.innerText = 'Add Role Tag';
  1008. if (idInput) idInput.value = '';
  1009. if (nameInput) nameInput.value = '';
  1010. if (colorSelect) colorSelect.value = 'blue';
  1011. if (descInput) descInput.value = '';
  1012. }
  1013. updateRoleModalPreview();
  1014. modal.classList.remove('hidden');
  1015. }
  1016. function closeRoleModal() {
  1017. const modal = document.getElementById('role-modal');
  1018. if (modal) modal.classList.add('hidden');
  1019. }
  1020. function updateRoleModalPreview() {
  1021. const name = document.getElementById('role-modal-name')?.value.trim() || 'Preview';
  1022. const colorKey = (document.getElementById('role-modal-color')?.value || 'blue').toLowerCase();
  1023. const theme = ROLE_COLORS[colorKey] || ROLE_COLORS.blue;
  1024. const preview = document.getElementById('role-modal-preview');
  1025. if (preview) {
  1026. preview.innerText = name;
  1027. preview.className = `px-2.5 py-1 rounded text-xs font-semibold ${theme.bg} ${theme.text} border ${theme.border}`;
  1028. }
  1029. }
  1030. async function submitSaveRole(e) {
  1031. e.preventDefault();
  1032. const id = document.getElementById('role-modal-id')?.value;
  1033. const name = document.getElementById('role-modal-name')?.value.trim();
  1034. const color = document.getElementById('role-modal-color')?.value;
  1035. const desc = document.getElementById('role-modal-desc')?.value.trim();
  1036. if (!name) return;
  1037. try {
  1038. const payload = { id, name, color, description: desc };
  1039. const method = id ? 'PUT' : 'POST';
  1040. const url = id ? `${API_BASE}/roles/${encodeURIComponent(id)}` : `${API_BASE}/roles`;
  1041. const res = await fetch(url, {
  1042. method,
  1043. headers: { 'Content-Type': 'application/json' },
  1044. body: JSON.stringify(payload)
  1045. });
  1046. if (res.ok) {
  1047. showToast('Role Tag Saved', `Role tag "${name}" saved successfully`, 'success');
  1048. closeRoleModal();
  1049. await loadRoles();
  1050. fetchData(false);
  1051. } else {
  1052. const err = await res.json();
  1053. showToast('Error', err.error || err.message || 'Failed to save role tag', 'error');
  1054. }
  1055. } catch (err) {
  1056. showToast('Error', err.message, 'error');
  1057. }
  1058. }
  1059. async function deleteRoleTag(id, name) {
  1060. if (!confirm(`Are you sure you want to delete role tag "${name}"?\nInterfaces assigned to this role will default to LAN.`)) return;
  1061. try {
  1062. const res = await fetch(`${API_BASE}/roles/${encodeURIComponent(id)}`, {
  1063. method: 'DELETE'
  1064. });
  1065. if (res.ok) {
  1066. showToast('Role Tag Deleted', `Role tag "${name}" removed`, 'success');
  1067. await loadRoles();
  1068. fetchData(false);
  1069. } else {
  1070. const err = await res.json();
  1071. showToast('Error', err.error || err.message || 'Failed to delete role tag', 'error');
  1072. }
  1073. } catch (err) {
  1074. showToast('Error', err.message, 'error');
  1075. }
  1076. }
  1077. function populateRoleSelects(selectedRole = '') {
  1078. const ifaceSelect = document.getElementById('modal-iface-role');
  1079. const vlanSelect = document.getElementById('vlan-role');
  1080. const roles = state.roles || [];
  1081. const optionsHtml = roles.map(r => `<option value="${escapeHtml(r.name)}">${escapeHtml(r.name)}${r.description ? ` (${escapeHtml(r.description)})` : ''}</option>`).join('');
  1082. if (ifaceSelect) {
  1083. const currentVal = selectedRole || ifaceSelect.value || 'LAN';
  1084. if (ifaceSelect.dataset.optionsSig !== optionsHtml) {
  1085. ifaceSelect.innerHTML = optionsHtml;
  1086. ifaceSelect.dataset.optionsSig = optionsHtml;
  1087. }
  1088. if (currentVal) ifaceSelect.value = currentVal;
  1089. }
  1090. if (vlanSelect) {
  1091. const currentVal = selectedRole || vlanSelect.value || 'LAN';
  1092. if (vlanSelect.dataset.optionsSig !== optionsHtml) {
  1093. vlanSelect.innerHTML = optionsHtml;
  1094. vlanSelect.dataset.optionsSig = optionsHtml;
  1095. }
  1096. if (currentVal) vlanSelect.value = currentVal;
  1097. }
  1098. }
  1099. // Filter and Render Hierarchical Interfaces List
  1100. function filterIfaces(filter) {
  1101. state.ifaceFilter = filter || 'all';
  1102. renderInterfacesList();
  1103. }
  1104. function renderInterfacesList() {
  1105. const tbody = document.getElementById('interfaces-tree-tbody');
  1106. const emptyState = document.getElementById('interfaces-empty-state');
  1107. const summary = document.getElementById('ifaces-list-summary');
  1108. const query = (document.getElementById('iface-search')?.value || '').trim().toLowerCase();
  1109. const allIfaces = state.interfaces || [];
  1110. const allVlans = state.vlans || [];
  1111. const parentIfaces = allIfaces.filter(i => !i.is_vlan);
  1112. const filteredParents = parentIfaces.filter(parent => {
  1113. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  1114. if (query) {
  1115. const matchName = parent.name.toLowerCase().includes(query);
  1116. const matchIp = (parent.ipv4 || []).some(ip => ip.toLowerCase().includes(query));
  1117. const matchRole = (parent.role || '').toLowerCase().includes(query);
  1118. const matchType = (parent.type || '').toLowerCase().includes(query);
  1119. const matchVlan = childVlans.some(v =>
  1120. v.name.toLowerCase().includes(query) ||
  1121. String(v.vlan_id).includes(query) ||
  1122. (v.ipv4 || []).some(ip => ip.toLowerCase().includes(query)) ||
  1123. (v.description || '').toLowerCase().includes(query)
  1124. );
  1125. if (!matchName && !matchIp && !matchRole && !matchType && !matchVlan) return false;
  1126. }
  1127. if (state.ifaceFilter === 'has_vlans') return childVlans.length > 0;
  1128. if (state.ifaceFilter === 'physical') return parent.type !== 'loopback';
  1129. if (state.ifaceFilter === 'up') return parent.state === 'UP';
  1130. return true;
  1131. });
  1132. if (summary) {
  1133. summary.innerText = `${parentIfaces.length} Interfaces • ${allVlans.length} Active VLANs`;
  1134. }
  1135. if (filteredParents.length === 0) {
  1136. emptyState?.classList.remove('hidden');
  1137. tbody.innerHTML = '';
  1138. return;
  1139. }
  1140. emptyState?.classList.add('hidden');
  1141. const sig = `${state.ifaceFilter}|${query}|` + filteredParents.map(p => {
  1142. const cVlans = allVlans.filter(v => v.parent_name === p.name || v.name.startsWith(p.name + '.'));
  1143. const dhcp = (state.dhcpClients || []).find(dc => dc.interface === p.name);
  1144. return `${p.name}:${p.state}:${p.role||'LAN'}:${(p.ipv4||[]).join(',')}:${p.mtu}:${cVlans.length}:${state.expandedParents.has(p.name)}:${dhcp?.status || ''}`;
  1145. }).join(';');
  1146. if (tbody.dataset.sig === sig) {
  1147. return; // ZERO changes to structure, links, IPs or VLANs! Do not rebuild DOM!
  1148. }
  1149. tbody.dataset.sig = sig;
  1150. tbody.innerHTML = '';
  1151. filteredParents.forEach(parent => {
  1152. const isUp = parent.state === 'UP';
  1153. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  1154. const hasVlans = childVlans.length > 0;
  1155. const isExpanded = hasVlans && state.expandedParents.has(parent.name);
  1156. const canHaveVlan = supportsVLAN(parent);
  1157. const parentRow = document.createElement('tr');
  1158. parentRow.className = `hover:bg-slate-800/50 transition border-b border-slate-800/80 ${isExpanded ? 'bg-slate-900/80' : ''}`;
  1159. parentRow.innerHTML = `
  1160. <td class="py-3 px-3 text-center">
  1161. ${hasVlans ? `
  1162. <button onclick="toggleExpand('${parent.name}')" title="${isExpanded ? 'Collapse VLANs' : 'Expand VLANs'}"
  1163. class="w-6 h-6 rounded flex items-center justify-center hover:bg-slate-800 text-slate-400 hover:text-white transition">
  1164. <svg class="w-4 h-4 chevron-icon ${isExpanded ? 'chevron-open text-cyan-400' : 'text-slate-500'}" fill="none" stroke="currentColor" viewBox="0 0 24 24">
  1165. <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M9 5l7 7-7 7" />
  1166. </svg>
  1167. </button>
  1168. ` : `
  1169. <div class="w-6 h-6 flex items-center justify-center text-slate-700 select-none">
  1170. <span class="w-1.5 h-1.5 rounded-full bg-slate-800"></span>
  1171. </div>
  1172. `}
  1173. </td>
  1174. <td class="py-3 px-4">
  1175. <div class="flex items-center space-x-2.5">
  1176. <div class="w-7 h-7 rounded-lg bg-slate-800 border border-slate-700/80 flex items-center justify-center text-[10px] font-bold text-slate-300">
  1177. ${parent.type === 'loopback' ? 'LO' : (parent.type === 'wireguard' ? 'WG' : (parent.type === 'bridge' ? 'BR' : 'NIC'))}
  1178. </div>
  1179. <div>
  1180. <div class="flex items-center gap-2">
  1181. <span class="font-bold text-white text-sm cursor-pointer hover:text-cyan-400 flex items-center gap-1.5" onclick="${hasVlans ? `toggleExpand('${parent.name}')` : `openIfaceModal('${parent.name}')`}" title="${hasVlans ? 'Click to expand VLANs, or click pencil to rename' : 'Click to configure or rename interface'}">
  1182. <span>${parent.name}</span>
  1183. <svg onclick="event.stopPropagation(); openIfaceModal('${parent.name}')" class="w-3.5 h-3.5 text-slate-500 hover:text-cyan-400 opacity-60 hover:opacity-100 cursor-pointer" title="Configure / Rename ${parent.name}" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"/></svg>
  1184. </span>
  1185. ${hasVlans ? `
  1186. <span onclick="toggleExpand('${parent.name}')" class="cursor-pointer text-[10px] bg-cyan-950 text-cyan-400 border border-cyan-800/60 px-2 py-0.5 rounded-full font-bold hover:bg-cyan-900 transition">${childVlans.length} VLAN${childVlans.length > 1 ? 's' : ''}</span>
  1187. ` : `
  1188. <span class="text-[10px] bg-slate-800/40 text-slate-500 px-1.5 py-0.5 rounded font-mono select-none">0 VLANs</span>
  1189. `}
  1190. </div>
  1191. <div class="text-[10px] text-slate-500 font-sans mt-0.5">${parent.type}</div>
  1192. </div>
  1193. </div>
  1194. </td>
  1195. <td class="py-3 px-4 font-sans">
  1196. <div class="flex items-center gap-1.5">
  1197. ${getRoleBadge(parent.role || 'LAN')}
  1198. <span class="text-xs text-slate-400 truncate max-w-[120px]">${parent.description || '-'}</span>
  1199. </div>
  1200. </td>
  1201. <td class="py-3 px-4">
  1202. ${parent.ipv4 && parent.ipv4.length > 0
  1203. ? `<div class="text-white font-medium">${parent.ipv4[0]}</div>`
  1204. : '<span class="text-slate-600 font-sans">Unassigned</span>'
  1205. }
  1206. ${(() => {
  1207. const c = (state.dhcpClients || []).find(dc => dc.interface === parent.name);
  1208. if (!c) return '';
  1209. const statusCls = c.status === 'bound' ? 'bg-amber-500/20 text-amber-300 border-amber-500/30' : (c.status === 'searching' ? 'bg-sky-500/20 text-sky-300 border-sky-500/30' : 'bg-slate-800 text-slate-400 border-slate-700');
  1210. return `<div class="mt-1"><span class="px-1.5 py-0.5 rounded text-[10px] font-mono border ${statusCls} cursor-pointer hover:underline" onclick="navigate('dhcp-client')" title="DHCP Client: ${c.status.toUpperCase()} (${c.ip_address || 'requesting...'})">⚡ DHCP: ${c.status.toUpperCase()}</span></div>`;
  1211. })()}
  1212. </td>
  1213. <td class="py-3 px-4 text-slate-400 text-[11px]">
  1214. <div>${parent.mac || 'N/A'}</div>
  1215. <div class="text-[10px] text-slate-500">MTU ${parent.mtu}</div>
  1216. </td>
  1217. <td class="py-3 px-4 text-[11px]">
  1218. <div class="flex items-center space-x-2">
  1219. <span id="iface-rate-rx-${parent.name}" class="text-emerald-400">↓ ${parent.rate?.rx_human || '0 B/s'}</span>
  1220. <span id="iface-rate-tx-${parent.name}" class="text-cyan-400">↑ ${parent.rate?.tx_human || '0 B/s'}</span>
  1221. </div>
  1222. </td>
  1223. <td class="py-3 px-4 font-sans">
  1224. <button onclick="toggleInterfaceState('${parent.name}', '${isUp ? 'down' : 'up'}')"
  1225. class="flex items-center gap-1.5 text-xs font-semibold px-2.5 py-1 rounded-full transition ${
  1226. isUp ? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/30 hover:bg-rose-500/10 hover:text-rose-400 hover:border-rose-500/30' : 'bg-rose-500/10 text-rose-400 border border-rose-500/30 hover:bg-emerald-500/10 hover:text-emerald-400'
  1227. }" title="Click to toggle link status">
  1228. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  1229. <span>${parent.state}</span>
  1230. </button>
  1231. </td>
  1232. <td class="py-3 px-4 text-right space-x-2 font-sans">
  1233. ${(() => {
  1234. const c = (state.dhcpClients || []).find(dc => dc.interface === parent.name);
  1235. if (c) {
  1236. return `<button onclick="navigate('dhcp-client')" title="Manage DHCP Client (${c.status})" class="text-xs bg-amber-500/10 hover:bg-amber-500/20 text-amber-400 font-medium px-2.5 py-1 rounded-lg border border-amber-500/30 transition">⚡ DHCP</button>`;
  1237. }
  1238. if (!supportsDHCPClient(parent)) {
  1239. return '';
  1240. }
  1241. return `<button onclick="openDHCPClientModalForIface('${parent.name}')" title="Add DHCP Client on ${parent.name}" class="text-xs bg-slate-800/80 hover:bg-slate-700 text-slate-300 hover:text-amber-400 font-medium px-2 py-1 rounded-lg border border-slate-700 transition">+ DHCP</button>`;
  1242. })()}
  1243. ${canHaveVlan ? `
  1244. <button onclick="openVlanModal('${parent.name}')"
  1245. class="text-xs bg-cyan-950/60 hover:bg-cyan-900 text-cyan-300 font-semibold px-2.5 py-1 rounded-lg border border-cyan-800/70 shadow-sm transition">
  1246. + Add VLAN
  1247. </button>
  1248. ` : ''}
  1249. <button onclick="openIfaceModal('${parent.name}')"
  1250. class="text-xs bg-slate-800 hover:bg-slate-700 text-white font-medium px-2.5 py-1 rounded-lg border border-slate-700 transition">
  1251. Edit
  1252. </button>
  1253. </td>
  1254. `;
  1255. tbody.appendChild(parentRow);
  1256. if (isExpanded) {
  1257. const drawerRow = document.createElement('tr');
  1258. drawerRow.className = 'bg-slate-950/80 border-b border-slate-800/90';
  1259. const drawerCell = document.createElement('td');
  1260. drawerCell.colSpan = 8;
  1261. drawerCell.className = 'p-0';
  1262. drawerCell.innerHTML = `
  1263. <div class="py-4 pl-12 pr-6 border-l-4 border-cyan-500 bg-gradient-to-r from-cyan-950/20 via-slate-900/40 to-transparent">
  1264. <div class="flex items-center justify-between mb-3">
  1265. <div class="flex items-center space-x-3">
  1266. <span class="font-bold text-xs text-white uppercase tracking-wider flex items-center gap-1.5 font-sans">
  1267. <span>VLAN Sub-interfaces on <code class="text-cyan-300 lowercase">${parent.name}</code></span>
  1268. </span>
  1269. <span class="text-[11px] bg-cyan-950 text-cyan-400 px-2 py-0.5 rounded-full border border-cyan-800/60 font-mono">
  1270. ${childVlans.length} Attached
  1271. </span>
  1272. </div>
  1273. <button onclick="openVlanModal('${parent.name}')"
  1274. class="flex items-center space-x-1.5 text-xs bg-cyan-600 hover:bg-cyan-500 text-white font-semibold px-3 py-1.5 rounded-lg shadow-md shadow-cyan-500/20 transition font-sans">
  1275. <span>+ Create VLAN on ${parent.name}</span>
  1276. </button>
  1277. </div>
  1278. ${childVlans.length === 0 ? `
  1279. <div class="p-6 text-center border border-dashed border-slate-800 rounded-xl bg-slate-900/40 font-sans">
  1280. <p class="text-xs text-slate-400 mb-2">No 802.1Q tagged VLANs have been created under <strong class="text-white">${parent.name}</strong> yet.</p>
  1281. <button onclick="openVlanModal('${parent.name}')" class="inline-flex items-center space-x-1.5 text-xs text-cyan-400 hover:text-cyan-300 bg-cyan-950/60 border border-cyan-800/70 px-3 py-1.5 rounded-lg transition font-medium">
  1282. <span>+ Create Your First VLAN on ${parent.name}</span>
  1283. </button>
  1284. </div>
  1285. ` : `
  1286. <div class="overflow-x-auto rounded-lg border border-slate-800 bg-slate-900/90 shadow-inner">
  1287. <table class="w-full text-left text-xs font-mono">
  1288. <thead class="text-slate-400 bg-slate-950/70 border-b border-slate-800 uppercase tracking-wider text-[10px] font-sans">
  1289. <tr>
  1290. <th class="py-2.5 px-4">VLAN ID</th>
  1291. <th class="py-2.5 px-4">Interface Device</th>
  1292. <th class="py-2.5 px-4">Subnet Gateway</th>
  1293. <th class="py-2.5 px-4">Role / Alias</th>
  1294. <th class="py-2.5 px-4">MTU</th>
  1295. <th class="py-2.5 px-4">Throughput</th>
  1296. <th class="py-2.5 px-4">Status</th>
  1297. <th class="py-2.5 px-4 text-right">Actions</th>
  1298. </tr>
  1299. </thead>
  1300. <tbody class="divide-y divide-slate-800/70">
  1301. ${childVlans.map(v => {
  1302. const isVlanUp = v.state === 'UP';
  1303. return `
  1304. <tr class="hover:bg-slate-800/40 transition">
  1305. <td class="py-2.5 px-4">
  1306. <span class="px-2 py-0.5 rounded text-xs font-bold bg-cyan-950 text-cyan-300 border border-cyan-800 shadow-sm">
  1307. VLAN ${v.vlan_id}
  1308. </span>
  1309. </td>
  1310. <td class="py-2.5 px-4 font-bold text-white flex items-center gap-1.5">
  1311. <span class="text-cyan-500">└─</span>
  1312. <span class="cursor-pointer hover:text-cyan-400 flex items-center gap-1" onclick="openIfaceModal('${v.name}')" title="Configure / Rename ${v.name}">
  1313. <span>${v.name}</span>
  1314. <svg class="w-3 h-3 text-slate-500 hover:text-cyan-400 opacity-60 hover:opacity-100" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"/></svg>
  1315. </span>
  1316. </td>
  1317. <td class="py-2.5 px-4 text-emerald-400 font-medium">
  1318. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  1319. ${(() => {
  1320. const c = (state.dhcpClients || []).find(dc => dc.interface === v.name);
  1321. if (!c) return '';
  1322. const statusCls = c.status === 'bound' ? 'bg-amber-500/20 text-amber-300 border-amber-500/30' : 'bg-slate-800 text-slate-400 border-slate-700';
  1323. return `<div class="mt-0.5"><span class="px-1.5 py-0.2 rounded text-[9px] font-mono border ${statusCls} cursor-pointer hover:underline" onclick="navigate('dhcp-client')" title="DHCP Client: ${c.status.toUpperCase()}">⚡ DHCP: ${c.status.toUpperCase()}</span></div>`;
  1324. })()}
  1325. </td>
  1326. <td class="py-2.5 px-4 font-sans text-slate-300">
  1327. <div class="flex items-center gap-1.5">
  1328. ${getRoleBadge(v.role || 'LAN')}
  1329. <span class="text-slate-400 text-xs">${v.description || '-'}</span>
  1330. </div>
  1331. </td>
  1332. <td class="py-2.5 px-4 text-slate-400">${v.mtu}</td>
  1333. <td class="py-2.5 px-4 text-[11px]">
  1334. <span id="vlan-rate-rx-${v.name}" class="text-emerald-400">↓ ${v.rate?.rx_human || '0 B/s'}</span>
  1335. <span id="vlan-rate-tx-${v.name}" class="text-cyan-400 ml-1.5">↑ ${v.rate?.tx_human || '0 B/s'}</span>
  1336. </td>
  1337. <td class="py-2.5 px-4 font-sans">
  1338. <button onclick="toggleInterfaceState('${v.name}', '${isVlanUp ? 'down' : 'up'}')"
  1339. class="flex items-center gap-1 text-[11px] font-semibold px-2 py-0.5 rounded-full ${
  1340. isVlanUp ? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/30' : 'bg-rose-500/10 text-rose-400 border border-rose-500/30'
  1341. }">
  1342. <span class="w-1.5 h-1.5 rounded-full ${isVlanUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  1343. <span>${v.state}</span>
  1344. </button>
  1345. </td>
  1346. <td class="py-2.5 px-4 text-right space-x-1.5 font-sans">
  1347. ${(() => {
  1348. const c = (state.dhcpClients || []).find(dc => dc.interface === v.name);
  1349. if (c) {
  1350. return `<button onclick="navigate('dhcp-client')" class="text-xs text-amber-400 hover:text-amber-300 px-2 py-0.5 rounded bg-amber-950/40 border border-amber-800/50">⚡ DHCP</button>`;
  1351. }
  1352. if (!supportsDHCPClient(v)) {
  1353. return '';
  1354. }
  1355. return `<button onclick="openDHCPClientModalForIface('${v.name}')" class="text-xs text-slate-400 hover:text-amber-400 px-1.5 py-0.5 rounded border border-slate-700">+ DHCP</button>`;
  1356. })()}
  1357. <button onclick="openIfaceModal('${v.name}')" class="text-xs bg-slate-800 hover:bg-slate-700 text-slate-200 px-2 py-0.5 rounded border border-slate-700">Edit</button>
  1358. <button onclick="confirmDeleteVlan('${v.name}')" class="text-xs text-rose-400 hover:text-rose-300 hover:bg-rose-950/40 px-2 py-0.5 rounded transition">Delete</button>
  1359. </td>
  1360. </tr>
  1361. `;
  1362. }).join('')}
  1363. </tbody>
  1364. </table>
  1365. </div>
  1366. `}
  1367. </div>
  1368. `;
  1369. drawerRow.appendChild(drawerCell);
  1370. tbody.appendChild(drawerRow);
  1371. }
  1372. });
  1373. }
  1374. // Render VLANs Dedicated View
  1375. function renderVlansList() {
  1376. const tbody = document.getElementById('vlans-table-body');
  1377. if (!tbody) return;
  1378. const emptyState = document.getElementById('vlans-empty-state');
  1379. const countBadge = document.getElementById('vlans-table-count');
  1380. const query = (document.getElementById('vlan-search')?.value || '').toLowerCase();
  1381. const allVlans = state.vlans || [];
  1382. if (countBadge) countBadge.innerText = allVlans.length;
  1383. const filtered = allVlans.filter(v => {
  1384. if (!query) return true;
  1385. return v.name.toLowerCase().includes(query) ||
  1386. String(v.vlan_id).includes(query) ||
  1387. (v.description || '').toLowerCase().includes(query) ||
  1388. (v.ipv4 && v.ipv4.some(ip => ip.includes(query)));
  1389. });
  1390. if (allVlans.length === 0) {
  1391. emptyState.classList.remove('hidden');
  1392. tbody.innerHTML = '';
  1393. return;
  1394. }
  1395. emptyState.classList.add('hidden');
  1396. const sig = `${query}|` + filtered.map(v => `${v.name}:${v.state}:${(v.ipv4||[]).join(',')}:${v.vlan_id}:${v.mtu}`).join(';');
  1397. if (tbody.dataset.sig === sig) return;
  1398. tbody.dataset.sig = sig;
  1399. tbody.innerHTML = '';
  1400. filtered.forEach(v => {
  1401. const isUp = v.state === 'UP';
  1402. const tr = document.createElement('tr');
  1403. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  1404. tr.innerHTML = `
  1405. <td class="py-3 px-4">
  1406. <span class="px-2.5 py-1 rounded-md text-xs font-bold bg-cyan-950 text-cyan-300 border border-cyan-800/70 shadow-sm">
  1407. VLAN ${v.vlan_id}
  1408. </span>
  1409. </td>
  1410. <td class="py-3 px-4 font-bold text-white">
  1411. <span class="cursor-pointer hover:text-cyan-400 flex items-center gap-1.5" onclick="openIfaceModal('${v.name}')" title="Configure / Rename ${v.name}">
  1412. <span>${v.name}</span>
  1413. <svg class="w-3.5 h-3.5 text-slate-500 hover:text-cyan-400 opacity-60 hover:opacity-100" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"/></svg>
  1414. </span>
  1415. </td>
  1416. <td class="py-3 px-4 text-slate-300">
  1417. <span class="bg-slate-800 text-slate-200 px-2 py-0.5 rounded text-[11px]">${v.parent_name || 'eth0'}</span>
  1418. </td>
  1419. <td class="py-3 px-4 text-emerald-400 font-medium">
  1420. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  1421. </td>
  1422. <td class="py-3 px-4 text-slate-300 font-sans">
  1423. <span class="text-slate-400 text-xs">${v.description || v.role || '-'}</span>
  1424. </td>
  1425. <td class="py-3 px-4 text-slate-400">${v.mtu}</td>
  1426. <td class="py-3 px-4 font-sans">
  1427. <button onclick="toggleInterfaceState('${v.name}', '${isUp ? 'down' : 'up'}')"
  1428. class="flex items-center gap-1.5 text-xs font-semibold px-2 py-0.5 rounded-full ${
  1429. isUp ? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/30' : 'bg-rose-500/10 text-rose-400 border border-rose-500/30'
  1430. }">
  1431. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  1432. <span>${v.state}</span>
  1433. </button>
  1434. </td>
  1435. <td class="py-3 px-4 text-right space-x-2 font-sans">
  1436. <button onclick="openIfaceModal('${v.name}')" class="text-xs bg-slate-800 hover:bg-slate-700 text-slate-200 px-2.5 py-1 rounded border border-slate-700">Edit</button>
  1437. <button onclick="confirmDeleteVlan('${v.name}')" class="text-xs text-rose-400 hover:text-rose-300 hover:bg-rose-950/40 px-2 py-1 rounded transition">Delete</button>
  1438. </td>
  1439. `;
  1440. tbody.appendChild(tr);
  1441. });
  1442. }
  1443. // Toggle interface UP / DOWN
  1444. async function toggleInterfaceState(name, newState) {
  1445. try {
  1446. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(name)}/state`, {
  1447. method: 'POST',
  1448. headers: { 'Content-Type': 'application/json' },
  1449. body: JSON.stringify({ state: newState })
  1450. });
  1451. const data = await res.json();
  1452. if (res.ok) {
  1453. showToast('Interface Updated', `Interface ${name} is now ${newState.toUpperCase()}`, 'success');
  1454. fetchData(false);
  1455. } else {
  1456. showToast('Error', data.message || 'Failed to toggle interface state', 'error');
  1457. }
  1458. } catch (err) {
  1459. showToast('Error', err.message, 'error');
  1460. }
  1461. }
  1462. // ---------------- MikroTik Flag & Utilities ----------------
  1463. function renderMikroTikFlag(running, disabled) {
  1464. if (running) {
  1465. return `<span class="inline-flex items-center justify-center w-5 h-5 rounded-md font-mono font-bold text-[11px] bg-emerald-500/20 text-emerald-400 border border-emerald-500/40 shadow-sm" title="Running (Connected)">R</span>`;
  1466. }
  1467. if (disabled) {
  1468. return `<span class="inline-flex items-center justify-center w-5 h-5 rounded-md font-mono font-bold text-[11px] bg-rose-500/20 text-rose-400 border border-rose-500/40 shadow-sm" title="Disabled">X</span>`;
  1469. }
  1470. return `<span class="inline-flex items-center justify-center w-5 h-5 rounded-md font-mono font-bold text-[11px] text-slate-500 bg-slate-800/80 border border-slate-700/60" title="Idle / Disconnected">-</span>`;
  1471. }
  1472. function copyToClipboard(text, label = 'Text') {
  1473. navigator.clipboard.writeText(text).then(() => {
  1474. showToast('Copied', `${label} copied to clipboard`, 'success');
  1475. }).catch(() => {
  1476. prompt('Copy value:', text);
  1477. });
  1478. }
  1479. // ======================== PPP Profiles Shared Helper ========================
  1480. async function fetchPPPProfilesList() {
  1481. try {
  1482. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`);
  1483. if (res.ok) {
  1484. state.pppProfiles = await res.json();
  1485. }
  1486. } catch (err) {
  1487. console.error('Failed to load PPP profiles:', err);
  1488. }
  1489. }
  1490. function populateProfileSelect(selectId, selectedVal, defaultVal = 'default') {
  1491. const sel = document.getElementById(selectId);
  1492. if (!sel) return;
  1493. const profiles = (state.pppProfiles && state.pppProfiles.length > 0) ? state.pppProfiles : [
  1494. { name: 'default', use_encryption: 'no' },
  1495. { name: 'default-encryption', use_encryption: 'required' }
  1496. ];
  1497. sel.innerHTML = '';
  1498. profiles.forEach(p => {
  1499. const opt = document.createElement('option');
  1500. opt.value = p.name;
  1501. const encBadge = p.use_encryption === 'required' ? ' (MPPE-128)' : (p.use_encryption === 'yes' ? ' (MPPE)' : '');
  1502. opt.innerText = `${p.name}${encBadge}`;
  1503. sel.appendChild(opt);
  1504. });
  1505. if (selectedVal) {
  1506. sel.value = selectedVal;
  1507. } else {
  1508. sel.value = defaultVal;
  1509. }
  1510. if (!sel.value && sel.options.length > 0) {
  1511. sel.selectedIndex = 0;
  1512. }
  1513. }
  1514. // ======================== PPPoE Multi-Instance ========================
  1515. async function loadPPPoE(populateInputs = true) {
  1516. try {
  1517. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  1518. await fetchPPPProfilesList();
  1519. }
  1520. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`);
  1521. const list = await res.json();
  1522. state.pppoeList = Array.isArray(list) ? list : [];
  1523. const badge = document.getElementById('pppoe-count-badge');
  1524. if (badge) badge.innerText = `${state.pppoeList.length} Interface${state.pppoeList.length !== 1 ? 's' : ''}`;
  1525. const tbody = document.getElementById('pppoe-table-body');
  1526. const empty = document.getElementById('pppoe-empty');
  1527. if (!tbody) return;
  1528. tbody.innerHTML = '';
  1529. if (state.pppoeList.length === 0) {
  1530. if (empty) empty.classList.remove('hidden');
  1531. } else {
  1532. if (empty) empty.classList.add('hidden');
  1533. state.pppoeList.forEach(inst => {
  1534. const tr = document.createElement('tr');
  1535. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1536. tr.innerHTML = `
  1537. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  1538. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  1539. <td class="py-2.5 px-3 text-cyan-400 font-mono">${escapeHtml(inst.interface)}</td>
  1540. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  1541. <td class="py-2.5 px-3 font-mono text-cyan-300"><span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 border border-slate-700">${escapeHtml(inst.profile || 'default')}</span></td>
  1542. <td class="py-2.5 px-3 font-mono ${inst.assigned_ip ? 'text-emerald-400 font-bold' : 'text-slate-500'}">${escapeHtml(inst.assigned_ip || '-')}</td>
  1543. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  1544. <td class="py-2.5 px-3 text-center">
  1545. <span class="px-2 py-0.5 rounded text-[10px] font-sans ${inst.default_route ? 'bg-blue-500/20 text-blue-300 border border-blue-500/30' : 'bg-slate-800 text-slate-500'}">
  1546. ${inst.default_route ? 'Yes' : 'No'}
  1547. </span>
  1548. </td>
  1549. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  1550. ${inst.running ? `
  1551. <button onclick="disconnectPPPoEInstance('${inst.name}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  1552. ` : `
  1553. <button onclick="connectPPPoEInstance('${inst.name}')" class="text-xs bg-blue-600/30 hover:bg-blue-600/50 text-blue-300 px-2 py-0.5 rounded border border-blue-500/30">Connect</button>
  1554. `}
  1555. <button onclick="togglePPPoEState('${inst.name}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  1556. ${inst.disabled ? 'Enable' : 'Disable'}
  1557. </button>
  1558. <button onclick="openEditPPPoEModal('${inst.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  1559. <button onclick="deletePPPoEInstance('${inst.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  1560. </td>
  1561. `;
  1562. tbody.appendChild(tr);
  1563. });
  1564. }
  1565. } catch (err) {
  1566. console.error('Failed to load PPPoE:', err);
  1567. }
  1568. }
  1569. function openAddPPPoEModal() {
  1570. document.getElementById('pppoe-modal-title').innerText = 'Add PPPoE Client Interface';
  1571. document.getElementById('pppoe-modal-edit-orig').value = '';
  1572. document.getElementById('pppoe-modal-name').value = `pppoe-out${(state.pppoeList || []).length + 1}`;
  1573. document.getElementById('pppoe-modal-name').readOnly = false;
  1574. document.getElementById('pppoe-modal-user').value = '';
  1575. document.getElementById('pppoe-modal-pass').value = '';
  1576. document.getElementById('pppoe-modal-service').value = '';
  1577. document.getElementById('pppoe-modal-mtu').value = '1492';
  1578. document.getElementById('pppoe-modal-defroute').checked = true;
  1579. document.getElementById('pppoe-modal-reconnect').checked = true;
  1580. document.getElementById('pppoe-modal-disabled').checked = false;
  1581. // Populate profiles
  1582. populateProfileSelect('pppoe-modal-profile', 'default', 'default');
  1583. // Populate interfaces
  1584. const sel = document.getElementById('pppoe-modal-iface');
  1585. sel.innerHTML = '';
  1586. (state.interfaces || []).forEach(i => {
  1587. if (i.name === 'lo') return;
  1588. const opt = document.createElement('option');
  1589. opt.value = i.name;
  1590. opt.innerText = `${i.name} (${i.role || i.type})`;
  1591. sel.appendChild(opt);
  1592. });
  1593. document.getElementById('pppoe-modal').classList.remove('hidden');
  1594. }
  1595. function openEditPPPoEModal(name) {
  1596. const inst = (state.pppoeList || []).find(i => i.name === name);
  1597. if (!inst) return;
  1598. document.getElementById('pppoe-modal-title').innerText = `Edit PPPoE Client: ${name}`;
  1599. document.getElementById('pppoe-modal-edit-orig').value = name;
  1600. document.getElementById('pppoe-modal-name').value = inst.name;
  1601. document.getElementById('pppoe-modal-name').readOnly = true;
  1602. document.getElementById('pppoe-modal-user').value = inst.username || '';
  1603. document.getElementById('pppoe-modal-pass').value = inst.password || '';
  1604. document.getElementById('pppoe-modal-service').value = inst.service_name || '';
  1605. document.getElementById('pppoe-modal-mtu').value = inst.mtu || 1492;
  1606. document.getElementById('pppoe-modal-defroute').checked = inst.default_route ?? true;
  1607. document.getElementById('pppoe-modal-reconnect').checked = inst.auto_reconnect ?? true;
  1608. document.getElementById('pppoe-modal-disabled').checked = !!inst.disabled;
  1609. // Populate profiles
  1610. populateProfileSelect('pppoe-modal-profile', inst.profile || 'default', 'default');
  1611. const sel = document.getElementById('pppoe-modal-iface');
  1612. sel.innerHTML = '';
  1613. (state.interfaces || []).forEach(i => {
  1614. if (i.name === 'lo') return;
  1615. const opt = document.createElement('option');
  1616. opt.value = i.name;
  1617. opt.innerText = `${i.name} (${i.role || i.type})`;
  1618. if (i.name === inst.interface) opt.selected = true;
  1619. sel.appendChild(opt);
  1620. });
  1621. document.getElementById('pppoe-modal').classList.remove('hidden');
  1622. }
  1623. function closePPPoEModal() {
  1624. document.getElementById('pppoe-modal').classList.add('hidden');
  1625. }
  1626. async function submitSavePPPoE(e) {
  1627. e.preventDefault();
  1628. const name = document.getElementById('pppoe-modal-name').value.trim();
  1629. const iface = document.getElementById('pppoe-modal-iface').value;
  1630. const user = document.getElementById('pppoe-modal-user').value.trim();
  1631. const pass = document.getElementById('pppoe-modal-pass').value;
  1632. const profile = document.getElementById('pppoe-modal-profile')?.value || 'default';
  1633. const service = document.getElementById('pppoe-modal-service').value.trim();
  1634. const mtu = parseInt(document.getElementById('pppoe-modal-mtu').value, 10) || 1492;
  1635. const defRoute = document.getElementById('pppoe-modal-defroute').checked;
  1636. const reconnect = document.getElementById('pppoe-modal-reconnect').checked;
  1637. const disabled = document.getElementById('pppoe-modal-disabled').checked;
  1638. try {
  1639. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`, {
  1640. method: 'POST',
  1641. headers: { 'Content-Type': 'application/json' },
  1642. body: JSON.stringify({
  1643. name,
  1644. interface: iface,
  1645. username: user,
  1646. password: pass,
  1647. profile: profile,
  1648. service_name: service,
  1649. mtu,
  1650. default_route: defRoute,
  1651. auto_reconnect: reconnect,
  1652. disabled
  1653. })
  1654. });
  1655. if (res.ok) {
  1656. showToast('PPPoE Saved', `Configuration for ${name} saved`, 'success');
  1657. closePPPoEModal();
  1658. loadPPPoE(false);
  1659. fetchData(false);
  1660. } else {
  1661. const err = await res.json();
  1662. showToast('Error', err.message || 'Failed to save PPPoE', 'error');
  1663. }
  1664. } catch (err) {
  1665. showToast('Error', err.message, 'error');
  1666. }
  1667. }
  1668. async function connectPPPoEInstance(name) {
  1669. try {
  1670. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  1671. if (res.ok) {
  1672. showToast('Connecting', `Dialing ${name}...`, 'info');
  1673. setTimeout(() => loadPPPoE(false), 2000);
  1674. }
  1675. } catch (err) {
  1676. showToast('Error', err.message, 'error');
  1677. }
  1678. }
  1679. async function disconnectPPPoEInstance(name) {
  1680. try {
  1681. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  1682. if (res.ok) {
  1683. showToast('Disconnected', `${name} session terminated`, 'info');
  1684. setTimeout(() => loadPPPoE(false), 1000);
  1685. }
  1686. } catch (err) {
  1687. showToast('Error', err.message, 'error');
  1688. }
  1689. }
  1690. async function togglePPPoEState(name, enable) {
  1691. try {
  1692. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/state`, {
  1693. method: 'POST',
  1694. headers: { 'Content-Type': 'application/json' },
  1695. body: JSON.stringify({ enabled: enable })
  1696. });
  1697. if (res.ok) {
  1698. showToast(enable ? 'Enabled' : 'Disabled', `${name} is now ${enable ? 'enabled' : 'disabled'}`, 'info');
  1699. loadPPPoE(false);
  1700. }
  1701. } catch (err) {
  1702. showToast('Error', err.message, 'error');
  1703. }
  1704. }
  1705. async function deletePPPoEInstance(name) {
  1706. if (!confirm(`Are you sure you want to delete PPPoE client ${name}?`)) return;
  1707. try {
  1708. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1709. if (res.ok) {
  1710. showToast('Deleted', `PPPoE client ${name} removed`, 'success');
  1711. loadPPPoE(false);
  1712. fetchData(false);
  1713. }
  1714. } catch (err) {
  1715. showToast('Error', err.message, 'error');
  1716. }
  1717. }
  1718. // ======================== WireGuard Multi-Interface & Multi-Peer ========================
  1719. state.wgSubTab = 'ifaces';
  1720. function switchWGSubTab(tab) {
  1721. state.wgSubTab = tab;
  1722. const ifacesPanel = document.getElementById('wg-subtab-ifaces');
  1723. const peersPanel = document.getElementById('wg-subtab-peers');
  1724. const ifacesBtn = document.getElementById('wg-subtab-btn-ifaces');
  1725. const peersBtn = document.getElementById('wg-subtab-btn-peers');
  1726. if (tab === 'ifaces') {
  1727. ifacesPanel?.classList.remove('hidden');
  1728. peersPanel?.classList.add('hidden');
  1729. ifacesBtn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-rose-500 text-white transition flex items-center gap-2';
  1730. peersBtn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition flex items-center gap-2';
  1731. } else {
  1732. ifacesPanel?.classList.add('hidden');
  1733. peersPanel?.classList.remove('hidden');
  1734. ifacesBtn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition flex items-center gap-2';
  1735. peersBtn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-rose-500 text-white transition flex items-center gap-2';
  1736. renderWGPeers();
  1737. }
  1738. }
  1739. async function loadWireGuard(populateInputs = true) {
  1740. try {
  1741. const [ifacesRes, peersRes] = await Promise.all([
  1742. fetch(`${API_BASE}/vpn/wireguard/interfaces`),
  1743. fetch(`${API_BASE}/vpn/wireguard/peers`)
  1744. ]);
  1745. const ifaces = ifacesRes.ok ? await ifacesRes.json() : [];
  1746. const peers = peersRes.ok ? await peersRes.json() : [];
  1747. state.wgInterfaces = Array.isArray(ifaces) ? ifaces : [];
  1748. state.wgPeers = Array.isArray(peers) ? peers : [];
  1749. // Badges
  1750. const ifacesCountBadge = document.getElementById('wg-ifaces-count');
  1751. if (ifacesCountBadge) ifacesCountBadge.innerText = `${state.wgInterfaces.length} Interfaces`;
  1752. const peersCountBadge = document.getElementById('wg-peers-count');
  1753. if (peersCountBadge) peersCountBadge.innerText = `${state.wgPeers.length} Peers`;
  1754. const subTabIfaces = document.getElementById('wg-subtab-badge-ifaces');
  1755. if (subTabIfaces) subTabIfaces.innerText = state.wgInterfaces.length;
  1756. const subTabPeers = document.getElementById('wg-subtab-badge-peers');
  1757. if (subTabPeers) subTabPeers.innerText = state.wgPeers.length;
  1758. // Render Interfaces
  1759. const ifacesTbody = document.getElementById('wg-ifaces-table-body');
  1760. const ifacesEmpty = document.getElementById('wg-ifaces-empty');
  1761. if (ifacesTbody) {
  1762. ifacesTbody.innerHTML = '';
  1763. if (state.wgInterfaces.length === 0) {
  1764. if (ifacesEmpty) ifacesEmpty.classList.remove('hidden');
  1765. } else {
  1766. if (ifacesEmpty) ifacesEmpty.classList.add('hidden');
  1767. state.wgInterfaces.forEach(iface => {
  1768. const peersOnIface = state.wgPeers.filter(p => p.interface === iface.name).length;
  1769. const tr = document.createElement('tr');
  1770. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1771. tr.innerHTML = `
  1772. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(iface.running, iface.disabled)}</td>
  1773. <td class="py-2.5 px-3">
  1774. <div class="flex items-center gap-1.5">
  1775. <span class="font-bold text-white">${escapeHtml(iface.name)}</span>
  1776. ${iface.comment ? `<span class="text-[10px] text-slate-400 font-sans italic">(${escapeHtml(iface.comment)})</span>` : ''}
  1777. </div>
  1778. </td>
  1779. <td class="py-2.5 px-3 text-amber-400 font-mono">${iface.listen_port}</td>
  1780. <td class="py-2.5 px-3 text-emerald-400 font-mono">${iface.address || '<span class="text-slate-600 font-sans">--</span>'}</td>
  1781. <td class="py-2.5 px-3 text-slate-300 font-mono">
  1782. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${iface.public_key}', 'Public Key')" title="Click to copy: ${iface.public_key}">
  1783. ${(iface.public_key || '').substring(0, 10)}... 📋
  1784. </span>
  1785. </td>
  1786. <td class="py-2.5 px-3 text-slate-400 font-mono">${iface.mtu || 1420}</td>
  1787. <td class="py-2.5 px-3 text-center">
  1788. <span class="px-2 py-0.5 rounded text-[10px] font-sans bg-slate-800 text-slate-300">${peersOnIface} peer${peersOnIface !== 1 ? 's' : ''}</span>
  1789. </td>
  1790. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  1791. ${iface.running ? `
  1792. <button onclick="stopWGInterface('${iface.name}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Stop</button>
  1793. ` : `
  1794. <button onclick="startWGInterface('${iface.name}')" class="text-xs bg-rose-600/30 hover:bg-rose-600/50 text-rose-300 px-2 py-0.5 rounded border border-rose-500/30 font-medium">Start</button>
  1795. `}
  1796. <button onclick="toggleWGInterfaceState('${iface.name}', ${iface.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white font-medium">
  1797. ${iface.disabled ? 'Enable' : 'Disable'}
  1798. </button>
  1799. <button onclick="openEditWGInterfaceModal('${iface.name}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Edit</button>
  1800. <button onclick="deleteWGInterface('${iface.name}')" class="text-xs text-slate-500 hover:text-rose-400 font-medium">Delete</button>
  1801. </td>
  1802. `;
  1803. ifacesTbody.appendChild(tr);
  1804. });
  1805. }
  1806. }
  1807. // Populate filter dropdown in peers tab
  1808. const filterSel = document.getElementById('wg-peers-filter-iface');
  1809. if (filterSel) {
  1810. const currentVal = filterSel.value;
  1811. filterSel.innerHTML = '<option value="">All Interfaces</option>';
  1812. state.wgInterfaces.forEach(i => {
  1813. const opt = document.createElement('option');
  1814. opt.value = i.name;
  1815. opt.innerText = i.name;
  1816. if (i.name === currentVal) opt.selected = true;
  1817. filterSel.appendChild(opt);
  1818. });
  1819. }
  1820. renderWGPeers();
  1821. } catch (err) {
  1822. console.error('Failed to load WireGuard:', err);
  1823. }
  1824. }
  1825. function formatWGPeerEndpoint(address, port) {
  1826. if (!address || address === '(none)') return '--';
  1827. let addr = address.trim();
  1828. let p = port || 0;
  1829. while (addr.includes(':') && !addr.startsWith('[')) {
  1830. const lastColon = addr.lastIndexOf(':');
  1831. const maybePort = addr.substring(lastColon + 1);
  1832. if (!isNaN(parseInt(maybePort, 10)) && parseInt(maybePort, 10) > 0) {
  1833. if (!p) p = parseInt(maybePort, 10);
  1834. addr = addr.substring(0, lastColon);
  1835. } else {
  1836. break;
  1837. }
  1838. }
  1839. return p ? `${addr}:${p}` : addr;
  1840. }
  1841. function renderWGPeers() {
  1842. const filterSel = document.getElementById('wg-peers-filter-iface');
  1843. const selectedIface = filterSel ? filterSel.value : '';
  1844. const tbody = document.getElementById('wg-peers-table-body');
  1845. const empty = document.getElementById('wg-peers-empty');
  1846. if (!tbody) return;
  1847. tbody.innerHTML = '';
  1848. const filtered = selectedIface ? state.wgPeers.filter(p => p.interface === selectedIface) : state.wgPeers;
  1849. if (filtered.length === 0) {
  1850. if (empty) empty.classList.remove('hidden');
  1851. } else {
  1852. if (empty) empty.classList.add('hidden');
  1853. filtered.forEach(p => {
  1854. const isOnline = p.latest_handshake && !p.latest_handshake.includes('Never');
  1855. const tr = document.createElement('tr');
  1856. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1857. tr.innerHTML = `
  1858. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(isOnline, p.disabled)}</td>
  1859. <td class="py-2.5 px-3 font-mono font-bold text-rose-400">${escapeHtml(p.interface)}</td>
  1860. <td class="py-2.5 px-3 font-bold text-white font-sans">${escapeHtml(p.name || 'Unnamed')}</td>
  1861. <td class="py-2.5 px-3 text-slate-300 font-mono">
  1862. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${p.public_key}', 'Peer Public Key')" title="${p.public_key}">
  1863. ${(p.public_key || '').substring(0, 10)}... 📋
  1864. </span>
  1865. </td>
  1866. <td class="py-2.5 px-3 text-emerald-400 font-mono font-semibold">${(p.allowed_ips || []).join(', ')}</td>
  1867. <td class="py-2.5 px-3 text-slate-400 font-mono">${formatWGPeerEndpoint(p.endpoint_address, p.endpoint_port)}</td>
  1868. <td class="py-2.5 px-3 text-slate-300 font-sans">${p.latest_handshake || 'Never'}</td>
  1869. <td class="py-2.5 px-3 font-mono text-[11px]">
  1870. <span class="text-emerald-400">↓ ${p.transfer_rx_human || '0 B'}</span>
  1871. <span class="text-cyan-400 ml-1">↑ ${p.transfer_tx_human || '0 B'}</span>
  1872. </td>
  1873. <td class="py-2.5 px-3 text-right font-sans space-x-2 whitespace-nowrap">
  1874. <button onclick="toggleWGPeerState('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}', ${p.disabled ? 'true' : 'false'})" class="text-xs ${p.disabled ? 'text-emerald-400 hover:text-emerald-300' : 'text-slate-400 hover:text-white'} font-medium">
  1875. ${p.disabled ? 'Enable' : 'Disable'}
  1876. </button>
  1877. <button onclick="openEditWGPeerModal('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Edit</button>
  1878. <button onclick="openWGClientConfModal('${escapeHtml(p.interface)}', '${(p.allowed_ips || [])[0] || '10.10.0.2/32'}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold" title="Generate WireGuard Client Profile (.conf)">Config (.conf)</button>
  1879. <button onclick="deleteWGPeer('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Delete</button>
  1880. </td>
  1881. `;
  1882. tbody.appendChild(tr);
  1883. });
  1884. }
  1885. }
  1886. function openAddWGInterfaceModal() {
  1887. document.getElementById('wg-iface-modal-title').innerText = 'Add WireGuard Interface';
  1888. document.getElementById('wg-iface-modal-edit-orig').value = '';
  1889. const nameEl = document.getElementById('wg-iface-modal-name');
  1890. nameEl.value = `wg${(state.wgInterfaces || []).length}`;
  1891. nameEl.readOnly = false;
  1892. document.getElementById('wg-iface-modal-port').value = 51820 + (state.wgInterfaces || []).length;
  1893. document.getElementById('wg-iface-modal-addr').value = `10.${10 + (state.wgInterfaces || []).length}.0.1/24`;
  1894. document.getElementById('wg-iface-modal-mtu').value = '1420';
  1895. document.getElementById('wg-iface-modal-comment').value = '';
  1896. document.getElementById('wg-iface-modal-pubkey').value = '';
  1897. document.getElementById('wg-iface-modal-privkey').value = '';
  1898. document.getElementById('wg-iface-modal-disabled').checked = false;
  1899. generateWGInterfaceKeys();
  1900. document.getElementById('wg-iface-modal').classList.remove('hidden');
  1901. }
  1902. function openEditWGInterfaceModal(name) {
  1903. const iface = (state.wgInterfaces || []).find(i => i.name === name);
  1904. if (!iface) return;
  1905. document.getElementById('wg-iface-modal-title').innerText = `Edit WireGuard Interface: ${name}`;
  1906. document.getElementById('wg-iface-modal-edit-orig').value = name;
  1907. const nameEl = document.getElementById('wg-iface-modal-name');
  1908. nameEl.value = iface.name;
  1909. nameEl.readOnly = false; // ALLOW RENAMING
  1910. document.getElementById('wg-iface-modal-port').value = iface.listen_port || 51820;
  1911. document.getElementById('wg-iface-modal-addr').value = iface.address || '';
  1912. document.getElementById('wg-iface-modal-mtu').value = iface.mtu || 1420;
  1913. document.getElementById('wg-iface-modal-comment').value = iface.comment || '';
  1914. document.getElementById('wg-iface-modal-pubkey').value = iface.public_key || '';
  1915. document.getElementById('wg-iface-modal-privkey').value = iface.private_key || '';
  1916. document.getElementById('wg-iface-modal-disabled').checked = !!iface.disabled;
  1917. document.getElementById('wg-iface-modal').classList.remove('hidden');
  1918. }
  1919. function closeAddWGInterfaceModal() {
  1920. document.getElementById('wg-iface-modal').classList.add('hidden');
  1921. }
  1922. async function generateWGInterfaceKeys() {
  1923. try {
  1924. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  1925. const keys = await res.json();
  1926. if (res.ok) {
  1927. document.getElementById('wg-iface-modal-privkey').value = keys.private_key;
  1928. document.getElementById('wg-iface-modal-pubkey').value = keys.public_key;
  1929. }
  1930. } catch (err) {
  1931. showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
  1932. }
  1933. }
  1934. async function onWGInterfacePrivKeyInput() {
  1935. const privKey = document.getElementById('wg-iface-modal-privkey').value.trim();
  1936. if (!privKey) return;
  1937. try {
  1938. const res = await fetch(`${API_BASE}/vpn/wireguard/calc-pubkey`, {
  1939. method: 'POST',
  1940. headers: { 'Content-Type': 'application/json' },
  1941. body: JSON.stringify({ private_key: privKey })
  1942. });
  1943. if (res.ok) {
  1944. const data = await res.json();
  1945. if (data.public_key) {
  1946. document.getElementById('wg-iface-modal-pubkey').value = data.public_key;
  1947. }
  1948. }
  1949. } catch (err) {
  1950. // Ignore while typing
  1951. }
  1952. }
  1953. function toggleWGPrivKeyVisibility() {
  1954. const el = document.getElementById('wg-iface-modal-privkey');
  1955. const btn = document.getElementById('btn-toggle-wg-privkey');
  1956. if (el.type === 'password') {
  1957. el.type = 'text';
  1958. btn.innerText = '🙈 Hide';
  1959. } else {
  1960. el.type = 'password';
  1961. btn.innerText = '👁️ Show';
  1962. }
  1963. }
  1964. function copyWGInterfacePubKey() {
  1965. const pub = document.getElementById('wg-iface-modal-pubkey').value;
  1966. if (pub) copyToClipboard(pub, 'Interface Public Key');
  1967. }
  1968. async function submitSaveWGInterface(e) {
  1969. e.preventDefault();
  1970. const origName = document.getElementById('wg-iface-modal-edit-orig').value.trim();
  1971. const name = document.getElementById('wg-iface-modal-name').value.trim();
  1972. const port = parseInt(document.getElementById('wg-iface-modal-port').value, 10) || 51820;
  1973. const addr = document.getElementById('wg-iface-modal-addr').value.trim();
  1974. const mtu = parseInt(document.getElementById('wg-iface-modal-mtu').value, 10) || 1420;
  1975. const comment = document.getElementById('wg-iface-modal-comment').value.trim();
  1976. const pub = document.getElementById('wg-iface-modal-pubkey').value.trim();
  1977. const priv = document.getElementById('wg-iface-modal-privkey').value.trim();
  1978. const disabled = document.getElementById('wg-iface-modal-disabled').checked;
  1979. try {
  1980. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces`, {
  1981. method: 'POST',
  1982. headers: { 'Content-Type': 'application/json' },
  1983. body: JSON.stringify({
  1984. orig_name: origName,
  1985. name,
  1986. listen_port: port,
  1987. address: addr,
  1988. mtu,
  1989. comment,
  1990. public_key: pub,
  1991. private_key: priv,
  1992. disabled
  1993. })
  1994. });
  1995. const data = await res.json();
  1996. if (res.ok) {
  1997. showToast('WireGuard Saved', `Interface ${name} configured successfully`, 'success');
  1998. closeAddWGInterfaceModal();
  1999. loadWireGuard(false);
  2000. fetchData(false);
  2001. } else {
  2002. showToast('Error', data.error || 'Failed to save interface', 'error');
  2003. }
  2004. } catch (err) {
  2005. showToast('Error', err.message, 'error');
  2006. }
  2007. }
  2008. async function startWGInterface(name) {
  2009. try {
  2010. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/start`, { method: 'POST' });
  2011. if (res.ok) {
  2012. showToast('Interface UP', `Started WireGuard interface ${name}`, 'success');
  2013. loadWireGuard(false);
  2014. fetchData(false);
  2015. }
  2016. } catch (err) {
  2017. showToast('Error', err.message, 'error');
  2018. }
  2019. }
  2020. async function stopWGInterface(name) {
  2021. try {
  2022. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  2023. if (res.ok) {
  2024. showToast('Interface DOWN', `Stopped WireGuard interface ${name}`, 'info');
  2025. loadWireGuard(false);
  2026. fetchData(false);
  2027. }
  2028. } catch (err) {
  2029. showToast('Error', err.message, 'error');
  2030. }
  2031. }
  2032. async function toggleWGInterfaceState(name, enable) {
  2033. try {
  2034. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/state`, {
  2035. method: 'POST',
  2036. headers: { 'Content-Type': 'application/json' },
  2037. body: JSON.stringify({ enabled: enable })
  2038. });
  2039. if (res.ok) {
  2040. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  2041. loadWireGuard(false);
  2042. fetchData(false);
  2043. }
  2044. } catch (err) {
  2045. showToast('Error', err.message, 'error');
  2046. }
  2047. }
  2048. async function deleteWGInterface(name) {
  2049. if (!confirm(`Are you sure you want to delete WireGuard interface ${name}? All associated peers will also be removed.`)) return;
  2050. try {
  2051. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2052. if (res.ok) {
  2053. showToast('Deleted', `Interface ${name} removed`, 'success');
  2054. loadWireGuard(false);
  2055. fetchData(false);
  2056. }
  2057. } catch (err) {
  2058. showToast('Error', err.message, 'error');
  2059. }
  2060. }
  2061. function populateWGPeerIfaceSelect(selectedIface = '') {
  2062. const sel = document.getElementById('wg-peer-modal-iface');
  2063. if (!sel) return;
  2064. sel.innerHTML = '';
  2065. (state.wgInterfaces || []).forEach(i => {
  2066. const opt = document.createElement('option');
  2067. opt.value = i.name;
  2068. opt.innerText = `${i.name} (${i.address || 'No IP'})`;
  2069. if (i.name === selectedIface) opt.selected = true;
  2070. sel.appendChild(opt);
  2071. });
  2072. }
  2073. function openAddWGPeerModal() {
  2074. if ((state.wgInterfaces || []).length === 0) {
  2075. showToast('No Interfaces', 'Please add a WireGuard interface first before adding peers', 'warning');
  2076. openAddWGInterfaceModal();
  2077. return;
  2078. }
  2079. document.getElementById('wg-peer-modal-title').innerText = 'Add WireGuard Peer';
  2080. document.getElementById('wg-peer-modal-edit-orig-iface').value = '';
  2081. document.getElementById('wg-peer-modal-edit-orig-pubkey').value = '';
  2082. populateWGPeerIfaceSelect();
  2083. document.getElementById('wg-peer-modal-name').value = '';
  2084. document.getElementById('wg-peer-modal-pubkey').value = '';
  2085. document.getElementById('wg-peer-modal-allowedips').value = '10.10.0.2/32';
  2086. document.getElementById('wg-peer-modal-endpoint').value = '';
  2087. document.getElementById('wg-peer-modal-port').value = '';
  2088. document.getElementById('wg-peer-modal-keepalive').value = '25';
  2089. document.getElementById('wg-peer-modal-preshared').value = '';
  2090. document.getElementById('wg-peer-modal-disabled').checked = false;
  2091. document.getElementById('wg-peer-key-warning').classList.add('hidden');
  2092. document.getElementById('wg-peer-gen-key-box').classList.add('hidden');
  2093. document.getElementById('wg-peer-modal').classList.remove('hidden');
  2094. }
  2095. function openEditWGPeerModal(ifaceName, pubKey) {
  2096. const peer = (state.wgPeers || []).find(p => p.interface === ifaceName && p.public_key === pubKey);
  2097. if (!peer) {
  2098. showToast('Not Found', 'Peer not found', 'warning');
  2099. return;
  2100. }
  2101. document.getElementById('wg-peer-modal-title').innerText = `Edit WireGuard Peer (${peer.name || ifaceName})`;
  2102. document.getElementById('wg-peer-modal-edit-orig-iface').value = peer.interface;
  2103. document.getElementById('wg-peer-modal-edit-orig-pubkey').value = peer.public_key;
  2104. populateWGPeerIfaceSelect(peer.interface);
  2105. document.getElementById('wg-peer-modal-name').value = peer.name || '';
  2106. document.getElementById('wg-peer-modal-pubkey').value = peer.public_key || '';
  2107. document.getElementById('wg-peer-modal-allowedips').value = (peer.allowed_ips || []).join(', ');
  2108. let epHost = (peer.endpoint_address || '').trim();
  2109. let epPort = peer.endpoint_port || '';
  2110. while (epHost.includes(':') && !epHost.startsWith('[')) {
  2111. const lastColon = epHost.lastIndexOf(':');
  2112. const maybePort = epHost.substring(lastColon + 1);
  2113. if (!isNaN(parseInt(maybePort, 10)) && parseInt(maybePort, 10) > 0) {
  2114. if (!epPort) epPort = parseInt(maybePort, 10);
  2115. epHost = epHost.substring(0, lastColon);
  2116. } else {
  2117. break;
  2118. }
  2119. }
  2120. document.getElementById('wg-peer-modal-endpoint').value = epHost;
  2121. document.getElementById('wg-peer-modal-port').value = epPort;
  2122. document.getElementById('wg-peer-modal-keepalive').value = peer.persistent_keepalive ?? 25;
  2123. document.getElementById('wg-peer-modal-preshared').value = peer.preshared_key || '';
  2124. document.getElementById('wg-peer-modal-disabled').checked = !!peer.disabled;
  2125. document.getElementById('wg-peer-key-warning').classList.add('hidden');
  2126. document.getElementById('wg-peer-gen-key-box').classList.add('hidden');
  2127. document.getElementById('wg-peer-modal').classList.remove('hidden');
  2128. }
  2129. function closeAddWGPeerModal() {
  2130. document.getElementById('wg-peer-modal').classList.add('hidden');
  2131. }
  2132. async function generatePeerKeypairHelper() {
  2133. try {
  2134. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  2135. const keys = await res.json();
  2136. if (res.ok) {
  2137. document.getElementById('wg-peer-modal-pubkey').value = keys.public_key;
  2138. document.getElementById('wg-peer-gen-privkey').value = keys.private_key;
  2139. document.getElementById('wg-peer-gen-key-box').classList.remove('hidden');
  2140. checkWGPeerKeyValidity();
  2141. showToast('Keypair Generated', 'Public key inserted and client private key ready to copy', 'info');
  2142. }
  2143. } catch (err) {
  2144. showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
  2145. }
  2146. }
  2147. function copyGeneratedPeerPrivKey() {
  2148. const priv = document.getElementById('wg-peer-gen-privkey').value;
  2149. if (priv) copyToClipboard(priv, 'Client Private Key');
  2150. }
  2151. async function generatePeerPSK() {
  2152. try {
  2153. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  2154. const keys = await res.json();
  2155. if (res.ok && keys.private_key) {
  2156. document.getElementById('wg-peer-modal-preshared').value = keys.private_key;
  2157. showToast('PSK Generated', 'Generated 256-bit preshared key', 'info');
  2158. }
  2159. } catch (err) {
  2160. showToast('Error', err.message, 'error');
  2161. }
  2162. }
  2163. function checkWGPeerKeyValidity() {
  2164. const ifaceName = document.getElementById('wg-peer-modal-iface').value;
  2165. const peerPubKey = document.getElementById('wg-peer-modal-pubkey').value.trim();
  2166. const warningEl = document.getElementById('wg-peer-key-warning');
  2167. if (!warningEl) return;
  2168. const targetIface = (state.wgInterfaces || []).find(i => i.name === ifaceName);
  2169. if (targetIface && targetIface.public_key && peerPubKey && targetIface.public_key === peerPubKey) {
  2170. warningEl.classList.remove('hidden');
  2171. } else {
  2172. warningEl.classList.add('hidden');
  2173. }
  2174. }
  2175. async function submitSaveWGPeer(e) {
  2176. e.preventDefault();
  2177. const origIface = document.getElementById('wg-peer-modal-edit-orig-iface').value.trim();
  2178. const origPubKey = document.getElementById('wg-peer-modal-edit-orig-pubkey').value.trim();
  2179. const iface = document.getElementById('wg-peer-modal-iface').value;
  2180. const name = document.getElementById('wg-peer-modal-name').value.trim();
  2181. const pub = document.getElementById('wg-peer-modal-pubkey').value.trim();
  2182. const allowed = document.getElementById('wg-peer-modal-allowedips').value
  2183. .split(',')
  2184. .map(s => s.trim())
  2185. .filter(s => s.length > 0);
  2186. let epHost = document.getElementById('wg-peer-modal-endpoint').value.trim();
  2187. let epPort = parseInt(document.getElementById('wg-peer-modal-port').value, 10) || 0;
  2188. while (epHost.includes(':') && !epHost.startsWith('[')) {
  2189. const lastColon = epHost.lastIndexOf(':');
  2190. const maybePort = epHost.substring(lastColon + 1);
  2191. if (!isNaN(parseInt(maybePort, 10)) && parseInt(maybePort, 10) > 0) {
  2192. if (!epPort) epPort = parseInt(maybePort, 10);
  2193. epHost = epHost.substring(0, lastColon);
  2194. } else {
  2195. break;
  2196. }
  2197. }
  2198. const keepalive = parseInt(document.getElementById('wg-peer-modal-keepalive').value, 10) || 0;
  2199. const psk = document.getElementById('wg-peer-modal-preshared').value.trim();
  2200. const disabled = document.getElementById('wg-peer-modal-disabled').checked;
  2201. // Validation
  2202. const targetIface = (state.wgInterfaces || []).find(i => i.name === iface);
  2203. if (targetIface && targetIface.public_key === pub) {
  2204. showToast('Invalid Peer Key', 'Peer public key cannot be the same as the interface public key!', 'error');
  2205. return;
  2206. }
  2207. try {
  2208. const res = await fetch(`${API_BASE}/vpn/wireguard/peers`, {
  2209. method: 'POST',
  2210. headers: { 'Content-Type': 'application/json' },
  2211. body: JSON.stringify({
  2212. orig_interface: origIface,
  2213. orig_public_key: origPubKey,
  2214. interface: iface,
  2215. name,
  2216. public_key: pub,
  2217. allowed_ips: allowed,
  2218. endpoint_address: epHost,
  2219. endpoint_port: epPort,
  2220. persistent_keepalive: keepalive,
  2221. preshared_key: psk,
  2222. disabled
  2223. })
  2224. });
  2225. const data = await res.json();
  2226. if (res.ok) {
  2227. showToast('Peer Saved', `Peer ${name} saved on ${iface}`, 'success');
  2228. closeAddWGPeerModal();
  2229. loadWireGuard(false);
  2230. } else {
  2231. showToast('Error', data.error || 'Failed to save peer', 'error');
  2232. }
  2233. } catch (err) {
  2234. showToast('Error', err.message, 'error');
  2235. }
  2236. }
  2237. async function toggleWGPeerState(iface, pubkey, enable) {
  2238. try {
  2239. const res = await fetch(`${API_BASE}/vpn/wireguard/peers/state`, {
  2240. method: 'POST',
  2241. headers: { 'Content-Type': 'application/json' },
  2242. body: JSON.stringify({ interface: iface, public_key: pubkey, enabled: enable })
  2243. });
  2244. const data = await res.json();
  2245. if (res.ok) {
  2246. showToast(enable ? 'Peer Enabled' : 'Peer Disabled', `Peer state updated on ${iface}`, 'info');
  2247. loadWireGuard(false);
  2248. } else {
  2249. showToast('Error', data.error || 'Failed to update peer state', 'error');
  2250. }
  2251. } catch (err) {
  2252. showToast('Error', err.message, 'error');
  2253. }
  2254. }
  2255. async function deleteWGPeer(iface, pubkey) {
  2256. if (!confirm(`Are you sure you want to remove peer from ${iface}?`)) return;
  2257. try {
  2258. const res = await fetch(`${API_BASE}/vpn/wireguard/peers/delete`, {
  2259. method: 'POST',
  2260. headers: { 'Content-Type': 'application/json' },
  2261. body: JSON.stringify({ interface: iface, public_key: pubkey })
  2262. });
  2263. const data = await res.json();
  2264. if (res.ok) {
  2265. showToast('Peer Deleted', 'WireGuard peer removed', 'success');
  2266. loadWireGuard(false);
  2267. } else {
  2268. showToast('Error', data.error || 'Failed to remove peer', 'error');
  2269. }
  2270. } catch (err) {
  2271. showToast('Error', err.message, 'error');
  2272. }
  2273. }
  2274. // ======================== IPSec FortiGate Phase 1 & 2 Multi-Tunnel Engine ========================
  2275. function switchIpsecModalTab(tab) {
  2276. const p1Tab = document.getElementById('tab-btn-ipsec-p1');
  2277. const p2Tab = document.getElementById('tab-btn-ipsec-p2');
  2278. const p1Content = document.getElementById('ipsec-tab-content-p1');
  2279. const p2Content = document.getElementById('ipsec-tab-content-p2');
  2280. const stepBtn = document.getElementById('btn-ipsec-switch-step');
  2281. if (tab === 'p1') {
  2282. if (p1Tab) {
  2283. p1Tab.className = 'px-4 py-2 text-xs font-bold border-b-2 border-amber-500 text-amber-300 transition flex items-center gap-2';
  2284. }
  2285. if (p2Tab) {
  2286. p2Tab.className = 'px-4 py-2 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition flex items-center gap-2';
  2287. }
  2288. if (p1Content) p1Content.classList.remove('hidden');
  2289. if (p2Content) p2Content.classList.add('hidden');
  2290. if (stepBtn) stepBtn.innerHTML = 'Next: Phase 2 Selectors &rarr;';
  2291. } else {
  2292. if (p1Tab) {
  2293. p1Tab.className = 'px-4 py-2 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition flex items-center gap-2';
  2294. }
  2295. if (p2Tab) {
  2296. p2Tab.className = 'px-4 py-2 text-xs font-bold border-b-2 border-cyan-500 text-cyan-300 transition flex items-center gap-2';
  2297. }
  2298. if (p1Content) p1Content.classList.add('hidden');
  2299. if (p2Content) p2Content.classList.remove('hidden');
  2300. if (stepBtn) stepBtn.innerHTML = '&larr; Back: Phase 1 (IKE)';
  2301. }
  2302. }
  2303. function toggleIpsecPhaseStep() {
  2304. const p1Content = document.getElementById('ipsec-tab-content-p1');
  2305. if (p1Content && !p1Content.classList.contains('hidden')) {
  2306. switchIpsecModalTab('p2');
  2307. } else {
  2308. switchIpsecModalTab('p1');
  2309. }
  2310. }
  2311. function toggleIpsecPskVisibility() {
  2312. const pskInput = document.getElementById('ipsec-modal-psk');
  2313. if (!pskInput) return;
  2314. pskInput.type = pskInput.type === 'password' ? 'text' : 'password';
  2315. }
  2316. function addIpsecLocalSubnet(val = '') {
  2317. const container = document.getElementById('ipsec-modal-local-subnets-container');
  2318. if (!container) return;
  2319. const row = document.createElement('div');
  2320. row.className = 'flex items-center gap-2 ipsec-subnet-row';
  2321. row.innerHTML = `
  2322. <input type="text" value="${escapeHtml(val)}" placeholder="e.g. 192.168.10.0/24 or 10.0.1.0/24" class="flex-1 bg-slate-900 border border-slate-700 rounded-lg px-3 py-1.5 text-white font-mono text-xs focus:outline-none focus:border-cyan-500">
  2323. <button type="button" onclick="this.closest('.ipsec-subnet-row').remove()" class="w-7 h-7 flex items-center justify-center bg-slate-800 hover:bg-rose-950 text-slate-400 hover:text-rose-400 border border-slate-700 rounded-lg text-base font-bold transition" title="Remove local subnet">-</button>
  2324. `;
  2325. container.appendChild(row);
  2326. }
  2327. function addIpsecRemoteSubnet(val = '') {
  2328. const container = document.getElementById('ipsec-modal-remote-subnets-container');
  2329. if (!container) return;
  2330. const row = document.createElement('div');
  2331. row.className = 'flex items-center gap-2 ipsec-subnet-row';
  2332. row.innerHTML = `
  2333. <input type="text" value="${escapeHtml(val)}" placeholder="e.g. 192.168.20.0/24 or 10.0.2.0/24" class="flex-1 bg-slate-900 border border-slate-700 rounded-lg px-3 py-1.5 text-white font-mono text-xs focus:outline-none focus:border-purple-500">
  2334. <button type="button" onclick="this.closest('.ipsec-subnet-row').remove()" class="w-7 h-7 flex items-center justify-center bg-slate-800 hover:bg-rose-950 text-slate-400 hover:text-rose-400 border border-slate-700 rounded-lg text-base font-bold transition" title="Remove remote subnet">-</button>
  2335. `;
  2336. container.appendChild(row);
  2337. }
  2338. function updateIpsecEspProposalFromPFS(val) {
  2339. const prop = document.getElementById('ipsec-modal-espprop');
  2340. if (!prop) return;
  2341. if (val === 'none') {
  2342. prop.value = 'aes256-sha256,aes128-sha256,default';
  2343. } else {
  2344. prop.value = `aes256-sha256-${val},aes128-sha256-${val},default`;
  2345. }
  2346. }
  2347. function updateIpsecIkeProposalFromDH(dh) {
  2348. const el = document.getElementById('ipsec-modal-ikeprop');
  2349. if (el) {
  2350. el.value = `aes256-sha256-${dh},aes128-sha256-${dh},default`;
  2351. }
  2352. }
  2353. function safeSetVal(id, val) {
  2354. const el = document.getElementById(id);
  2355. if (el) el.value = val;
  2356. }
  2357. function safeSetChecked(id, val) {
  2358. const el = document.getElementById(id);
  2359. if (el) el.checked = !!val;
  2360. }
  2361. function safeGetVal(id, def = '') {
  2362. const el = document.getElementById(id);
  2363. return el ? el.value : def;
  2364. }
  2365. async function loadIPSec(populateInputs = true) {
  2366. try {
  2367. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`);
  2368. const list = await res.json();
  2369. state.ipsecTunnels = Array.isArray(list) ? list : [];
  2370. const activeCount = state.ipsecTunnels.filter(t => t.running || t.status === 'ESTABLISHED').length;
  2371. const badge = document.getElementById('ipsec-sas-badge');
  2372. if (badge) badge.innerText = `${activeCount} Active SAs`;
  2373. const tbody = document.getElementById('ipsec-table-body');
  2374. const empty = document.getElementById('ipsec-empty');
  2375. if (!tbody) return;
  2376. tbody.innerHTML = '';
  2377. if (state.ipsecTunnels.length === 0) {
  2378. if (empty) empty.classList.remove('hidden');
  2379. } else {
  2380. if (empty) empty.classList.add('hidden');
  2381. state.ipsecTunnels.forEach(c => {
  2382. const isEstablished = c.running || c.status === 'ESTABLISHED';
  2383. const tr = document.createElement('tr');
  2384. tr.className = 'hover:bg-slate-800/40 transition text-xs select-none';
  2385. // Local subnets tags
  2386. const localList = (c.local_subnets && c.local_subnets.length > 0) ? c.local_subnets : (c.local_subnet ? [c.local_subnet] : ['0.0.0.0/0']);
  2387. const localBadges = localList.map(s => `<span class="px-1.5 py-0.5 rounded bg-cyan-950/60 border border-cyan-800/60 text-cyan-300 font-mono text-[10px] mr-1">${escapeHtml(s)}</span>`).join('');
  2388. // Remote subnets tags
  2389. const remoteList = (c.remote_subnets && c.remote_subnets.length > 0) ? c.remote_subnets : (c.remote_subnet ? [c.remote_subnet] : ['0.0.0.0/0']);
  2390. const remoteBadges = remoteList.map(s => `<span class="px-1.5 py-0.5 rounded bg-purple-950/60 border border-purple-800/60 text-purple-300 font-mono text-[10px] mr-1">${escapeHtml(s)}</span>`).join('');
  2391. const ikeVersionBadge = (c.ike_version || 'ikev2').toUpperCase();
  2392. const p2Name = c.phase2_name || `${c.name}_p2`;
  2393. tr.innerHTML = `
  2394. <td class="py-2.5 px-3 text-center">
  2395. ${isEstablished ? `
  2396. <span class="inline-flex items-center gap-1.5 text-emerald-400 font-mono font-bold text-[11px]" title="Active SA Established">
  2397. <span class="w-2.5 h-2.5 rounded-full bg-emerald-400 animate-pulse"></span>
  2398. <span>UP</span>
  2399. </span>
  2400. ` : (c.disabled ? `
  2401. <span class="inline-flex items-center gap-1.5 text-slate-500 font-mono text-[11px]" title="Tunnel Disabled">
  2402. <span class="w-2 h-2 rounded-full bg-rose-500"></span>
  2403. <span>DOWN</span>
  2404. </span>
  2405. ` : `
  2406. <span class="inline-flex items-center gap-1.5 text-amber-400 font-mono text-[11px]" title="Disconnected / Idle">
  2407. <span class="w-2 h-2 rounded-full bg-amber-400"></span>
  2408. <span>IDLE</span>
  2409. </span>
  2410. `)}
  2411. </td>
  2412. <td class="py-2.5 px-4 font-bold text-white">
  2413. <div class="flex items-center gap-2">
  2414. <span class="text-amber-400">🛡</span>
  2415. <div>
  2416. <div>${escapeHtml(c.name)}</div>
  2417. <div class="text-[10px] text-slate-500 font-normal">P2: ${escapeHtml(p2Name)}</div>
  2418. </div>
  2419. </div>
  2420. </td>
  2421. <td class="py-2.5 px-4 text-slate-300 font-mono font-medium">${escapeHtml(c.remote_addrs || '%any')}</td>
  2422. <td class="py-2.5 px-4 font-sans">
  2423. <div class="flex items-center gap-1.5">
  2424. <span class="px-1.5 py-0.5 rounded bg-amber-500/10 text-amber-300 border border-amber-500/30 font-mono text-[10px] font-semibold">${ikeVersionBadge}</span>
  2425. <span class="text-[10px] text-slate-400">${c.auth_method || 'PSK'}</span>
  2426. </div>
  2427. </td>
  2428. <td class="py-2.5 px-4">
  2429. <div class="space-y-1">
  2430. <div class="flex items-center flex-wrap gap-1">
  2431. <span class="text-[9px] text-cyan-400 uppercase font-bold mr-1">Local:</span>
  2432. ${localBadges}
  2433. </div>
  2434. <div class="flex items-center flex-wrap gap-1">
  2435. <span class="text-[9px] text-purple-400 uppercase font-bold mr-1">Remote:</span>
  2436. ${remoteBadges}
  2437. </div>
  2438. </div>
  2439. </td>
  2440. <td class="py-2.5 px-4 font-mono text-[11px] text-slate-400">
  2441. <div class="truncate max-w-[140px]" title="${escapeHtml(c.esp_proposals || '')}">
  2442. ${escapeHtml(c.esp_proposals || 'aes256-sha256')}
  2443. </div>
  2444. <div class="text-[10px] text-slate-500">PFS: ${escapeHtml(c.pfs_group || 'modp2048')}</div>
  2445. </td>
  2446. <td class="py-2.5 px-4 text-right space-x-2 font-sans">
  2447. ${isEstablished ? `
  2448. <button onclick="stopIPSecTunnel('${c.name}')" class="px-2 py-0.5 text-xs bg-rose-500/20 text-rose-400 hover:bg-rose-500/30 rounded border border-rose-500/30 font-medium">Bring Down</button>
  2449. ` : `
  2450. <button onclick="startIPSecTunnel('${c.name}')" class="px-2 py-0.5 text-xs bg-emerald-500/20 text-emerald-400 hover:bg-emerald-500/30 rounded border border-emerald-500/30 font-semibold">Bring Up</button>
  2451. `}
  2452. <button onclick="toggleIPSecState('${c.name}', ${c.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  2453. ${c.disabled ? 'Enable' : 'Disable'}
  2454. </button>
  2455. <button onclick="openEditIPSecModal('${c.name}')" class="text-xs text-amber-400 hover:text-amber-300">Edit</button>
  2456. <button onclick="deleteIPSecConn('${c.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2457. </td>
  2458. `;
  2459. tbody.appendChild(tr);
  2460. });
  2461. }
  2462. } catch (err) {
  2463. console.error('Failed to load IPSec:', err);
  2464. }
  2465. }
  2466. function openAddIPSecModal() {
  2467. const modal = document.getElementById('ipsec-modal');
  2468. if (!modal) return;
  2469. const title = document.getElementById('ipsec-modal-title');
  2470. if (title) title.innerText = 'Configure IPSec Site-to-Site Tunnel';
  2471. // Phase 1 Fields
  2472. safeSetVal('ipsec-modal-name', `tunnel-${(state.ipsecTunnels || []).length + 1}`);
  2473. const nameEl = document.getElementById('ipsec-modal-name');
  2474. if (nameEl) nameEl.readOnly = false;
  2475. safeSetVal('ipsec-modal-ikeversion', 'ikev2');
  2476. safeSetVal('ipsec-modal-ikever', 'ikev2');
  2477. safeSetVal('ipsec-modal-remotegw', '');
  2478. safeSetVal('ipsec-modal-localaddrs', '');
  2479. safeSetVal('ipsec-modal-comments', '');
  2480. safeSetVal('ipsec-modal-psk', '');
  2481. safeSetVal('ipsec-modal-ikeprop', 'aes256-sha256-modp2048,aes128-sha256-modp2048,default');
  2482. safeSetVal('ipsec-modal-dhgroup', 'modp2048');
  2483. safeSetVal('ipsec-modal-ikekeylife', '86400');
  2484. safeSetVal('ipsec-modal-localid', '');
  2485. safeSetVal('ipsec-modal-remoteid', '');
  2486. safeSetVal('ipsec-modal-dpd', 'on-demand');
  2487. // Phase 2 Fields
  2488. safeSetVal('ipsec-modal-p2name', `tunnel-${(state.ipsecTunnels || []).length + 1}_p2`);
  2489. safeSetVal('ipsec-modal-espkeylife', '28800');
  2490. safeSetVal('ipsec-modal-espprop', 'aes256-sha256-modp2048,aes128-sha256-modp2048,default');
  2491. safeSetVal('ipsec-modal-pfsgroup', 'modp2048');
  2492. safeSetChecked('ipsec-modal-autostart', true);
  2493. safeSetChecked('ipsec-modal-disabled', false);
  2494. // Clear & Populate default dynamic subnets
  2495. const localContainer = document.getElementById('ipsec-modal-local-subnets-container');
  2496. const remoteContainer = document.getElementById('ipsec-modal-remote-subnets-container');
  2497. if (localContainer) {
  2498. localContainer.innerHTML = '';
  2499. addIpsecLocalSubnet('192.168.10.0/24');
  2500. }
  2501. if (remoteContainer) {
  2502. remoteContainer.innerHTML = '';
  2503. addIpsecRemoteSubnet('192.168.20.0/24');
  2504. }
  2505. switchIpsecModalTab('p1');
  2506. modal.classList.remove('hidden');
  2507. }
  2508. function openEditIPSecModal(name) {
  2509. const modal = document.getElementById('ipsec-modal');
  2510. if (!modal) return;
  2511. const conn = (state.ipsecTunnels || []).find(c => c.name === name);
  2512. if (!conn) return;
  2513. const title = document.getElementById('ipsec-modal-title');
  2514. if (title) title.innerText = `Edit IPSec Tunnel: ${name}`;
  2515. // Phase 1 Fields
  2516. safeSetVal('ipsec-modal-name', conn.name);
  2517. const nameEl = document.getElementById('ipsec-modal-name');
  2518. if (nameEl) nameEl.readOnly = true;
  2519. safeSetVal('ipsec-modal-ikeversion', conn.ike_version || 'ikev2');
  2520. safeSetVal('ipsec-modal-ikever', conn.ike_version || 'ikev2');
  2521. safeSetVal('ipsec-modal-remotegw', conn.remote_addrs || '');
  2522. safeSetVal('ipsec-modal-localaddrs', conn.local_addrs || '');
  2523. safeSetVal('ipsec-modal-comments', conn.comment || '');
  2524. safeSetVal('ipsec-modal-psk', conn.preshared_key || '');
  2525. safeSetVal('ipsec-modal-ikeprop', conn.ike_proposals || 'aes256-sha256-modp2048,default');
  2526. safeSetVal('ipsec-modal-ikekeylife', conn.ike_keylife || 86400);
  2527. safeSetVal('ipsec-modal-localid', conn.local_id || '');
  2528. safeSetVal('ipsec-modal-remoteid', conn.remote_id || '');
  2529. safeSetVal('ipsec-modal-dpd', conn.dpd || 'on-demand');
  2530. // Phase 2 Fields
  2531. safeSetVal('ipsec-modal-p2name', conn.phase2_name || `${conn.name}_p2`);
  2532. safeSetVal('ipsec-modal-espkeylife', conn.esp_keylife || 28800);
  2533. safeSetVal('ipsec-modal-espprop', conn.esp_proposals || 'aes256-sha256-modp2048,default');
  2534. safeSetVal('ipsec-modal-pfsgroup', conn.pfs_group || 'modp2048');
  2535. safeSetChecked('ipsec-modal-autostart', conn.auto_start ?? true);
  2536. safeSetChecked('ipsec-modal-disabled', !!conn.disabled);
  2537. // Populate dynamic subnets
  2538. const localContainer = document.getElementById('ipsec-modal-local-subnets-container');
  2539. const remoteContainer = document.getElementById('ipsec-modal-remote-subnets-container');
  2540. if (localContainer) {
  2541. localContainer.innerHTML = '';
  2542. const locals = (conn.local_subnets && conn.local_subnets.length > 0) ? conn.local_subnets : (conn.local_subnet ? [conn.local_subnet] : ['192.168.10.0/24']);
  2543. locals.forEach(s => addIpsecLocalSubnet(s));
  2544. }
  2545. if (remoteContainer) {
  2546. remoteContainer.innerHTML = '';
  2547. const remotes = (conn.remote_subnets && conn.remote_subnets.length > 0) ? conn.remote_subnets : (conn.remote_subnet ? [conn.remote_subnet] : ['192.168.20.0/24']);
  2548. remotes.forEach(s => addIpsecRemoteSubnet(s));
  2549. }
  2550. switchIpsecModalTab('p1');
  2551. modal.classList.remove('hidden');
  2552. }
  2553. function closeAddIPSecModal() {
  2554. const modal = document.getElementById('ipsec-modal');
  2555. if (modal) modal.classList.add('hidden');
  2556. }
  2557. async function submitSaveIPSec(e) {
  2558. if (e) e.preventDefault();
  2559. const name = safeGetVal('ipsec-modal-name').trim();
  2560. if (!name) {
  2561. showToast('Error', 'Tunnel name is required', 'error');
  2562. return;
  2563. }
  2564. const ikeVersion = safeGetVal('ipsec-modal-ikeversion') || safeGetVal('ipsec-modal-ikever', 'ikev2');
  2565. const remotegw = safeGetVal('ipsec-modal-remotegw').trim();
  2566. const localAddrs = safeGetVal('ipsec-modal-localaddrs').trim() || '%any';
  2567. const comments = safeGetVal('ipsec-modal-comments').trim();
  2568. const psk = safeGetVal('ipsec-modal-psk');
  2569. const ikeProposals = safeGetVal('ipsec-modal-ikeprop', 'aes256-sha256-modp2048,default').trim();
  2570. const ikeKeylife = parseInt(safeGetVal('ipsec-modal-ikekeylife', '86400'), 10) || 86400;
  2571. const localId = safeGetVal('ipsec-modal-localid').trim();
  2572. const remoteId = safeGetVal('ipsec-modal-remoteid').trim();
  2573. const dpd = safeGetVal('ipsec-modal-dpd', 'on-demand');
  2574. const phase2Name = safeGetVal('ipsec-modal-p2name').trim() || `${name}_p2`;
  2575. const espProposals = safeGetVal('ipsec-modal-espprop', 'aes256-sha256-modp2048,default').trim();
  2576. const espKeylife = parseInt(safeGetVal('ipsec-modal-espkeylife', '28800'), 10) || 28800;
  2577. const pfsGroup = safeGetVal('ipsec-modal-pfsgroup', 'modp2048');
  2578. const autostart = document.getElementById('ipsec-modal-autostart')?.checked ?? true;
  2579. const disabled = document.getElementById('ipsec-modal-disabled')?.checked ?? false;
  2580. // Scrape dynamic local and remote subnets
  2581. const localInputs = document.querySelectorAll('#ipsec-modal-local-subnets-container input');
  2582. const localSubnets = [];
  2583. localInputs.forEach(inp => {
  2584. const v = inp.value.trim();
  2585. if (v) localSubnets.push(v);
  2586. });
  2587. const remoteInputs = document.querySelectorAll('#ipsec-modal-remote-subnets-container input');
  2588. const remoteSubnets = [];
  2589. remoteInputs.forEach(inp => {
  2590. const v = inp.value.trim();
  2591. if (v) remoteSubnets.push(v);
  2592. });
  2593. try {
  2594. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`, {
  2595. method: 'POST',
  2596. headers: { 'Content-Type': 'application/json' },
  2597. body: JSON.stringify({
  2598. name,
  2599. comment: comments,
  2600. ike_version: ikeVersion,
  2601. local_addrs: localAddrs,
  2602. remote_addrs: remotegw,
  2603. preshared_key: psk,
  2604. ike_proposals: ikeProposals,
  2605. ike_keylife: ikeKeylife,
  2606. local_id: localId,
  2607. remote_id: remoteId,
  2608. dpd: dpd,
  2609. phase2_name: phase2Name,
  2610. esp_proposals: espProposals,
  2611. esp_keylife: espKeylife,
  2612. pfs_group: pfsGroup,
  2613. pfs: pfsGroup !== 'none',
  2614. local_subnets: localSubnets,
  2615. remote_subnets: remoteSubnets,
  2616. local_subnet: localSubnets[0] || '0.0.0.0/0',
  2617. remote_subnet: remoteSubnets[0] || '0.0.0.0/0',
  2618. auto_start: autostart,
  2619. disabled
  2620. })
  2621. });
  2622. if (res.ok) {
  2623. showToast('IPSec Saved', `FortiGate Tunnel ${name} configured`, 'success');
  2624. closeAddIPSecModal();
  2625. loadIPSec(false);
  2626. } else {
  2627. const err = await res.json();
  2628. showToast('Error', err.error || 'Failed to save IPSec tunnel', 'error');
  2629. }
  2630. } catch (err) {
  2631. showToast('Error', err.message, 'error');
  2632. }
  2633. }
  2634. async function startIPSecTunnel(name) {
  2635. try {
  2636. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/start`, { method: 'POST' });
  2637. if (res.ok) {
  2638. showToast('Initiating Tunnel', `Attempting SA handshake for ${name}...`, 'info');
  2639. setTimeout(() => loadIPSec(false), 2000);
  2640. }
  2641. } catch (err) {
  2642. showToast('Error', err.message, 'error');
  2643. }
  2644. }
  2645. async function stopIPSecTunnel(name) {
  2646. try {
  2647. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  2648. if (res.ok) {
  2649. showToast('Terminated', `IPSec SA for ${name} closed`, 'info');
  2650. loadIPSec(false);
  2651. }
  2652. } catch (err) {
  2653. showToast('Error', err.message, 'error');
  2654. }
  2655. }
  2656. async function toggleIPSecState(name, enable) {
  2657. try {
  2658. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/state`, {
  2659. method: 'POST',
  2660. headers: { 'Content-Type': 'application/json' },
  2661. body: JSON.stringify({ enabled: enable })
  2662. });
  2663. if (res.ok) {
  2664. showToast(enable ? 'Enabled' : 'Disabled', `IPSec tunnel ${name} updated`, 'info');
  2665. loadIPSec(false);
  2666. }
  2667. } catch (err) {
  2668. showToast('Error', err.message, 'error');
  2669. }
  2670. }
  2671. async function deleteIPSecConn(name) {
  2672. if (!confirm(`Are you sure you want to delete IPSec tunnel ${name}?`)) return;
  2673. try {
  2674. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2675. if (res.ok) {
  2676. showToast('Deleted', `IPSec connection ${name} removed`, 'success');
  2677. loadIPSec(false);
  2678. fetchData(false);
  2679. }
  2680. } catch (err) {
  2681. showToast('Error', err.message, 'error');
  2682. }
  2683. }
  2684. // ======================== L2TP Multi-Instance ========================
  2685. async function loadL2TP(populateInputs = true) {
  2686. try {
  2687. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2688. await fetchPPPProfilesList();
  2689. }
  2690. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`);
  2691. const list = await res.json();
  2692. state.l2tpList = Array.isArray(list) ? list : [];
  2693. const badge = document.getElementById('l2tp-count-badge');
  2694. if (badge) badge.innerText = `${state.l2tpList.length} Client${state.l2tpList.length !== 1 ? 's' : ''}`;
  2695. const tbody = document.getElementById('l2tp-table-body');
  2696. const empty = document.getElementById('l2tp-empty');
  2697. if (!tbody) return;
  2698. tbody.innerHTML = '';
  2699. if (state.l2tpList.length === 0) {
  2700. if (empty) empty.classList.remove('hidden');
  2701. } else {
  2702. if (empty) empty.classList.add('hidden');
  2703. state.l2tpList.forEach(inst => {
  2704. const tr = document.createElement('tr');
  2705. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  2706. tr.innerHTML = `
  2707. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  2708. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  2709. <td class="py-2.5 px-3 text-cyan-400 font-mono">${escapeHtml(inst.connect_to)}</td>
  2710. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  2711. <td class="py-2.5 px-3 font-mono text-cyan-300"><span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 border border-slate-700">${escapeHtml(inst.profile || 'default-encryption')}</span></td>
  2712. <td class="py-2.5 px-3 font-mono ${inst.assigned_ip ? 'text-emerald-400 font-bold' : 'text-slate-500'}">${escapeHtml(inst.assigned_ip || '-')}</td>
  2713. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  2714. <td class="py-2.5 px-3 text-center">
  2715. <span class="px-2 py-0.5 rounded text-[10px] font-sans ${inst.default_route ? 'bg-cyan-500/20 text-cyan-300 border border-cyan-500/30' : 'bg-slate-800 text-slate-500'}">
  2716. ${inst.default_route ? 'Yes' : 'No'}
  2717. </span>
  2718. </td>
  2719. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  2720. ${inst.running ? `
  2721. <button onclick="disconnectL2TPInstance('${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  2722. ` : `
  2723. <button onclick="connectL2TPInstance('${escapeHtml(inst.name)}')" class="text-xs bg-cyan-600/30 hover:bg-cyan-600/50 text-cyan-300 px-2 py-0.5 rounded border border-cyan-500/30">Connect</button>
  2724. `}
  2725. <button onclick="toggleL2TPState('${escapeHtml(inst.name)}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  2726. ${inst.disabled ? 'Enable' : 'Disable'}
  2727. </button>
  2728. <button onclick="openEditL2TPModal('${escapeHtml(inst.name)}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2729. <button onclick="deleteL2TPInstance('${escapeHtml(inst.name)}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2730. </td>
  2731. `;
  2732. tbody.appendChild(tr);
  2733. });
  2734. }
  2735. } catch (err) {
  2736. console.error('Failed to load L2TP:', err);
  2737. }
  2738. }
  2739. async function openAddL2TPModal() {
  2740. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2741. await fetchPPPProfilesList();
  2742. }
  2743. document.getElementById('l2tp-modal-title').innerText = 'Add L2TP Client Interface';
  2744. document.getElementById('l2tp-modal-name').value = `l2tp-out${(state.l2tpList || []).length + 1}`;
  2745. document.getElementById('l2tp-modal-name').readOnly = false;
  2746. document.getElementById('l2tp-modal-server').value = '';
  2747. document.getElementById('l2tp-modal-user').value = '';
  2748. document.getElementById('l2tp-modal-pass').value = '';
  2749. document.getElementById('l2tp-modal-ipsec').value = '';
  2750. document.getElementById('l2tp-modal-defroute').checked = true;
  2751. document.getElementById('l2tp-modal-disabled').checked = false;
  2752. populateProfileSelect('l2tp-modal-profile', 'default-encryption', 'default-encryption');
  2753. document.getElementById('l2tp-modal').classList.remove('hidden');
  2754. }
  2755. async function openEditL2TPModal(name) {
  2756. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2757. await fetchPPPProfilesList();
  2758. }
  2759. const inst = (state.l2tpList || []).find(i => i.name === name);
  2760. if (!inst) return;
  2761. document.getElementById('l2tp-modal-title').innerText = `Edit L2TP Client: ${name}`;
  2762. document.getElementById('l2tp-modal-name').value = inst.name;
  2763. document.getElementById('l2tp-modal-name').readOnly = true;
  2764. document.getElementById('l2tp-modal-server').value = inst.connect_to || '';
  2765. document.getElementById('l2tp-modal-user').value = inst.username || '';
  2766. document.getElementById('l2tp-modal-pass').value = inst.password || '';
  2767. document.getElementById('l2tp-modal-ipsec').value = inst.ipsec_secret || '';
  2768. document.getElementById('l2tp-modal-defroute').checked = inst.default_route ?? true;
  2769. document.getElementById('l2tp-modal-disabled').checked = !!inst.disabled;
  2770. populateProfileSelect('l2tp-modal-profile', inst.profile || 'default-encryption', 'default-encryption');
  2771. document.getElementById('l2tp-modal').classList.remove('hidden');
  2772. }
  2773. function closeL2TPModal() {
  2774. document.getElementById('l2tp-modal').classList.add('hidden');
  2775. }
  2776. async function submitSaveL2TP(e) {
  2777. e.preventDefault();
  2778. const name = document.getElementById('l2tp-modal-name').value.trim();
  2779. const server = document.getElementById('l2tp-modal-server').value.trim();
  2780. const user = document.getElementById('l2tp-modal-user').value.trim();
  2781. const pass = document.getElementById('l2tp-modal-pass').value;
  2782. const profile = document.getElementById('l2tp-modal-profile')?.value || 'default-encryption';
  2783. const ipsec = document.getElementById('l2tp-modal-ipsec').value;
  2784. const defRoute = document.getElementById('l2tp-modal-defroute').checked;
  2785. const disabled = document.getElementById('l2tp-modal-disabled').checked;
  2786. try {
  2787. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`, {
  2788. method: 'POST',
  2789. headers: { 'Content-Type': 'application/json' },
  2790. body: JSON.stringify({
  2791. name,
  2792. connect_to: server,
  2793. username: user,
  2794. password: pass,
  2795. profile: profile,
  2796. ipsec_secret: ipsec,
  2797. default_route: defRoute,
  2798. disabled
  2799. })
  2800. });
  2801. if (res.ok) {
  2802. showToast('L2TP Saved', `Client ${name} configuration saved`, 'success');
  2803. closeL2TPModal();
  2804. loadL2TP(false);
  2805. fetchData(false);
  2806. }
  2807. } catch (err) {
  2808. showToast('Error', err.message, 'error');
  2809. }
  2810. }
  2811. async function connectL2TPInstance(name) {
  2812. try {
  2813. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  2814. if (res.ok) {
  2815. showToast('Connecting', `Dialing L2TP ${name}...`, 'info');
  2816. setTimeout(() => loadL2TP(false), 2000);
  2817. }
  2818. } catch (err) {
  2819. showToast('Error', err.message, 'error');
  2820. }
  2821. }
  2822. async function disconnectL2TPInstance(name) {
  2823. try {
  2824. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  2825. if (res.ok) {
  2826. showToast('Disconnected', `L2TP tunnel ${name} terminated`, 'info');
  2827. loadL2TP(false);
  2828. }
  2829. } catch (err) {
  2830. showToast('Error', err.message, 'error');
  2831. }
  2832. }
  2833. async function toggleL2TPState(name, enable) {
  2834. try {
  2835. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/state`, {
  2836. method: 'POST',
  2837. headers: { 'Content-Type': 'application/json' },
  2838. body: JSON.stringify({ enabled: enable })
  2839. });
  2840. if (res.ok) {
  2841. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  2842. loadL2TP(false);
  2843. }
  2844. } catch (err) {
  2845. showToast('Error', err.message, 'error');
  2846. }
  2847. }
  2848. async function deleteL2TPInstance(name) {
  2849. if (!confirm(`Are you sure you want to delete L2TP client ${name}?`)) return;
  2850. try {
  2851. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2852. if (res.ok) {
  2853. showToast('Deleted', `L2TP client ${name} removed`, 'success');
  2854. loadL2TP(false);
  2855. fetchData(false);
  2856. }
  2857. } catch (err) {
  2858. showToast('Error', err.message, 'error');
  2859. }
  2860. }
  2861. // ======================== PPTP Multi-Instance ========================
  2862. async function loadPPTP(populateInputs = true) {
  2863. try {
  2864. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2865. await fetchPPPProfilesList();
  2866. }
  2867. const res = await fetch(`${API_BASE}/vpn/pptp/clients`);
  2868. const list = await res.json();
  2869. state.pptpList = Array.isArray(list) ? list : [];
  2870. const badge = document.getElementById('pptp-count-badge');
  2871. if (badge) badge.innerText = `${state.pptpList.length} Client${state.pptpList.length !== 1 ? 's' : ''}`;
  2872. const tbody = document.getElementById('pptp-table-body');
  2873. const empty = document.getElementById('pptp-empty');
  2874. if (!tbody) return;
  2875. tbody.innerHTML = '';
  2876. if (state.pptpList.length === 0) {
  2877. if (empty) empty.classList.remove('hidden');
  2878. } else {
  2879. if (empty) empty.classList.add('hidden');
  2880. state.pptpList.forEach(inst => {
  2881. const tr = document.createElement('tr');
  2882. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  2883. tr.innerHTML = `
  2884. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  2885. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  2886. <td class="py-2.5 px-3 text-purple-400 font-mono">${escapeHtml(inst.connect_to)}</td>
  2887. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  2888. <td class="py-2.5 px-3 font-mono text-purple-300"><span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 border border-slate-700">${escapeHtml(inst.profile || 'default-encryption')}</span></td>
  2889. <td class="py-2.5 px-3 font-mono ${inst.assigned_ip ? 'text-emerald-400 font-bold' : 'text-slate-500'}">${escapeHtml(inst.assigned_ip || '-')}</td>
  2890. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  2891. <td class="py-2.5 px-3 text-center">
  2892. <span class="px-2 py-0.5 rounded text-[10px] font-sans ${inst.require_mppe ? 'bg-purple-500/20 text-purple-300 border border-purple-500/30' : 'bg-slate-800 text-slate-500'}">
  2893. ${inst.require_mppe ? 'MPPE-128' : 'None'}
  2894. </span>
  2895. </td>
  2896. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  2897. ${inst.running ? `
  2898. <button onclick="disconnectPPTPInstance('${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  2899. ` : `
  2900. <button onclick="connectPPTPInstance('${escapeHtml(inst.name)}')" class="text-xs bg-purple-600/30 hover:bg-purple-600/50 text-purple-300 px-2 py-0.5 rounded border border-purple-500/30">Connect</button>
  2901. `}
  2902. <button onclick="togglePPTPState('${escapeHtml(inst.name)}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  2903. ${inst.disabled ? 'Enable' : 'Disable'}
  2904. </button>
  2905. <button onclick="openEditPPTPModal('${escapeHtml(inst.name)}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2906. <button onclick="deletePPTPInstance('${escapeHtml(inst.name)}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2907. </td>
  2908. `;
  2909. tbody.appendChild(tr);
  2910. });
  2911. }
  2912. } catch (err) {
  2913. console.error('Failed to load PPTP:', err);
  2914. }
  2915. }
  2916. async function openAddPPTPModal() {
  2917. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2918. await fetchPPPProfilesList();
  2919. }
  2920. document.getElementById('pptp-modal-title').innerText = 'Add PPTP Client Interface';
  2921. document.getElementById('pptp-modal-name').value = `pptp-out${(state.pptpList || []).length + 1}`;
  2922. document.getElementById('pptp-modal-name').readOnly = false;
  2923. document.getElementById('pptp-modal-server').value = '';
  2924. document.getElementById('pptp-modal-user').value = '';
  2925. document.getElementById('pptp-modal-pass').value = '';
  2926. document.getElementById('pptp-modal-mppe').checked = true;
  2927. document.getElementById('pptp-modal-defroute').checked = true;
  2928. document.getElementById('pptp-modal-disabled').checked = false;
  2929. populateProfileSelect('pptp-modal-profile', 'default-encryption', 'default-encryption');
  2930. document.getElementById('pptp-modal').classList.remove('hidden');
  2931. }
  2932. async function openEditPPTPModal(name) {
  2933. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2934. await fetchPPPProfilesList();
  2935. }
  2936. const inst = (state.pptpList || []).find(i => i.name === name);
  2937. if (!inst) return;
  2938. document.getElementById('pptp-modal-title').innerText = `Edit PPTP Client: ${name}`;
  2939. document.getElementById('pptp-modal-name').value = inst.name;
  2940. document.getElementById('pptp-modal-name').readOnly = true;
  2941. document.getElementById('pptp-modal-server').value = inst.connect_to || '';
  2942. document.getElementById('pptp-modal-user').value = inst.username || '';
  2943. document.getElementById('pptp-modal-pass').value = inst.password || '';
  2944. document.getElementById('pptp-modal-mppe').checked = inst.require_mppe ?? true;
  2945. document.getElementById('pptp-modal-defroute').checked = inst.default_route ?? true;
  2946. document.getElementById('pptp-modal-disabled').checked = !!inst.disabled;
  2947. populateProfileSelect('pptp-modal-profile', inst.profile || 'default-encryption', 'default-encryption');
  2948. document.getElementById('pptp-modal').classList.remove('hidden');
  2949. }
  2950. function closePPTPModal() {
  2951. document.getElementById('pptp-modal').classList.add('hidden');
  2952. }
  2953. async function submitSavePPTP(e) {
  2954. e.preventDefault();
  2955. const name = document.getElementById('pptp-modal-name').value.trim();
  2956. const server = document.getElementById('pptp-modal-server').value.trim();
  2957. const user = document.getElementById('pptp-modal-user').value.trim();
  2958. const pass = document.getElementById('pptp-modal-pass').value;
  2959. const profile = document.getElementById('pptp-modal-profile')?.value || 'default-encryption';
  2960. const mppe = document.getElementById('pptp-modal-mppe').checked;
  2961. const defRoute = document.getElementById('pptp-modal-defroute').checked;
  2962. const disabled = document.getElementById('pptp-modal-disabled').checked;
  2963. try {
  2964. const res = await fetch(`${API_BASE}/vpn/pptp/clients`, {
  2965. method: 'POST',
  2966. headers: { 'Content-Type': 'application/json' },
  2967. body: JSON.stringify({
  2968. name,
  2969. connect_to: server,
  2970. username: user,
  2971. password: pass,
  2972. profile: profile,
  2973. require_mppe: mppe,
  2974. default_route: defRoute,
  2975. auto_reconnect: true,
  2976. disabled
  2977. })
  2978. });
  2979. if (res.ok) {
  2980. showToast('PPTP Saved', `Client ${name} configuration saved`, 'success');
  2981. closePPTPModal();
  2982. loadPPTP(false);
  2983. fetchData(false);
  2984. }
  2985. } catch (err) {
  2986. showToast('Error', err.message, 'error');
  2987. }
  2988. }
  2989. async function connectPPTPInstance(name) {
  2990. try {
  2991. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  2992. if (res.ok) {
  2993. showToast('Connecting', `Dialing PPTP ${name}...`, 'info');
  2994. setTimeout(() => loadPPTP(false), 2000);
  2995. }
  2996. } catch (err) {
  2997. showToast('Error', err.message, 'error');
  2998. }
  2999. }
  3000. async function disconnectPPTPInstance(name) {
  3001. try {
  3002. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  3003. if (res.ok) {
  3004. showToast('Disconnected', `PPTP tunnel ${name} terminated`, 'info');
  3005. loadPPTP(false);
  3006. }
  3007. } catch (err) {
  3008. showToast('Error', err.message, 'error');
  3009. }
  3010. }
  3011. async function togglePPTPState(name, enable) {
  3012. try {
  3013. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/state`, {
  3014. method: 'POST',
  3015. headers: { 'Content-Type': 'application/json' },
  3016. body: JSON.stringify({ enabled: enable })
  3017. });
  3018. if (res.ok) {
  3019. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  3020. loadPPTP(false);
  3021. }
  3022. } catch (err) {
  3023. showToast('Error', err.message, 'error');
  3024. }
  3025. }
  3026. async function deletePPTPInstance(name) {
  3027. if (!confirm(`Are you sure you want to delete PPTP client ${name}?`)) return;
  3028. try {
  3029. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  3030. if (res.ok) {
  3031. showToast('Deleted', `PPTP client ${name} removed`, 'success');
  3032. loadPPTP(false);
  3033. fetchData(false);
  3034. }
  3035. } catch (err) {
  3036. showToast('Error', err.message, 'error');
  3037. }
  3038. }
  3039. // ---------------- Modal & Helper Functions ----------------
  3040. function openVlanModal(defaultParent = '') {
  3041. const select = document.getElementById('vlan-parent');
  3042. select.innerHTML = '';
  3043. const allIfaces = state.interfaces || [];
  3044. const eligible = allIfaces.filter(i => supportsVLAN(i));
  3045. if (eligible.length === 0) {
  3046. const opt = document.createElement('option');
  3047. opt.value = '';
  3048. opt.innerText = 'No VLAN-capable interfaces available';
  3049. select.appendChild(opt);
  3050. } else {
  3051. eligible.forEach(i => {
  3052. const opt = document.createElement('option');
  3053. opt.value = i.name;
  3054. opt.innerText = `${i.name} (${i.role || i.type || 'Ethernet'} - ${i.state})`;
  3055. if (i.name === defaultParent) opt.selected = true;
  3056. select.appendChild(opt);
  3057. });
  3058. }
  3059. document.getElementById('vlan-id').value = '';
  3060. document.getElementById('vlan-name').value = '';
  3061. document.getElementById('vlan-ip').value = '';
  3062. document.getElementById('vlan-desc').value = '';
  3063. populateRoleSelects('LAN');
  3064. autoSuggestVlanName();
  3065. document.getElementById('vlan-modal').classList.remove('hidden');
  3066. }
  3067. function closeVlanModal() {
  3068. document.getElementById('vlan-modal').classList.add('hidden');
  3069. }
  3070. function autoSuggestVlanName() {
  3071. const parent = document.getElementById('vlan-parent').value;
  3072. if (!parent) return;
  3073. const id = document.getElementById('vlan-id').value;
  3074. const nameInput = document.getElementById('vlan-name');
  3075. if (parent && id) nameInput.placeholder = `${parent}.${id}`;
  3076. }
  3077. function setSubnetPreset(cidr) {
  3078. const ipInput = document.getElementById('vlan-ip');
  3079. const id = document.getElementById('vlan-id').value || '10';
  3080. ipInput.value = `192.168.${id}.1${cidr}`;
  3081. }
  3082. async function submitCreateVlan(e) {
  3083. e.preventDefault();
  3084. const btn = document.getElementById('vlan-submit-btn');
  3085. btn.disabled = true;
  3086. btn.innerText = 'Creating...';
  3087. const parent = document.getElementById('vlan-parent').value;
  3088. if (!parent) {
  3089. showToast('Error', 'Please select a valid VLAN-capable parent interface', 'error');
  3090. btn.disabled = false;
  3091. btn.innerText = 'Create VLAN';
  3092. return;
  3093. }
  3094. const id = parseInt(document.getElementById('vlan-id').value, 10);
  3095. const name = document.getElementById('vlan-name').value.trim();
  3096. const ip = document.getElementById('vlan-ip').value.trim();
  3097. const role = document.getElementById('vlan-role').value;
  3098. const desc = document.getElementById('vlan-desc').value.trim();
  3099. try {
  3100. const res = await fetch(`${API_BASE}/vlans`, {
  3101. method: 'POST',
  3102. headers: { 'Content-Type': 'application/json' },
  3103. body: JSON.stringify({
  3104. parent_name: parent,
  3105. vlan_id: id,
  3106. name: name,
  3107. ip_address: ip,
  3108. role: role,
  3109. description: desc,
  3110. mtu: 1500,
  3111. auto_up: true
  3112. })
  3113. });
  3114. const data = await res.json();
  3115. if (res.ok) {
  3116. showToast('VLAN Created', `Created ${data.name} (VLAN ${data.vlan_id})`, 'success');
  3117. state.expandedParents.add(parent);
  3118. closeVlanModal();
  3119. await fetchData(true);
  3120. if (state.activeTab !== 'interfaces') navigate('interfaces');
  3121. } else {
  3122. showToast('Creation Failed', data.message || 'Failed to create VLAN', 'error');
  3123. }
  3124. } catch (err) {
  3125. showToast('Error', err.message, 'error');
  3126. } finally {
  3127. btn.disabled = false;
  3128. btn.innerText = 'Create VLAN';
  3129. }
  3130. }
  3131. async function confirmDeleteVlan(name) {
  3132. if (!confirm(`Delete VLAN interface ${name}?`)) return;
  3133. try {
  3134. const res = await fetch(`${API_BASE}/vlans/${encodeURIComponent(name)}`, { method: 'DELETE' });
  3135. if (res.ok) {
  3136. showToast('VLAN Deleted', `Interface ${name} removed`, 'success');
  3137. closeIfaceModal();
  3138. fetchData(true);
  3139. }
  3140. } catch (err) {
  3141. showToast('Error', err.message, 'error');
  3142. }
  3143. }
  3144. function openIfaceModal(name) {
  3145. const iface = (state.interfaces || []).find(i => i.name === name);
  3146. if (!iface) return;
  3147. state.currentModalIface = iface.name;
  3148. document.getElementById('modal-iface-name').innerText = iface.name;
  3149. document.getElementById('modal-iface-badge').innerText = iface.is_vlan ? `VLAN ${iface.vlan_id}` : iface.type;
  3150. document.getElementById('modal-iface-mtu').value = iface.mtu;
  3151. populateRoleSelects(iface.role || 'LAN');
  3152. document.getElementById('modal-iface-desc').value = iface.description || '';
  3153. const nameInput = document.getElementById('modal-iface-new-name');
  3154. const renameBtn = document.getElementById('modal-btn-rename');
  3155. const renameHelp = document.getElementById('modal-iface-rename-help');
  3156. if (nameInput) {
  3157. nameInput.value = iface.name;
  3158. if (iface.name === 'lo' || iface.type === 'loopback') {
  3159. nameInput.disabled = true;
  3160. if (renameBtn) renameBtn.disabled = true;
  3161. if (renameHelp) renameHelp.innerText = 'Loopback interface cannot be renamed.';
  3162. } else {
  3163. nameInput.disabled = false;
  3164. if (renameBtn) renameBtn.disabled = false;
  3165. if (renameHelp) renameHelp.innerText = 'Device name in Linux (max 15 characters). Automatically preserves operational link state and metadata.';
  3166. }
  3167. }
  3168. const delBtn = document.getElementById('modal-delete-vlan-btn');
  3169. if (iface.is_vlan) {
  3170. delBtn.classList.remove('hidden');
  3171. } else {
  3172. delBtn.classList.add('hidden');
  3173. }
  3174. renderModalIPs(iface);
  3175. document.getElementById('iface-modal').classList.remove('hidden');
  3176. }
  3177. function renderModalIPs(iface) {
  3178. const container = document.getElementById('modal-ip-list');
  3179. container.innerHTML = '';
  3180. const addrs = [...(iface.ipv4 || []), ...(iface.ipv6 || [])];
  3181. if (addrs.length === 0) {
  3182. container.innerHTML = `<span class="text-slate-500 text-xs font-sans">No IP addresses currently bound</span>`;
  3183. return;
  3184. }
  3185. addrs.forEach(addr => {
  3186. const row = document.createElement('div');
  3187. row.className = 'flex items-center justify-between p-2 rounded bg-slate-900 border border-slate-800';
  3188. row.innerHTML = `
  3189. <span class="text-white">${addr}</span>
  3190. <button onclick="removeInterfaceIP('${addr}')" class="text-[11px] text-rose-400 hover:text-rose-300 font-sans">Remove</button>
  3191. `;
  3192. container.appendChild(row);
  3193. });
  3194. }
  3195. function closeIfaceModal() {
  3196. document.getElementById('iface-modal').classList.add('hidden');
  3197. state.currentModalIface = null;
  3198. }
  3199. async function setIfaceState(name, newState) {
  3200. const target = name || state.currentModalIface;
  3201. if (!target) return;
  3202. await toggleInterfaceState(target, newState);
  3203. const updated = (state.interfaces || []).find(i => i.name === target);
  3204. if (updated) openIfaceModal(target);
  3205. }
  3206. async function applyMTU() {
  3207. const mtu = parseInt(document.getElementById('modal-iface-mtu').value, 10);
  3208. try {
  3209. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/mtu`, {
  3210. method: 'POST',
  3211. headers: { 'Content-Type': 'application/json' },
  3212. body: JSON.stringify({ mtu })
  3213. });
  3214. if (res.ok) {
  3215. showToast('MTU Applied', `Set MTU to ${mtu} on ${state.currentModalIface}`, 'success');
  3216. fetchData(false);
  3217. }
  3218. } catch (err) {
  3219. showToast('Error', err.message, 'error');
  3220. }
  3221. }
  3222. async function addInterfaceIP() {
  3223. const ip = document.getElementById('modal-new-ip').value.trim();
  3224. if (!ip) return;
  3225. try {
  3226. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  3227. method: 'POST',
  3228. headers: { 'Content-Type': 'application/json' },
  3229. body: JSON.stringify({ ip })
  3230. });
  3231. if (res.ok) {
  3232. showToast('IP Added', `Bound ${ip} to ${state.currentModalIface}`, 'success');
  3233. document.getElementById('modal-new-ip').value = '';
  3234. await fetchData(false);
  3235. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  3236. if (iface) renderModalIPs(iface);
  3237. } else {
  3238. const err = await res.json();
  3239. showToast('Error', err.error || err.message || 'Failed to add IP address', 'error');
  3240. }
  3241. } catch (err) {
  3242. showToast('Error', err.message, 'error');
  3243. }
  3244. }
  3245. async function removeInterfaceIP(ip) {
  3246. if (!confirm(`Remove IP ${ip}?`)) return;
  3247. try {
  3248. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  3249. method: 'DELETE',
  3250. headers: { 'Content-Type': 'application/json' },
  3251. body: JSON.stringify({ ip })
  3252. });
  3253. if (res.ok) {
  3254. showToast('IP Removed', `Removed ${ip}`, 'success');
  3255. await fetchData(false);
  3256. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  3257. if (iface) renderModalIPs(iface);
  3258. }
  3259. } catch (err) {
  3260. showToast('Error', err.message, 'error');
  3261. }
  3262. }
  3263. async function renameInterface() {
  3264. const oldName = state.currentModalIface;
  3265. const newNameInput = document.getElementById('modal-iface-new-name');
  3266. const newName = (newNameInput?.value || '').trim();
  3267. if (!oldName) return;
  3268. if (!newName) {
  3269. showToast('Warning', 'Interface name cannot be empty', 'warning');
  3270. return;
  3271. }
  3272. if (newName === oldName) {
  3273. showToast('Info', `Interface name is already "${oldName}"`, 'info');
  3274. return;
  3275. }
  3276. if (newName.length > 15) {
  3277. showToast('Validation Error', 'Interface name cannot exceed 15 characters (Linux IFNAMSIZ)', 'error');
  3278. return;
  3279. }
  3280. if (!/^[a-zA-Z0-9_][a-zA-Z0-9_.-]*$/.test(newName)) {
  3281. showToast('Validation Error', 'Name must contain only alphanumeric characters, underscores, hyphens or dots', 'error');
  3282. return;
  3283. }
  3284. const renameBtn = document.getElementById('modal-btn-rename');
  3285. if (renameBtn) {
  3286. renameBtn.disabled = true;
  3287. renameBtn.innerHTML = `<span class="animate-spin inline-block mr-1">⟳</span> Renaming...`;
  3288. }
  3289. try {
  3290. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(oldName)}/rename`, {
  3291. method: 'POST',
  3292. headers: { 'Content-Type': 'application/json' },
  3293. body: JSON.stringify({ new_name: newName })
  3294. });
  3295. const data = await res.json();
  3296. if (!res.ok) {
  3297. showToast('Rename Failed', data.error || data.message || 'Failed to rename interface', 'error');
  3298. return;
  3299. }
  3300. showToast('Interface Renamed', `Successfully renamed ${oldName} → ${newName}`, 'success');
  3301. state.currentModalIface = newName;
  3302. document.getElementById('modal-iface-name').innerText = newName;
  3303. // Refresh application state
  3304. await fetchData(false);
  3305. const updated = (state.interfaces || []).find(i => i.name === newName);
  3306. if (updated) {
  3307. openIfaceModal(newName);
  3308. } else {
  3309. closeIfaceModal();
  3310. }
  3311. } catch (err) {
  3312. showToast('Error', err.message, 'error');
  3313. } finally {
  3314. if (renameBtn) {
  3315. renameBtn.disabled = false;
  3316. renameBtn.innerHTML = `
  3317. <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"/></svg>
  3318. <span>Rename</span>
  3319. `;
  3320. }
  3321. }
  3322. }
  3323. async function saveInterfaceMetadata() {
  3324. const oldName = state.currentModalIface;
  3325. const newName = (document.getElementById('modal-iface-new-name')?.value || '').trim();
  3326. const role = document.getElementById('modal-iface-role').value;
  3327. const desc = document.getElementById('modal-iface-desc').value.trim();
  3328. let targetName = oldName;
  3329. // If user changed the name before clicking Save Changes, execute rename first
  3330. if (newName && newName !== oldName && oldName !== 'lo') {
  3331. try {
  3332. const renameRes = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(oldName)}/rename`, {
  3333. method: 'POST',
  3334. headers: { 'Content-Type': 'application/json' },
  3335. body: JSON.stringify({ new_name: newName })
  3336. });
  3337. const data = await renameRes.json();
  3338. if (!renameRes.ok) {
  3339. showToast('Rename Failed', data.error || data.message || 'Could not rename interface', 'error');
  3340. return;
  3341. }
  3342. targetName = newName;
  3343. state.currentModalIface = newName;
  3344. showToast('Renamed', `Interface renamed from ${oldName} to ${newName}`, 'success');
  3345. } catch (err) {
  3346. showToast('Error', err.message, 'error');
  3347. return;
  3348. }
  3349. }
  3350. try {
  3351. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(targetName)}/metadata`, {
  3352. method: 'POST',
  3353. headers: { 'Content-Type': 'application/json' },
  3354. body: JSON.stringify({ role, description: desc })
  3355. });
  3356. if (res.ok) {
  3357. showToast('Saved', 'Interface configuration updated', 'success');
  3358. closeIfaceModal();
  3359. fetchData(false);
  3360. } else {
  3361. const err = await res.json();
  3362. showToast('Error', err.error || err.message || 'Failed to save metadata', 'error');
  3363. }
  3364. } catch (err) {
  3365. showToast('Error', err.message, 'error');
  3366. }
  3367. }
  3368. // ======================== MIKROTIK FIREWALL (/ip firewall) ========================
  3369. state.fwSubTab = 'filter';
  3370. state.routesSubTab = 'routes';
  3371. function renderRuleFlag(disabled, hasComment) {
  3372. let flags = '';
  3373. if (disabled) flags += '<span class="text-rose-400 font-bold" title="Disabled">X</span>';
  3374. if (hasComment) flags += '<span class="text-amber-400 font-bold ml-1" title="Has Comment">C</span>';
  3375. return flags || '<span class="text-slate-600">-</span>';
  3376. }
  3377. function renderActionBadge(action) {
  3378. const act = (action || '').toLowerCase();
  3379. let color = 'bg-slate-800 text-slate-300';
  3380. if (act === 'accept') color = 'bg-emerald-500/20 text-emerald-300 border border-emerald-500/30';
  3381. else if (act === 'drop' || act === 'reject') color = 'bg-rose-500/20 text-rose-300 border border-rose-500/30';
  3382. else if (act === 'masquerade' || act === 'src-nat' || act === 'dst-nat') color = 'bg-amber-500/20 text-amber-300 border border-amber-500/30';
  3383. else if (act.startsWith('mark-')) color = 'bg-purple-500/20 text-purple-300 border border-purple-500/30';
  3384. else if (act === 'log') color = 'bg-cyan-500/20 text-cyan-300 border border-cyan-500/30';
  3385. return `<span class="px-2 py-0.5 rounded text-[10px] font-mono font-semibold ${color}">${action}</span>`;
  3386. }
  3387. function switchFWSubTab(tab) {
  3388. state.fwSubTab = tab;
  3389. const tabs = ['filter', 'nat', 'mangle', 'addrlist', 'geo', 'connections'];
  3390. tabs.forEach(t => {
  3391. const panel = document.getElementById(`fw-subtab-${t}`);
  3392. const btn = document.getElementById(`fw-subtab-btn-${t}`);
  3393. if (panel) {
  3394. if (t === tab) panel.classList.remove('hidden');
  3395. else panel.classList.add('hidden');
  3396. }
  3397. if (btn) {
  3398. if (t === tab) {
  3399. btn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-emerald-500 text-white transition flex items-center gap-2 whitespace-nowrap';
  3400. } else {
  3401. btn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition flex items-center gap-2 whitespace-nowrap';
  3402. }
  3403. }
  3404. });
  3405. const addBtn = document.getElementById('fw-primary-add-btn');
  3406. if (addBtn) {
  3407. if (tab === 'filter') addBtn.innerHTML = '<span>+ Add Filter Rule</span>';
  3408. else if (tab === 'nat') addBtn.innerHTML = '<span>+ Add NAT Rule</span>';
  3409. else if (tab === 'mangle') addBtn.innerHTML = '<span>+ Add Mangle Rule</span>';
  3410. else if (tab === 'addrlist') addBtn.innerHTML = '<span>+ Add Address List</span>';
  3411. else if (tab === 'geo') addBtn.innerHTML = '<span>⚙️ Schedule Settings</span>';
  3412. else if (tab === 'connections') addBtn.innerHTML = '<span>Refresh Flows</span>';
  3413. }
  3414. if (tab === 'filter') renderFilterRules();
  3415. else if (tab === 'nat') renderNATRules();
  3416. else if (tab === 'mangle') renderMangleRules();
  3417. else if (tab === 'addrlist') renderAddressLists();
  3418. else if (tab === 'geo') loadGeoIP();
  3419. else if (tab === 'connections') loadConnections();
  3420. setTimeout(initTableSorting, 50);
  3421. }
  3422. function openCurrentFWModal() {
  3423. if (state.fwSubTab === 'filter') openAddFilterModal();
  3424. else if (state.fwSubTab === 'nat') openAddNATModal();
  3425. else if (state.fwSubTab === 'mangle') openAddMangleModal();
  3426. else if (state.fwSubTab === 'addrlist') openAddAddrListModal();
  3427. else if (state.fwSubTab === 'geo') openGeoIntervalModal();
  3428. else if (state.fwSubTab === 'connections') loadConnections();
  3429. }
  3430. async function loadFirewall(populateDropdowns = true) {
  3431. try {
  3432. const [summaryRes, filterRes, natRes, mangleRes, addrlistRes, geoStatusRes, geoCountriesRes] = await Promise.all([
  3433. fetch(`${API_BASE}/firewall/summary`),
  3434. fetch(`${API_BASE}/firewall/filter`),
  3435. fetch(`${API_BASE}/firewall/nat`),
  3436. fetch(`${API_BASE}/firewall/mangle`),
  3437. fetch(`${API_BASE}/firewall/address-lists`),
  3438. fetch(`${API_BASE}/firewall/geoip/status`),
  3439. fetch(`${API_BASE}/firewall/geoip/countries`)
  3440. ]);
  3441. if (summaryRes.ok) state.fwSummary = await summaryRes.json();
  3442. if (filterRes.ok) state.filterRules = await filterRes.json();
  3443. if (natRes.ok) state.natRules = await natRes.json();
  3444. if (mangleRes.ok) state.mangleRules = await mangleRes.json();
  3445. if (addrlistRes.ok) state.addressLists = await addrlistRes.json();
  3446. if (geoStatusRes.ok) state.geoStatus = await geoStatusRes.json();
  3447. if (geoCountriesRes.ok) state.geoCountries = await geoCountriesRes.json();
  3448. // Badges
  3449. const bFilter = document.getElementById('fw-badge-filter');
  3450. if (bFilter) bFilter.innerText = (state.filterRules || []).length;
  3451. const bNat = document.getElementById('fw-badge-nat');
  3452. if (bNat) bNat.innerText = (state.natRules || []).length;
  3453. const bMangle = document.getElementById('fw-badge-mangle');
  3454. if (bMangle) bMangle.innerText = (state.mangleRules || []).length;
  3455. const bAddr = document.getElementById('fw-badge-addrlist');
  3456. if (bAddr) bAddr.innerText = (state.addressLists || []).length;
  3457. const bGeo = document.getElementById('fw-badge-geo');
  3458. if (bGeo) bGeo.innerText = state.geoStatus?.enabled_count || 0;
  3459. const sigFilter = (state.filterRules || []).map(r => `${r.id}:${r.chain}:${r.action}:${r.disabled}`).join(';');
  3460. const sigNat = (state.natRules || []).map(r => `${r.id}:${r.chain}:${r.action}:${r.disabled}`).join(';');
  3461. const sigMangle = (state.mangleRules || []).map(r => `${r.id}:${r.chain}:${r.action}:${r.disabled}`).join(';');
  3462. const sigAddr = (state.addressLists || []).map(a => `${a.id}:${a.name}:${a.address}:${a.disabled}`).join(';');
  3463. const tbodyFilter = document.getElementById('filter-table-body');
  3464. if (tbodyFilter) {
  3465. if (populateDropdowns || tbodyFilter.dataset.sig !== sigFilter) {
  3466. tbodyFilter.dataset.sig = sigFilter;
  3467. renderFilterRules();
  3468. } else {
  3469. // In-place live stats update (ZERO flicker)
  3470. (state.filterRules || []).forEach(r => {
  3471. const p = document.getElementById(`filter-pkts-${r.id}`);
  3472. if (p) p.innerText = `${(r.packets || 0).toLocaleString()}p`;
  3473. const b = document.getElementById(`filter-bytes-${r.id}`);
  3474. if (b) b.innerText = formatTraffic(r.bytes || 0).replace('/s', '');
  3475. });
  3476. }
  3477. }
  3478. const tbodyNat = document.getElementById('nat-table-body');
  3479. if (tbodyNat) {
  3480. if (populateDropdowns || tbodyNat.dataset.sig !== sigNat) {
  3481. tbodyNat.dataset.sig = sigNat;
  3482. renderNATRules();
  3483. } else {
  3484. (state.natRules || []).forEach(r => {
  3485. const p = document.getElementById(`nat-pkts-${r.id}`);
  3486. if (p) p.innerText = `${(r.packets || 0).toLocaleString()}p`;
  3487. const b = document.getElementById(`nat-bytes-${r.id}`);
  3488. if (b) b.innerText = formatTraffic(r.bytes || 0).replace('/s', '');
  3489. });
  3490. }
  3491. }
  3492. const tbodyMangle = document.getElementById('mangle-table-body');
  3493. if (tbodyMangle) {
  3494. if (populateDropdowns || tbodyMangle.dataset.sig !== sigMangle) {
  3495. tbodyMangle.dataset.sig = sigMangle;
  3496. renderMangleRules();
  3497. } else {
  3498. (state.mangleRules || []).forEach(r => {
  3499. const p = document.getElementById(`mangle-pkts-${r.id}`);
  3500. if (p) p.innerText = `${(r.packets || 0).toLocaleString()}p`;
  3501. const b = document.getElementById(`mangle-bytes-${r.id}`);
  3502. if (b) b.innerText = formatTraffic(r.bytes || 0).replace('/s', '');
  3503. });
  3504. }
  3505. }
  3506. const tbodyAddr = document.getElementById('addrlist-table-body');
  3507. if (tbodyAddr && (populateDropdowns || tbodyAddr.dataset.sig !== sigAddr)) {
  3508. tbodyAddr.dataset.sig = sigAddr;
  3509. renderAddressLists();
  3510. }
  3511. renderGeoCountries();
  3512. if (state.fwSubTab === 'connections') {
  3513. loadConnections();
  3514. }
  3515. } catch (err) {
  3516. console.error('Failed to load firewall:', err);
  3517. }
  3518. }
  3519. // ----------------- Filter Rules -----------------
  3520. function renderFilterRules() {
  3521. const chainFilter = document.getElementById('filter-filter-chain')?.value || '';
  3522. const tbody = document.getElementById('filter-table-body');
  3523. const empty = document.getElementById('filter-empty');
  3524. if (!tbody) return;
  3525. tbody.innerHTML = '';
  3526. const rules = (state.filterRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  3527. document.getElementById('filter-count-badge').innerText = `${rules.length} Rules`;
  3528. if (rules.length === 0) {
  3529. empty?.classList.remove('hidden');
  3530. return;
  3531. }
  3532. empty?.classList.add('hidden');
  3533. rules.forEach((r, idx) => {
  3534. const tr = document.createElement('tr');
  3535. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  3536. const ports = [r.src_port ? 's:' + r.src_port : '', r.dst_port ? 'd:' + r.dst_port : ''].filter(Boolean).join(' ');
  3537. const ifaces = [r.in_interface ? 'in:' + r.in_interface : '', r.out_interface ? 'out:' + r.out_interface : ''].filter(Boolean).join(' ');
  3538. let actionExtra = '';
  3539. if (r.action === 'reject') {
  3540. actionExtra = `<span class="block text-[10px] text-rose-300 font-mono mt-0.5">(${r.reject_with || 'icmp-net-unreach'})</span>`;
  3541. } else if (r.action === 'jump') {
  3542. actionExtra = `<span class="block text-[10px] text-yellow-300 font-mono mt-0.5">&rarr; ${r.jump_target || '-'}</span>`;
  3543. } else if (r.action.includes('address-list') || r.action.includes('address list')) {
  3544. actionExtra = `<span class="block text-[10px] text-emerald-300 font-mono mt-0.5">&rarr; ${r.address_list || '-'}</span>`;
  3545. } else if (r.action === 'log' && r.log_prefix) {
  3546. actionExtra = `<span class="block text-[10px] text-slate-400 font-mono mt-0.5">${r.log_prefix}</span>`;
  3547. }
  3548. tr.innerHTML = `
  3549. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  3550. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  3551. <td class="py-2.5 px-3 font-bold text-white">${r.chain}</td>
  3552. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  3553. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  3554. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}</td>
  3555. <td class="py-2.5 px-3 text-amber-400">${ports || '-'}</td>
  3556. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  3557. <td class="py-2.5 px-3">${renderActionBadge(r.action)}${actionExtra}</td>
  3558. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  3559. <span class="text-slate-300" id="filter-pkts-${r.id}">${(r.packets || 0).toLocaleString()}p</span> /
  3560. <span class="text-slate-500" id="filter-bytes-${r.id}">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  3561. </td>
  3562. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  3563. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  3564. <button onclick="moveFilterRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  3565. <button onclick="moveFilterRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  3566. <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>
  3567. <button onclick="openEditFilterModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  3568. <button onclick="deleteFilterRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  3569. </td>
  3570. `;
  3571. tbody.appendChild(tr);
  3572. });
  3573. }
  3574. function formatTarget(addr, list, geo) {
  3575. const parts = [];
  3576. if (addr) parts.push(`<span>${addr}</span>`);
  3577. if (list) {
  3578. const inv = list.startsWith('!') ? '!' : '';
  3579. const clean = list.replace(/^!/, '');
  3580. 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>`);
  3581. }
  3582. if (geo) {
  3583. const inv = geo.startsWith('!') ? '!' : '';
  3584. const clean = geo.replace(/^!/, '').replace(/^geo:/, '');
  3585. 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>`);
  3586. }
  3587. if (parts.length === 0) return '<span class="text-slate-600">0.0.0.0/0</span>';
  3588. return parts.join(' ');
  3589. }
  3590. function populateInterfaceSelect(selectId, currentVal = '') {
  3591. const sel = document.getElementById(selectId);
  3592. if (!sel) return;
  3593. sel.innerHTML = '<option value="">(Any Interface)</option>';
  3594. (state.interfaces || []).forEach(i => {
  3595. const opt = document.createElement('option');
  3596. opt.value = i.name;
  3597. opt.innerText = `${i.name} (${i.role || i.type})`;
  3598. if (i.name === currentVal) opt.selected = true;
  3599. sel.appendChild(opt);
  3600. });
  3601. }
  3602. function populateAddressListSelect(selectId, currentVal = '') {
  3603. const sel = document.getElementById(selectId);
  3604. if (!sel) return;
  3605. sel.innerHTML = '<option value="">(None)</option>';
  3606. const cleanVal = (currentVal || '').replace(/^!/, '');
  3607. const customNames = Array.from(new Set((state.addressLists || []).map(a => a.name))).sort();
  3608. customNames.forEach(name => {
  3609. const count = (state.addressLists || []).filter(a => a.name === name).length;
  3610. const opt = document.createElement('option');
  3611. opt.value = name;
  3612. opt.innerText = `${name} (${count} entries)`;
  3613. if (name === cleanVal) opt.selected = true;
  3614. sel.appendChild(opt);
  3615. });
  3616. if (cleanVal && !sel.querySelector(`option[value="${cleanVal}"]`)) {
  3617. const opt = document.createElement('option');
  3618. opt.value = cleanVal;
  3619. opt.innerText = cleanVal;
  3620. opt.selected = true;
  3621. sel.appendChild(opt);
  3622. }
  3623. populateCommonAddrListDatalist();
  3624. }
  3625. function populateCommonAddrListDatalist() {
  3626. const dl = document.getElementById('fw-addrlist-datalist');
  3627. if (!dl) return;
  3628. dl.innerHTML = '';
  3629. const names = Array.from(new Set((state.addressLists || []).map(a => a.name).filter(Boolean))).sort();
  3630. names.forEach(name => {
  3631. const opt = document.createElement('option');
  3632. opt.value = name;
  3633. dl.appendChild(opt);
  3634. });
  3635. }
  3636. function populateGeoIPSelect(selectId, currentVal = '') {
  3637. const sel = document.getElementById(selectId);
  3638. if (!sel) return;
  3639. sel.innerHTML = '<option value="">(None)</option>';
  3640. const cleanVal = (currentVal || '').replace(/^!/, '').replace(/^geo:/, '').toUpperCase();
  3641. // Presets optgroup
  3642. const grpPresets = document.createElement('optgroup');
  3643. grpPresets.label = '⚡ Regional Presets';
  3644. const presets = [
  3645. { code: 'EU', label: '🇪🇺 European Union (EU - 27 countries)' },
  3646. { code: 'BALKANS', label: '🏛️ Balkans (GR, CY, BG, RO, AL, etc.)' },
  3647. { code: 'BLOCKLIST', label: '🛡️ High-Risk Blocklist (CN, RU, IR, KP, BY)' }
  3648. ];
  3649. presets.forEach(p => {
  3650. const opt = document.createElement('option');
  3651. opt.value = p.code;
  3652. opt.innerText = p.label;
  3653. if (p.code === cleanVal) opt.selected = true;
  3654. grpPresets.appendChild(opt);
  3655. });
  3656. sel.appendChild(grpPresets);
  3657. // All Countries optgroup
  3658. const grpCountries = document.createElement('optgroup');
  3659. grpCountries.label = '🌍 All Countries';
  3660. const countries = (state.geoCountries || []).slice().sort((a, b) => a.name.localeCompare(b.name));
  3661. countries.forEach(c => {
  3662. const opt = document.createElement('option');
  3663. opt.value = c.code;
  3664. const subnetsInfo = c.subnet_count ? ` [${c.subnet_count.toLocaleString()} subnets]` : '';
  3665. opt.innerText = `${c.name} (${c.code})${subnetsInfo}`;
  3666. if (c.code === cleanVal) opt.selected = true;
  3667. grpCountries.appendChild(opt);
  3668. });
  3669. sel.appendChild(grpCountries);
  3670. }
  3671. // ==================== FIREWALL FILTER MODAL (DEBTIK WEBFIG / WINBOX V4) ====================
  3672. function switchFwRuleTab(tab) {
  3673. state.activeFwRuleTab = tab;
  3674. document.querySelectorAll('.fw-rule-tab-btn').forEach(btn => {
  3675. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  3676. btn.classList.add('text-slate-400', 'border-transparent');
  3677. });
  3678. const activeBtn = document.getElementById(`fw-tab-btn-${tab}`);
  3679. if (activeBtn) {
  3680. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  3681. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  3682. }
  3683. document.querySelectorAll('.fw-rule-pane').forEach(p => p.classList.add('hidden'));
  3684. const activePane = document.getElementById(`fw-pane-${tab}`);
  3685. if (activePane) activePane.classList.remove('hidden');
  3686. if (tab === 'statistics') {
  3687. startFwStatPolling();
  3688. } else {
  3689. stopFwStatPolling();
  3690. }
  3691. }
  3692. function toggleFwField(fieldKey, expand) {
  3693. const plusBtn = document.getElementById(`fw-plus-${fieldKey}`);
  3694. const fieldBox = document.getElementById(`fw-field-${fieldKey}`);
  3695. if (!plusBtn || !fieldBox) return;
  3696. if (expand) {
  3697. plusBtn.classList.add('hidden');
  3698. fieldBox.classList.remove('hidden');
  3699. const valInput = document.getElementById(`fw-val-${fieldKey}`);
  3700. if (valInput) valInput.focus();
  3701. } else {
  3702. fieldBox.classList.add('hidden');
  3703. plusBtn.classList.remove('hidden');
  3704. const valInput = document.getElementById(`fw-val-${fieldKey}`);
  3705. if (valInput) {
  3706. if (valInput.tagName === 'SELECT') {
  3707. valInput.selectedIndex = 0;
  3708. } else {
  3709. valInput.value = '';
  3710. }
  3711. }
  3712. const invInput = document.getElementById(`fw-inv-${fieldKey}`);
  3713. if (invInput) invInput.checked = false;
  3714. if (fieldKey === 'cs') {
  3715. ['filter-modal-cs-established', 'filter-modal-cs-related', 'filter-modal-cs-new', 'filter-modal-cs-invalid', 'filter-modal-cs-untracked'].forEach(id => {
  3716. const el = document.getElementById(id);
  3717. if (el) el.checked = false;
  3718. });
  3719. }
  3720. if (fieldKey === 'natstate') {
  3721. ['filter-modal-nat-srcnat', 'filter-modal-nat-dstnat'].forEach(id => {
  3722. const el = document.getElementById(id);
  3723. if (el) el.checked = false;
  3724. });
  3725. }
  3726. if (fieldKey === 'days') {
  3727. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3728. const el = document.getElementById(`fw-day-${d}`);
  3729. if (el) el.checked = true;
  3730. });
  3731. }
  3732. }
  3733. }
  3734. function setFwFieldVal(fieldKey, value, hasInvert = false) {
  3735. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  3736. toggleFwField(fieldKey, true);
  3737. let strVal = String(value);
  3738. if (hasInvert) {
  3739. const inv = strVal.startsWith('!');
  3740. if (inv) strVal = strVal.slice(1);
  3741. const invEl = document.getElementById(`fw-inv-${fieldKey}`);
  3742. if (invEl) invEl.checked = inv;
  3743. }
  3744. const valEl = document.getElementById(`fw-val-${fieldKey}`);
  3745. if (valEl) valEl.value = strVal;
  3746. } else {
  3747. toggleFwField(fieldKey, false);
  3748. }
  3749. }
  3750. function getFwFieldVal(fieldKey, hasInvert = false) {
  3751. const fieldBox = document.getElementById(`fw-field-${fieldKey}`);
  3752. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  3753. const valEl = document.getElementById(`fw-val-${fieldKey}`);
  3754. let v = valEl ? valEl.value.trim() : '';
  3755. if (!v) return '';
  3756. if (hasInvert) {
  3757. const invEl = document.getElementById(`fw-inv-${fieldKey}`);
  3758. if (invEl && invEl.checked) {
  3759. v = '!' + v.replace(/^!/, '');
  3760. }
  3761. }
  3762. return v;
  3763. }
  3764. function toggleMaximizeFilterModal() {
  3765. const win = document.getElementById('filter-modal-window');
  3766. if (!win) return;
  3767. if (win.classList.contains('max-w-[720px]')) {
  3768. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  3769. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  3770. } else {
  3771. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  3772. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  3773. }
  3774. }
  3775. function openAddFilterModal() {
  3776. switchFwRuleTab('general');
  3777. const badge = document.getElementById('fw-modal-badge');
  3778. if (badge) badge.innerText = 'New...';
  3779. document.getElementById('filter-modal-id').value = '';
  3780. document.getElementById('filter-modal-enabled').checked = true;
  3781. document.getElementById('filter-modal-comment').value = '';
  3782. document.getElementById('filter-modal-chain').value = 'forward';
  3783. document.getElementById('filter-modal-action').value = 'accept';
  3784. document.getElementById('filter-modal-log').checked = false;
  3785. populateInterfaceSelect('fw-val-iniface');
  3786. populateInterfaceSelect('fw-val-outiface');
  3787. populateAddressListSelect('fw-val-srclist');
  3788. populateAddressListSelect('fw-val-dstlist');
  3789. populateGeoIPSelect('fw-val-srcgeo');
  3790. populateGeoIPSelect('fw-val-dstgeo');
  3791. const allFieldKeys = [
  3792. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  3793. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  3794. 'routingmark', 'conntype', 'cs', 'natstate',
  3795. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  3796. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  3797. 'ipsec', 'tlshost', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  3798. 'pktsize', 'random', 'tcpflags', 'icmpoptions', 'ipv4options', 'ttl',
  3799. 'time', 'days', 'limit', 'dstlimit', 'psd', 'logprefix'
  3800. ];
  3801. allFieldKeys.forEach(k => toggleFwField(k, false));
  3802. resetCurrentRuleCounters();
  3803. toggleFilterActionFields();
  3804. document.getElementById('filter-modal').classList.remove('hidden');
  3805. }
  3806. function openEditFilterModal(id) {
  3807. const r = (state.filterRules || []).find(rule => rule.id === id);
  3808. if (!r) return;
  3809. switchFwRuleTab('general');
  3810. const badge = document.getElementById('fw-modal-badge');
  3811. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  3812. document.getElementById('filter-modal-id').value = r.id;
  3813. document.getElementById('filter-modal-enabled').checked = !r.disabled;
  3814. document.getElementById('filter-modal-comment').value = r.comment || '';
  3815. document.getElementById('filter-modal-chain').value = r.chain || 'forward';
  3816. document.getElementById('filter-modal-action').value = r.action || 'accept';
  3817. document.getElementById('filter-modal-log').checked = !!r.log;
  3818. populateInterfaceSelect('fw-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  3819. populateInterfaceSelect('fw-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  3820. populateAddressListSelect('fw-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  3821. populateAddressListSelect('fw-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  3822. populateGeoIPSelect('fw-val-srcgeo', r.src_geoip || '');
  3823. populateGeoIPSelect('fw-val-dstgeo', r.dst_geoip || '');
  3824. setFwFieldVal('src', r.src_address, true);
  3825. setFwFieldVal('dst', r.dst_address, true);
  3826. setFwFieldVal('srclist', r.src_address_list, true);
  3827. setFwFieldVal('dstlist', r.dst_address_list, true);
  3828. setFwFieldVal('srcgeo', r.src_geoip, true);
  3829. setFwFieldVal('dstgeo', r.dst_geoip, true);
  3830. if (r.protocol && r.protocol !== 'all') {
  3831. setFwFieldVal('proto', r.protocol, true);
  3832. } else {
  3833. toggleFwField('proto', false);
  3834. }
  3835. setFwFieldVal('sport', r.src_port, true);
  3836. setFwFieldVal('dport', r.dst_port, true);
  3837. setFwFieldVal('anyport', r.any_port, true);
  3838. setFwFieldVal('iniface', r.in_interface, true);
  3839. setFwFieldVal('outiface', r.out_interface, true);
  3840. setFwFieldVal('inifacelist', r.in_interface_list, true);
  3841. setFwFieldVal('outifacelist', r.out_interface_list, true);
  3842. setFwFieldVal('pktmark', r.packet_mark, true);
  3843. setFwFieldVal('connmark', r.connection_mark, true);
  3844. setFwFieldVal('routingmark', r.routing_mark, true);
  3845. setFwFieldVal('conntype', r.connection_type, false);
  3846. const states = r.connection_state || [];
  3847. if (states.length > 0) {
  3848. toggleFwField('cs', true);
  3849. document.getElementById('filter-modal-cs-established').checked = states.includes('established');
  3850. document.getElementById('filter-modal-cs-related').checked = states.includes('related');
  3851. document.getElementById('filter-modal-cs-new').checked = states.includes('new');
  3852. document.getElementById('filter-modal-cs-invalid').checked = states.includes('invalid');
  3853. document.getElementById('filter-modal-cs-untracked').checked = states.includes('untracked');
  3854. } else {
  3855. toggleFwField('cs', false);
  3856. }
  3857. const natStates = r.connection_nat_state || [];
  3858. if (natStates.length > 0) {
  3859. toggleFwField('natstate', true);
  3860. document.getElementById('filter-modal-nat-srcnat').checked = natStates.includes('srcnat');
  3861. document.getElementById('filter-modal-nat-dstnat').checked = natStates.includes('dstnat');
  3862. } else {
  3863. toggleFwField('natstate', false);
  3864. }
  3865. // Advanced tab fields
  3866. setFwFieldVal('layer7', r.layer7_protocol, false);
  3867. setFwFieldVal('content', r.content, false);
  3868. setFwFieldVal('connbytes', r.connection_bytes, false);
  3869. setFwFieldVal('connrate', r.connection_rate, false);
  3870. setFwFieldVal('pcc', r.pcc, false);
  3871. setFwFieldVal('srcmac', r.src_mac_address, true);
  3872. setFwFieldVal('outbridgeport', r.out_bridge_port, false);
  3873. setFwFieldVal('inbridgeport', r.in_bridge_port, false);
  3874. setFwFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  3875. setFwFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  3876. setFwFieldVal('ipsec', r.ipsec_policy, false);
  3877. setFwFieldVal('tlshost', r.tls_host, false);
  3878. setFwFieldVal('ingresspriority', r.ingress_priority, false);
  3879. setFwFieldVal('priority', r.priority, false);
  3880. setFwFieldVal('dscp', r.dscp, false);
  3881. setFwFieldVal('tcpmss', r.tcp_mss, false);
  3882. if (r.tos) {
  3883. const tosEl = document.getElementById('fw-val-tos');
  3884. if (tosEl) tosEl.value = r.tos;
  3885. }
  3886. setFwFieldVal('pktsize', r.packet_size, false);
  3887. setFwFieldVal('random', r.random, false);
  3888. setFwFieldVal('tcpflags', r.tcp_flags, false);
  3889. setFwFieldVal('icmpoptions', r.icmp_options, false);
  3890. setFwFieldVal('ipv4options', r.ipv4_options, false);
  3891. setFwFieldVal('ttl', r.ttl, false);
  3892. // Extra tab fields
  3893. setFwFieldVal('time', r.time, false);
  3894. if (r.days) {
  3895. toggleFwField('days', true);
  3896. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3897. const chk = document.getElementById(`fw-day-${d}`);
  3898. if (chk) chk.checked = r.days.includes(d);
  3899. });
  3900. } else {
  3901. toggleFwField('days', false);
  3902. }
  3903. setFwFieldVal('limit', r.limit, false);
  3904. setFwFieldVal('dstlimit', r.dst_limit, false);
  3905. setFwFieldVal('psd', r.psd, false);
  3906. // Action fields
  3907. if (r.reject_with) {
  3908. const rwEl = document.getElementById('filter-modal-rejectwith');
  3909. if (rwEl) rwEl.value = r.reject_with;
  3910. }
  3911. if (r.jump_target) {
  3912. const jtEl = document.getElementById('filter-modal-jumptarget');
  3913. if (jtEl) jtEl.value = r.jump_target;
  3914. }
  3915. if (r.address_list) {
  3916. const alEl = document.getElementById('filter-modal-action-addrlist');
  3917. if (alEl) alEl.value = r.address_list;
  3918. }
  3919. if (r.address_list_timeout) {
  3920. const toEl = document.getElementById('filter-modal-action-timeout');
  3921. if (toEl) toEl.value = r.address_list_timeout;
  3922. }
  3923. setFwFieldVal('logprefix', r.log_prefix, false);
  3924. // Statistics
  3925. const bEl = document.getElementById('fw-stat-bytes');
  3926. const pEl = document.getElementById('fw-stat-packets');
  3927. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  3928. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  3929. state.fwLastBytes = r.bytes || 0;
  3930. state.fwLastPackets = r.packets || 0;
  3931. state.fwLastTimestamp = Date.now();
  3932. state.fwStatRateHistory = new Array(30).fill(0);
  3933. state.fwStatPktHistory = new Array(30).fill(0);
  3934. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  3935. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  3936. toggleFilterActionFields();
  3937. document.getElementById('filter-modal').classList.remove('hidden');
  3938. }
  3939. function closeFilterModal() {
  3940. stopFwStatPolling();
  3941. document.getElementById('filter-modal').classList.add('hidden');
  3942. }
  3943. function toggleFilterActionFields() {
  3944. const act = document.getElementById('filter-modal-action')?.value || 'accept';
  3945. const rejectBox = document.getElementById('filter-action-reject-box');
  3946. const jumpBox = document.getElementById('filter-action-jump-box');
  3947. const addrBox = document.getElementById('filter-action-addrlist-box');
  3948. if (rejectBox) {
  3949. if (act === 'reject') rejectBox.classList.remove('hidden');
  3950. else rejectBox.classList.add('hidden');
  3951. }
  3952. if (jumpBox) {
  3953. if (act === 'jump') jumpBox.classList.remove('hidden');
  3954. else jumpBox.classList.add('hidden');
  3955. }
  3956. if (addrBox) {
  3957. if (act === 'add-dst-to-address-list' || act === 'add-src-to-address-list' || act.includes('address-list') || act.includes('address list')) {
  3958. addrBox.classList.remove('hidden');
  3959. } else {
  3960. addrBox.classList.add('hidden');
  3961. }
  3962. }
  3963. if (act === 'log') {
  3964. const logEl = document.getElementById('filter-modal-log');
  3965. if (logEl) logEl.checked = true;
  3966. toggleFwField('logprefix', true);
  3967. }
  3968. }
  3969. function toggleFwLogPrefix() {
  3970. const isLog = document.getElementById('filter-modal-log')?.checked;
  3971. toggleFwField('logprefix', !!isLog);
  3972. }
  3973. function copyFilterRule() {
  3974. document.getElementById('filter-modal-id').value = '';
  3975. const badge = document.getElementById('fw-modal-badge');
  3976. if (badge) badge.innerText = 'New...';
  3977. showToast('Rule Cloned', 'Ready to save as a new rule copy', 'info');
  3978. }
  3979. function resetCurrentRuleCounters() {
  3980. state.fwStatRateHistory = new Array(30).fill(0);
  3981. state.fwStatPktHistory = new Array(30).fill(0);
  3982. state.fwLastBytes = 0;
  3983. state.fwLastPackets = 0;
  3984. state.fwLastTimestamp = Date.now();
  3985. const bEl = document.getElementById('fw-stat-bytes');
  3986. const pEl = document.getElementById('fw-stat-packets');
  3987. const rEl = document.getElementById('fw-stat-rate');
  3988. const prEl = document.getElementById('fw-stat-pktrate');
  3989. if (bEl) bEl.value = '0 B';
  3990. if (pEl) pEl.value = '0';
  3991. if (rEl) rEl.value = '0 bps';
  3992. if (prEl) prEl.value = '0 p/s';
  3993. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  3994. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  3995. showToast('Counters Reset', 'Rule counter display reset to 0', 'info');
  3996. }
  3997. async function resetAllFwCounters() {
  3998. try {
  3999. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  4000. if (res.ok) {
  4001. resetCurrentRuleCounters();
  4002. showToast('All Counters Reset', 'All firewall counters zeroed', 'success');
  4003. loadFirewall(false);
  4004. }
  4005. } catch (err) {
  4006. showToast('Error', err.message, 'error');
  4007. }
  4008. }
  4009. async function applyFilterRule(closeAfter = false) {
  4010. const id = document.getElementById('filter-modal-id').value;
  4011. const chain = document.getElementById('filter-modal-chain').value;
  4012. const action = document.getElementById('filter-modal-action').value;
  4013. const comment = document.getElementById('filter-modal-comment').value.trim();
  4014. const enabled = document.getElementById('filter-modal-enabled').checked;
  4015. const src = getFwFieldVal('src', true);
  4016. const dst = getFwFieldVal('dst', true);
  4017. const srclist = getFwFieldVal('srclist', true);
  4018. const dstlist = getFwFieldVal('dstlist', true);
  4019. const srcgeo = getFwFieldVal('srcgeo', true);
  4020. const dstgeo = getFwFieldVal('dstgeo', true);
  4021. const proto = getFwFieldVal('proto', true);
  4022. const sport = getFwFieldVal('sport', true);
  4023. const dport = getFwFieldVal('dport', true);
  4024. const anyport = getFwFieldVal('anyport', true);
  4025. const iniface = getFwFieldVal('iniface', true);
  4026. const outiface = getFwFieldVal('outiface', true);
  4027. const inifacelist = getFwFieldVal('inifacelist', true);
  4028. const outifacelist = getFwFieldVal('outifacelist', true);
  4029. const pktmark = getFwFieldVal('pktmark', true);
  4030. const connmark = getFwFieldVal('connmark', true);
  4031. const routingmark = getFwFieldVal('routingmark', true);
  4032. const conntype = getFwFieldVal('conntype', false);
  4033. const states = [];
  4034. const csBox = document.getElementById('fw-field-cs');
  4035. if (csBox && !csBox.classList.contains('hidden')) {
  4036. if (document.getElementById('filter-modal-cs-established')?.checked) states.push('established');
  4037. if (document.getElementById('filter-modal-cs-related')?.checked) states.push('related');
  4038. if (document.getElementById('filter-modal-cs-new')?.checked) states.push('new');
  4039. if (document.getElementById('filter-modal-cs-invalid')?.checked) states.push('invalid');
  4040. if (document.getElementById('filter-modal-cs-untracked')?.checked) states.push('untracked');
  4041. }
  4042. const natStates = [];
  4043. const natBox = document.getElementById('fw-field-natstate');
  4044. if (natBox && !natBox.classList.contains('hidden')) {
  4045. if (document.getElementById('filter-modal-nat-srcnat')?.checked) natStates.push('srcnat');
  4046. if (document.getElementById('filter-modal-nat-dstnat')?.checked) natStates.push('dstnat');
  4047. }
  4048. const payload = {
  4049. id,
  4050. chain,
  4051. action,
  4052. protocol: proto || 'all',
  4053. src_address: src,
  4054. dst_address: dst,
  4055. src_port: sport,
  4056. dst_port: dport,
  4057. any_port: anyport,
  4058. in_interface: iniface,
  4059. out_interface: outiface,
  4060. in_interface_list: inifacelist,
  4061. out_interface_list: outifacelist,
  4062. packet_mark: pktmark,
  4063. connection_mark: connmark,
  4064. routing_mark: routingmark,
  4065. connection_type: conntype,
  4066. connection_state: states,
  4067. connection_nat_state: natStates,
  4068. src_address_list: srclist,
  4069. dst_address_list: dstlist,
  4070. src_geoip: srcgeo,
  4071. dst_geoip: dstgeo,
  4072. comment,
  4073. disabled: !enabled,
  4074. // Advanced tab
  4075. layer7_protocol: getFwFieldVal('layer7', false),
  4076. content: getFwFieldVal('content', false),
  4077. connection_bytes: getFwFieldVal('connbytes', false),
  4078. connection_rate: getFwFieldVal('connrate', false),
  4079. pcc: getFwFieldVal('pcc', false),
  4080. src_mac_address: getFwFieldVal('srcmac', true),
  4081. out_bridge_port: getFwFieldVal('outbridgeport', false),
  4082. in_bridge_port: getFwFieldVal('inbridgeport', false),
  4083. in_bridge_port_list: getFwFieldVal('inbridgeportlist', false),
  4084. out_bridge_port_list: getFwFieldVal('outbridgeportlist', false),
  4085. ipsec_policy: getFwFieldVal('ipsec', false),
  4086. tls_host: getFwFieldVal('tlshost', false),
  4087. ingress_priority: getFwFieldVal('ingresspriority', false),
  4088. priority: getFwFieldVal('priority', false),
  4089. dscp: getFwFieldVal('dscp', false),
  4090. tcp_mss: getFwFieldVal('tcpmss', false),
  4091. tos: document.getElementById('fw-val-tos')?.value || '',
  4092. packet_size: getFwFieldVal('pktsize', false),
  4093. random: getFwFieldVal('random', false),
  4094. tcp_flags: getFwFieldVal('tcpflags', false),
  4095. icmp_options: getFwFieldVal('icmpoptions', false),
  4096. ipv4_options: getFwFieldVal('ipv4options', false),
  4097. ttl: getFwFieldVal('ttl', false),
  4098. // Extra tab
  4099. time: getFwFieldVal('time', false),
  4100. limit: getFwFieldVal('limit', false),
  4101. dst_limit: getFwFieldVal('dstlimit', false),
  4102. psd: getFwFieldVal('psd', false),
  4103. // Action tab
  4104. reject_with: action === 'reject' ? (document.getElementById('filter-modal-rejectwith')?.value || '') : '',
  4105. jump_target: action === 'jump' ? (document.getElementById('filter-modal-jumptarget')?.value || '') : '',
  4106. address_list: action.startsWith('add-') ? (document.getElementById('filter-modal-action-addrlist')?.value || '') : '',
  4107. address_list_timeout: action.startsWith('add-') ? (document.getElementById('filter-modal-action-timeout')?.value || '') : '',
  4108. log: document.getElementById('filter-modal-log')?.checked || false,
  4109. log_prefix: getFwFieldVal('logprefix', false)
  4110. };
  4111. try {
  4112. const res = await fetch(`${API_BASE}/firewall/filter`, {
  4113. method: 'POST',
  4114. headers: { 'Content-Type': 'application/json' },
  4115. body: JSON.stringify(payload)
  4116. });
  4117. if (res.ok) {
  4118. const data = await res.json();
  4119. showToast('Filter Rule Saved', 'Rule applied successfully to firewall', 'success');
  4120. loadFirewall(false);
  4121. if (closeAfter) {
  4122. closeFilterModal();
  4123. } else {
  4124. if (data.id) {
  4125. document.getElementById('filter-modal-id').value = data.id;
  4126. const badge = document.getElementById('fw-modal-badge');
  4127. if (badge) badge.innerText = `#${data.id}`;
  4128. }
  4129. }
  4130. } else {
  4131. const err = await res.json();
  4132. showToast('Error', err.message || 'Failed to save rule', 'error');
  4133. }
  4134. } catch (err) {
  4135. showToast('Error', err.message, 'error');
  4136. }
  4137. }
  4138. function submitSaveFilterRule(e) {
  4139. if (e && e.preventDefault) e.preventDefault();
  4140. return applyFilterRule(true);
  4141. }
  4142. function startFwStatPolling() {
  4143. stopFwStatPolling();
  4144. pollRuleStats();
  4145. state.fwStatInterval = setInterval(pollRuleStats, 1000);
  4146. }
  4147. function stopFwStatPolling() {
  4148. if (state.fwStatInterval) {
  4149. clearInterval(state.fwStatInterval);
  4150. state.fwStatInterval = null;
  4151. }
  4152. }
  4153. async function pollRuleStats() {
  4154. const id = document.getElementById('filter-modal-id')?.value;
  4155. if (!id) {
  4156. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory || new Array(30).fill(0), 'bps', 'fw-stat-legend-rate');
  4157. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory || new Array(30).fill(0), 'p/s', 'fw-stat-legend-pktrate');
  4158. return;
  4159. }
  4160. try {
  4161. const res = await fetch(`${API_BASE}/firewall/filter`);
  4162. if (!res.ok) return;
  4163. const rules = await res.json();
  4164. const r = rules.find(x => x.id === id);
  4165. if (!r) return;
  4166. const now = Date.now();
  4167. const dt = Math.max(0.2, (now - (state.fwLastTimestamp || now)) / 1000);
  4168. state.fwLastTimestamp = now;
  4169. const curBytes = r.bytes || 0;
  4170. const curPackets = r.packets || 0;
  4171. const deltaBytes = Math.max(0, curBytes - (state.fwLastBytes || curBytes));
  4172. const deltaPkts = Math.max(0, curPackets - (state.fwLastPackets || curPackets));
  4173. state.fwLastBytes = curBytes;
  4174. state.fwLastPackets = curPackets;
  4175. const rateBps = Math.round((deltaBytes * 8) / dt);
  4176. const ratePkt = Math.round(deltaPkts / dt);
  4177. if (!state.fwStatRateHistory) state.fwStatRateHistory = new Array(30).fill(0);
  4178. if (!state.fwStatPktHistory) state.fwStatPktHistory = new Array(30).fill(0);
  4179. state.fwStatRateHistory.push(rateBps);
  4180. if (state.fwStatRateHistory.length > 30) state.fwStatRateHistory.shift();
  4181. state.fwStatPktHistory.push(ratePkt);
  4182. if (state.fwStatPktHistory.length > 30) state.fwStatPktHistory.shift();
  4183. const bEl = document.getElementById('fw-stat-bytes');
  4184. const pEl = document.getElementById('fw-stat-packets');
  4185. const rEl = document.getElementById('fw-stat-rate');
  4186. const prEl = document.getElementById('fw-stat-pktrate');
  4187. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  4188. if (pEl) pEl.value = curPackets.toLocaleString();
  4189. if (rEl) rEl.value = formatBps(rateBps);
  4190. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  4191. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  4192. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  4193. } catch (e) {
  4194. console.error('Error polling rule stats', e);
  4195. }
  4196. }
  4197. function formatBps(bps) {
  4198. if (bps >= 1000000000) return (bps / 1000000000).toFixed(1) + ' Gbps';
  4199. if (bps >= 1000000) return (bps / 1000000).toFixed(1) + ' Mbps';
  4200. if (bps >= 1000) return (bps / 1000).toFixed(1) + ' kbps';
  4201. return bps + ' bps';
  4202. }
  4203. function renderFwSparkline(svgId, dataArray, unit, legendId) {
  4204. const svg = document.getElementById(svgId);
  4205. if (!svg) return;
  4206. const w = 500;
  4207. const h = 100;
  4208. const paddingRight = 45;
  4209. const graphWidth = w - paddingRight;
  4210. const maxVal = Math.max(5, ...dataArray);
  4211. const currentVal = dataArray[dataArray.length - 1] || 0;
  4212. const leg = document.getElementById(legendId);
  4213. if (leg) {
  4214. leg.innerText = unit === 'bps' ? formatBps(currentVal) : `${currentVal.toLocaleString()} p/s`;
  4215. }
  4216. let gridLines = '';
  4217. for (let i = 0; i <= 5; i++) {
  4218. const y = 8 + (i * (h - 18) / 5);
  4219. const valAtLevel = Math.round(maxVal * (5 - i) / 5);
  4220. const label = unit === 'bps' ? formatBps(valAtLevel) : `${valAtLevel} p/s`;
  4221. gridLines += `
  4222. <line x1="0" y1="${y.toFixed(1)}" x2="${graphWidth}" y2="${y.toFixed(1)}" stroke="#1e2c3e" stroke-width="1" />
  4223. <text x="${w - 2}" y="${(y + 3).toFixed(1)}" fill="#64748b" font-size="9" font-family="monospace" text-anchor="end">${label}</text>
  4224. `;
  4225. }
  4226. const step = graphWidth / (dataArray.length - 1);
  4227. const points = dataArray.map((val, idx) => {
  4228. const x = idx * step;
  4229. const y = (h - 10) - (val / maxVal) * (h - 20);
  4230. return `${x.toFixed(1)},${y.toFixed(1)}`;
  4231. });
  4232. const polylineStr = points.join(' ');
  4233. const areaPath = `M 0,${h - 10} L ${polylineStr} L ${graphWidth},${h - 10} Z`;
  4234. svg.innerHTML = `
  4235. ${gridLines}
  4236. <path d="${areaPath}" fill="rgba(14, 165, 233, 0.12)" />
  4237. <polyline fill="none" stroke="#38bdf8" stroke-width="1.8" stroke-linejoin="round" points="${polylineStr}" />
  4238. <circle cx="${graphWidth}" cy="${points[points.length - 1].split(',')[1]}" r="3" fill="#38bdf8" />
  4239. `;
  4240. }
  4241. async function moveFilterRule(id, dir) {
  4242. try {
  4243. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/move`, {
  4244. method: 'POST',
  4245. headers: { 'Content-Type': 'application/json' },
  4246. body: JSON.stringify({ direction: dir })
  4247. });
  4248. if (res.ok) loadFirewall(false);
  4249. } catch (err) {
  4250. showToast('Error', err.message, 'error');
  4251. }
  4252. }
  4253. async function toggleFilterRuleState(id, disabled) {
  4254. try {
  4255. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/state`, {
  4256. method: 'POST',
  4257. headers: { 'Content-Type': 'application/json' },
  4258. body: JSON.stringify({ disabled })
  4259. });
  4260. if (res.ok) loadFirewall(false);
  4261. } catch (err) {
  4262. showToast('Error', err.message, 'error');
  4263. }
  4264. }
  4265. async function deleteFilterRule(id) {
  4266. if (!confirm('Are you sure you want to delete this filter rule?')) return;
  4267. try {
  4268. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4269. if (res.ok) {
  4270. showToast('Deleted', 'Filter rule removed', 'success');
  4271. loadFirewall(false);
  4272. }
  4273. } catch (err) {
  4274. showToast('Error', err.message, 'error');
  4275. }
  4276. }
  4277. // ----------------- NAT Rules -----------------
  4278. function renderNATRules() {
  4279. const chainFilter = document.getElementById('nat-filter-chain')?.value || '';
  4280. const tbody = document.getElementById('nat-table-body');
  4281. const empty = document.getElementById('nat-empty');
  4282. if (!tbody) return;
  4283. tbody.innerHTML = '';
  4284. const rules = (state.natRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  4285. document.getElementById('nat-count-badge').innerText = `${rules.length} Rules`;
  4286. if (rules.length === 0) {
  4287. empty?.classList.remove('hidden');
  4288. return;
  4289. }
  4290. empty?.classList.add('hidden');
  4291. rules.forEach((r, idx) => {
  4292. const tr = document.createElement('tr');
  4293. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  4294. let toTarget = '-';
  4295. if (r.action === 'jump') {
  4296. toTarget = `<span class="text-yellow-300 font-mono font-bold">&rarr; ${r.jump_target || '-'}</span>`;
  4297. } else if (r.action.includes('address-list') || r.action.includes('address list')) {
  4298. toTarget = `<span class="text-emerald-300 font-mono font-bold">&rarr; ${r.address_list || '-'}</span>`;
  4299. } else if (r.action === 'redirect') {
  4300. toTarget = `<span class="text-amber-300 font-mono font-bold">ports:${r.to_ports || 'all'}</span>`;
  4301. } else if (r.action === 'masquerade') {
  4302. 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>`;
  4303. } else if (r.action === 'log') {
  4304. toTarget = `<span class="text-slate-400 font-mono font-bold">${r.log_prefix || 'log'}</span>`;
  4305. } else {
  4306. const parts = [r.to_addresses, r.to_ports].filter(Boolean);
  4307. toTarget = parts.length ? `<span class="text-amber-300 font-mono font-bold">${parts.join(':')}</span>` : '-';
  4308. }
  4309. const ifaces = [r.out_interface ? 'out:' + r.out_interface : '', r.in_interface ? 'in:' + r.in_interface : ''].filter(Boolean).join(' ');
  4310. tr.innerHTML = `
  4311. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  4312. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  4313. <td class="py-2.5 px-3 font-bold text-amber-400">${r.chain}</td>
  4314. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  4315. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  4316. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}${r.dst_port ? ':' + r.dst_port : ''}</td>
  4317. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  4318. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  4319. <td class="py-2.5 px-3 font-mono text-xs">${toTarget}</td>
  4320. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  4321. <span class="text-slate-300" id="nat-pkts-${r.id}">${(r.packets || 0).toLocaleString()}p</span> /
  4322. <span class="text-slate-500" id="nat-bytes-${r.id}">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  4323. </td>
  4324. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  4325. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  4326. <button onclick="moveNATRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  4327. <button onclick="moveNATRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  4328. <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>
  4329. <button onclick="openEditNATModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  4330. <button onclick="deleteNATRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  4331. </td>
  4332. `;
  4333. tbody.appendChild(tr);
  4334. });
  4335. }
  4336. // ==================== FIREWALL NAT MODAL (DEBTIK WEBFIG / WINBOX V4) ====================
  4337. function switchNATRuleTab(tab) {
  4338. state.activeNATRuleTab = tab;
  4339. document.querySelectorAll('.nat-rule-tab-btn').forEach(btn => {
  4340. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  4341. btn.classList.add('text-slate-400', 'border-transparent');
  4342. });
  4343. const activeBtn = document.getElementById(`nat-tab-btn-${tab}`);
  4344. if (activeBtn) {
  4345. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  4346. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  4347. }
  4348. document.querySelectorAll('.nat-rule-pane').forEach(p => p.classList.add('hidden'));
  4349. const activePane = document.getElementById(`nat-pane-${tab}`);
  4350. if (activePane) activePane.classList.remove('hidden');
  4351. if (tab === 'statistics') {
  4352. startNATStatPolling();
  4353. } else {
  4354. stopNATStatPolling();
  4355. }
  4356. }
  4357. function toggleNATField(fieldKey, expand) {
  4358. const plusBtn = document.getElementById(`nat-plus-${fieldKey}`);
  4359. const fieldBox = document.getElementById(`nat-field-${fieldKey}`);
  4360. if (!plusBtn || !fieldBox) return;
  4361. if (expand) {
  4362. plusBtn.classList.add('hidden');
  4363. fieldBox.classList.remove('hidden');
  4364. const valInput = document.getElementById(`nat-val-${fieldKey}`);
  4365. if (valInput) valInput.focus();
  4366. } else {
  4367. fieldBox.classList.add('hidden');
  4368. plusBtn.classList.remove('hidden');
  4369. const valInput = document.getElementById(`nat-val-${fieldKey}`);
  4370. if (valInput) {
  4371. if (valInput.tagName === 'SELECT') {
  4372. valInput.selectedIndex = 0;
  4373. } else {
  4374. valInput.value = '';
  4375. }
  4376. }
  4377. const invInput = document.getElementById(`nat-inv-${fieldKey}`);
  4378. if (invInput) invInput.checked = false;
  4379. if (fieldKey === 'days') {
  4380. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  4381. const el = document.getElementById(`nat-day-${d}`);
  4382. if (el) el.checked = true;
  4383. });
  4384. }
  4385. }
  4386. }
  4387. function setNATFieldVal(fieldKey, value, hasInvert = false) {
  4388. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  4389. toggleNATField(fieldKey, true);
  4390. let strVal = String(value);
  4391. if (hasInvert) {
  4392. const inv = strVal.startsWith('!');
  4393. if (inv) strVal = strVal.slice(1);
  4394. const invEl = document.getElementById(`nat-inv-${fieldKey}`);
  4395. if (invEl) invEl.checked = inv;
  4396. }
  4397. const valEl = document.getElementById(`nat-val-${fieldKey}`);
  4398. if (valEl) valEl.value = strVal;
  4399. } else {
  4400. toggleNATField(fieldKey, false);
  4401. }
  4402. }
  4403. function getNATFieldVal(fieldKey, hasInvert = false) {
  4404. const fieldBox = document.getElementById(`nat-field-${fieldKey}`);
  4405. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  4406. const valEl = document.getElementById(`nat-val-${fieldKey}`);
  4407. let v = valEl ? valEl.value.trim() : '';
  4408. if (!v) return '';
  4409. if (hasInvert) {
  4410. const invEl = document.getElementById(`nat-inv-${fieldKey}`);
  4411. if (invEl && invEl.checked) {
  4412. v = '!' + v.replace(/^!/, '');
  4413. }
  4414. }
  4415. return v;
  4416. }
  4417. function toggleMaximizeNATModal() {
  4418. const win = document.getElementById('nat-modal-window');
  4419. if (!win) return;
  4420. if (win.classList.contains('max-w-[720px]')) {
  4421. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  4422. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  4423. } else {
  4424. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  4425. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  4426. }
  4427. }
  4428. function handleNATChainChange() {
  4429. const ch = document.getElementById('nat-modal-chain')?.value || 'srcnat';
  4430. const actSel = document.getElementById('nat-modal-action');
  4431. if (actSel) {
  4432. if (ch === 'srcnat' && (actSel.value === 'dst-nat' || actSel.value === 'redirect')) {
  4433. actSel.value = 'masquerade';
  4434. } else if (ch === 'dstnat' && (actSel.value === 'masquerade' || actSel.value === 'src-nat')) {
  4435. actSel.value = 'dst-nat';
  4436. }
  4437. }
  4438. toggleNATActionFields();
  4439. }
  4440. function toggleNATActionFields() {
  4441. const act = document.getElementById('nat-modal-action')?.value || 'masquerade';
  4442. const rowAddr = document.getElementById('nat-row-toaddr');
  4443. const rowPort = document.getElementById('nat-row-toport');
  4444. const jumpBox = document.getElementById('nat-action-jump-box');
  4445. const addrBox = document.getElementById('nat-action-addrlist-box');
  4446. // Hide all dynamic rows first
  4447. if (rowAddr) rowAddr.classList.add('hidden');
  4448. if (rowPort) rowPort.classList.add('hidden');
  4449. if (jumpBox) jumpBox.classList.add('hidden');
  4450. if (addrBox) addrBox.classList.add('hidden');
  4451. if (['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat'].includes(act)) {
  4452. if (rowAddr) rowAddr.classList.remove('hidden');
  4453. if (rowPort) rowPort.classList.remove('hidden');
  4454. } else if (act === 'redirect' || act === 'masquerade') {
  4455. if (rowPort) rowPort.classList.remove('hidden');
  4456. } else if (act === 'jump') {
  4457. if (jumpBox) jumpBox.classList.remove('hidden');
  4458. } else if (act.includes('address-list') || act.includes('address list')) {
  4459. if (addrBox) addrBox.classList.remove('hidden');
  4460. }
  4461. if (act === 'log') {
  4462. const logEl = document.getElementById('nat-modal-log');
  4463. if (logEl) logEl.checked = true;
  4464. toggleNATField('logprefix', true);
  4465. }
  4466. }
  4467. function toggleNATLogPrefix() {
  4468. const isLog = document.getElementById('nat-modal-log')?.checked;
  4469. toggleNATField('logprefix', !!isLog);
  4470. }
  4471. function openAddNATModal() {
  4472. switchNATRuleTab('general');
  4473. const badge = document.getElementById('nat-modal-badge');
  4474. if (badge) badge.innerText = 'New...';
  4475. document.getElementById('nat-modal-id').value = '';
  4476. document.getElementById('nat-modal-enabled').checked = true;
  4477. document.getElementById('nat-modal-comment').value = '';
  4478. document.getElementById('nat-modal-chain').value = 'srcnat';
  4479. document.getElementById('nat-modal-action').value = 'masquerade';
  4480. document.getElementById('nat-modal-toaddr').value = '';
  4481. document.getElementById('nat-modal-toport').value = '';
  4482. document.getElementById('nat-modal-log').checked = false;
  4483. populateInterfaceSelect('nat-val-iniface');
  4484. populateInterfaceSelect('nat-val-outiface');
  4485. populateAddressListSelect('nat-val-srclist');
  4486. populateAddressListSelect('nat-val-dstlist');
  4487. populateGeoIPSelect('nat-val-srcgeo');
  4488. populateGeoIPSelect('nat-val-dstgeo');
  4489. const allFieldKeys = [
  4490. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  4491. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  4492. 'routingmark', 'conntype',
  4493. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  4494. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  4495. 'ipsec', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  4496. 'pktsize', 'random', 'icmpoptions', 'ipv4options', 'ttl',
  4497. 'time', 'days', 'limit', 'dstlimit', 'psd', 'logprefix'
  4498. ];
  4499. allFieldKeys.forEach(k => toggleNATField(k, false));
  4500. resetCurrentNATRuleCounters();
  4501. toggleNATActionFields();
  4502. document.getElementById('nat-modal').classList.remove('hidden');
  4503. }
  4504. function openEditNATModal(id) {
  4505. const r = (state.natRules || []).find(rule => rule.id === id);
  4506. if (!r) return;
  4507. switchNATRuleTab('general');
  4508. const badge = document.getElementById('nat-modal-badge');
  4509. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  4510. document.getElementById('nat-modal-id').value = r.id;
  4511. document.getElementById('nat-modal-enabled').checked = !r.disabled;
  4512. document.getElementById('nat-modal-comment').value = r.comment || '';
  4513. document.getElementById('nat-modal-chain').value = r.chain || 'srcnat';
  4514. document.getElementById('nat-modal-action').value = r.action || 'masquerade';
  4515. document.getElementById('nat-modal-toaddr').value = r.to_addresses || '';
  4516. document.getElementById('nat-modal-toport').value = r.to_ports || '';
  4517. document.getElementById('nat-modal-log').checked = !!r.log;
  4518. populateInterfaceSelect('nat-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  4519. populateInterfaceSelect('nat-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  4520. populateAddressListSelect('nat-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  4521. populateAddressListSelect('nat-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  4522. populateGeoIPSelect('nat-val-srcgeo', r.src_geoip || '');
  4523. populateGeoIPSelect('nat-val-dstgeo', r.dst_geoip || '');
  4524. setNATFieldVal('src', r.src_address, true);
  4525. setNATFieldVal('dst', r.dst_address, true);
  4526. setNATFieldVal('srclist', r.src_address_list, true);
  4527. setNATFieldVal('dstlist', r.dst_address_list, true);
  4528. setNATFieldVal('srcgeo', r.src_geoip, true);
  4529. setNATFieldVal('dstgeo', r.dst_geoip, true);
  4530. if (r.protocol && r.protocol !== 'all') {
  4531. setNATFieldVal('proto', r.protocol, true);
  4532. } else {
  4533. toggleNATField('proto', false);
  4534. }
  4535. setNATFieldVal('sport', r.src_port, true);
  4536. setNATFieldVal('dport', r.dst_port, true);
  4537. setNATFieldVal('anyport', r.any_port, true);
  4538. setNATFieldVal('iniface', r.in_interface, true);
  4539. setNATFieldVal('outiface', r.out_interface, true);
  4540. setNATFieldVal('inifacelist', r.in_interface_list, true);
  4541. setNATFieldVal('outifacelist', r.out_interface_list, true);
  4542. setNATFieldVal('pktmark', r.packet_mark, true);
  4543. setNATFieldVal('connmark', r.connection_mark, true);
  4544. setNATFieldVal('routingmark', r.routing_mark, true);
  4545. setNATFieldVal('conntype', r.connection_type, false);
  4546. // Advanced tab fields
  4547. setNATFieldVal('layer7', r.layer7_protocol, false);
  4548. setNATFieldVal('content', r.content, false);
  4549. setNATFieldVal('connbytes', r.connection_bytes, false);
  4550. setNATFieldVal('connrate', r.connection_rate, false);
  4551. setNATFieldVal('pcc', r.pcc, false);
  4552. setNATFieldVal('srcmac', r.src_mac_address, true);
  4553. setNATFieldVal('outbridgeport', r.out_bridge_port, false);
  4554. setNATFieldVal('inbridgeport', r.in_bridge_port, false);
  4555. setNATFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  4556. setNATFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  4557. setNATFieldVal('ipsec', r.ipsec_policy, false);
  4558. setNATFieldVal('ingresspriority', r.ingress_priority, false);
  4559. setNATFieldVal('priority', r.priority, false);
  4560. setNATFieldVal('dscp', r.dscp, false);
  4561. setNATFieldVal('tcpmss', r.tcp_mss, false);
  4562. if (r.tos) {
  4563. const tosEl = document.getElementById('nat-val-tos');
  4564. if (tosEl) tosEl.value = r.tos;
  4565. }
  4566. setNATFieldVal('pktsize', r.packet_size, false);
  4567. setNATFieldVal('random', r.random, false);
  4568. setNATFieldVal('icmpoptions', r.icmp_options, false);
  4569. setNATFieldVal('ipv4options', r.ipv4_options, false);
  4570. setNATFieldVal('ttl', r.ttl, false);
  4571. // Extra tab fields
  4572. setNATFieldVal('time', r.time, false);
  4573. if (r.days) {
  4574. toggleNATField('days', true);
  4575. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  4576. const chk = document.getElementById(`nat-day-${d}`);
  4577. if (chk) chk.checked = r.days.includes(d);
  4578. });
  4579. } else {
  4580. toggleNATField('days', false);
  4581. }
  4582. setNATFieldVal('limit', r.limit, false);
  4583. setNATFieldVal('dstlimit', r.dst_limit, false);
  4584. setNATFieldVal('psd', r.psd, false);
  4585. // Action fields
  4586. if (r.jump_target) {
  4587. const jtEl = document.getElementById('nat-modal-jumptarget');
  4588. if (jtEl) jtEl.value = r.jump_target;
  4589. }
  4590. if (r.address_list) {
  4591. const alEl = document.getElementById('nat-modal-action-addrlist');
  4592. if (alEl) alEl.value = r.address_list;
  4593. }
  4594. if (r.address_list_timeout) {
  4595. const toEl = document.getElementById('nat-modal-action-timeout');
  4596. if (toEl) toEl.value = r.address_list_timeout;
  4597. }
  4598. setNATFieldVal('logprefix', r.log_prefix, false);
  4599. // Statistics
  4600. const bEl = document.getElementById('nat-stat-bytes');
  4601. const pEl = document.getElementById('nat-stat-packets');
  4602. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  4603. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  4604. state.natLastBytes = r.bytes || 0;
  4605. state.natLastPackets = r.packets || 0;
  4606. state.natLastTimestamp = Date.now();
  4607. state.natStatRateHistory = new Array(30).fill(0);
  4608. state.natStatPktHistory = new Array(30).fill(0);
  4609. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  4610. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  4611. toggleNATActionFields();
  4612. document.getElementById('nat-modal').classList.remove('hidden');
  4613. }
  4614. function closeNATModal() {
  4615. stopNATStatPolling();
  4616. document.getElementById('nat-modal').classList.add('hidden');
  4617. }
  4618. function copyNATRule() {
  4619. document.getElementById('nat-modal-id').value = '';
  4620. const badge = document.getElementById('nat-modal-badge');
  4621. if (badge) badge.innerText = 'New...';
  4622. showToast('Rule Cloned', 'Ready to save as a new NAT rule copy', 'info');
  4623. }
  4624. function resetCurrentNATRuleCounters() {
  4625. state.natStatRateHistory = new Array(30).fill(0);
  4626. state.natStatPktHistory = new Array(30).fill(0);
  4627. state.natLastBytes = 0;
  4628. state.natLastPackets = 0;
  4629. state.natLastTimestamp = Date.now();
  4630. const bEl = document.getElementById('nat-stat-bytes');
  4631. const pEl = document.getElementById('nat-stat-packets');
  4632. const rEl = document.getElementById('nat-stat-rate');
  4633. const prEl = document.getElementById('nat-stat-pktrate');
  4634. if (bEl) bEl.value = '0 B';
  4635. if (pEl) pEl.value = '0';
  4636. if (rEl) rEl.value = '0 bps';
  4637. if (prEl) prEl.value = '0 p/s';
  4638. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  4639. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  4640. showToast('Counters Reset', 'NAT rule counter display reset to 0', 'info');
  4641. }
  4642. async function applyNATRule(closeAfter = false) {
  4643. const id = document.getElementById('nat-modal-id').value;
  4644. const chain = document.getElementById('nat-modal-chain').value;
  4645. const action = document.getElementById('nat-modal-action').value;
  4646. const comment = document.getElementById('nat-modal-comment').value.trim();
  4647. const enabled = document.getElementById('nat-modal-enabled').checked;
  4648. const src = getNATFieldVal('src', true);
  4649. const dst = getNATFieldVal('dst', true);
  4650. const srclist = getNATFieldVal('srclist', true);
  4651. const dstlist = getNATFieldVal('dstlist', true);
  4652. const srcgeo = getNATFieldVal('srcgeo', true);
  4653. const dstgeo = getNATFieldVal('dstgeo', true);
  4654. const proto = getNATFieldVal('proto', true);
  4655. const sport = getNATFieldVal('sport', true);
  4656. const dport = getNATFieldVal('dport', true);
  4657. const anyport = getNATFieldVal('anyport', true);
  4658. const iniface = getNATFieldVal('iniface', true);
  4659. const outiface = getNATFieldVal('outiface', true);
  4660. const inifacelist = getNATFieldVal('inifacelist', true);
  4661. const outifacelist = getNATFieldVal('outifacelist', true);
  4662. const pktmark = getNATFieldVal('pktmark', true);
  4663. const connmark = getNATFieldVal('connmark', true);
  4664. const routingmark = getNATFieldVal('routingmark', true);
  4665. const conntype = getNATFieldVal('conntype', false);
  4666. const usesAddr = ['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat'].includes(action);
  4667. const usesPort = ['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat', 'redirect', 'masquerade'].includes(action);
  4668. const payload = {
  4669. id,
  4670. chain,
  4671. action,
  4672. to_addresses: usesAddr ? (document.getElementById('nat-modal-toaddr')?.value.trim() || '') : '',
  4673. to_ports: usesPort ? (document.getElementById('nat-modal-toport')?.value.trim() || '') : '',
  4674. protocol: proto || 'all',
  4675. src_address: src,
  4676. dst_address: dst,
  4677. src_port: sport,
  4678. dst_port: dport,
  4679. any_port: anyport,
  4680. in_interface: iniface,
  4681. out_interface: outiface,
  4682. in_interface_list: inifacelist,
  4683. out_interface_list: outifacelist,
  4684. packet_mark: pktmark,
  4685. connection_mark: connmark,
  4686. routing_mark: routingmark,
  4687. connection_type: conntype,
  4688. src_address_list: srclist,
  4689. dst_address_list: dstlist,
  4690. src_geoip: srcgeo,
  4691. dst_geoip: dstgeo,
  4692. comment,
  4693. disabled: !enabled,
  4694. // Advanced tab
  4695. layer7_protocol: getNATFieldVal('layer7', false),
  4696. content: getNATFieldVal('content', false),
  4697. connection_bytes: getNATFieldVal('connbytes', false),
  4698. connection_rate: getNATFieldVal('connrate', false),
  4699. pcc: getNATFieldVal('pcc', false),
  4700. src_mac_address: getNATFieldVal('srcmac', true),
  4701. out_bridge_port: getNATFieldVal('outbridgeport', false),
  4702. in_bridge_port: getNATFieldVal('inbridgeport', false),
  4703. in_bridge_port_list: getNATFieldVal('inbridgeportlist', false),
  4704. out_bridge_port_list: getNATFieldVal('outbridgeportlist', false),
  4705. ipsec_policy: getNATFieldVal('ipsec', false),
  4706. ingress_priority: getNATFieldVal('ingresspriority', false),
  4707. priority: getNATFieldVal('priority', false),
  4708. dscp: getNATFieldVal('dscp', false),
  4709. tcp_mss: getNATFieldVal('tcpmss', false),
  4710. tos: document.getElementById('nat-val-tos')?.value || '',
  4711. packet_size: getNATFieldVal('pktsize', false),
  4712. random: getNATFieldVal('random', false),
  4713. icmp_options: getNATFieldVal('icmpoptions', false),
  4714. ipv4_options: getNATFieldVal('ipv4options', false),
  4715. ttl: getNATFieldVal('ttl', false),
  4716. // Extra tab
  4717. time: getNATFieldVal('time', false),
  4718. limit: getNATFieldVal('limit', false),
  4719. dst_limit: getNATFieldVal('dstlimit', false),
  4720. psd: getNATFieldVal('psd', false),
  4721. // Action tab
  4722. jump_target: action === 'jump' ? (document.getElementById('nat-modal-jumptarget')?.value || '') : '',
  4723. address_list: action.includes('address') ? (document.getElementById('nat-modal-action-addrlist')?.value || '') : '',
  4724. address_list_timeout: action.includes('address') ? (document.getElementById('nat-modal-action-timeout')?.value || '') : '',
  4725. log: document.getElementById('nat-modal-log')?.checked || false,
  4726. log_prefix: getNATFieldVal('logprefix', false)
  4727. };
  4728. try {
  4729. const res = await fetch(`${API_BASE}/firewall/nat`, {
  4730. method: 'POST',
  4731. headers: { 'Content-Type': 'application/json' },
  4732. body: JSON.stringify(payload)
  4733. });
  4734. if (res.ok) {
  4735. const data = await res.json();
  4736. showToast('NAT Rule Saved', 'NAT mapping updated', 'success');
  4737. loadFirewall(false);
  4738. if (closeAfter) {
  4739. closeNATModal();
  4740. } else {
  4741. if (data.id) {
  4742. document.getElementById('nat-modal-id').value = data.id;
  4743. const badge = document.getElementById('nat-modal-badge');
  4744. if (badge) badge.innerText = `#${data.id}`;
  4745. }
  4746. }
  4747. } else {
  4748. const err = await res.json();
  4749. showToast('Error', err.message || 'Failed to save rule', 'error');
  4750. }
  4751. } catch (err) {
  4752. showToast('Error', err.message, 'error');
  4753. }
  4754. }
  4755. function submitSaveNATRule(e) {
  4756. if (e && e.preventDefault) e.preventDefault();
  4757. return applyNATRule(true);
  4758. }
  4759. function startNATStatPolling() {
  4760. stopNATStatPolling();
  4761. pollNATRuleStats();
  4762. state.natStatInterval = setInterval(pollNATRuleStats, 1000);
  4763. }
  4764. function stopNATStatPolling() {
  4765. if (state.natStatInterval) {
  4766. clearInterval(state.natStatInterval);
  4767. state.natStatInterval = null;
  4768. }
  4769. }
  4770. async function pollNATRuleStats() {
  4771. const id = document.getElementById('nat-modal-id')?.value;
  4772. if (!id) {
  4773. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory || new Array(30).fill(0), 'bps', 'nat-stat-legend-rate');
  4774. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory || new Array(30).fill(0), 'p/s', 'nat-stat-legend-pktrate');
  4775. return;
  4776. }
  4777. try {
  4778. const res = await fetch(`${API_BASE}/firewall/nat`);
  4779. if (!res.ok) return;
  4780. const rules = await res.json();
  4781. const r = rules.find(x => x.id === id);
  4782. if (!r) return;
  4783. const now = Date.now();
  4784. const dt = Math.max(0.2, (now - (state.natLastTimestamp || now)) / 1000);
  4785. state.natLastTimestamp = now;
  4786. const curBytes = r.bytes || 0;
  4787. const curPackets = r.packets || 0;
  4788. const deltaBytes = Math.max(0, curBytes - (state.natLastBytes || curBytes));
  4789. const deltaPkts = Math.max(0, curPackets - (state.natLastPackets || curPackets));
  4790. state.natLastBytes = curBytes;
  4791. state.natLastPackets = curPackets;
  4792. const rateBps = Math.round((deltaBytes * 8) / dt);
  4793. const ratePkt = Math.round(deltaPkts / dt);
  4794. if (!state.natStatRateHistory) state.natStatRateHistory = new Array(30).fill(0);
  4795. if (!state.natStatPktHistory) state.natStatPktHistory = new Array(30).fill(0);
  4796. state.natStatRateHistory.push(rateBps);
  4797. if (state.natStatRateHistory.length > 30) state.natStatRateHistory.shift();
  4798. state.natStatPktHistory.push(ratePkt);
  4799. if (state.natStatPktHistory.length > 30) state.natStatPktHistory.shift();
  4800. const bEl = document.getElementById('nat-stat-bytes');
  4801. const pEl = document.getElementById('nat-stat-packets');
  4802. const rEl = document.getElementById('nat-stat-rate');
  4803. const prEl = document.getElementById('nat-stat-pktrate');
  4804. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  4805. if (pEl) pEl.value = curPackets.toLocaleString();
  4806. if (rEl) rEl.value = formatBps(rateBps);
  4807. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  4808. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  4809. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  4810. } catch (e) {
  4811. console.error('Error polling NAT rule stats', e);
  4812. }
  4813. }
  4814. async function moveNATRule(id, dir) {
  4815. try {
  4816. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/move`, {
  4817. method: 'POST',
  4818. headers: { 'Content-Type': 'application/json' },
  4819. body: JSON.stringify({ direction: dir })
  4820. });
  4821. if (res.ok) loadFirewall(false);
  4822. } catch (err) {
  4823. showToast('Error', err.message, 'error');
  4824. }
  4825. }
  4826. async function toggleNATRuleState(id, disabled) {
  4827. try {
  4828. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/state`, {
  4829. method: 'POST',
  4830. headers: { 'Content-Type': 'application/json' },
  4831. body: JSON.stringify({ disabled })
  4832. });
  4833. if (res.ok) loadFirewall(false);
  4834. } catch (err) {
  4835. showToast('Error', err.message, 'error');
  4836. }
  4837. }
  4838. async function deleteNATRule(id) {
  4839. if (!confirm('Are you sure you want to delete this NAT rule?')) return;
  4840. try {
  4841. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4842. if (res.ok) {
  4843. showToast('Deleted', 'NAT rule removed', 'success');
  4844. loadFirewall(false);
  4845. }
  4846. } catch (err) {
  4847. showToast('Error', err.message, 'error');
  4848. }
  4849. }
  4850. // ----------------- Mangle Rules -----------------
  4851. function renderMangleRules() {
  4852. const chainFilter = document.getElementById('mangle-filter-chain')?.value || '';
  4853. const tbody = document.getElementById('mangle-table-body');
  4854. const empty = document.getElementById('mangle-empty');
  4855. if (!tbody) return;
  4856. tbody.innerHTML = '';
  4857. const rules = (state.mangleRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  4858. document.getElementById('mangle-count-badge').innerText = `${rules.length} Rules`;
  4859. if (rules.length === 0) {
  4860. empty?.classList.remove('hidden');
  4861. return;
  4862. }
  4863. empty?.classList.add('hidden');
  4864. rules.forEach((r, idx) => {
  4865. const tr = document.createElement('tr');
  4866. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  4867. let markVal = '<span class="text-slate-500">-</span>';
  4868. if (r.new_connection_mark) markVal = `<span class="text-cyan-300 font-mono font-bold">${r.new_connection_mark}</span>`;
  4869. else if (r.new_routing_mark) markVal = `<span class="text-amber-300 font-mono font-bold">${r.new_routing_mark}</span>`;
  4870. else if (r.new_packet_mark) markVal = `<span class="text-emerald-300 font-mono font-bold">${r.new_packet_mark}</span>`;
  4871. else if (r.new_mss) markVal = `<span class="text-sky-300 font-mono font-bold">mss:${r.new_mss}</span>`;
  4872. else if (r.new_dscp) markVal = `<span class="text-purple-300 font-mono font-bold">dscp:${r.new_dscp}</span>`;
  4873. else if (r.new_ttl) markVal = `<span class="text-blue-300 font-mono font-bold">ttl:${r.new_ttl}</span>`;
  4874. else if (r.new_priority) markVal = `<span class="text-indigo-300 font-mono font-bold">prio:${r.new_priority}</span>`;
  4875. else if (r.route) markVal = `<span class="text-orange-300 font-mono font-bold">route:${r.route}</span>`;
  4876. else if (r.sniff_target) markVal = `<span class="text-pink-300 font-mono font-bold">sniff:${r.sniff_target}</span>`;
  4877. else if (r.action === 'jump') markVal = `<span class="text-yellow-300 font-mono font-bold">&rarr; ${r.jump_target || '-'}</span>`;
  4878. 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>`;
  4879. else if (r.action === 'log') markVal = `<span class="text-slate-400 font-mono font-bold">${r.log_prefix || 'log'}</span>`;
  4880. tr.innerHTML = `
  4881. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  4882. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  4883. <td class="py-2.5 px-3 font-bold text-purple-400">${r.chain}</td>
  4884. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  4885. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  4886. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  4887. <td class="py-2.5 px-3 font-mono text-xs">${markVal}</td>
  4888. <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>
  4889. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  4890. <span class="text-slate-300" id="mangle-pkts-${r.id}">${(r.packets || 0).toLocaleString()}p</span> /
  4891. <span class="text-slate-500" id="mangle-bytes-${r.id}">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  4892. </td>
  4893. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  4894. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  4895. <button onclick="moveMangleRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  4896. <button onclick="moveMangleRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  4897. <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>
  4898. <button onclick="openEditMangleModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  4899. <button onclick="deleteMangleRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  4900. </td>
  4901. `;
  4902. tbody.appendChild(tr);
  4903. });
  4904. }
  4905. // ==================== FIREWALL MANGLE MODAL (DEBTIK WEBFIG / WINBOX V4) ====================
  4906. function switchMangleRuleTab(tab) {
  4907. state.activeMangleRuleTab = tab;
  4908. document.querySelectorAll('.mangle-rule-tab-btn').forEach(btn => {
  4909. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  4910. btn.classList.add('text-slate-400', 'border-transparent');
  4911. });
  4912. const activeBtn = document.getElementById(`mangle-tab-btn-${tab}`);
  4913. if (activeBtn) {
  4914. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  4915. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  4916. }
  4917. document.querySelectorAll('.mangle-rule-pane').forEach(p => p.classList.add('hidden'));
  4918. const activePane = document.getElementById(`mangle-pane-${tab}`);
  4919. if (activePane) activePane.classList.remove('hidden');
  4920. if (tab === 'statistics') {
  4921. startMangleStatPolling();
  4922. } else {
  4923. stopMangleStatPolling();
  4924. }
  4925. }
  4926. function toggleMangleField(fieldKey, expand) {
  4927. const plusBtn = document.getElementById(`mangle-plus-${fieldKey}`);
  4928. const fieldBox = document.getElementById(`mangle-field-${fieldKey}`);
  4929. if (!plusBtn || !fieldBox) return;
  4930. if (expand) {
  4931. plusBtn.classList.add('hidden');
  4932. fieldBox.classList.remove('hidden');
  4933. const valInput = document.getElementById(`mangle-val-${fieldKey}`);
  4934. if (valInput) valInput.focus();
  4935. } else {
  4936. fieldBox.classList.add('hidden');
  4937. plusBtn.classList.remove('hidden');
  4938. const valInput = document.getElementById(`mangle-val-${fieldKey}`);
  4939. if (valInput) {
  4940. if (valInput.tagName === 'SELECT') {
  4941. valInput.selectedIndex = 0;
  4942. } else {
  4943. valInput.value = '';
  4944. }
  4945. }
  4946. const invInput = document.getElementById(`mangle-inv-${fieldKey}`);
  4947. if (invInput) invInput.checked = false;
  4948. if (fieldKey === 'cs') {
  4949. ['mangle-modal-cs-established', 'mangle-modal-cs-related', 'mangle-modal-cs-new', 'mangle-modal-cs-invalid', 'mangle-modal-cs-untracked'].forEach(id => {
  4950. const el = document.getElementById(id);
  4951. if (el) el.checked = false;
  4952. });
  4953. }
  4954. if (fieldKey === 'natstate') {
  4955. ['mangle-modal-nat-srcnat', 'mangle-modal-nat-dstnat'].forEach(id => {
  4956. const el = document.getElementById(id);
  4957. if (el) el.checked = false;
  4958. });
  4959. }
  4960. }
  4961. }
  4962. function setMangleFieldVal(fieldKey, value, hasInvert = false) {
  4963. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  4964. toggleMangleField(fieldKey, true);
  4965. let strVal = String(value);
  4966. if (hasInvert) {
  4967. const inv = strVal.startsWith('!');
  4968. if (inv) strVal = strVal.slice(1);
  4969. const invEl = document.getElementById(`mangle-inv-${fieldKey}`);
  4970. if (invEl) invEl.checked = inv;
  4971. }
  4972. const valEl = document.getElementById(`mangle-val-${fieldKey}`);
  4973. if (valEl) valEl.value = strVal;
  4974. } else {
  4975. toggleMangleField(fieldKey, false);
  4976. }
  4977. }
  4978. function getMangleFieldVal(fieldKey, hasInvert = false) {
  4979. const fieldBox = document.getElementById(`mangle-field-${fieldKey}`);
  4980. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  4981. const valEl = document.getElementById(`mangle-val-${fieldKey}`);
  4982. let v = valEl ? valEl.value.trim() : '';
  4983. if (!v) return '';
  4984. if (hasInvert) {
  4985. const invEl = document.getElementById(`mangle-inv-${fieldKey}`);
  4986. if (invEl && invEl.checked) {
  4987. v = '!' + v.replace(/^!/, '');
  4988. }
  4989. }
  4990. return v;
  4991. }
  4992. function toggleMaximizeMangleModal() {
  4993. const win = document.getElementById('mangle-modal-window');
  4994. if (!win) return;
  4995. if (win.classList.contains('max-w-[720px]')) {
  4996. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  4997. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  4998. } else {
  4999. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  5000. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  5001. }
  5002. }
  5003. function toggleMangleActionFields() {
  5004. const act = document.getElementById('mangle-modal-action')?.value || 'mark-connection';
  5005. // Hide all dynamic rows first
  5006. ['newconnmark', 'newroutingmark', 'newpktmark', 'newmss', 'newdscp', 'newttl', 'newpriority', 'route', 'sniff', 'passthrough'].forEach(id => {
  5007. const el = document.getElementById(`mangle-row-${id}`);
  5008. if (el) el.classList.add('hidden');
  5009. });
  5010. const jumpBox = document.getElementById('mangle-action-jump-box');
  5011. const addrBox = document.getElementById('mangle-action-addrlist-box');
  5012. if (jumpBox) jumpBox.classList.add('hidden');
  5013. if (addrBox) addrBox.classList.add('hidden');
  5014. // Activate matching rows
  5015. if (act === 'mark-connection') {
  5016. document.getElementById('mangle-row-newconnmark')?.classList.remove('hidden');
  5017. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5018. } else if (act === 'mark-routing') {
  5019. document.getElementById('mangle-row-newroutingmark')?.classList.remove('hidden');
  5020. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5021. } else if (act === 'mark-packet') {
  5022. document.getElementById('mangle-row-newpktmark')?.classList.remove('hidden');
  5023. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5024. } else if (act === 'change-mss') {
  5025. document.getElementById('mangle-row-newmss')?.classList.remove('hidden');
  5026. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5027. } else if (act === 'change-dscp') {
  5028. document.getElementById('mangle-row-newdscp')?.classList.remove('hidden');
  5029. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5030. } else if (act === 'change-ttl') {
  5031. document.getElementById('mangle-row-newttl')?.classList.remove('hidden');
  5032. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5033. } else if (act === 'set-priority') {
  5034. document.getElementById('mangle-row-newpriority')?.classList.remove('hidden');
  5035. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5036. } else if (act === 'route') {
  5037. document.getElementById('mangle-row-route')?.classList.remove('hidden');
  5038. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5039. } else if (act === 'sniff-pc' || act === 'sniff-tzsp') {
  5040. document.getElementById('mangle-row-sniff')?.classList.remove('hidden');
  5041. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5042. } else if (act === 'clear-df' || act === 'strip-ipv4-options') {
  5043. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5044. } else if (act === 'jump') {
  5045. if (jumpBox) jumpBox.classList.remove('hidden');
  5046. } else if (act.includes('address-list') || act.includes('address list')) {
  5047. if (addrBox) addrBox.classList.remove('hidden');
  5048. }
  5049. if (act === 'log') {
  5050. const logEl = document.getElementById('mangle-modal-log');
  5051. if (logEl) logEl.checked = true;
  5052. toggleMangleField('logprefix', true);
  5053. }
  5054. }
  5055. function toggleMangleLogPrefix() {
  5056. const isLog = document.getElementById('mangle-modal-log')?.checked;
  5057. toggleMangleField('logprefix', !!isLog);
  5058. }
  5059. const allMangleFieldKeys = [
  5060. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  5061. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  5062. 'routingmark', 'conntype', 'cs', 'natstate',
  5063. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  5064. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  5065. 'ipsec', 'tlshost', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  5066. 'pktsize', 'random', 'tcpflags', 'icmpoptions', 'ipv4options', 'ttl',
  5067. 'nth', 'connlimit', 'srcaddrtype', 'dstaddrtype', 'hotspot', 'ipfragment',
  5068. 'limit', 'dstlimit', 'time', 'psd', 'logprefix'
  5069. ];
  5070. function openAddMangleModal() {
  5071. switchMangleRuleTab('general');
  5072. const badge = document.getElementById('mangle-modal-badge');
  5073. if (badge) badge.innerText = 'New...';
  5074. document.getElementById('mangle-modal-id').value = '';
  5075. document.getElementById('mangle-modal-enabled').checked = true;
  5076. document.getElementById('mangle-modal-comment').value = '';
  5077. document.getElementById('mangle-modal-chain').value = 'prerouting';
  5078. document.getElementById('mangle-modal-action').value = 'mark-connection';
  5079. if (document.getElementById('mangle-modal-newconnmark')) document.getElementById('mangle-modal-newconnmark').value = '';
  5080. if (document.getElementById('mangle-modal-newroutingmark')) document.getElementById('mangle-modal-newroutingmark').value = '';
  5081. if (document.getElementById('mangle-modal-newpktmark')) document.getElementById('mangle-modal-newpktmark').value = '';
  5082. if (document.getElementById('mangle-modal-newmss')) document.getElementById('mangle-modal-newmss').value = '';
  5083. if (document.getElementById('mangle-modal-newdscp')) document.getElementById('mangle-modal-newdscp').value = '';
  5084. if (document.getElementById('mangle-modal-newttl')) document.getElementById('mangle-modal-newttl').value = '';
  5085. if (document.getElementById('mangle-modal-newpriority')) document.getElementById('mangle-modal-newpriority').value = '';
  5086. if (document.getElementById('mangle-modal-route')) document.getElementById('mangle-modal-route').value = '';
  5087. if (document.getElementById('mangle-modal-sniff')) document.getElementById('mangle-modal-sniff').value = '';
  5088. if (document.getElementById('mangle-modal-jumptarget')) document.getElementById('mangle-modal-jumptarget').value = '';
  5089. if (document.getElementById('mangle-modal-action-addrlist')) document.getElementById('mangle-modal-action-addrlist').value = '';
  5090. if (document.getElementById('mangle-modal-action-timeout')) document.getElementById('mangle-modal-action-timeout').value = '';
  5091. if (document.getElementById('mangle-modal-passthrough')) document.getElementById('mangle-modal-passthrough').checked = true;
  5092. if (document.getElementById('mangle-modal-log')) document.getElementById('mangle-modal-log').checked = false;
  5093. populateInterfaceSelect('mangle-val-iniface');
  5094. populateInterfaceSelect('mangle-val-outiface');
  5095. populateAddressListSelect('mangle-val-srclist');
  5096. populateAddressListSelect('mangle-val-dstlist');
  5097. populateGeoIPSelect('mangle-val-srcgeo');
  5098. populateGeoIPSelect('mangle-val-dstgeo');
  5099. allMangleFieldKeys.forEach(k => toggleMangleField(k, false));
  5100. resetCurrentMangleRuleCounters();
  5101. toggleMangleActionFields();
  5102. document.getElementById('mangle-modal').classList.remove('hidden');
  5103. }
  5104. function openEditMangleModal(id) {
  5105. const r = (state.mangleRules || []).find(rule => rule.id === id);
  5106. if (!r) return;
  5107. switchMangleRuleTab('general');
  5108. const badge = document.getElementById('mangle-modal-badge');
  5109. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  5110. document.getElementById('mangle-modal-id').value = r.id;
  5111. document.getElementById('mangle-modal-enabled').checked = !r.disabled;
  5112. document.getElementById('mangle-modal-comment').value = r.comment || '';
  5113. document.getElementById('mangle-modal-chain').value = r.chain || 'prerouting';
  5114. document.getElementById('mangle-modal-action').value = r.action || 'mark-connection';
  5115. if (document.getElementById('mangle-modal-newconnmark')) document.getElementById('mangle-modal-newconnmark').value = r.new_connection_mark || '';
  5116. if (document.getElementById('mangle-modal-newroutingmark')) document.getElementById('mangle-modal-newroutingmark').value = r.new_routing_mark || '';
  5117. if (document.getElementById('mangle-modal-newpktmark')) document.getElementById('mangle-modal-newpktmark').value = r.new_packet_mark || '';
  5118. if (document.getElementById('mangle-modal-newmss')) document.getElementById('mangle-modal-newmss').value = r.new_mss || '';
  5119. if (document.getElementById('mangle-modal-newdscp')) document.getElementById('mangle-modal-newdscp').value = r.new_dscp != null ? r.new_dscp : '';
  5120. if (document.getElementById('mangle-modal-newttl')) document.getElementById('mangle-modal-newttl').value = r.new_ttl || '';
  5121. if (document.getElementById('mangle-modal-newpriority')) document.getElementById('mangle-modal-newpriority').value = r.new_priority || '';
  5122. if (document.getElementById('mangle-modal-route')) document.getElementById('mangle-modal-route').value = r.route || '';
  5123. if (document.getElementById('mangle-modal-sniff')) document.getElementById('mangle-modal-sniff').value = r.sniff_target || '';
  5124. if (document.getElementById('mangle-modal-jumptarget')) document.getElementById('mangle-modal-jumptarget').value = r.jump_target || '';
  5125. if (document.getElementById('mangle-modal-action-addrlist')) document.getElementById('mangle-modal-action-addrlist').value = r.address_list || '';
  5126. if (document.getElementById('mangle-modal-action-timeout')) document.getElementById('mangle-modal-action-timeout').value = r.address_list_timeout || '';
  5127. if (document.getElementById('mangle-modal-passthrough')) document.getElementById('mangle-modal-passthrough').checked = r.passthrough ?? true;
  5128. if (document.getElementById('mangle-modal-log')) document.getElementById('mangle-modal-log').checked = !!r.log;
  5129. populateInterfaceSelect('mangle-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  5130. populateInterfaceSelect('mangle-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  5131. populateAddressListSelect('mangle-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  5132. populateAddressListSelect('mangle-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  5133. populateGeoIPSelect('mangle-val-srcgeo', r.src_geoip || '');
  5134. populateGeoIPSelect('mangle-val-dstgeo', r.dst_geoip || '');
  5135. setMangleFieldVal('src', r.src_address, true);
  5136. setMangleFieldVal('dst', r.dst_address, true);
  5137. setMangleFieldVal('srclist', r.src_address_list, true);
  5138. setMangleFieldVal('dstlist', r.dst_address_list, true);
  5139. setMangleFieldVal('srcgeo', r.src_geoip, true);
  5140. setMangleFieldVal('dstgeo', r.dst_geoip, true);
  5141. if (r.protocol && r.protocol !== 'all') {
  5142. setMangleFieldVal('proto', r.protocol, true);
  5143. } else {
  5144. toggleMangleField('proto', false);
  5145. }
  5146. setMangleFieldVal('sport', r.src_port, true);
  5147. setMangleFieldVal('dport', r.dst_port, true);
  5148. setMangleFieldVal('anyport', r.any_port, true);
  5149. setMangleFieldVal('iniface', r.in_interface, true);
  5150. setMangleFieldVal('outiface', r.out_interface, true);
  5151. setMangleFieldVal('inifacelist', r.in_interface_list, true);
  5152. setMangleFieldVal('outifacelist', r.out_interface_list, true);
  5153. setMangleFieldVal('pktmark', r.packet_mark, true);
  5154. setMangleFieldVal('connmark', r.connection_mark, true);
  5155. setMangleFieldVal('routingmark', r.routing_mark, true);
  5156. setMangleFieldVal('conntype', r.connection_type, false);
  5157. // Connection State
  5158. const states = r.connection_state || [];
  5159. if (states.length > 0) {
  5160. toggleMangleField('cs', true);
  5161. ['established', 'related', 'new', 'invalid', 'untracked'].forEach(s => {
  5162. const el = document.getElementById(`mangle-modal-cs-${s}`);
  5163. if (el) el.checked = states.includes(s);
  5164. });
  5165. } else {
  5166. toggleMangleField('cs', false);
  5167. }
  5168. // Connection NAT State
  5169. const natStates = r.connection_nat_state || [];
  5170. if (natStates.length > 0) {
  5171. toggleMangleField('natstate', true);
  5172. ['srcnat', 'dstnat'].forEach(s => {
  5173. const el = document.getElementById(`mangle-modal-nat-${s}`);
  5174. if (el) el.checked = natStates.includes(s);
  5175. });
  5176. } else {
  5177. toggleMangleField('natstate', false);
  5178. }
  5179. // Advanced tab fields
  5180. setMangleFieldVal('layer7', r.layer7_protocol, false);
  5181. setMangleFieldVal('content', r.content, false);
  5182. setMangleFieldVal('connbytes', r.connection_bytes, false);
  5183. setMangleFieldVal('connrate', r.connection_rate, false);
  5184. setMangleFieldVal('pcc', r.pcc, false);
  5185. setMangleFieldVal('srcmac', r.src_mac_address, true);
  5186. setMangleFieldVal('outbridgeport', r.out_bridge_port, false);
  5187. setMangleFieldVal('inbridgeport', r.in_bridge_port, false);
  5188. setMangleFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  5189. setMangleFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  5190. setMangleFieldVal('ipsec', r.ipsec_policy, false);
  5191. setMangleFieldVal('tlshost', r.tls_host, false);
  5192. setMangleFieldVal('ingresspriority', r.ingress_priority, false);
  5193. setMangleFieldVal('priority', r.priority, false);
  5194. setMangleFieldVal('dscp', r.dscp, false);
  5195. setMangleFieldVal('tcpmss', r.tcp_mss, false);
  5196. if (r.tos) {
  5197. const tosEl = document.getElementById('mangle-val-tos');
  5198. if (tosEl) tosEl.value = r.tos;
  5199. }
  5200. setMangleFieldVal('pktsize', r.packet_size, false);
  5201. setMangleFieldVal('random', r.random, false);
  5202. setMangleFieldVal('tcpflags', r.tcp_flags, false);
  5203. setMangleFieldVal('icmpoptions', r.icmp_options, false);
  5204. setMangleFieldVal('ipv4options', r.ipv4_options, false);
  5205. setMangleFieldVal('ttl', r.ttl, false);
  5206. // Extra tab fields
  5207. setMangleFieldVal('nth', r.nth, false);
  5208. setMangleFieldVal('connlimit', r.connection_limit, false);
  5209. setMangleFieldVal('srcaddrtype', r.src_address_type, false);
  5210. setMangleFieldVal('dstaddrtype', r.dst_address_type, false);
  5211. setMangleFieldVal('hotspot', r.hotspot, false);
  5212. setMangleFieldVal('ipfragment', r.ip_fragment, false);
  5213. setMangleFieldVal('limit', r.limit, false);
  5214. setMangleFieldVal('dstlimit', r.dst_limit, false);
  5215. setMangleFieldVal('time', r.time, false);
  5216. setMangleFieldVal('psd', r.psd, false);
  5217. // Action fields
  5218. if (r.jump_target) {
  5219. const jtEl = document.getElementById('mangle-modal-jumptarget');
  5220. if (jtEl) jtEl.value = r.jump_target;
  5221. }
  5222. if (r.address_list) {
  5223. const alEl = document.getElementById('mangle-modal-action-addrlist');
  5224. if (alEl) alEl.value = r.address_list;
  5225. }
  5226. if (r.address_list_timeout) {
  5227. const toEl = document.getElementById('mangle-modal-action-timeout');
  5228. if (toEl) toEl.value = r.address_list_timeout;
  5229. }
  5230. setMangleFieldVal('logprefix', r.log_prefix, false);
  5231. // Statistics
  5232. const bEl = document.getElementById('mangle-stat-bytes');
  5233. const pEl = document.getElementById('mangle-stat-packets');
  5234. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  5235. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  5236. state.mangleLastBytes = r.bytes || 0;
  5237. state.mangleLastPackets = r.packets || 0;
  5238. state.mangleLastTimestamp = Date.now();
  5239. state.mangleStatRateHistory = new Array(30).fill(0);
  5240. state.mangleStatPktHistory = new Array(30).fill(0);
  5241. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  5242. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  5243. toggleMangleActionFields();
  5244. document.getElementById('mangle-modal').classList.remove('hidden');
  5245. }
  5246. function closeMangleModal() {
  5247. stopMangleStatPolling();
  5248. document.getElementById('mangle-modal').classList.add('hidden');
  5249. }
  5250. function copyMangleRule() {
  5251. document.getElementById('mangle-modal-id').value = '';
  5252. const badge = document.getElementById('mangle-modal-badge');
  5253. if (badge) badge.innerText = 'New...';
  5254. showToast('Rule Cloned', 'Ready to save as a new Mangle rule copy', 'info');
  5255. }
  5256. function resetCurrentMangleRuleCounters() {
  5257. state.mangleStatRateHistory = new Array(30).fill(0);
  5258. state.mangleStatPktHistory = new Array(30).fill(0);
  5259. state.mangleLastBytes = 0;
  5260. state.mangleLastPackets = 0;
  5261. state.mangleLastTimestamp = Date.now();
  5262. const bEl = document.getElementById('mangle-stat-bytes');
  5263. const pEl = document.getElementById('mangle-stat-packets');
  5264. const rEl = document.getElementById('mangle-stat-rate');
  5265. const prEl = document.getElementById('mangle-stat-pktrate');
  5266. if (bEl) bEl.value = '0 B';
  5267. if (pEl) pEl.value = '0';
  5268. if (rEl) rEl.value = '0 bps';
  5269. if (prEl) prEl.value = '0 p/s';
  5270. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  5271. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  5272. showToast('Counters Reset', 'Mangle rule counter display reset to 0', 'info');
  5273. }
  5274. async function applyMangleRule(closeAfter = false) {
  5275. const id = document.getElementById('mangle-modal-id').value;
  5276. const chain = document.getElementById('mangle-modal-chain').value;
  5277. const action = document.getElementById('mangle-modal-action').value;
  5278. const comment = document.getElementById('mangle-modal-comment').value.trim();
  5279. const enabled = document.getElementById('mangle-modal-enabled').checked;
  5280. const src = getMangleFieldVal('src', true);
  5281. const dst = getMangleFieldVal('dst', true);
  5282. const srclist = getMangleFieldVal('srclist', true);
  5283. const dstlist = getMangleFieldVal('dstlist', true);
  5284. const srcgeo = getMangleFieldVal('srcgeo', true);
  5285. const dstgeo = getMangleFieldVal('dstgeo', true);
  5286. const proto = getMangleFieldVal('proto', true);
  5287. const sport = getMangleFieldVal('sport', true);
  5288. const dport = getMangleFieldVal('dport', true);
  5289. const anyport = getMangleFieldVal('anyport', true);
  5290. const iniface = getMangleFieldVal('iniface', true);
  5291. const outiface = getMangleFieldVal('outiface', true);
  5292. const inifacelist = getMangleFieldVal('inifacelist', true);
  5293. const outifacelist = getMangleFieldVal('outifacelist', true);
  5294. const pktmark = getMangleFieldVal('pktmark', true);
  5295. const connmark = getMangleFieldVal('connmark', true);
  5296. const routingmark = getMangleFieldVal('routingmark', true);
  5297. const conntype = getMangleFieldVal('conntype', false);
  5298. const states = [];
  5299. const csBox = document.getElementById('mangle-field-cs');
  5300. if (csBox && !csBox.classList.contains('hidden')) {
  5301. ['established', 'related', 'new', 'invalid', 'untracked'].forEach(s => {
  5302. if (document.getElementById(`mangle-modal-cs-${s}`)?.checked) states.push(s);
  5303. });
  5304. }
  5305. const natStates = [];
  5306. const natBox = document.getElementById('mangle-field-natstate');
  5307. if (natBox && !natBox.classList.contains('hidden')) {
  5308. ['srcnat', 'dstnat'].forEach(s => {
  5309. if (document.getElementById(`mangle-modal-nat-${s}`)?.checked) natStates.push(s);
  5310. });
  5311. }
  5312. const payload = {
  5313. id,
  5314. chain,
  5315. action,
  5316. protocol: proto || 'all',
  5317. src_address: src,
  5318. dst_address: dst,
  5319. src_port: sport,
  5320. dst_port: dport,
  5321. any_port: anyport,
  5322. in_interface: iniface,
  5323. out_interface: outiface,
  5324. in_interface_list: inifacelist,
  5325. out_interface_list: outifacelist,
  5326. packet_mark: pktmark,
  5327. connection_mark: connmark,
  5328. routing_mark: routingmark,
  5329. connection_type: conntype,
  5330. connection_state: states,
  5331. connection_nat_state: natStates,
  5332. src_address_list: srclist,
  5333. dst_address_list: dstlist,
  5334. src_geoip: srcgeo,
  5335. dst_geoip: dstgeo,
  5336. comment,
  5337. disabled: !enabled,
  5338. // Advanced tab
  5339. layer7_protocol: getMangleFieldVal('layer7', false),
  5340. content: getMangleFieldVal('content', false),
  5341. connection_bytes: getMangleFieldVal('connbytes', false),
  5342. connection_rate: getMangleFieldVal('connrate', false),
  5343. pcc: getMangleFieldVal('pcc', false),
  5344. src_mac_address: getMangleFieldVal('srcmac', true),
  5345. out_bridge_port: getMangleFieldVal('outbridgeport', false),
  5346. in_bridge_port: getMangleFieldVal('inbridgeport', false),
  5347. in_bridge_port_list: getMangleFieldVal('inbridgeportlist', false),
  5348. out_bridge_port_list: getMangleFieldVal('outbridgeportlist', false),
  5349. ipsec_policy: getMangleFieldVal('ipsec', false),
  5350. tls_host: getMangleFieldVal('tlshost', false),
  5351. ingress_priority: getMangleFieldVal('ingresspriority', false),
  5352. priority: getMangleFieldVal('priority', false),
  5353. dscp: getMangleFieldVal('dscp', false),
  5354. tcp_mss: getMangleFieldVal('tcpmss', false),
  5355. tos: document.getElementById('mangle-val-tos')?.value || '',
  5356. packet_size: getMangleFieldVal('pktsize', false),
  5357. random: getMangleFieldVal('random', false),
  5358. tcp_flags: getMangleFieldVal('tcpflags', false),
  5359. icmp_options: getMangleFieldVal('icmpoptions', false),
  5360. ipv4_options: getMangleFieldVal('ipv4options', false),
  5361. ttl: getMangleFieldVal('ttl', false),
  5362. // Extra tab
  5363. nth: getMangleFieldVal('nth', false),
  5364. connection_limit: getMangleFieldVal('connlimit', false),
  5365. src_address_type: getMangleFieldVal('srcaddrtype', false),
  5366. dst_address_type: getMangleFieldVal('dstaddrtype', false),
  5367. hotspot: getMangleFieldVal('hotspot', false),
  5368. ip_fragment: getMangleFieldVal('ipfragment', false),
  5369. limit: getMangleFieldVal('limit', false),
  5370. dst_limit: getMangleFieldVal('dstlimit', false),
  5371. time: getMangleFieldVal('time', false),
  5372. psd: getMangleFieldVal('psd', false),
  5373. // Action tab
  5374. new_connection_mark: action === 'mark-connection' ? (document.getElementById('mangle-modal-newconnmark')?.value.trim() || '') : '',
  5375. new_routing_mark: action === 'mark-routing' ? (document.getElementById('mangle-modal-newroutingmark')?.value.trim() || '') : '',
  5376. new_packet_mark: action === 'mark-packet' ? (document.getElementById('mangle-modal-newpktmark')?.value.trim() || '') : '',
  5377. new_mss: action === 'change-mss' ? (document.getElementById('mangle-modal-newmss')?.value.trim() || '') : '',
  5378. new_dscp: action === 'change-dscp' ? parseInt(document.getElementById('mangle-modal-newdscp')?.value || '0', 10) : 0,
  5379. new_ttl: action === 'change-ttl' ? (document.getElementById('mangle-modal-newttl')?.value.trim() || '') : '',
  5380. new_priority: action === 'set-priority' ? (document.getElementById('mangle-modal-newpriority')?.value.trim() || '') : '',
  5381. route: action === 'route' ? (document.getElementById('mangle-modal-route')?.value.trim() || '') : '',
  5382. sniff_target: (action === 'sniff-pc' || action === 'sniff-tzsp') ? (document.getElementById('mangle-modal-sniff')?.value.trim() || '') : '',
  5383. passthrough: document.getElementById('mangle-modal-passthrough')?.checked ?? true,
  5384. jump_target: action === 'jump' ? (document.getElementById('mangle-modal-jumptarget')?.value || '') : '',
  5385. address_list: action.includes('address') ? (document.getElementById('mangle-modal-action-addrlist')?.value || '') : '',
  5386. address_list_timeout: action.includes('address') ? (document.getElementById('mangle-modal-action-timeout')?.value || '') : '',
  5387. log: document.getElementById('mangle-modal-log')?.checked || false,
  5388. log_prefix: getMangleFieldVal('logprefix', false)
  5389. };
  5390. try {
  5391. const res = await fetch(`${API_BASE}/firewall/mangle`, {
  5392. method: 'POST',
  5393. headers: { 'Content-Type': 'application/json' },
  5394. body: JSON.stringify(payload)
  5395. });
  5396. if (res.ok) {
  5397. const data = await res.json();
  5398. showToast('Mangle Rule Saved', 'Marking rule updated', 'success');
  5399. loadFirewall(false);
  5400. if (closeAfter) {
  5401. closeMangleModal();
  5402. } else {
  5403. if (data.id) {
  5404. document.getElementById('mangle-modal-id').value = data.id;
  5405. const badge = document.getElementById('mangle-modal-badge');
  5406. if (badge) badge.innerText = `#${data.id}`;
  5407. }
  5408. }
  5409. } else {
  5410. const err = await res.json();
  5411. showToast('Error', err.message || 'Failed to save mangle rule', 'error');
  5412. }
  5413. } catch (err) {
  5414. showToast('Error', err.message, 'error');
  5415. }
  5416. }
  5417. function submitSaveMangleRule(e) {
  5418. if (e && e.preventDefault) e.preventDefault();
  5419. return applyMangleRule(true);
  5420. }
  5421. function startMangleStatPolling() {
  5422. stopMangleStatPolling();
  5423. pollMangleRuleStats();
  5424. state.mangleStatInterval = setInterval(pollMangleRuleStats, 1000);
  5425. }
  5426. function stopMangleStatPolling() {
  5427. if (state.mangleStatInterval) {
  5428. clearInterval(state.mangleStatInterval);
  5429. state.mangleStatInterval = null;
  5430. }
  5431. }
  5432. async function pollMangleRuleStats() {
  5433. const id = document.getElementById('mangle-modal-id')?.value;
  5434. if (!id) {
  5435. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory || new Array(30).fill(0), 'bps', 'mangle-stat-legend-rate');
  5436. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory || new Array(30).fill(0), 'p/s', 'mangle-stat-legend-pktrate');
  5437. return;
  5438. }
  5439. try {
  5440. const res = await fetch(`${API_BASE}/firewall/mangle`);
  5441. if (!res.ok) return;
  5442. const rules = await res.json();
  5443. const r = rules.find(x => x.id === id);
  5444. if (!r) return;
  5445. const now = Date.now();
  5446. const dt = Math.max(0.2, (now - (state.mangleLastTimestamp || now)) / 1000);
  5447. state.mangleLastTimestamp = now;
  5448. const curBytes = r.bytes || 0;
  5449. const curPackets = r.packets || 0;
  5450. const deltaBytes = Math.max(0, curBytes - (state.mangleLastBytes || curBytes));
  5451. const deltaPkts = Math.max(0, curPackets - (state.mangleLastPackets || curPackets));
  5452. state.mangleLastBytes = curBytes;
  5453. state.mangleLastPackets = curPackets;
  5454. const rateBps = Math.round((deltaBytes * 8) / dt);
  5455. const ratePkt = Math.round(deltaPkts / dt);
  5456. if (!state.mangleStatRateHistory) state.mangleStatRateHistory = new Array(30).fill(0);
  5457. if (!state.mangleStatPktHistory) state.mangleStatPktHistory = new Array(30).fill(0);
  5458. state.mangleStatRateHistory.push(rateBps);
  5459. if (state.mangleStatRateHistory.length > 30) state.mangleStatRateHistory.shift();
  5460. state.mangleStatPktHistory.push(ratePkt);
  5461. if (state.mangleStatPktHistory.length > 30) state.mangleStatPktHistory.shift();
  5462. const bEl = document.getElementById('mangle-stat-bytes');
  5463. const pEl = document.getElementById('mangle-stat-packets');
  5464. const rEl = document.getElementById('mangle-stat-rate');
  5465. const prEl = document.getElementById('mangle-stat-pktrate');
  5466. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  5467. if (pEl) pEl.value = curPackets.toLocaleString();
  5468. if (rEl) rEl.value = formatBps(rateBps);
  5469. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  5470. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  5471. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  5472. } catch (e) {
  5473. console.error('Error polling Mangle rule stats', e);
  5474. }
  5475. }
  5476. async function moveMangleRule(id, dir) {
  5477. try {
  5478. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/move`, {
  5479. method: 'POST',
  5480. headers: { 'Content-Type': 'application/json' },
  5481. body: JSON.stringify({ direction: dir })
  5482. });
  5483. if (res.ok) loadFirewall(false);
  5484. } catch (err) {
  5485. showToast('Error', err.message, 'error');
  5486. }
  5487. }
  5488. async function toggleMangleRuleState(id, disabled) {
  5489. try {
  5490. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/state`, {
  5491. method: 'POST',
  5492. headers: { 'Content-Type': 'application/json' },
  5493. body: JSON.stringify({ disabled })
  5494. });
  5495. if (res.ok) loadFirewall(false);
  5496. } catch (err) {
  5497. showToast('Error', err.message, 'error');
  5498. }
  5499. }
  5500. async function deleteMangleRule(id) {
  5501. if (!confirm('Are you sure you want to delete this mangle rule?')) return;
  5502. try {
  5503. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5504. if (res.ok) {
  5505. showToast('Deleted', 'Mangle rule removed', 'success');
  5506. loadFirewall(false);
  5507. }
  5508. } catch (err) {
  5509. showToast('Error', err.message, 'error');
  5510. }
  5511. }
  5512. // ----------------- Address Lists -----------------
  5513. function renderAddressLists() {
  5514. const filterList = document.getElementById('addrlist-filter-name')?.value || '';
  5515. const tbody = document.getElementById('addrlist-table-body');
  5516. const empty = document.getElementById('addrlist-empty');
  5517. if (!tbody) return;
  5518. tbody.innerHTML = '';
  5519. const entries = (state.addressLists || []).filter(e => !filterList || e.name === filterList);
  5520. document.getElementById('addrlist-count-badge').innerText = `${entries.length} Entries`;
  5521. // Update filter select
  5522. const sel = document.getElementById('addrlist-filter-name');
  5523. if (sel) {
  5524. const cur = sel.value;
  5525. sel.innerHTML = '<option value="">All Lists</option>';
  5526. const set = new Set((state.addressLists || []).map(a => a.name));
  5527. set.forEach(n => {
  5528. const opt = document.createElement('option');
  5529. opt.value = n;
  5530. opt.innerText = n;
  5531. if (n === cur) opt.selected = true;
  5532. sel.appendChild(opt);
  5533. });
  5534. }
  5535. if (entries.length === 0) {
  5536. empty?.classList.remove('hidden');
  5537. return;
  5538. }
  5539. empty?.classList.add('hidden');
  5540. entries.forEach((e, idx) => {
  5541. const tr = document.createElement('tr');
  5542. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${e.disabled ? 'opacity-50' : ''}`;
  5543. tr.setAttribute('ondblclick', `openEditAddrListModal('${e.id}')`);
  5544. tr.innerHTML = `
  5545. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  5546. <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>
  5547. <td class="py-2.5 px-3 font-bold text-white font-mono">${e.name}</td>
  5548. <td class="py-2.5 px-3 font-mono font-bold text-emerald-400">${e.address}</td>
  5549. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[150px]">${e.comment || '-'}</td>
  5550. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  5551. <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>
  5552. <button onclick="openEditAddrListModal('${e.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-medium">Edit</button>
  5553. <button onclick="deleteAddrList('${e.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  5554. </td>
  5555. `;
  5556. tbody.appendChild(tr);
  5557. });
  5558. populateCommonAddrListDatalist();
  5559. }
  5560. function openAddAddrListModal() {
  5561. document.getElementById('addrlist-modal-title').innerText = 'Add Address List Entry';
  5562. document.getElementById('addrlist-modal-id').value = '';
  5563. document.getElementById('addrlist-modal-name').value = '';
  5564. document.getElementById('addrlist-modal-addr').value = '';
  5565. document.getElementById('addrlist-modal-comment').value = '';
  5566. document.getElementById('addrlist-modal-disabled').checked = false;
  5567. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  5568. if (submitBtn) submitBtn.innerText = 'Add to List';
  5569. document.getElementById('addrlist-modal').classList.remove('hidden');
  5570. }
  5571. function openEditAddrListModal(id) {
  5572. const e = (state.addressLists || []).find(item => item.id === id);
  5573. if (!e) return;
  5574. document.getElementById('addrlist-modal-title').innerText = `Edit Address List Entry: ${e.name}`;
  5575. document.getElementById('addrlist-modal-id').value = e.id;
  5576. document.getElementById('addrlist-modal-name').value = e.name;
  5577. document.getElementById('addrlist-modal-addr').value = e.address;
  5578. document.getElementById('addrlist-modal-comment').value = e.comment || '';
  5579. document.getElementById('addrlist-modal-disabled').checked = !!e.disabled;
  5580. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  5581. if (submitBtn) submitBtn.innerText = 'Save Changes';
  5582. document.getElementById('addrlist-modal').classList.remove('hidden');
  5583. }
  5584. function closeAddrListModal() {
  5585. document.getElementById('addrlist-modal').classList.add('hidden');
  5586. }
  5587. async function submitSaveAddrList(e) {
  5588. e.preventDefault();
  5589. const id = document.getElementById('addrlist-modal-id').value;
  5590. const name = document.getElementById('addrlist-modal-name').value.trim();
  5591. const addr = document.getElementById('addrlist-modal-addr').value.trim();
  5592. const comment = document.getElementById('addrlist-modal-comment').value.trim();
  5593. const disabled = document.getElementById('addrlist-modal-disabled').checked;
  5594. try {
  5595. const res = await fetch(`${API_BASE}/firewall/address-lists`, {
  5596. method: 'POST',
  5597. headers: { 'Content-Type': 'application/json' },
  5598. body: JSON.stringify({ id, name, address: addr, comment, disabled })
  5599. });
  5600. if (res.ok) {
  5601. showToast('Address List Item Saved', `Saved ${addr} in ${name}`, 'success');
  5602. closeAddrListModal();
  5603. loadFirewall(false);
  5604. } else {
  5605. const err = await res.json();
  5606. showToast('Error', err.message || 'Failed to save address list', 'error');
  5607. }
  5608. } catch (err) {
  5609. showToast('Error', err.message, 'error');
  5610. }
  5611. }
  5612. async function toggleAddrListState(id, disabled) {
  5613. try {
  5614. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}/state`, {
  5615. method: 'POST',
  5616. headers: { 'Content-Type': 'application/json' },
  5617. body: JSON.stringify({ disabled })
  5618. });
  5619. if (res.ok) {
  5620. loadFirewall(false);
  5621. }
  5622. } catch (err) {
  5623. showToast('Error', err.message, 'error');
  5624. }
  5625. }
  5626. async function deleteAddrList(id) {
  5627. if (!confirm('Are you sure you want to delete this address list item?')) return;
  5628. try {
  5629. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5630. if (res.ok) {
  5631. showToast('Deleted', 'Address list item removed', 'info');
  5632. loadFirewall(false);
  5633. }
  5634. } catch (err) {
  5635. showToast('Error', err.message, 'error');
  5636. }
  5637. }
  5638. // ----------------- Geo-Location IP Management -----------------
  5639. async function loadGeoIP() {
  5640. try {
  5641. const [statusRes, countriesRes] = await Promise.all([
  5642. fetch(`${API_BASE}/firewall/geoip/status`),
  5643. fetch(`${API_BASE}/firewall/geoip/countries`)
  5644. ]);
  5645. if (statusRes.ok) state.geoStatus = await statusRes.json();
  5646. if (countriesRes.ok) state.geoCountries = await countriesRes.json();
  5647. updateGeoHeader();
  5648. renderGeoCountries();
  5649. } catch (err) {
  5650. console.error('Failed to load GeoIP:', err);
  5651. }
  5652. }
  5653. function getGeoUsageMap() {
  5654. const usage = {};
  5655. const checkRule = (r, type) => {
  5656. ['src_geoip', 'dst_geoip'].forEach(field => {
  5657. let val = (r && r[field]) || '';
  5658. let code = val.replace(/^!/, '').replace(/^geo:/, '').replace(/^geo_/, '').toUpperCase().trim();
  5659. if (code) {
  5660. if (!usage[code]) usage[code] = [];
  5661. const label = `${type} #${r.priority !== undefined ? r.priority : (r.id || '')}`;
  5662. if (!usage[code].includes(label)) usage[code].push(label);
  5663. }
  5664. });
  5665. };
  5666. (state.filterRules || []).forEach(r => checkRule(r, 'Filter'));
  5667. (state.natRules || []).forEach(r => checkRule(r, 'NAT'));
  5668. (state.mangleRules || []).forEach(r => checkRule(r, 'Mangle'));
  5669. return usage;
  5670. }
  5671. function updateGeoHeader() {
  5672. const s = state.geoStatus || {};
  5673. const statusBadge = document.getElementById('geo-status-badge');
  5674. if (statusBadge) {
  5675. statusBadge.innerText = s.auto_update ? 'Auto-Update ON' : 'Auto-Update OFF';
  5676. statusBadge.className = s.auto_update
  5677. ? 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-emerald-500/20 text-emerald-300 border border-emerald-500/30'
  5678. : 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 text-slate-400';
  5679. }
  5680. const intervalLabel = document.getElementById('geo-interval-label');
  5681. if (intervalLabel) {
  5682. intervalLabel.innerText = `Every ${s.interval_hours || 24}h`;
  5683. }
  5684. const usageMap = getGeoUsageMap();
  5685. const inUseCount = Object.keys(usageMap).length;
  5686. const activeCountEl = document.getElementById('geo-stat-active-countries');
  5687. if (activeCountEl) activeCountEl.innerText = inUseCount.toLocaleString();
  5688. const totalSubnetsEl = document.getElementById('geo-stat-total-subnets');
  5689. if (totalSubnetsEl) totalSubnetsEl.innerText = (s.total_subnets || 0).toLocaleString();
  5690. const lastSyncEl = document.getElementById('geo-stat-last-sync');
  5691. if (lastSyncEl) {
  5692. if (s.last_updated && !s.last_updated.startsWith('0001')) {
  5693. const d = new Date(s.last_updated);
  5694. lastSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  5695. } else {
  5696. lastSyncEl.innerText = 'Never (Sync Pending)';
  5697. }
  5698. }
  5699. const nextSyncEl = document.getElementById('geo-stat-next-sync');
  5700. if (nextSyncEl) {
  5701. if (s.next_update && !s.next_update.startsWith('0001')) {
  5702. const d = new Date(s.next_update);
  5703. nextSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  5704. } else {
  5705. nextSyncEl.innerText = '-';
  5706. }
  5707. }
  5708. const badge = document.getElementById('fw-badge-geo');
  5709. if (badge) badge.innerText = inUseCount || (state.geoCountries || []).filter(c => c.subnet_count > 0).length || 0;
  5710. }
  5711. function renderGeoCountries() {
  5712. const tbody = document.getElementById('geo-table-body');
  5713. const empty = document.getElementById('geo-empty');
  5714. if (!tbody) return;
  5715. tbody.innerHTML = '';
  5716. const q = (document.getElementById('geo-search-input')?.value || '').trim().toLowerCase();
  5717. const continent = document.getElementById('geo-continent-filter')?.value || '';
  5718. const inUseOnly = document.getElementById('geo-filter-inuse-only')?.checked;
  5719. const cachedOnly = document.getElementById('geo-filter-cached-only')?.checked;
  5720. const usageMap = getGeoUsageMap();
  5721. const countries = (state.geoCountries || []).filter(c => {
  5722. const isUsed = !!usageMap[c.code];
  5723. if (inUseOnly && !isUsed) return false;
  5724. if (cachedOnly && (!c.subnet_count || c.subnet_count === 0)) return false;
  5725. if (continent && c.continent !== continent) return false;
  5726. if (q) {
  5727. const matchCode = c.code.toLowerCase().includes(q);
  5728. const matchName = c.name.toLowerCase().includes(q);
  5729. if (!matchCode && !matchName) return false;
  5730. }
  5731. return true;
  5732. });
  5733. if (countries.length === 0) {
  5734. empty?.classList.remove('hidden');
  5735. return;
  5736. }
  5737. empty?.classList.add('hidden');
  5738. countries.forEach(c => {
  5739. const tr = document.createElement('tr');
  5740. const isUsed = !!usageMap[c.code];
  5741. const rulesUsing = usageMap[c.code] || [];
  5742. tr.className = `hover:bg-slate-800/40 transition text-xs ${isUsed ? 'bg-emerald-950/20' : ''}`;
  5743. let statusHtml = '';
  5744. if (isUsed) {
  5745. 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>`;
  5746. } else if (c.subnet_count > 0) {
  5747. 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>';
  5748. } else {
  5749. statusHtml = '<span class="px-2 py-0.5 rounded text-[10px] font-mono text-slate-500 bg-slate-800/60">READY</span>';
  5750. }
  5751. tr.innerHTML = `
  5752. <td class="py-2.5 px-3 text-center">
  5753. <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'}">
  5754. ${c.code}
  5755. </span>
  5756. </td>
  5757. <td class="py-2.5 px-3 font-bold text-white">${c.name}</td>
  5758. <td class="py-2.5 px-3 text-slate-400">${c.continent}</td>
  5759. <td class="py-2.5 px-3 font-mono ${c.subnet_count > 0 ? 'text-emerald-400 font-bold' : 'text-slate-500'}">
  5760. ${c.subnet_count > 0 ? c.subnet_count.toLocaleString() + ' CIDRs' : 'Not Cached'}
  5761. </td>
  5762. <td class="py-2.5 px-3 font-mono text-purple-300">${c.ipset_name}</td>
  5763. <td class="py-2.5 px-3">
  5764. ${statusHtml}
  5765. </td>
  5766. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  5767. <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>
  5768. <button onclick="viewGeoSubnets('${c.code}')" class="text-xs text-slate-400 hover:text-white" title="Preview Subnet Ranges">View</button>
  5769. </td>
  5770. `;
  5771. tbody.appendChild(tr);
  5772. });
  5773. }
  5774. function quickFilterGeo(preset) {
  5775. const searchInput = document.getElementById('geo-search-input');
  5776. const continentSel = document.getElementById('geo-continent-filter');
  5777. const inUseCheck = document.getElementById('geo-filter-inuse-only');
  5778. const cachedCheck = document.getElementById('geo-filter-cached-only');
  5779. if (searchInput) searchInput.value = '';
  5780. if (continentSel) continentSel.value = '';
  5781. if (inUseCheck) inUseCheck.checked = false;
  5782. if (cachedCheck) cachedCheck.checked = false;
  5783. if (preset === 'GR') {
  5784. if (searchInput) searchInput.value = 'Greece';
  5785. } else if (preset === 'Europe') {
  5786. if (continentSel) continentSel.value = 'Europe';
  5787. } else if (preset === 'HIGHRISK') {
  5788. if (searchInput) searchInput.value = 'China';
  5789. }
  5790. renderGeoCountries();
  5791. }
  5792. async function toggleGeoCountry(code, enabled) {
  5793. try {
  5794. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/toggle`, {
  5795. method: 'POST',
  5796. headers: { 'Content-Type': 'application/json' },
  5797. body: JSON.stringify({ enabled })
  5798. });
  5799. if (res.ok) {
  5800. showToast(enabled ? 'Country Enabled' : 'Country Disabled', `${code} ${enabled ? 'active in firewall' : 'removed from firewall'}`, 'success');
  5801. loadGeoIP();
  5802. } else {
  5803. const err = await res.json();
  5804. showToast('Error', err.message || 'Failed to toggle country', 'error');
  5805. }
  5806. } catch (err) {
  5807. showToast('Error', err.message, 'error');
  5808. }
  5809. }
  5810. async function updateGeoCountry(code) {
  5811. try {
  5812. showToast('Syncing Country', `Downloading latest IP blocks for ${code}...`, 'info');
  5813. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/update`, { method: 'POST' });
  5814. if (res.ok) {
  5815. const data = await res.json();
  5816. showToast('Synced', `Loaded ${data.subnets} CIDR blocks for ${code}`, 'success');
  5817. loadGeoIP();
  5818. } else {
  5819. const err = await res.json();
  5820. showToast('Sync Error', err.message || 'Failed to sync country', 'error');
  5821. }
  5822. } catch (err) {
  5823. showToast('Error', err.message, 'error');
  5824. }
  5825. }
  5826. async function triggerGeoUpdateNow() {
  5827. const spinner = document.getElementById('geo-update-spinner');
  5828. if (spinner) spinner.classList.remove('hidden');
  5829. try {
  5830. const res = await fetch(`${API_BASE}/firewall/geoip/update-now`, { method: 'POST' });
  5831. if (res.ok) {
  5832. showToast('Update Started', 'Updating all active GeoIP country zones in background...', 'info');
  5833. setTimeout(() => {
  5834. loadGeoIP();
  5835. if (spinner) spinner.classList.add('hidden');
  5836. }, 2500);
  5837. } else {
  5838. const err = await res.json();
  5839. showToast('Notice', err.message || 'Update in progress', 'info');
  5840. if (spinner) spinner.classList.add('hidden');
  5841. }
  5842. } catch (err) {
  5843. showToast('Error', err.message, 'error');
  5844. if (spinner) spinner.classList.add('hidden');
  5845. }
  5846. }
  5847. async function applyGeoPreset(preset) {
  5848. try {
  5849. const res = await fetch(`${API_BASE}/firewall/geoip/batch-toggle`, {
  5850. method: 'POST',
  5851. headers: { 'Content-Type': 'application/json' },
  5852. body: JSON.stringify({ preset, enabled: preset !== 'NONE' })
  5853. });
  5854. if (res.ok) {
  5855. showToast('Preset Applied', `Preset ${preset} updated in firewall`, 'success');
  5856. loadGeoIP();
  5857. }
  5858. } catch (err) {
  5859. showToast('Error', err.message, 'error');
  5860. }
  5861. }
  5862. function openGeoIntervalModal() {
  5863. const s = state.geoStatus || {};
  5864. document.getElementById('geo-cfg-autoupdate').checked = s.auto_update !== false;
  5865. const sel = document.getElementById('geo-cfg-interval');
  5866. const customBox = document.getElementById('geo-cfg-custom-box');
  5867. const customHoursInput = document.getElementById('geo-cfg-custom-hours');
  5868. const curHours = s.interval_hours || 24;
  5869. const matchOption = Array.from(sel.options).find(o => parseInt(o.value, 10) === curHours);
  5870. if (matchOption) {
  5871. sel.value = String(curHours);
  5872. customBox.classList.add('hidden');
  5873. } else {
  5874. sel.value = 'custom';
  5875. customHoursInput.value = curHours;
  5876. customBox.classList.remove('hidden');
  5877. }
  5878. document.getElementById('geo-interval-modal').classList.remove('hidden');
  5879. }
  5880. function closeGeoIntervalModal() {
  5881. document.getElementById('geo-interval-modal').classList.add('hidden');
  5882. }
  5883. function toggleCustomGeoInterval() {
  5884. const val = document.getElementById('geo-cfg-interval').value;
  5885. const customBox = document.getElementById('geo-cfg-custom-box');
  5886. if (val === 'custom') {
  5887. customBox.classList.remove('hidden');
  5888. } else {
  5889. customBox.classList.add('hidden');
  5890. }
  5891. }
  5892. async function submitGeoIntervalSettings(e) {
  5893. e.preventDefault();
  5894. const autoUpdate = document.getElementById('geo-cfg-autoupdate').checked;
  5895. const intervalVal = document.getElementById('geo-cfg-interval').value;
  5896. let hours = 24;
  5897. if (intervalVal === 'custom') {
  5898. hours = parseInt(document.getElementById('geo-cfg-custom-hours').value, 10) || 24;
  5899. } else {
  5900. hours = parseInt(intervalVal, 10) || 24;
  5901. }
  5902. try {
  5903. const res = await fetch(`${API_BASE}/firewall/geoip/config`, {
  5904. method: 'POST',
  5905. headers: { 'Content-Type': 'application/json' },
  5906. body: JSON.stringify({ auto_update: autoUpdate, interval_hours: hours })
  5907. });
  5908. if (res.ok) {
  5909. showToast('Schedule Saved', `Auto-update set to every ${hours} hours`, 'success');
  5910. closeGeoIntervalModal();
  5911. loadGeoIP();
  5912. } else {
  5913. const err = await res.json();
  5914. showToast('Error', err.message || 'Failed to save schedule', 'error');
  5915. }
  5916. } catch (err) {
  5917. showToast('Error', err.message, 'error');
  5918. }
  5919. }
  5920. async function viewGeoSubnets(code, name) {
  5921. if (!name) {
  5922. const found = (state.geoCountries || []).find(x => x.code === code);
  5923. name = found ? found.name : code;
  5924. }
  5925. document.getElementById('geo-subnets-title').innerText = `${name} (${code}) Subnets`;
  5926. document.getElementById('geo-subnets-subtitle').innerText = `Kernel IPSet: mk_geo_${code}`;
  5927. const listEl = document.getElementById('geo-subnets-list');
  5928. listEl.innerHTML = '<span class="text-slate-500">Loading subnets...</span>';
  5929. document.getElementById('geo-subnets-modal').classList.remove('hidden');
  5930. try {
  5931. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/subnets`);
  5932. if (res.ok) {
  5933. const data = await res.json();
  5934. const subnets = data.subnets || [];
  5935. if (subnets.length === 0) {
  5936. listEl.innerHTML = '<span class="text-slate-500">No cached subnets found. Click Sync to download this zone.</span>';
  5937. } else {
  5938. listEl.innerHTML = subnets.map(s => `<div>${s}</div>`).join('');
  5939. }
  5940. } else {
  5941. listEl.innerHTML = '<span class="text-rose-400">Failed to load subnets.</span>';
  5942. }
  5943. } catch (err) {
  5944. listEl.innerHTML = `<span class="text-rose-400">Error: ${err.message}</span>`;
  5945. }
  5946. }
  5947. function closeGeoSubnetsModal() {
  5948. document.getElementById('geo-subnets-modal').classList.add('hidden');
  5949. }
  5950. // ----------------- Active Connections Tracking -----------------
  5951. async function loadConnections() {
  5952. try {
  5953. const res = await fetch(`${API_BASE}/firewall/connections`);
  5954. const data = await res.json();
  5955. state.connections = Array.isArray(data) ? data : [];
  5956. document.getElementById('fw-badge-connections').innerText = state.connections.length;
  5957. document.getElementById('conns-count-badge').innerText = `${state.connections.length} Flows`;
  5958. renderConnections();
  5959. } catch (err) {
  5960. console.error('Failed to load connections:', err);
  5961. }
  5962. }
  5963. function renderConnections() {
  5964. const search = (document.getElementById('conns-search-input')?.value || '').toLowerCase();
  5965. const protoFilter = document.getElementById('conns-filter-proto')?.value || '';
  5966. const tbody = document.getElementById('conns-table-body');
  5967. const empty = document.getElementById('conns-empty');
  5968. if (!tbody) return;
  5969. tbody.innerHTML = '';
  5970. const conns = (state.connections || []).filter(c => {
  5971. if (protoFilter && c.protocol !== protoFilter) return false;
  5972. if (search) {
  5973. const line = `${c.protocol} ${c.src_address} ${c.dst_address} ${c.src_port} ${c.dst_port} ${c.tcp_state} ${c.connection_mark}`.toLowerCase();
  5974. if (!line.includes(search)) return false;
  5975. }
  5976. return true;
  5977. });
  5978. if (conns.length === 0) {
  5979. empty?.classList.remove('hidden');
  5980. return;
  5981. }
  5982. empty?.classList.add('hidden');
  5983. conns.slice(0, 150).forEach(c => {
  5984. const tr = document.createElement('tr');
  5985. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  5986. let stateColor = 'text-slate-400';
  5987. if (c.tcp_state === 'ESTABLISHED') stateColor = 'text-emerald-400 font-bold';
  5988. else if (c.tcp_state === 'TIME_WAIT' || c.tcp_state === 'SYN_SENT') stateColor = 'text-amber-400';
  5989. tr.innerHTML = `
  5990. <td class="py-2.5 px-3 font-bold text-cyan-400">${c.protocol}</td>
  5991. <td class="py-2.5 px-3 font-mono text-white">${c.src_address}:${c.src_port}</td>
  5992. <td class="py-2.5 px-3 font-mono text-white">${c.dst_address}:${c.dst_port}</td>
  5993. <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>
  5994. <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>
  5995. <td class="py-2.5 px-3 font-mono ${stateColor}">${c.tcp_state}</td>
  5996. <td class="py-2.5 px-3 font-mono text-purple-300">${c.connection_mark || '-'}</td>
  5997. <td class="py-2.5 px-3 text-slate-500">${c.timeout ? c.timeout + 's' : '-'}</td>
  5998. <td class="py-2.5 px-3 text-right font-sans">
  5999. <button onclick="killConnection('${c.protocol}', '${c.src_address}', ${c.src_port}, '${c.dst_address}', ${c.dst_port})" class="text-xs text-rose-400 hover:text-rose-300">Kill</button>
  6000. </td>
  6001. `;
  6002. tbody.appendChild(tr);
  6003. });
  6004. }
  6005. async function killConnection(protocol, src, sport, dst, dport) {
  6006. try {
  6007. const res = await fetch(`${API_BASE}/firewall/connections/kill`, {
  6008. method: 'POST',
  6009. headers: { 'Content-Type': 'application/json' },
  6010. body: JSON.stringify({ protocol, src, sport, dst, dport })
  6011. });
  6012. if (res.ok) {
  6013. showToast('Terminated', `Killed flow ${src}:${sport} -> ${dst}:${dport}`, 'info');
  6014. loadConnections();
  6015. }
  6016. } catch (err) {
  6017. showToast('Error', err.message, 'error');
  6018. }
  6019. }
  6020. async function resetFirewallCounters() {
  6021. if (!confirm('Reset all firewall packet and byte counters to zero?')) return;
  6022. try {
  6023. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  6024. if (res.ok) {
  6025. showToast('Counters Reset', 'All rules counters reset to 0', 'success');
  6026. loadFirewall(false);
  6027. }
  6028. } catch (err) {
  6029. showToast('Error', err.message, 'error');
  6030. }
  6031. }
  6032. // ======================== MIKROTIK ROUTING & POLICY (/ip route) ========================
  6033. function switchRoutesSubTab(tab) {
  6034. state.routesSubTab = tab;
  6035. const tabs = ['routes', 'rules', 'tables'];
  6036. tabs.forEach(t => {
  6037. const panel = document.getElementById(`routes-subtab-${t}`);
  6038. const btn = document.getElementById(`routes-subtab-btn-${t}`);
  6039. if (panel) {
  6040. if (t === tab) panel.classList.remove('hidden');
  6041. else panel.classList.add('hidden');
  6042. }
  6043. if (btn) {
  6044. if (t === tab) {
  6045. 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';
  6046. } else {
  6047. 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';
  6048. }
  6049. }
  6050. });
  6051. setTimeout(initTableSorting, 50);
  6052. }
  6053. async function loadRoutes() {
  6054. try {
  6055. const [routesRes, rulesRes, tablesRes] = await Promise.all([
  6056. fetch(`${API_BASE}/routes`),
  6057. fetch(`${API_BASE}/routing/rules`),
  6058. fetch(`${API_BASE}/routing/tables`)
  6059. ]);
  6060. if (routesRes.ok) state.routes = await routesRes.json();
  6061. if (rulesRes.ok) state.policyRules = await rulesRes.json();
  6062. if (tablesRes.ok) state.routingTables = await tablesRes.json();
  6063. const bRoutes = document.getElementById('routes-badge-routes');
  6064. if (bRoutes) bRoutes.innerText = (state.routes || []).length;
  6065. const showSystem = document.getElementById('prule-show-system')?.checked;
  6066. const userRules = (state.policyRules || []).filter(pr => showSystem || (!pr.is_default && !pr.is_system));
  6067. const bRules = document.getElementById('routes-badge-rules');
  6068. if (bRules) bRules.innerText = userRules.length;
  6069. const bTables = document.getElementById('routes-badge-tables');
  6070. if (bTables) bTables.innerText = (state.routingTables || []).length;
  6071. const bRoutesCount = document.getElementById('badge-routes-count');
  6072. if (bRoutesCount) bRoutesCount.innerText = (state.routes || []).length;
  6073. renderRoutesList();
  6074. renderPolicyRules();
  6075. renderRoutingTables();
  6076. } catch (err) {
  6077. console.error('Failed to load routing:', err);
  6078. }
  6079. }
  6080. function getRouteProtocolBadge(proto) {
  6081. const p = (proto || 'static').toLowerCase();
  6082. switch (p) {
  6083. case 'bgp':
  6084. 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>`;
  6085. case 'ibgp':
  6086. 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>`;
  6087. case 'ospf':
  6088. 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>`;
  6089. case 'rip':
  6090. 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>`;
  6091. case 'static':
  6092. 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>`;
  6093. case 'connected':
  6094. 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>`;
  6095. case 'dhcp':
  6096. 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>`;
  6097. case 'multicast':
  6098. 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>`;
  6099. default:
  6100. 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>`;
  6101. }
  6102. }
  6103. function renderRoutesList() {
  6104. const tableFilter = document.getElementById('routes-filter-table')?.value || '';
  6105. const typeFilter = document.getElementById('routes-filter-type')?.value || '';
  6106. const tbody = document.getElementById('routes-table-body');
  6107. const empty = document.getElementById('routes-empty');
  6108. if (!tbody) return;
  6109. // Update table filter select
  6110. const sel = document.getElementById('routes-filter-table');
  6111. if (sel) {
  6112. const cur = sel.value;
  6113. sel.innerHTML = '<option value="">All Tables</option>';
  6114. (state.routingTables || []).forEach(t => {
  6115. const opt = document.createElement('option');
  6116. opt.value = t.name;
  6117. opt.innerText = t.name;
  6118. if (t.name === cur) opt.selected = true;
  6119. sel.appendChild(opt);
  6120. });
  6121. }
  6122. const routes = (state.routes || []).filter(r => {
  6123. if (tableFilter && r.routing_table !== tableFilter) return false;
  6124. if (typeFilter === 'ecmp' && !r.ecmp) return false;
  6125. if (typeFilter === 'multicast' && !r.multicast) return false;
  6126. if (typeFilter === 'static' && !r.static) return false;
  6127. if (typeFilter === 'dynamic' && !r.dynamic) return false;
  6128. if (typeFilter === 'connected' && !r.connect) return false;
  6129. if (typeFilter === 'bgp' && (r.protocol || '').toLowerCase() !== 'bgp' && (r.protocol || '').toLowerCase() !== 'ibgp') return false;
  6130. if (typeFilter === 'ospf' && (r.protocol || '').toLowerCase() !== 'ospf') return false;
  6131. if (typeFilter === 'dhcp' && (r.protocol || '').toLowerCase() !== 'dhcp') return false;
  6132. return true;
  6133. });
  6134. const ecmpCount = (state.routes || []).filter(r => r.ecmp).length;
  6135. const mcCount = (state.routes || []).filter(r => r.multicast).length;
  6136. let summaryText = `${routes.length} Routes`;
  6137. if (ecmpCount > 0) summaryText += ` • ${ecmpCount} ECMP`;
  6138. if (mcCount > 0) summaryText += ` • ${mcCount} Multicast/IGMP`;
  6139. const badgeEl = document.getElementById('routes-count-badge');
  6140. if (badgeEl) badgeEl.innerText = summaryText;
  6141. if (routes.length === 0) {
  6142. empty?.classList.remove('hidden');
  6143. tbody.innerHTML = '';
  6144. return;
  6145. }
  6146. empty?.classList.add('hidden');
  6147. 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(';');
  6148. if (tbody.dataset.sig === sig) {
  6149. return; // Routes table unchanged! Do not wipe DOM or flicker!
  6150. }
  6151. tbody.dataset.sig = sig;
  6152. tbody.innerHTML = '';
  6153. routes.forEach(r => {
  6154. const tr = document.createElement('tr');
  6155. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${r.disabled ? 'opacity-50' : ''}`;
  6156. tr.setAttribute('ondblclick', `openEditRouteModal('${r.id}')`);
  6157. // Routing Flags string: D=Dynamic, A=Active, C=Connect, S=Static, E=ECMP, M=Multicast, X=Disabled
  6158. let flags = '';
  6159. if (r.dynamic) flags += 'D';
  6160. if (r.active) flags += 'A';
  6161. if (r.connect) flags += 'C';
  6162. if (r.static) flags += 'S';
  6163. if (r.ecmp) flags += 'E';
  6164. if (r.multicast) flags += 'M';
  6165. if (r.disabled) flags += 'X';
  6166. const isDefault = r.dst_address === 'default' || r.dst_address === '0.0.0.0/0';
  6167. let healthCell = `<span class="text-slate-600 font-mono text-[11px]">-</span>`;
  6168. if (r.check_gateway === 'internet') {
  6169. if (r.health_status === 'online') {
  6170. const ms = (r.health_rtt_ms || 0).toFixed(0);
  6171. healthCell = `
  6172. <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)">
  6173. <span class="w-1.5 h-1.5 rounded-full bg-emerald-400 animate-pulse"></span>
  6174. <span>Internet OK (${ms}ms)</span>
  6175. </span>
  6176. `;
  6177. } else if (r.health_status === 'offline') {
  6178. healthCell = `
  6179. <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.">
  6180. <span class="w-1.5 h-1.5 rounded-full bg-rose-400"></span>
  6181. <span>Internet Down</span>
  6182. </span>
  6183. `;
  6184. } else {
  6185. healthCell = `
  6186. <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">
  6187. <span class="w-1.5 h-1.5 rounded-full bg-amber-400 animate-ping"></span>
  6188. <span>Checking...</span>
  6189. </span>
  6190. `;
  6191. }
  6192. } else if (r.check_gateway === 'ping') {
  6193. if (r.health_status === 'online') {
  6194. healthCell = `
  6195. <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">
  6196. <span class="w-1.5 h-1.5 rounded-full bg-cyan-400"></span>
  6197. <span>Gateway OK (${(r.health_rtt_ms || 0).toFixed(0)}ms)</span>
  6198. </span>
  6199. `;
  6200. } else if (r.health_status === 'offline') {
  6201. healthCell = `
  6202. <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">
  6203. <span class="w-1.5 h-1.5 rounded-full bg-rose-400"></span>
  6204. <span>Gateway Dead</span>
  6205. </span>
  6206. `;
  6207. }
  6208. }
  6209. const flagDescriptions = [];
  6210. if (r.dynamic) flagDescriptions.push('Dynamic (D)');
  6211. if (r.active) flagDescriptions.push('Active (A)');
  6212. if (r.connect) flagDescriptions.push('Connected (C)');
  6213. if (r.static) flagDescriptions.push('Static (S)');
  6214. if (r.ecmp) flagDescriptions.push('ECMP - Equal-Cost Multi-Path (E)');
  6215. if (r.multicast) flagDescriptions.push('Multicast / IGMP Group (M)');
  6216. if (r.disabled) flagDescriptions.push('Disabled (X)');
  6217. tr.innerHTML = `
  6218. <td class="py-2.5 px-3 text-center">
  6219. <span class="px-1.5 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 ${
  6220. 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')
  6221. }" title="Flags: ${flagDescriptions.join(', ')}">
  6222. ${flags || '-'}
  6223. </span>
  6224. </td>
  6225. <td class="py-2.5 px-3">
  6226. <div class="flex items-center gap-1.5 flex-wrap">
  6227. <span class="font-bold ${isDefault ? 'text-cyan-300' : 'text-white'}">${escapeHtml(r.dst_address)}</span>
  6228. ${r.ecmp ? `
  6229. <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)">
  6230. <span>⚡ ECMP</span>
  6231. </span>
  6232. ` : ''}
  6233. ${r.multicast ? `
  6234. <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">
  6235. <span>IGMP</span>
  6236. </span>
  6237. ` : ''}
  6238. </div>
  6239. </td>
  6240. <td class="py-2.5 px-3">${getRouteProtocolBadge(r.protocol)}</td>
  6241. <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>
  6242. <td class="py-2.5 px-3 text-slate-400 font-mono">${(r.distance !== undefined && r.distance !== null) ? r.distance : 0}</td>
  6243. <td class="py-2.5 px-3 font-mono font-semibold text-purple-300">${r.routing_table || 'main'}</td>
  6244. <td class="py-2.5 px-3 text-emerald-400 font-mono">${r.interface || '-'}</td>
  6245. <td class="py-2.5 px-3">${healthCell}</td>
  6246. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]">${r.comment || '-'}</td>
  6247. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  6248. ${r.static ? `
  6249. <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>
  6250. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold">Edit</button>
  6251. <button onclick="deleteRoute('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  6252. ` : `
  6253. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">View</button>
  6254. `}
  6255. </td>
  6256. `;
  6257. tbody.appendChild(tr);
  6258. });
  6259. }
  6260. function openAddRouteModal() {
  6261. document.getElementById('route-modal-title').innerText = 'Add Static Route';
  6262. document.getElementById('route-modal-id').value = '';
  6263. document.getElementById('route-modal-old-dst').value = '';
  6264. document.getElementById('route-modal-old-gw').value = '';
  6265. document.getElementById('route-modal-old-distance').value = '';
  6266. document.getElementById('route-modal-old-table').value = '';
  6267. document.getElementById('route-modal-old-iface').value = '';
  6268. const dstInput = document.getElementById('route-modal-dst');
  6269. const gwInput = document.getElementById('route-modal-gw');
  6270. const distInput = document.getElementById('route-modal-distance');
  6271. const ifaceSelect = document.getElementById('route-modal-iface');
  6272. const tableSelect = document.getElementById('route-modal-table');
  6273. const commentInput = document.getElementById('route-modal-comment');
  6274. const disCheck = document.getElementById('route-modal-disabled');
  6275. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  6276. dstInput.disabled = false;
  6277. dstInput.value = '0.0.0.0/0';
  6278. gwInput.disabled = false;
  6279. gwInput.value = '';
  6280. distInput.disabled = false;
  6281. distInput.value = '1';
  6282. ifaceSelect.disabled = false;
  6283. tableSelect.disabled = false;
  6284. commentInput.disabled = false;
  6285. commentInput.value = '';
  6286. disCheck.disabled = false;
  6287. disCheck.checked = false;
  6288. if (saveBtn) saveBtn.classList.remove('hidden');
  6289. const checkGw = document.getElementById('route-modal-check-gw');
  6290. if (checkGw) checkGw.value = 'internet';
  6291. const checkTarget = document.getElementById('route-modal-check-target');
  6292. if (checkTarget) checkTarget.value = '1.1.1.1';
  6293. const checkInterval = document.getElementById('route-modal-check-interval');
  6294. if (checkInterval) checkInterval.value = '5';
  6295. const checkThresh = document.getElementById('route-modal-check-threshold');
  6296. if (checkThresh) checkThresh.value = '3';
  6297. toggleRouteCheckModeUI();
  6298. populateInterfaceSelect('route-modal-iface');
  6299. // Populate tables
  6300. tableSelect.innerHTML = '';
  6301. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  6302. const opt = document.createElement('option');
  6303. opt.value = t.name;
  6304. opt.innerText = t.name;
  6305. if (t.name === 'main') opt.selected = true;
  6306. tableSelect.appendChild(opt);
  6307. });
  6308. document.getElementById('route-modal').classList.remove('hidden');
  6309. }
  6310. function openEditRouteModal(id) {
  6311. const r = (state.routes || []).find(route => route.id === id);
  6312. if (!r) return;
  6313. const isStatic = !!r.static;
  6314. document.getElementById('route-modal-title').innerText = isStatic
  6315. ? `Edit Route: ${r.dst_address}`
  6316. : `Route Properties (Read Only): ${r.dst_address}`;
  6317. document.getElementById('route-modal-id').value = r.id;
  6318. document.getElementById('route-modal-old-dst').value = r.dst_address || '';
  6319. document.getElementById('route-modal-old-gw').value = r.gateway || '';
  6320. document.getElementById('route-modal-old-distance').value = (r.distance !== undefined && r.distance !== null) ? r.distance : '';
  6321. document.getElementById('route-modal-old-table').value = r.routing_table || 'main';
  6322. document.getElementById('route-modal-old-iface').value = r.interface || '';
  6323. const dstInput = document.getElementById('route-modal-dst');
  6324. const gwInput = document.getElementById('route-modal-gw');
  6325. const distInput = document.getElementById('route-modal-distance');
  6326. const ifaceSelect = document.getElementById('route-modal-iface');
  6327. const tableSelect = document.getElementById('route-modal-table');
  6328. const commentInput = document.getElementById('route-modal-comment');
  6329. const disCheck = document.getElementById('route-modal-disabled');
  6330. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  6331. dstInput.value = r.dst_address;
  6332. gwInput.value = r.gateway || '';
  6333. distInput.value = (r.distance !== undefined && r.distance !== null) ? r.distance : 1;
  6334. commentInput.value = r.comment || '';
  6335. disCheck.checked = !!r.disabled;
  6336. const checkGw = document.getElementById('route-modal-check-gw');
  6337. if (checkGw) checkGw.value = r.check_gateway || 'none';
  6338. const checkTarget = document.getElementById('route-modal-check-target');
  6339. if (checkTarget) checkTarget.value = r.check_target || '1.1.1.1';
  6340. const checkInterval = document.getElementById('route-modal-check-interval');
  6341. if (checkInterval) checkInterval.value = r.check_interval || 5;
  6342. const checkThresh = document.getElementById('route-modal-check-threshold');
  6343. if (checkThresh) checkThresh.value = r.check_threshold || 3;
  6344. toggleRouteCheckModeUI();
  6345. dstInput.disabled = !isStatic;
  6346. gwInput.disabled = !isStatic;
  6347. distInput.disabled = !isStatic;
  6348. ifaceSelect.disabled = !isStatic;
  6349. tableSelect.disabled = !isStatic;
  6350. commentInput.disabled = !isStatic;
  6351. disCheck.disabled = !isStatic;
  6352. if (checkGw) checkGw.disabled = !isStatic;
  6353. if (checkTarget) checkTarget.disabled = !isStatic;
  6354. if (checkInterval) checkInterval.disabled = !isStatic;
  6355. if (checkThresh) checkThresh.disabled = !isStatic;
  6356. if (saveBtn) {
  6357. if (isStatic) {
  6358. saveBtn.classList.remove('hidden');
  6359. } else {
  6360. saveBtn.classList.add('hidden');
  6361. }
  6362. }
  6363. populateInterfaceSelect('route-modal-iface', r.interface);
  6364. tableSelect.innerHTML = '';
  6365. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  6366. const opt = document.createElement('option');
  6367. opt.value = t.name;
  6368. opt.innerText = t.name;
  6369. if (t.name === (r.routing_table || 'main')) opt.selected = true;
  6370. tableSelect.appendChild(opt);
  6371. });
  6372. document.getElementById('route-modal').classList.remove('hidden');
  6373. }
  6374. function closeRouteModal() {
  6375. document.getElementById('route-modal').classList.add('hidden');
  6376. }
  6377. function setRouteCheckTarget(ip) {
  6378. const inp = document.getElementById('route-modal-check-target');
  6379. if (inp) inp.value = ip;
  6380. }
  6381. function toggleRouteCheckModeUI() {
  6382. const mode = document.getElementById('route-modal-check-gw')?.value || 'none';
  6383. const targetRow = document.getElementById('route-row-check-target');
  6384. const paramsRow = document.getElementById('route-row-check-params');
  6385. if (mode === 'none') {
  6386. if (targetRow) targetRow.classList.add('opacity-40', 'pointer-events-none');
  6387. if (paramsRow) paramsRow.classList.add('opacity-40', 'pointer-events-none');
  6388. } else if (mode === 'ping') {
  6389. if (targetRow) targetRow.classList.add('opacity-40', 'pointer-events-none');
  6390. if (paramsRow) paramsRow.classList.remove('opacity-40', 'pointer-events-none');
  6391. } else { // internet
  6392. if (targetRow) targetRow.classList.remove('opacity-40', 'pointer-events-none');
  6393. if (paramsRow) paramsRow.classList.remove('opacity-40', 'pointer-events-none');
  6394. }
  6395. }
  6396. async function submitSaveRoute(e) {
  6397. e.preventDefault();
  6398. const id = document.getElementById('route-modal-id').value;
  6399. const oldDst = document.getElementById('route-modal-old-dst')?.value || '';
  6400. const oldGw = document.getElementById('route-modal-old-gw')?.value || '';
  6401. const oldDistStr = document.getElementById('route-modal-old-distance')?.value;
  6402. const oldTable = document.getElementById('route-modal-old-table')?.value || '';
  6403. const oldIface = document.getElementById('route-modal-old-iface')?.value || '';
  6404. const dst = document.getElementById('route-modal-dst').value.trim();
  6405. const gw = document.getElementById('route-modal-gw').value.trim();
  6406. const table = document.getElementById('route-modal-table').value;
  6407. const distance = parseInt(document.getElementById('route-modal-distance').value, 10) || 0;
  6408. const iface = document.getElementById('route-modal-iface').value;
  6409. const comment = document.getElementById('route-modal-comment').value.trim();
  6410. const disabled = document.getElementById('route-modal-disabled').checked;
  6411. const check_gateway = document.getElementById('route-modal-check-gw')?.value || 'none';
  6412. const check_target = document.getElementById('route-modal-check-target')?.value.trim() || '1.1.1.1';
  6413. const check_interval = parseInt(document.getElementById('route-modal-check-interval')?.value, 10) || 5;
  6414. const check_threshold = parseInt(document.getElementById('route-modal-check-threshold')?.value, 10) || 3;
  6415. if (!dst) {
  6416. showToast('Error', 'Destination address is required', 'error');
  6417. return;
  6418. }
  6419. if (!gw && !iface) {
  6420. showToast('Error', 'Either Gateway IP or Interface must be specified', 'error');
  6421. return;
  6422. }
  6423. const payload = {
  6424. id,
  6425. old_dst_address: oldDst,
  6426. old_gateway: oldGw,
  6427. old_routing_table: oldTable,
  6428. old_interface: oldIface,
  6429. dst_address: dst,
  6430. gateway: gw || iface,
  6431. routing_table: table,
  6432. distance,
  6433. interface: iface,
  6434. comment,
  6435. disabled,
  6436. check_gateway,
  6437. check_target,
  6438. check_interval,
  6439. check_threshold
  6440. };
  6441. if (oldDistStr !== undefined && oldDistStr !== '') {
  6442. payload.old_distance = parseInt(oldDistStr, 10);
  6443. }
  6444. try {
  6445. const res = await fetch(`${API_BASE}/routes`, {
  6446. method: 'POST',
  6447. headers: { 'Content-Type': 'application/json' },
  6448. body: JSON.stringify(payload)
  6449. });
  6450. if (res.ok) {
  6451. showToast('Route Saved', `Route to ${dst} installed`, 'success');
  6452. closeRouteModal();
  6453. loadRoutes();
  6454. } else {
  6455. const err = await res.json();
  6456. showToast('Error', err.message || 'Failed to save route', 'error');
  6457. }
  6458. } catch (err) {
  6459. showToast('Error', err.message, 'error');
  6460. }
  6461. }
  6462. async function toggleRouteState(id, disabled) {
  6463. try {
  6464. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}/state`, {
  6465. method: 'POST',
  6466. headers: { 'Content-Type': 'application/json' },
  6467. body: JSON.stringify({ disabled })
  6468. });
  6469. if (res.ok) loadRoutes();
  6470. } catch (err) {
  6471. showToast('Error', err.message, 'error');
  6472. }
  6473. }
  6474. async function deleteRoute(id) {
  6475. if (!confirm('Are you sure you want to delete this route?')) return;
  6476. try {
  6477. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6478. if (res.ok) {
  6479. showToast('Deleted', 'Route removed', 'success');
  6480. loadRoutes();
  6481. }
  6482. } catch (err) {
  6483. showToast('Error', err.message, 'error');
  6484. }
  6485. }
  6486. // ----------------- Policy Rules (/ip route rule) -----------------
  6487. function renderPolicyRules() {
  6488. const tbody = document.getElementById('rules-table-body');
  6489. const empty = document.getElementById('rules-empty');
  6490. if (!tbody) return;
  6491. const showSystem = document.getElementById('prule-show-system')?.checked;
  6492. const filtered = (state.policyRules || []).filter(pr => showSystem || (!pr.is_default && !pr.is_system));
  6493. const countBadge = document.getElementById('rules-count-badge');
  6494. if (countBadge) countBadge.innerText = `${filtered.length} Rules`;
  6495. const bRules = document.getElementById('routes-badge-rules');
  6496. if (bRules) bRules.innerText = filtered.length;
  6497. if (filtered.length === 0) {
  6498. empty?.classList.remove('hidden');
  6499. tbody.innerHTML = '';
  6500. return;
  6501. }
  6502. empty?.classList.add('hidden');
  6503. const sig = `${showSystem}|` + filtered.map(pr => `${pr.id}:${pr.priority}:${pr.src_address}:${pr.dst_address}:${pr.table}:${pr.routing_mark}`).join(';');
  6504. if (tbody.dataset.sig === sig) return;
  6505. tbody.dataset.sig = sig;
  6506. tbody.innerHTML = '';
  6507. filtered.forEach(pr => {
  6508. const isSys = pr.is_default || pr.is_system;
  6509. const tr = document.createElement('tr');
  6510. tr.className = `hover:bg-slate-800/40 transition text-xs ${isSys ? 'opacity-70 bg-slate-950/20' : ''}`;
  6511. tr.innerHTML = `
  6512. <td class="py-2.5 px-3 font-mono text-cyan-400 font-bold">${pr.priority}</td>
  6513. <td class="py-2.5 px-3 font-mono text-white">${pr.src_address || '<span class="text-slate-600">all</span>'}</td>
  6514. <td class="py-2.5 px-3 font-mono text-white">${pr.dst_address || '<span class="text-slate-600">all</span>'}</td>
  6515. <td class="py-2.5 px-3 font-mono font-bold text-purple-300">${pr.routing_mark || '<span class="text-slate-600">-</span>'}</td>
  6516. <td class="py-2.5 px-3 font-mono font-bold text-amber-300">${pr.table}</td>
  6517. <td class="py-2.5 px-3 font-mono text-slate-300">${pr.action}</td>
  6518. <td class="py-2.5 px-3 text-right font-sans">
  6519. ${!pr.is_default ? `
  6520. <button onclick="deletePolicyRule('${pr.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  6521. ` : `<span class="text-slate-600 text-[10px]">Default</span>`}
  6522. </td>
  6523. `;
  6524. tbody.appendChild(tr);
  6525. });
  6526. }
  6527. function openAddPolicyRuleModal() {
  6528. const userRules = (state.policyRules || []).filter(pr => !pr.is_default && !pr.is_system);
  6529. document.getElementById('prule-modal-pref').value = userRules.length * 10 + 1000;
  6530. document.getElementById('prule-modal-mark').value = '';
  6531. document.getElementById('prule-modal-src').value = '';
  6532. document.getElementById('prule-modal-dst').value = '';
  6533. const sel = document.getElementById('prule-modal-table');
  6534. sel.innerHTML = '';
  6535. (state.routingTables || []).forEach(t => {
  6536. const opt = document.createElement('option');
  6537. opt.value = t.name;
  6538. opt.innerText = t.name;
  6539. sel.appendChild(opt);
  6540. });
  6541. document.getElementById('prule-modal').classList.remove('hidden');
  6542. }
  6543. function closePolicyRuleModal() {
  6544. document.getElementById('prule-modal').classList.add('hidden');
  6545. }
  6546. async function submitSavePolicyRule(e) {
  6547. e.preventDefault();
  6548. const pref = parseInt(document.getElementById('prule-modal-pref').value, 10) || 1000;
  6549. const mark = document.getElementById('prule-modal-mark').value.trim();
  6550. const src = document.getElementById('prule-modal-src').value.trim();
  6551. const dst = document.getElementById('prule-modal-dst').value.trim();
  6552. const table = document.getElementById('prule-modal-table').value;
  6553. const action = document.getElementById('prule-modal-action').value;
  6554. try {
  6555. const res = await fetch(`${API_BASE}/routing/rules`, {
  6556. method: 'POST',
  6557. headers: { 'Content-Type': 'application/json' },
  6558. body: JSON.stringify({ priority: pref, routing_mark: mark, src_address: src, dst_address: dst, table, action })
  6559. });
  6560. if (res.ok) {
  6561. showToast('Rule Added', `Policy rule installed for table ${table}`, 'success');
  6562. closePolicyRuleModal();
  6563. loadRoutes();
  6564. } else {
  6565. const err = await res.json();
  6566. showToast('Error', err.message, 'error');
  6567. }
  6568. } catch (err) {
  6569. showToast('Error', err.message, 'error');
  6570. }
  6571. }
  6572. async function deletePolicyRule(id) {
  6573. if (!confirm('Are you sure you want to remove this policy rule?')) return;
  6574. try {
  6575. const res = await fetch(`${API_BASE}/routing/rules/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6576. if (res.ok) {
  6577. showToast('Rule Removed', 'Policy rule deleted', 'success');
  6578. loadRoutes();
  6579. }
  6580. } catch (err) {
  6581. showToast('Error', err.message, 'error');
  6582. }
  6583. }
  6584. // ----------------- Routing Tables -----------------
  6585. function renderRoutingTables() {
  6586. const tbody = document.getElementById('tables-table-body');
  6587. if (!tbody) return;
  6588. const tables = state.routingTables || [];
  6589. const sig = tables.map(t => `${t.table_id}:${t.name}:${t.comment}`).join(';');
  6590. if (tbody.dataset.sig === sig) return;
  6591. tbody.dataset.sig = sig;
  6592. tbody.innerHTML = '';
  6593. (state.routingTables || []).forEach(t => {
  6594. const tr = document.createElement('tr');
  6595. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  6596. tr.innerHTML = `
  6597. <td class="py-2.5 px-3 text-cyan-400 font-bold">${t.table_id}</td>
  6598. <td class="py-2.5 px-3 font-bold text-white">${t.name}</td>
  6599. <td class="py-2.5 px-3 text-slate-400 italic">${t.comment || '-'}</td>
  6600. `;
  6601. tbody.appendChild(tr);
  6602. });
  6603. }
  6604. function openAddTableModal() {
  6605. document.getElementById('table-modal-name').value = '';
  6606. document.getElementById('table-modal-id').value = '';
  6607. document.getElementById('table-modal-comment').value = '';
  6608. document.getElementById('table-modal').classList.remove('hidden');
  6609. }
  6610. function closeTableModal() {
  6611. document.getElementById('table-modal').classList.add('hidden');
  6612. }
  6613. async function submitSaveTable(e) {
  6614. e.preventDefault();
  6615. const name = document.getElementById('table-modal-name').value.trim();
  6616. const id = parseInt(document.getElementById('table-modal-id').value, 10) || 0;
  6617. const comment = document.getElementById('table-modal-comment').value.trim();
  6618. try {
  6619. const res = await fetch(`${API_BASE}/routing/tables`, {
  6620. method: 'POST',
  6621. headers: { 'Content-Type': 'application/json' },
  6622. body: JSON.stringify({ name, table_id: id, comment })
  6623. });
  6624. if (res.ok) {
  6625. showToast('Table Created', `Routing table ${name} registered`, 'success');
  6626. closeTableModal();
  6627. loadRoutes();
  6628. } else {
  6629. const err = await res.json();
  6630. showToast('Error', err.message, 'error');
  6631. }
  6632. } catch (err) {
  6633. showToast('Error', err.message, 'error');
  6634. }
  6635. }
  6636. async function loadDebianConfig() {
  6637. const view = document.getElementById('debian-config-view');
  6638. view.innerText = 'Generating live configuration...';
  6639. try {
  6640. const res = await fetch(`${API_BASE}/debian/config`);
  6641. const data = await res.json();
  6642. view.innerText = data.content || '# Empty config';
  6643. } catch (err) {
  6644. view.innerText = 'Failed to generate Debian network config.';
  6645. }
  6646. }
  6647. async function saveDebianConfig() {
  6648. try {
  6649. const res = await fetch(`${API_BASE}/debian/apply`, { method: 'POST' });
  6650. const data = await res.json();
  6651. if (res.ok) {
  6652. showToast('Configuration Saved', data.message || 'Saved to /etc/network/interfaces.d/vlans.cfg', 'success');
  6653. loadDebianConfig();
  6654. }
  6655. } catch (err) {
  6656. showToast('Error', err.message, 'error');
  6657. }
  6658. }
  6659. function showToast(title, message, type = 'info') {
  6660. const container = document.getElementById('toast-container');
  6661. const toast = document.createElement('div');
  6662. const borderColors = {
  6663. success: 'border-emerald-500/40 bg-slate-900/95 text-emerald-400',
  6664. error: 'border-rose-500/40 bg-slate-900/95 text-rose-400',
  6665. info: 'border-cyan-500/40 bg-slate-900/95 text-cyan-400'
  6666. };
  6667. 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}`;
  6668. toast.innerHTML = `
  6669. <div class="flex-1">
  6670. <div class="font-bold text-xs text-white">${title}</div>
  6671. <div class="text-[11px] text-slate-300 mt-0.5 leading-relaxed font-sans">${message}</div>
  6672. </div>
  6673. `;
  6674. container.appendChild(toast);
  6675. requestAnimationFrame(() => toast.classList.remove('translate-y-2', 'opacity-0'));
  6676. setTimeout(() => {
  6677. toast.classList.add('opacity-0', 'translate-y-2');
  6678. setTimeout(() => toast.remove(), 300);
  6679. }, 4000);
  6680. }
  6681. function formatTraffic(bytesPerSec) {
  6682. if (bytesPerSec < 1024) return `${Math.round(bytesPerSec)} B/s`;
  6683. const kb = bytesPerSec / 1024;
  6684. if (kb < 1024) return `${kb.toFixed(1)} KB/s`;
  6685. const mb = kb / 1024;
  6686. return `${mb.toFixed(2)} MB/s`;
  6687. }
  6688. function toggleSidebar() {
  6689. const sb = document.getElementById('sidebar');
  6690. sb.classList.toggle('-translate-x-full');
  6691. }
  6692. // ======================== EoIP (Ethernet over IP) ========================
  6693. async function loadEoIP(populate = true) {
  6694. try {
  6695. const res = await fetch(`${API_BASE}/vpn/eoip`);
  6696. const data = await res.json();
  6697. state.eoipTunnels = Array.isArray(data) ? data : [];
  6698. const badge = document.getElementById('eoip-count-badge');
  6699. if (badge) badge.innerText = `${state.eoipTunnels.length} Tunnels`;
  6700. const sideBadge = document.getElementById('badge-eoip-count');
  6701. if (sideBadge) sideBadge.innerText = state.eoipTunnels.length;
  6702. renderEoIPTunnels();
  6703. } catch (err) {
  6704. console.error('Failed to load EoIP:', err);
  6705. }
  6706. }
  6707. function renderEoIPTunnels() {
  6708. const tbody = document.getElementById('eoip-table-body');
  6709. const empty = document.getElementById('eoip-empty');
  6710. if (!tbody) return;
  6711. tbody.innerHTML = '';
  6712. const tunnels = state.eoipTunnels || [];
  6713. if (tunnels.length === 0) {
  6714. empty?.classList.remove('hidden');
  6715. return;
  6716. }
  6717. empty?.classList.add('hidden');
  6718. tunnels.forEach(t => {
  6719. const tr = document.createElement('tr');
  6720. tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
  6721. tr.innerHTML = `
  6722. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.running, t.disabled)}</td>
  6723. <td class="py-2.5 px-3 font-bold text-white font-mono">${t.name}</td>
  6724. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${t.tunnel_id}</td>
  6725. <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>
  6726. <td class="py-2.5 px-3 text-cyan-300 font-mono">${t.remote_address}</td>
  6727. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.local_address || '(any)'}</td>
  6728. <td class="py-2.5 px-3 text-slate-300 font-mono text-[11px]">${t.mac_address || '-'}</td>
  6729. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.mtu || 1500}</td>
  6730. <td class="py-2.5 px-3 font-mono text-[11px]">
  6731. <span class="text-emerald-400">↓ ${t.rx_human || '0 B'}</span>
  6732. <span class="text-cyan-400 ml-1">↑ ${t.tx_human || '0 B'}</span>
  6733. </td>
  6734. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${t.comment || ''}">${t.comment || '-'}</td>
  6735. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  6736. <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>
  6737. <button onclick="openEditEoIPModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  6738. <button onclick="deleteEoIP('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  6739. </td>
  6740. `;
  6741. tbody.appendChild(tr);
  6742. });
  6743. }
  6744. function openAddEoIPModal() {
  6745. document.getElementById('eoip-modal-title').innerText = 'Add EoIP Tunnel';
  6746. document.getElementById('eoip-modal-id').value = '';
  6747. document.getElementById('eoip-modal-name').value = `eoip-tunnel${(state.eoipTunnels || []).length + 1}`;
  6748. document.getElementById('eoip-modal-tunnelid').value = (state.eoipTunnels || []).length + 10;
  6749. document.getElementById('eoip-modal-remote').value = '';
  6750. document.getElementById('eoip-modal-ip').value = '';
  6751. document.getElementById('eoip-modal-local').value = '';
  6752. document.getElementById('eoip-modal-mac').value = '';
  6753. document.getElementById('eoip-modal-mtu').value = '1500';
  6754. document.getElementById('eoip-modal-comment').value = '';
  6755. document.getElementById('eoip-modal-clampmss').checked = true;
  6756. document.getElementById('eoip-modal-disabled').checked = false;
  6757. document.getElementById('eoip-modal').classList.remove('hidden');
  6758. }
  6759. function openEditEoIPModal(id) {
  6760. const t = (state.eoipTunnels || []).find(tun => tun.id === id);
  6761. if (!t) return;
  6762. document.getElementById('eoip-modal-title').innerText = `Edit EoIP Tunnel (${t.name})`;
  6763. document.getElementById('eoip-modal-id').value = t.id;
  6764. document.getElementById('eoip-modal-name').value = t.name;
  6765. document.getElementById('eoip-modal-tunnelid').value = t.tunnel_id;
  6766. document.getElementById('eoip-modal-remote').value = t.remote_address;
  6767. document.getElementById('eoip-modal-ip').value = t.ip_address || '';
  6768. document.getElementById('eoip-modal-local').value = t.local_address || '';
  6769. document.getElementById('eoip-modal-mac').value = t.mac_address || '';
  6770. document.getElementById('eoip-modal-mtu').value = t.mtu || 1500;
  6771. document.getElementById('eoip-modal-comment').value = t.comment || '';
  6772. document.getElementById('eoip-modal-clampmss').checked = !!t.clamp_mss;
  6773. document.getElementById('eoip-modal-disabled').checked = !!t.disabled;
  6774. document.getElementById('eoip-modal').classList.remove('hidden');
  6775. }
  6776. function closeEoIPModal() {
  6777. document.getElementById('eoip-modal').classList.add('hidden');
  6778. }
  6779. async function submitSaveEoIP(e) {
  6780. e.preventDefault();
  6781. const id = document.getElementById('eoip-modal-id').value;
  6782. const name = document.getElementById('eoip-modal-name').value.trim();
  6783. const tunnelId = parseInt(document.getElementById('eoip-modal-tunnelid').value);
  6784. const remote = document.getElementById('eoip-modal-remote').value.trim();
  6785. const ipAddress = document.getElementById('eoip-modal-ip').value.trim();
  6786. const local = document.getElementById('eoip-modal-local').value.trim();
  6787. const mac = document.getElementById('eoip-modal-mac').value.trim();
  6788. const mtu = parseInt(document.getElementById('eoip-modal-mtu').value) || 1500;
  6789. const comment = document.getElementById('eoip-modal-comment').value.trim();
  6790. const clampMss = document.getElementById('eoip-modal-clampmss').checked;
  6791. const disabled = document.getElementById('eoip-modal-disabled').checked;
  6792. try {
  6793. const res = await fetch(`${API_BASE}/vpn/eoip`, {
  6794. method: 'POST',
  6795. headers: { 'Content-Type': 'application/json' },
  6796. body: JSON.stringify({
  6797. id,
  6798. name,
  6799. tunnel_id: tunnelId,
  6800. remote_address: remote,
  6801. ip_address: ipAddress,
  6802. local_address: local,
  6803. mac_address: mac,
  6804. mtu,
  6805. clamp_mss: clampMss,
  6806. comment,
  6807. disabled
  6808. })
  6809. });
  6810. if (res.ok) {
  6811. showToast('EoIP Saved', `Tunnel ${name} configured successfully`, 'success');
  6812. closeEoIPModal();
  6813. loadEoIP(false);
  6814. fetchData(false);
  6815. } else {
  6816. const err = await res.json();
  6817. showToast('Error', err.message, 'error');
  6818. }
  6819. } catch (err) {
  6820. showToast('Error', err.message, 'error');
  6821. }
  6822. }
  6823. async function toggleEoIPState(id, disabled) {
  6824. try {
  6825. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}/state`, {
  6826. method: 'POST',
  6827. headers: { 'Content-Type': 'application/json' },
  6828. body: JSON.stringify({ disabled })
  6829. });
  6830. if (res.ok) {
  6831. showToast(disabled ? 'Disabled' : 'Enabled', 'EoIP tunnel state updated', 'info');
  6832. loadEoIP(false);
  6833. fetchData(false);
  6834. }
  6835. } catch (err) {
  6836. showToast('Error', err.message, 'error');
  6837. }
  6838. }
  6839. async function deleteEoIP(id) {
  6840. if (!confirm('Are you sure you want to delete this EoIP tunnel?')) return;
  6841. try {
  6842. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6843. if (res.ok) {
  6844. showToast('Deleted', 'EoIP tunnel removed', 'success');
  6845. loadEoIP(false);
  6846. fetchData(false);
  6847. }
  6848. } catch (err) {
  6849. showToast('Error', err.message, 'error');
  6850. }
  6851. }
  6852. // ======================== AeroTUN (Custom Encrypted VPN with Adaptive LZ4) ========================
  6853. async function loadAeroTUN(populate = true) {
  6854. try {
  6855. const [tunnelsRes, statsRes] = await Promise.all([
  6856. fetch(`${API_BASE}/vpn/aerotun/tunnels`),
  6857. fetch(`${API_BASE}/vpn/aerotun/stats`)
  6858. ]);
  6859. if (tunnelsRes.ok) {
  6860. const data = await tunnelsRes.json();
  6861. state.aerotunTunnels = Array.isArray(data) ? data : [];
  6862. }
  6863. if (statsRes.ok) {
  6864. state.aerotunStats = await statsRes.json();
  6865. }
  6866. const countBadge = document.getElementById('aerotun-count-badge');
  6867. if (countBadge) countBadge.innerText = `${(state.aerotunTunnels || []).length} Tunnels`;
  6868. const sideBadge = document.getElementById('badge-aerotun-count');
  6869. if (sideBadge) sideBadge.innerText = (state.aerotunTunnels || []).length;
  6870. renderAeroTUN();
  6871. } catch (err) {
  6872. console.error('Failed to load AeroTUN:', err);
  6873. }
  6874. }
  6875. function renderAeroTUN() {
  6876. const tbody = document.getElementById('aerotun-table-body');
  6877. const empty = document.getElementById('aerotun-empty');
  6878. // Update summary cards
  6879. const stats = state.aerotunStats || {};
  6880. const tunnels = state.aerotunTunnels || [];
  6881. const statActive = document.getElementById('aerotun-stat-active');
  6882. if (statActive) {
  6883. const activeCount = tunnels.filter(t => t.connected).length;
  6884. statActive.innerText = `${activeCount} / ${tunnels.length}`;
  6885. }
  6886. const statSaved = document.getElementById('aerotun-stat-saved');
  6887. if (statSaved) {
  6888. statSaved.innerText = formatBytes(stats.total_saved_bytes || 0);
  6889. }
  6890. const statRatio = document.getElementById('aerotun-stat-ratio');
  6891. if (statRatio) {
  6892. statRatio.innerText = stats.average_ratio || '1.00x (0% saved)';
  6893. }
  6894. const statTraffic = document.getElementById('aerotun-stat-traffic');
  6895. if (statTraffic) {
  6896. statTraffic.innerText = `↓ ${formatBytes(stats.total_rx_bytes || 0)} / ↑ ${formatBytes(stats.total_tx_bytes || 0)}`;
  6897. }
  6898. if (!tbody) return;
  6899. tbody.innerHTML = '';
  6900. if (tunnels.length === 0) {
  6901. empty?.classList.remove('hidden');
  6902. return;
  6903. }
  6904. empty?.classList.add('hidden');
  6905. tunnels.forEach(t => {
  6906. const tr = document.createElement('tr');
  6907. tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
  6908. const modeBadge = t.mode === 'server'
  6909. ? `<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>`
  6910. : `<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>`;
  6911. const endpointInfo = t.mode === 'server'
  6912. ? `<span class="text-sky-300 font-mono">Port :${t.listen_port || 51830}</span>`
  6913. : `<span class="text-indigo-300 font-mono">${escapeHtml(t.remote_endpoint || '(not set)')}</span>`;
  6914. const compBadge = t.compression
  6915. ? `<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>`
  6916. : `<span class="text-slate-500 text-[10px]">Off</span>`;
  6917. const activePeer = t.connected && t.active_peer_endpoint
  6918. ? `<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>`
  6919. : `<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>`;
  6920. const rawRx = formatBytes(t.rx_bytes || 0);
  6921. const rawTx = formatBytes(t.tx_bytes || 0);
  6922. const wireRx = formatBytes(t.wire_bytes_in || 0);
  6923. const wireTx = formatBytes(t.wire_bytes_out || 0);
  6924. tr.innerHTML = `
  6925. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.connected, t.disabled)}</td>
  6926. <td class="py-2.5 px-3 font-bold text-white font-mono flex items-center gap-1.5">
  6927. <span>${escapeHtml(t.name)}</span>
  6928. ${t.default_route ? '<span class="text-[9px] px-1 rounded bg-amber-500/20 text-amber-300 border border-amber-500/30">DEF</span>' : ''}
  6929. <span class="text-slate-400 text-[10px]">v${t.protocol_version || 2}</span>
  6930. </td>
  6931. <td class="py-2.5 px-3">${modeBadge}</td>
  6932. <td class="py-2.5 px-3 text-xs font-mono">${endpointInfo}</td>
  6933. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${escapeHtml(t.local_address || '-')}</td>
  6934. <td class="py-2.5 px-3">${compBadge}</td>
  6935. <td class="py-2.5 px-3">${activePeer}</td>
  6936. <td class="py-2.5 px-3 font-mono text-[11px]">
  6937. <span class="text-emerald-400">↓ ${rawRx}</span>
  6938. <span class="text-cyan-400 ml-1">↑ ${rawTx}</span>
  6939. </td>
  6940. <td class="py-2.5 px-3 font-mono text-[11px]">
  6941. <span class="text-slate-400">↓ ${wireRx}</span>
  6942. <span class="text-slate-400 ml-1">↑ ${wireTx}</span>
  6943. </td>
  6944. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(t.comment || '')}">${escapeHtml(t.comment || '-')}</td>
  6945. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  6946. ${t.running
  6947. ? `<button onclick="stopAeroTUNTunnel('${t.id}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Stop</button>`
  6948. : `<button onclick="startAeroTUNTunnel('${t.id}')" class="text-xs text-emerald-400 hover:text-emerald-300 font-medium">Start</button>`
  6949. }
  6950. <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>
  6951. <button onclick="openEditAeroTUNModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  6952. <button onclick="deleteAeroTUN('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  6953. </td>
  6954. `;
  6955. tbody.appendChild(tr);
  6956. });
  6957. }
  6958. function onAeroTUNModeChange() {
  6959. const mode = document.getElementById('aerotun-modal-mode').value;
  6960. const endpointInput = document.getElementById('aerotun-modal-endpoint');
  6961. const portInput = document.getElementById('aerotun-modal-port');
  6962. if (mode === 'server') {
  6963. if (!portInput.value) portInput.value = '51830';
  6964. endpointInput.placeholder = 'Optional / learned roaming peer';
  6965. } else {
  6966. endpointInput.placeholder = 'vpn.example.com:51830 (required)';
  6967. if (!portInput.value) portInput.value = '';
  6968. }
  6969. }
  6970. async function generateAeroTUNKey() {
  6971. try {
  6972. const res = await fetch(`${API_BASE}/vpn/aerotun/genkey`);
  6973. if (!res.ok) throw new Error(await responseError(res));
  6974. const data = await res.json();
  6975. document.getElementById('aerotun-modal-psk').value = data.key;
  6976. showToast('Key Generated', 'Share this PSK securely with the peer before enabling', 'success');
  6977. } catch (err) {
  6978. showToast('Key Generation Failed', err.message, 'error');
  6979. }
  6980. }
  6981. function updateAeroTUNSetupHint() {
  6982. const version = document.getElementById('aerotun-modal-protocol').value;
  6983. const key = document.getElementById('aerotun-modal-public').value;
  6984. const peer = document.getElementById('aerotun-modal-peerkey').value.trim();
  6985. const hint = document.getElementById('aerotun-setup-hint');
  6986. if (!hint) return;
  6987. hint.innerText = version !== '3' ? 'Legacy v2 uses a shared PSK. Both endpoints must use the same protocol.' : !key ? '1. Save disabled to create the local identity. 2. Exchange public keys and share the same PSK. 3. Set allowed peer prefixes, then enable.' : !peer ? 'Local identity saved. Copy the public key to the peer and paste its public key here. Use the same PSK on both endpoints.' : 'Peer identity configured. Check reciprocal addresses, allowed peer source prefixes and the shared PSK before enabling. Allowed prefixes do not create LAN routes.';
  6988. }
  6989. async function copyAeroTUNPublicKey() {
  6990. const input = document.getElementById('aerotun-modal-public');
  6991. if (!input.value) { showToast('Save First', 'Save the disabled tunnel to create its public key', 'info'); return; }
  6992. try {
  6993. await navigator.clipboard.writeText(input.value);
  6994. showToast('Public Key Copied', 'Paste it into the other endpoint’s pinned peer key', 'success');
  6995. } catch {
  6996. input.focus(); input.select();
  6997. showToast('Copy Public Key', 'Key selected; press Ctrl+C to copy', 'info');
  6998. }
  6999. }
  7000. function openAddAeroTUNModal() {
  7001. const tunnels = state.aerotunTunnels || [];
  7002. document.getElementById('aerotun-modal-title').innerText = 'Add AeroTUN Interface';
  7003. document.getElementById('aerotun-modal-id').value = '';
  7004. document.getElementById('aerotun-modal-protocol').value='3';
  7005. document.getElementById('aerotun-modal-public').value='';
  7006. document.getElementById('aerotun-modal-peerkey').value='';
  7007. document.getElementById('aerotun-modal-allowed').value=`10.99.${tunnels.length}.2/32`;
  7008. document.getElementById('aerotun-modal-name').value = `aerotun${tunnels.length}`;
  7009. document.getElementById('aerotun-modal-mode').value = 'server';
  7010. document.getElementById('aerotun-modal-port').value = 51830 + tunnels.length;
  7011. document.getElementById('aerotun-modal-endpoint').value = '';
  7012. document.getElementById('aerotun-modal-local').value = `10.99.${tunnels.length}.1/24`;
  7013. document.getElementById('aerotun-modal-peer').value = `10.99.${tunnels.length}.2/24`;
  7014. document.getElementById('aerotun-modal-psk').value = '';
  7015. document.getElementById('aerotun-modal-mtu').value = '1420';
  7016. document.getElementById('aerotun-modal-comment').value = '';
  7017. document.getElementById('aerotun-modal-compression').checked = false;
  7018. document.getElementById('aerotun-modal-defroute').checked = false;
  7019. document.getElementById('aerotun-modal-disabled').checked = true;
  7020. generateAeroTUNKey();
  7021. onAeroTUNModeChange();
  7022. updateAeroTUNSetupHint();
  7023. document.getElementById('aerotun-modal').classList.remove('hidden');
  7024. }
  7025. function openEditAeroTUNModal(id) {
  7026. const t = (state.aerotunTunnels || []).find(tun => tun.id === id);
  7027. if (!t) return;
  7028. document.getElementById('aerotun-modal-title').innerText = `Edit AeroTUN Interface (${t.name})`;
  7029. document.getElementById('aerotun-modal-id').value = t.id;
  7030. document.getElementById('aerotun-modal-protocol').value=String(t.protocol_version || 2);
  7031. document.getElementById('aerotun-modal-public').value=t.public_key || '';
  7032. document.getElementById('aerotun-modal-peerkey').value=t.peer_public_key || '';
  7033. document.getElementById('aerotun-modal-allowed').value=(t.allowed_ips || []).join(', ');
  7034. document.getElementById('aerotun-modal-name').value = t.name;
  7035. document.getElementById('aerotun-modal-mode').value = t.mode || 'server';
  7036. document.getElementById('aerotun-modal-port').value = t.listen_port || '';
  7037. document.getElementById('aerotun-modal-endpoint').value = t.remote_endpoint || '';
  7038. document.getElementById('aerotun-modal-local').value = t.local_address || '';
  7039. document.getElementById('aerotun-modal-peer').value = t.peer_address || '';
  7040. document.getElementById('aerotun-modal-psk').value = '';
  7041. document.getElementById('aerotun-modal-psk').placeholder = t.has_psk ? 'Leave blank to keep the existing key' : 'New random 256-bit PSK';
  7042. document.getElementById('aerotun-modal-mtu').value = t.mtu || 1420;
  7043. document.getElementById('aerotun-modal-comment').value = t.comment || '';
  7044. document.getElementById('aerotun-modal-compression').checked = !!t.compression;
  7045. document.getElementById('aerotun-modal-defroute').checked = !!t.default_route;
  7046. document.getElementById('aerotun-modal-disabled').checked = !!t.disabled;
  7047. onAeroTUNModeChange();
  7048. updateAeroTUNSetupHint();
  7049. document.getElementById('aerotun-modal').classList.remove('hidden');
  7050. }
  7051. function closeAeroTUNModal() {
  7052. document.getElementById('aerotun-modal').classList.add('hidden');
  7053. }
  7054. async function submitSaveAeroTUN(e) {
  7055. e.preventDefault();
  7056. const id = document.getElementById('aerotun-modal-id').value;
  7057. const name = document.getElementById('aerotun-modal-name').value.trim();
  7058. const mode = document.getElementById('aerotun-modal-mode').value;
  7059. const port = parseInt(document.getElementById('aerotun-modal-port').value) || 0;
  7060. const endpoint = document.getElementById('aerotun-modal-endpoint').value.trim();
  7061. const local = document.getElementById('aerotun-modal-local').value.trim();
  7062. const peer = document.getElementById('aerotun-modal-peer').value.trim();
  7063. const psk = document.getElementById('aerotun-modal-psk').value.trim();
  7064. const mtu = parseInt(document.getElementById('aerotun-modal-mtu').value) || 1420;
  7065. const comment = document.getElementById('aerotun-modal-comment').value.trim();
  7066. const compression = document.getElementById('aerotun-modal-compression').checked;
  7067. const defaultRoute = document.getElementById('aerotun-modal-defroute').checked;
  7068. const disabled = document.getElementById('aerotun-modal-disabled').checked;
  7069. if (mode === 'client' && !endpoint) {
  7070. showToast('Validation Error', 'Remote endpoint (host:port) is required in client mode', 'error');
  7071. return;
  7072. }
  7073. const version = parseInt(document.getElementById('aerotun-modal-protocol').value, 10);
  7074. if (version === 3 && !disabled && !document.getElementById('aerotun-modal-peerkey').value.trim()) {
  7075. showToast('Peer Key Required', 'Save disabled first, exchange public keys, then enable', 'error');
  7076. return;
  7077. }
  7078. if (!psk && !id) {
  7079. showToast('Validation Error', 'Pre-shared key (PSK) is required', 'error');
  7080. return;
  7081. }
  7082. try {
  7083. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels`, {
  7084. method: 'POST',
  7085. headers: { 'Content-Type': 'application/json' },
  7086. body: JSON.stringify({
  7087. protocol_version:parseInt(document.getElementById('aerotun-modal-protocol').value,10),
  7088. peer_public_key:document.getElementById('aerotun-modal-peerkey').value.trim(),
  7089. allowed_ips:document.getElementById('aerotun-modal-allowed').value.split(',').map(s=>s.trim()).filter(Boolean),
  7090. id,
  7091. name,
  7092. mode,
  7093. listen_port: port,
  7094. remote_endpoint: endpoint,
  7095. local_address: local,
  7096. peer_address: peer,
  7097. psk,
  7098. mtu,
  7099. compression,
  7100. default_route: defaultRoute,
  7101. comment,
  7102. disabled
  7103. })
  7104. });
  7105. if (res.ok) {
  7106. const saved = await res.json();
  7107. await loadAeroTUN(false);
  7108. if (!id && version === 3) {
  7109. openEditAeroTUNModal(saved.id);
  7110. showToast('Identity Saved', 'Copy the local public key and exchange keys with the peer', 'success');
  7111. } else {
  7112. closeAeroTUNModal();
  7113. showToast('AeroTUN Saved', disabled ? 'Configuration saved; tunnel is disabled' : 'Configuration saved; waiting for authenticated peer traffic', 'success');
  7114. }
  7115. fetchData(false);
  7116. } else {
  7117. const err = await res.text();
  7118. showToast('Error Saving Tunnel', err, 'error');
  7119. }
  7120. } catch (err) {
  7121. showToast('Network Error', err.message, 'error');
  7122. }
  7123. }
  7124. async function startAeroTUNTunnel(id) {
  7125. try {
  7126. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/start`, { method: 'POST' });
  7127. if (res.ok) {
  7128. showToast('AeroTUN Started', 'Interface started; connection is confirmed by authenticated peer traffic', 'info');
  7129. loadAeroTUN(false);
  7130. fetchData(false);
  7131. } else {
  7132. const err = await res.text();
  7133. showToast('Failed to Start', err, 'error');
  7134. }
  7135. } catch (err) {
  7136. showToast('Error', err.message, 'error');
  7137. }
  7138. }
  7139. async function stopAeroTUNTunnel(id) {
  7140. try {
  7141. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/stop`, { method: 'POST' });
  7142. if (res.ok) {
  7143. showToast('AeroTUN Stopped', 'Tunnel stopped', 'info');
  7144. loadAeroTUN(false);
  7145. fetchData(false);
  7146. } else {
  7147. const err = await res.text();
  7148. showToast('Failed to Stop', err, 'error');
  7149. }
  7150. } catch (err) {
  7151. showToast('Error', err.message, 'error');
  7152. }
  7153. }
  7154. async function toggleAeroTUNState(id, disabled) {
  7155. try {
  7156. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/state`, {
  7157. method: 'POST',
  7158. headers: { 'Content-Type': 'application/json' },
  7159. body: JSON.stringify({ disabled })
  7160. });
  7161. if (res.ok) {
  7162. showToast('State Updated', disabled ? 'Tunnel disabled' : 'Tunnel enabled', 'info');
  7163. loadAeroTUN(false);
  7164. fetchData(false);
  7165. }
  7166. } catch (err) {
  7167. showToast('Error', err.message, 'error');
  7168. }
  7169. }
  7170. async function deleteAeroTUN(id) {
  7171. if (!confirm('Are you sure you want to delete this AeroTUN tunnel?')) return;
  7172. try {
  7173. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7174. if (res.ok) {
  7175. showToast('Deleted', 'AeroTUN tunnel removed', 'success');
  7176. loadAeroTUN(false);
  7177. fetchData(false);
  7178. }
  7179. } catch (err) {
  7180. showToast('Error', err.message, 'error');
  7181. }
  7182. }
  7183. // ======================== PPP Central Hub & Servers ========================
  7184. function switchPPPSubTab(tab) {
  7185. state.pppSubTab = tab;
  7186. const tabs = ['secrets', 'profiles', 'pppoe', 'pptp', 'l2tp', 'active'];
  7187. tabs.forEach(t => {
  7188. const panel = document.getElementById(`ppp-subtab-${t}`);
  7189. const btn = document.getElementById(`ppp-subtab-btn-${t}`);
  7190. if (panel) {
  7191. if (t === tab) panel.classList.remove('hidden');
  7192. else panel.classList.add('hidden');
  7193. }
  7194. if (btn) {
  7195. if (t === tab) {
  7196. 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';
  7197. } else {
  7198. 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';
  7199. }
  7200. }
  7201. });
  7202. const addBtn = document.getElementById('ppp-primary-add-btn');
  7203. if (addBtn) {
  7204. if (tab === 'secrets') addBtn.innerHTML = '<span>+ Add User (Secret)</span>';
  7205. else if (tab === 'profiles') addBtn.innerHTML = '<span>+ Add Profile</span>';
  7206. else if (tab === 'active') addBtn.innerHTML = '<span>Refresh Sessions</span>';
  7207. else addBtn.innerHTML = '<span>Save Config</span>';
  7208. }
  7209. if (tab === 'active') loadPPPSessions();
  7210. }
  7211. function openCurrentPPPModal() {
  7212. if (state.pppSubTab === 'secrets') openAddPPPSecretModal();
  7213. else if (state.pppSubTab === 'profiles') openAddPPPProfileModal();
  7214. else if (state.pppSubTab === 'active') loadPPPSessions();
  7215. else if (state.pppSubTab === 'pppoe') document.querySelector('#ppp-subtab-pppoe form')?.requestSubmit();
  7216. else if (state.pppSubTab === 'pptp') document.querySelector('#ppp-subtab-pptp form')?.requestSubmit();
  7217. else if (state.pppSubTab === 'l2tp') document.querySelector('#ppp-subtab-l2tp form')?.requestSubmit();
  7218. }
  7219. async function loadPPP(populateDropdowns = true) {
  7220. await Promise.all([
  7221. loadPPPSecrets(),
  7222. loadPPPProfiles(),
  7223. loadPPPServers(),
  7224. loadPPPSessions()
  7225. ]);
  7226. }
  7227. async function loadPPPSecrets() {
  7228. try {
  7229. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`);
  7230. const data = await res.json();
  7231. state.pppSecrets = Array.isArray(data) ? data : [];
  7232. const b = document.getElementById('ppp-badge-secrets');
  7233. if (b) b.innerText = state.pppSecrets.length;
  7234. const b2 = document.getElementById('secrets-count-badge');
  7235. if (b2) b2.innerText = `${state.pppSecrets.length} Users`;
  7236. renderPPPSecrets();
  7237. } catch (err) {
  7238. console.error('Failed to load PPP secrets:', err);
  7239. }
  7240. }
  7241. function renderPPPSecrets() {
  7242. const tbody = document.getElementById('secrets-table-body');
  7243. const empty = document.getElementById('secrets-empty');
  7244. if (!tbody) return;
  7245. tbody.innerHTML = '';
  7246. const secrets = state.pppSecrets || [];
  7247. if (secrets.length === 0) {
  7248. empty?.classList.remove('hidden');
  7249. return;
  7250. }
  7251. empty?.classList.add('hidden');
  7252. secrets.forEach(s => {
  7253. const tr = document.createElement('tr');
  7254. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  7255. tr.innerHTML = `
  7256. <td class="py-2.5 px-3 text-center">${renderRuleFlag(s.disabled, !!s.comment)}</td>
  7257. <td class="py-2.5 px-3 font-bold text-white font-mono">${s.name}</td>
  7258. <td class="py-2.5 px-3 text-purple-300 font-mono font-semibold">${s.service}</td>
  7259. <td class="py-2.5 px-3 text-amber-300 font-mono">${s.profile}</td>
  7260. <td class="py-2.5 px-3 text-slate-400 font-mono">${s.local_address || '(profile)'}</td>
  7261. <td class="py-2.5 px-3 text-cyan-400 font-mono font-bold">${s.remote_address || '(profile)'}</td>
  7262. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]">${s.comment || '-'}</td>
  7263. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  7264. <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>
  7265. <button onclick="openEditPPPSecretModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  7266. <button onclick="deletePPPSecret('${s.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  7267. </td>
  7268. `;
  7269. tbody.appendChild(tr);
  7270. });
  7271. }
  7272. async function loadPPPProfiles() {
  7273. try {
  7274. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`);
  7275. const data = await res.json();
  7276. state.pppProfiles = Array.isArray(data) ? data : [];
  7277. const b = document.getElementById('ppp-badge-profiles');
  7278. if (b) b.innerText = state.pppProfiles.length;
  7279. const b2 = document.getElementById('profiles-count-badge');
  7280. if (b2) b2.innerText = `${state.pppProfiles.length} Profiles`;
  7281. // Populate profile selects across modals
  7282. const selects = ['secret-modal-profile', 'pppoe-server-profile', 'pptp-server-profile', 'l2tp-server-profile'];
  7283. selects.forEach(sid => {
  7284. const el = document.getElementById(sid);
  7285. if (!el) return;
  7286. const cur = el.value;
  7287. el.innerHTML = '';
  7288. state.pppProfiles.forEach(p => {
  7289. const opt = document.createElement('option');
  7290. opt.value = p.name;
  7291. opt.innerText = `${p.name} (${p.remote_address})`;
  7292. if (p.name === cur) opt.selected = true;
  7293. el.appendChild(opt);
  7294. });
  7295. });
  7296. renderPPPProfiles();
  7297. } catch (err) {
  7298. console.error('Failed to load PPP profiles:', err);
  7299. }
  7300. }
  7301. function renderPPPProfiles() {
  7302. const tbody = document.getElementById('profiles-table-body');
  7303. if (!tbody) return;
  7304. tbody.innerHTML = '';
  7305. (state.pppProfiles || []).forEach(p => {
  7306. const isDefault = p.name.startsWith('default');
  7307. const tr = document.createElement('tr');
  7308. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  7309. tr.innerHTML = `
  7310. <td class="py-2.5 px-3 font-bold text-white">${p.name}</td>
  7311. <td class="py-2.5 px-3 text-slate-300">${p.local_address}</td>
  7312. <td class="py-2.5 px-3 text-cyan-400 font-bold">${p.remote_address}</td>
  7313. <td class="py-2.5 px-3 text-slate-400">${p.dns_servers || '-'}</td>
  7314. <td class="py-2.5 px-3 text-purple-300 font-semibold">${p.use_encryption}</td>
  7315. <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>
  7316. <td class="py-2.5 px-3 text-slate-400 italic">${p.comment || '-'}</td>
  7317. <td class="py-2.5 px-3 text-right font-sans whitespace-nowrap">
  7318. ${!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>`}
  7319. </td>
  7320. `;
  7321. tbody.appendChild(tr);
  7322. });
  7323. }
  7324. async function loadPPPServers() {
  7325. try {
  7326. const [pppoeRes, pptpRes, l2tpRes, ipsecRes] = await Promise.all([
  7327. fetch(`${API_BASE}/vpn/servers/pppoe`),
  7328. fetch(`${API_BASE}/vpn/servers/pptp`),
  7329. fetch(`${API_BASE}/vpn/servers/l2tp`),
  7330. fetch(`${API_BASE}/vpn/servers/ipsec`)
  7331. ]);
  7332. if (pppoeRes.ok) {
  7333. state.pppoeServer = await pppoeRes.json();
  7334. const s = state.pppoeServer;
  7335. document.getElementById('pppoe-server-enabled').checked = !!s.enabled;
  7336. document.getElementById('pppoe-server-name').value = s.service_name || 'proxmox-pppoe';
  7337. populateInterfaceSelect('pppoe-server-iface', s.interface || 'eth0');
  7338. document.getElementById('pppoe-server-profile').value = s.default_profile || 'default';
  7339. document.getElementById('pppoe-server-mtu').value = s.max_mtu || 1480;
  7340. document.getElementById('pppoe-server-onesession').checked = !!s.one_session_per_host;
  7341. const pill = document.getElementById('pppoe-server-status-pill');
  7342. if (pill) {
  7343. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  7344. 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';
  7345. }
  7346. setDotBadge('ppp-badge-pppoe-state', s.running);
  7347. }
  7348. if (pptpRes.ok) {
  7349. state.pptpServer = await pptpRes.json();
  7350. const s = state.pptpServer;
  7351. document.getElementById('pptp-server-enabled').checked = !!s.enabled;
  7352. document.getElementById('pptp-server-port').value = s.port || 1723;
  7353. document.getElementById('pptp-server-profile').value = s.default_profile || 'default-encryption';
  7354. document.getElementById('pptp-server-mppe').checked = s.require_mppe !== false;
  7355. const pill = document.getElementById('pptp-server-status-pill');
  7356. if (pill) {
  7357. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  7358. 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';
  7359. }
  7360. setDotBadge('ppp-badge-pptp-state', s.running);
  7361. }
  7362. if (l2tpRes.ok) {
  7363. state.l2tpServer = await l2tpRes.json();
  7364. const s = state.l2tpServer;
  7365. document.getElementById('l2tp-server-enabled').checked = !!s.enabled;
  7366. document.getElementById('l2tp-server-port').value = s.port || 1701;
  7367. document.getElementById('l2tp-server-profile').value = s.default_profile || 'default';
  7368. document.getElementById('l2tp-server-useipsec').value = s.use_ipsec || 'no';
  7369. document.getElementById('l2tp-server-ipsecsecret').value = s.ipsec_secret || '';
  7370. const pill = document.getElementById('l2tp-server-status-pill');
  7371. if (pill) {
  7372. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  7373. 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';
  7374. }
  7375. setDotBadge('ppp-badge-l2tp-state', s.running);
  7376. }
  7377. if (ipsecRes.ok) {
  7378. state.ipsecServer = await ipsecRes.json();
  7379. const s = state.ipsecServer;
  7380. const modalEn = document.getElementById('modal-ipsec-server-enabled');
  7381. if (modalEn) modalEn.checked = !!s.enabled;
  7382. const modalPsk = document.getElementById('modal-ipsec-server-psk');
  7383. if (modalPsk) modalPsk.value = s.preshared_key || '';
  7384. const modalPool = document.getElementById('modal-ipsec-server-pool');
  7385. if (modalPool) modalPool.value = s.pool_address || '10.10.30.0/24';
  7386. const modalDns = document.getElementById('modal-ipsec-server-dns');
  7387. if (modalDns) modalDns.value = s.dns_servers || '1.1.1.1,8.8.8.8';
  7388. const modalSubnet = document.getElementById('modal-ipsec-server-subnet');
  7389. if (modalSubnet) modalSubnet.value = s.local_subnet || '0.0.0.0/0';
  7390. const pill = document.getElementById('modal-ipsec-server-status');
  7391. if (pill) {
  7392. pill.innerText = s.running ? 'ACTIVE RESPONDER' : 'STOPPED';
  7393. 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';
  7394. }
  7395. }
  7396. } catch (err) {
  7397. console.error('Failed to load VPN servers:', err);
  7398. }
  7399. }
  7400. async function loadPPPSessions() {
  7401. try {
  7402. const res = await fetch(`${API_BASE}/vpn/ppp/active`);
  7403. const data = await res.json();
  7404. state.pppActiveSessions = Array.isArray(data) ? data : [];
  7405. const b = document.getElementById('ppp-badge-active');
  7406. if (b) b.innerText = state.pppActiveSessions.length;
  7407. const sideB = document.getElementById('badge-ppp-sessions');
  7408. if (sideB) sideB.innerText = state.pppActiveSessions.length;
  7409. renderPPPSessions();
  7410. } catch (err) {
  7411. console.error('Failed to load active PPP sessions:', err);
  7412. }
  7413. }
  7414. function renderPPPSessions() {
  7415. const tbody = document.getElementById('active-ppp-table-body');
  7416. const empty = document.getElementById('active-ppp-empty');
  7417. if (!tbody) return;
  7418. tbody.innerHTML = '';
  7419. const list = state.pppActiveSessions || [];
  7420. if (list.length === 0) {
  7421. empty?.classList.remove('hidden');
  7422. return;
  7423. }
  7424. empty?.classList.add('hidden');
  7425. list.forEach(s => {
  7426. const tr = document.createElement('tr');
  7427. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  7428. tr.innerHTML = `
  7429. <td class="py-2.5 px-3 font-bold text-white">${s.interface}</td>
  7430. <td class="py-2.5 px-3 font-semibold text-violet-300">${s.username}</td>
  7431. <td class="py-2.5 px-3 text-cyan-400 uppercase">${s.service}</td>
  7432. <td class="py-2.5 px-3 text-emerald-400 font-bold">${s.address || '-'}</td>
  7433. <td class="py-2.5 px-3 text-slate-400">${s.uptime}</td>
  7434. <td class="py-2.5 px-3 text-[11px]">
  7435. <span class="text-emerald-400">↓ ${s.rx_human || '0 B'}</span>
  7436. <span class="text-cyan-400 ml-1">↑ ${s.tx_human || '0 B'}</span>
  7437. </td>
  7438. <td class="py-2.5 px-3 text-right font-sans">
  7439. <button onclick="disconnectPPPSession('${s.interface}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  7440. </td>
  7441. `;
  7442. tbody.appendChild(tr);
  7443. });
  7444. }
  7445. async function disconnectPPPSession(iface) {
  7446. if (!confirm(`Disconnect session ${iface}?`)) return;
  7447. try {
  7448. const res = await fetch(`${API_BASE}/vpn/ppp/active/${encodeURIComponent(iface)}`, { method: 'DELETE' });
  7449. if (res.ok) {
  7450. showToast('Disconnected', `Session ${iface} terminated`, 'info');
  7451. loadPPPSessions();
  7452. }
  7453. } catch (err) {
  7454. showToast('Error', err.message, 'error');
  7455. }
  7456. }
  7457. // PPP Secret Modal handlers
  7458. function openAddPPPSecretModal() {
  7459. document.getElementById('secret-modal-title').innerText = 'Add PPP Secret';
  7460. document.getElementById('secret-modal-id').value = '';
  7461. document.getElementById('secret-modal-name').value = '';
  7462. document.getElementById('secret-modal-password').value = '';
  7463. document.getElementById('secret-modal-service').value = 'any';
  7464. document.getElementById('secret-modal-profile').value = 'default';
  7465. document.getElementById('secret-modal-local').value = '';
  7466. document.getElementById('secret-modal-remote').value = '';
  7467. document.getElementById('secret-modal-comment').value = '';
  7468. document.getElementById('secret-modal-disabled').checked = false;
  7469. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  7470. }
  7471. function openEditPPPSecretModal(id) {
  7472. const s = (state.pppSecrets || []).find(sec => sec.id === id);
  7473. if (!s) return;
  7474. document.getElementById('secret-modal-title').innerText = `Edit PPP Secret (${s.name})`;
  7475. document.getElementById('secret-modal-id').value = s.id;
  7476. document.getElementById('secret-modal-name').value = s.name;
  7477. document.getElementById('secret-modal-password').value = s.password;
  7478. document.getElementById('secret-modal-service').value = s.service || 'any';
  7479. document.getElementById('secret-modal-profile').value = s.profile || 'default';
  7480. document.getElementById('secret-modal-local').value = s.local_address || '';
  7481. document.getElementById('secret-modal-remote').value = s.remote_address || '';
  7482. document.getElementById('secret-modal-comment').value = s.comment || '';
  7483. document.getElementById('secret-modal-disabled').checked = !!s.disabled;
  7484. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  7485. }
  7486. function closePPPSecretModal() {
  7487. document.getElementById('ppp-secret-modal').classList.add('hidden');
  7488. }
  7489. async function submitSavePPPSecret(e) {
  7490. e.preventDefault();
  7491. const id = document.getElementById('secret-modal-id').value;
  7492. const name = document.getElementById('secret-modal-name').value.trim();
  7493. const password = document.getElementById('secret-modal-password').value.trim();
  7494. const service = document.getElementById('secret-modal-service').value;
  7495. const profile = document.getElementById('secret-modal-profile').value;
  7496. const local = document.getElementById('secret-modal-local').value.trim();
  7497. const remote = document.getElementById('secret-modal-remote').value.trim();
  7498. const comment = document.getElementById('secret-modal-comment').value.trim();
  7499. const disabled = document.getElementById('secret-modal-disabled').checked;
  7500. try {
  7501. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`, {
  7502. method: 'POST',
  7503. headers: { 'Content-Type': 'application/json' },
  7504. body: JSON.stringify({
  7505. id,
  7506. name,
  7507. password,
  7508. service,
  7509. profile,
  7510. local_address: local,
  7511. remote_address: remote,
  7512. comment,
  7513. disabled
  7514. })
  7515. });
  7516. if (res.ok) {
  7517. showToast('Secret Saved', `User ${name} saved to PPP database`, 'success');
  7518. closePPPSecretModal();
  7519. loadPPPSecrets();
  7520. } else {
  7521. const err = await res.json();
  7522. showToast('Error', err.message, 'error');
  7523. }
  7524. } catch (err) {
  7525. showToast('Error', err.message, 'error');
  7526. }
  7527. }
  7528. async function togglePPPSecretState(id, disabled) {
  7529. try {
  7530. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}/state`, {
  7531. method: 'POST',
  7532. headers: { 'Content-Type': 'application/json' },
  7533. body: JSON.stringify({ disabled })
  7534. });
  7535. if (res.ok) {
  7536. showToast(disabled ? 'Disabled' : 'Enabled', 'Secret user state updated', 'info');
  7537. loadPPPSecrets();
  7538. }
  7539. } catch (err) {
  7540. showToast('Error', err.message, 'error');
  7541. }
  7542. }
  7543. async function deletePPPSecret(id) {
  7544. if (!confirm('Are you sure you want to delete this secret account?')) return;
  7545. try {
  7546. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7547. if (res.ok) {
  7548. showToast('Deleted', 'Secret account removed', 'success');
  7549. loadPPPSecrets();
  7550. }
  7551. } catch (err) {
  7552. showToast('Error', err.message, 'error');
  7553. }
  7554. }
  7555. // PPP Profile Modal handlers
  7556. function openAddPPPProfileModal() {
  7557. document.getElementById('profile-modal-name').value = '';
  7558. document.getElementById('profile-modal-local').value = '10.10.10.1';
  7559. document.getElementById('profile-modal-remote').value = '10.10.10.10-10.10.10.50';
  7560. document.getElementById('profile-modal-dns').value = '1.1.1.1,8.8.8.8';
  7561. document.getElementById('profile-modal-encryption').value = 'required';
  7562. document.getElementById('profile-modal-onlyone').checked = true;
  7563. document.getElementById('profile-modal-comment').value = '';
  7564. document.getElementById('ppp-profile-modal').classList.remove('hidden');
  7565. }
  7566. function closePPPProfileModal() {
  7567. document.getElementById('ppp-profile-modal').classList.add('hidden');
  7568. }
  7569. async function submitSavePPPProfile(e) {
  7570. e.preventDefault();
  7571. const name = document.getElementById('profile-modal-name').value.trim();
  7572. const local = document.getElementById('profile-modal-local').value.trim();
  7573. const remote = document.getElementById('profile-modal-remote').value.trim();
  7574. const dns = document.getElementById('profile-modal-dns').value.trim();
  7575. const enc = document.getElementById('profile-modal-encryption').value;
  7576. const onlyone = document.getElementById('profile-modal-onlyone').checked;
  7577. const comment = document.getElementById('profile-modal-comment').value.trim();
  7578. try {
  7579. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`, {
  7580. method: 'POST',
  7581. headers: { 'Content-Type': 'application/json' },
  7582. body: JSON.stringify({
  7583. id: name,
  7584. name,
  7585. local_address: local,
  7586. remote_address: remote,
  7587. dns_servers: dns,
  7588. use_encryption: enc,
  7589. only_one: onlyone,
  7590. comment
  7591. })
  7592. });
  7593. if (res.ok) {
  7594. showToast('Profile Saved', `PPP profile ${name} created`, 'success');
  7595. closePPPProfileModal();
  7596. loadPPPProfiles();
  7597. } else {
  7598. const err = await res.json();
  7599. showToast('Error', err.message, 'error');
  7600. }
  7601. } catch (err) {
  7602. showToast('Error', err.message, 'error');
  7603. }
  7604. }
  7605. async function deletePPPProfile(name) {
  7606. if (!confirm(`Delete PPP profile ${name}?`)) return;
  7607. try {
  7608. const res = await fetch(`${API_BASE}/vpn/ppp/profiles/${encodeURIComponent(name)}`, { method: 'DELETE' });
  7609. if (res.ok) {
  7610. showToast('Deleted', 'Profile removed', 'success');
  7611. loadPPPProfiles();
  7612. } else {
  7613. const err = await res.json();
  7614. showToast('Error', err.message, 'error');
  7615. }
  7616. } catch (err) {
  7617. showToast('Error', err.message, 'error');
  7618. }
  7619. }
  7620. // Server Config submissions
  7621. async function savePPPoEServerConfig(e) {
  7622. e.preventDefault();
  7623. const enabled = document.getElementById('pppoe-server-enabled').checked;
  7624. const name = document.getElementById('pppoe-server-name').value.trim();
  7625. const iface = document.getElementById('pppoe-server-iface').value;
  7626. const profile = document.getElementById('pppoe-server-profile').value;
  7627. const mtu = parseInt(document.getElementById('pppoe-server-mtu').value) || 1480;
  7628. const onesession = document.getElementById('pppoe-server-onesession').checked;
  7629. try {
  7630. const res = await fetch(`${API_BASE}/vpn/servers/pppoe`, {
  7631. method: 'POST',
  7632. headers: { 'Content-Type': 'application/json' },
  7633. body: JSON.stringify({
  7634. enabled,
  7635. service_name: name,
  7636. interface: iface,
  7637. default_profile: profile,
  7638. max_mtu: mtu,
  7639. max_mru: mtu,
  7640. one_session_per_host: onesession
  7641. })
  7642. });
  7643. if (res.ok) {
  7644. showToast('PPPoE Server', enabled ? 'PPPoE Server started' : 'PPPoE Server stopped', 'success');
  7645. loadPPPServers();
  7646. fetchData(false);
  7647. } else {
  7648. const err = await res.json();
  7649. showToast('Error', err.message, 'error');
  7650. }
  7651. } catch (err) {
  7652. showToast('Error', err.message, 'error');
  7653. }
  7654. }
  7655. async function savePPTPServerConfig(e) {
  7656. e.preventDefault();
  7657. const enabled = document.getElementById('pptp-server-enabled').checked;
  7658. const port = parseInt(document.getElementById('pptp-server-port').value) || 1723;
  7659. const profile = document.getElementById('pptp-server-profile').value;
  7660. const mppe = document.getElementById('pptp-server-mppe').checked;
  7661. try {
  7662. const res = await fetch(`${API_BASE}/vpn/servers/pptp`, {
  7663. method: 'POST',
  7664. headers: { 'Content-Type': 'application/json' },
  7665. body: JSON.stringify({
  7666. enabled,
  7667. port,
  7668. default_profile: profile,
  7669. require_mppe: mppe
  7670. })
  7671. });
  7672. if (res.ok) {
  7673. showToast('PPTP Server', enabled ? 'PPTP Server started' : 'PPTP Server stopped', 'success');
  7674. loadPPPServers();
  7675. fetchData(false);
  7676. } else {
  7677. const err = await res.json();
  7678. showToast('Error', err.message, 'error');
  7679. }
  7680. } catch (err) {
  7681. showToast('Error', err.message, 'error');
  7682. }
  7683. }
  7684. async function saveL2TPServerConfig(e) {
  7685. e.preventDefault();
  7686. const enabled = document.getElementById('l2tp-server-enabled').checked;
  7687. const port = parseInt(document.getElementById('l2tp-server-port').value) || 1701;
  7688. const profile = document.getElementById('l2tp-server-profile').value;
  7689. const useipsec = document.getElementById('l2tp-server-useipsec').value;
  7690. const psk = document.getElementById('l2tp-server-ipsecsecret').value.trim();
  7691. try {
  7692. const res = await fetch(`${API_BASE}/vpn/servers/l2tp`, {
  7693. method: 'POST',
  7694. headers: { 'Content-Type': 'application/json' },
  7695. body: JSON.stringify({
  7696. enabled,
  7697. port,
  7698. default_profile: profile,
  7699. use_ipsec: useipsec,
  7700. ipsec_secret: psk
  7701. })
  7702. });
  7703. if (res.ok) {
  7704. showToast('L2TP Server', enabled ? 'L2TP Server started' : 'L2TP Server stopped', 'success');
  7705. loadPPPServers();
  7706. fetchData(false);
  7707. } else {
  7708. const err = await res.json();
  7709. showToast('Error', err.message, 'error');
  7710. }
  7711. } catch (err) {
  7712. showToast('Error', err.message, 'error');
  7713. }
  7714. }
  7715. // IPSec Server Modal
  7716. function openIPSecServerModal() {
  7717. loadPPPServers();
  7718. document.getElementById('ipsec-server-modal').classList.remove('hidden');
  7719. }
  7720. function closeIPSecServerModal() {
  7721. document.getElementById('ipsec-server-modal').classList.add('hidden');
  7722. }
  7723. async function submitSaveIPSecServer(e) {
  7724. e.preventDefault();
  7725. const enabled = document.getElementById('modal-ipsec-server-enabled').checked;
  7726. const psk = document.getElementById('modal-ipsec-server-psk').value.trim();
  7727. const pool = document.getElementById('modal-ipsec-server-pool').value.trim();
  7728. const dns = document.getElementById('modal-ipsec-server-dns').value.trim();
  7729. const subnet = document.getElementById('modal-ipsec-server-subnet').value.trim();
  7730. try {
  7731. const res = await fetch(`${API_BASE}/vpn/servers/ipsec`, {
  7732. method: 'POST',
  7733. headers: { 'Content-Type': 'application/json' },
  7734. body: JSON.stringify({
  7735. enabled,
  7736. preshared_key: psk,
  7737. pool_address: pool,
  7738. dns_servers: dns,
  7739. local_subnet: subnet
  7740. })
  7741. });
  7742. if (res.ok) {
  7743. showToast('IPSec Server', enabled ? 'IKEv2 Roadwarrior responder active' : 'IPSec Server stopped', 'success');
  7744. closeIPSecServerModal();
  7745. loadPPPServers();
  7746. fetchData(false);
  7747. } else {
  7748. const err = await res.json();
  7749. showToast('Error', err.message, 'error');
  7750. }
  7751. } catch (err) {
  7752. showToast('Error', err.message, 'error');
  7753. }
  7754. }
  7755. // WireGuard Client Config Viewer
  7756. let currentWGClientConf = '';
  7757. async function openWGClientConfModal(iface, clientIP) {
  7758. try {
  7759. const res = await fetch(`${API_BASE}/vpn/wireguard/client-config`, {
  7760. method: 'POST',
  7761. headers: { 'Content-Type': 'application/json' },
  7762. body: JSON.stringify({
  7763. interface: iface,
  7764. address: clientIP || '10.10.0.2/32',
  7765. dns: '1.1.1.1, 8.8.8.8'
  7766. })
  7767. });
  7768. if (res.ok) {
  7769. const data = await res.json();
  7770. currentWGClientConf = data.config;
  7771. document.getElementById('wg-client-conf-text').value = currentWGClientConf;
  7772. document.getElementById('wg-client-conf-modal').classList.remove('hidden');
  7773. } else {
  7774. const err = await res.json();
  7775. showToast('Error', err.message, 'error');
  7776. }
  7777. } catch (err) {
  7778. showToast('Error', err.message, 'error');
  7779. }
  7780. }
  7781. function closeWGClientConfModal() {
  7782. document.getElementById('wg-client-conf-modal').classList.add('hidden');
  7783. }
  7784. function copyWGClientConf() {
  7785. if (!currentWGClientConf) return;
  7786. copyToClipboard(currentWGClientConf, 'WireGuard Client Profile');
  7787. }
  7788. function downloadWGClientConf() {
  7789. if (!currentWGClientConf) return;
  7790. const blob = new Blob([currentWGClientConf], { type: 'text/plain;charset=utf-8' });
  7791. const a = document.createElement('a');
  7792. a.href = URL.createObjectURL(blob);
  7793. a.download = 'wireguard-client.conf';
  7794. document.body.appendChild(a);
  7795. a.click();
  7796. document.body.removeChild(a);
  7797. showToast('Downloaded', 'wireguard-client.conf saved', 'success');
  7798. }
  7799. // =========================================================================
  7800. // DYNAMIC ROUTING (FRRouting BGP & OSPFv2)
  7801. // =========================================================================
  7802. state.activeDynSubTab = 'bgp-peers';
  7803. state.activeBgpSubTab = 'bgp-peers';
  7804. state.activeOspfTab = 'instances';
  7805. state.bgpInstance = null;
  7806. state.bgpPeers = [];
  7807. state.bgpNets = [];
  7808. state.bgpRoutes = [];
  7809. state.ospfInstance = null;
  7810. state.ospfInstances = [];
  7811. state.ospfAreas = [];
  7812. state.ospfAreaRanges = [];
  7813. state.ospfTemplates = [];
  7814. state.ospfLiveInterfaces = [];
  7815. state.ospfStaticNbrs = [];
  7816. state.ospfNeighbors = [];
  7817. state.ospfLSA = [];
  7818. state.ospfRoutes = [];
  7819. state.selectedOspfRow = {
  7820. instances: null,
  7821. areas: null,
  7822. 'area-ranges': null,
  7823. templates: null,
  7824. interfaces: null,
  7825. 'static-nbrs': null,
  7826. neighbors: null,
  7827. lsa: null,
  7828. };
  7829. state.ospfSort = {
  7830. instances: { col: 'name', asc: true },
  7831. areas: { col: 'name', asc: true },
  7832. ranges: { col: 'area', asc: true },
  7833. templates: { col: 'interfaces', asc: true },
  7834. live_ifaces: { col: 'interface', asc: true },
  7835. snbrs: { col: 'address', asc: true },
  7836. neighbors: { col: 'address', asc: true },
  7837. lsa: { col: 'instance', asc: true },
  7838. };
  7839. function switchBgpSubTab(subTab) {
  7840. state.activeBgpSubTab = subTab;
  7841. const tabs = ['bgp-peers', 'bgp-nets', 'bgp-routes'];
  7842. tabs.forEach(t => {
  7843. const el = document.getElementById(`dyn-subtab-${t}`);
  7844. const btn = document.getElementById(`bgp-subtab-btn-${t}`);
  7845. if (el) el.classList.toggle('hidden', t !== subTab);
  7846. if (btn) {
  7847. if (t === subTab) {
  7848. 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';
  7849. } else {
  7850. 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';
  7851. }
  7852. }
  7853. });
  7854. }
  7855. function switchOspfTab(tabName) {
  7856. state.activeOspfTab = tabName;
  7857. const tabs = ['instances', 'areas', 'area-ranges', 'templates', 'interfaces', 'static-nbrs', 'neighbors', 'lsa'];
  7858. tabs.forEach(t => {
  7859. const pane = document.getElementById(`ospf-pane-${t}`);
  7860. const btn = document.getElementById(`ospf-tab-btn-${t}`);
  7861. if (pane) pane.classList.toggle('hidden', t !== tabName);
  7862. if (btn) {
  7863. if (t === tabName) {
  7864. 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';
  7865. } else {
  7866. 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';
  7867. }
  7868. }
  7869. });
  7870. }
  7871. function switchOspfSubTab(tab) {
  7872. // Legacy alias
  7873. if (tab === 'ospf-ifaces') switchOspfTab('templates');
  7874. else if (tab === 'ospf-areas') switchOspfTab('areas');
  7875. else if (tab === 'ospf-nbrs') switchOspfTab('neighbors');
  7876. else switchOspfTab('instances');
  7877. }
  7878. function switchDynSubTab(subTab) {
  7879. if (subTab.startsWith('bgp')) {
  7880. if (state.activeTab !== 'bgp') navigate('bgp');
  7881. switchBgpSubTab(subTab);
  7882. } else if (subTab.startsWith('ospf')) {
  7883. if (state.activeTab !== 'ospf') navigate('ospf');
  7884. switchOspfTab('instances');
  7885. }
  7886. }
  7887. async function loadDynamicRouting(showToastMsg = false) {
  7888. try {
  7889. const fetchSafeJson = async (url) => {
  7890. try {
  7891. const r = await fetch(url);
  7892. return r.ok ? await r.json() : null;
  7893. } catch (e) {
  7894. return null;
  7895. }
  7896. };
  7897. const [
  7898. sum, bgpInst, bgpPeers, bgpNets, bgpRoutes,
  7899. ospfInsts, ospfAreas, ospfRanges, ospfTemplates, ospfLiveIfaces, ospfStaticNbrs, ospfNbrs, ospfLsa, filters,
  7900. selectRules, commLists, asLists
  7901. ] = await Promise.all([
  7902. fetchSafeJson(`${API_BASE}/routing/dynamic/summary`),
  7903. fetchSafeJson(`${API_BASE}/routing/bgp/instance`),
  7904. fetchSafeJson(`${API_BASE}/routing/bgp/peers`),
  7905. fetchSafeJson(`${API_BASE}/routing/bgp/networks`),
  7906. fetchSafeJson(`${API_BASE}/routing/bgp/routes`),
  7907. fetchSafeJson(`${API_BASE}/routing/ospf/instances`),
  7908. fetchSafeJson(`${API_BASE}/routing/ospf/areas`),
  7909. fetchSafeJson(`${API_BASE}/routing/ospf/area-ranges`),
  7910. fetchSafeJson(`${API_BASE}/routing/ospf/templates`),
  7911. fetchSafeJson(`${API_BASE}/routing/ospf/interfaces-live`),
  7912. fetchSafeJson(`${API_BASE}/routing/ospf/static-neighbors`),
  7913. fetchSafeJson(`${API_BASE}/routing/ospf/neighbors`),
  7914. fetchSafeJson(`${API_BASE}/routing/ospf/lsa`),
  7915. fetchSafeJson(`${API_BASE}/routing/filters`),
  7916. fetchSafeJson(`${API_BASE}/routing/filters/select-rules`),
  7917. fetchSafeJson(`${API_BASE}/routing/filters/community-lists`),
  7918. fetchSafeJson(`${API_BASE}/routing/filters/as-lists`)
  7919. ]);
  7920. if (sum) state.dynSummary = sum;
  7921. if (bgpInst) state.bgpInstance = bgpInst;
  7922. if (bgpPeers) state.bgpPeers = bgpPeers;
  7923. if (bgpNets) state.bgpNets = bgpNets;
  7924. if (bgpRoutes) state.bgpRoutes = bgpRoutes;
  7925. if (ospfInsts) state.ospfInstances = ospfInsts;
  7926. if (ospfAreas) state.ospfAreas = ospfAreas;
  7927. if (ospfRanges) state.ospfAreaRanges = ospfRanges;
  7928. if (ospfTemplates) state.ospfTemplates = ospfTemplates;
  7929. if (ospfLiveIfaces) state.ospfLiveInterfaces = ospfLiveIfaces;
  7930. if (ospfStaticNbrs) state.ospfStaticNbrs = ospfStaticNbrs;
  7931. if (ospfNbrs) state.ospfNeighbors = ospfNbrs;
  7932. if (ospfLsa) state.ospfLSA = ospfLsa;
  7933. if (filters) state.routingFilters = filters;
  7934. if (selectRules) state.routingSelectRules = selectRules;
  7935. if (commLists) state.routingCommunityLists = commLists;
  7936. if (asLists) state.routingASLists = asLists;
  7937. try { renderBgpStatusPill(); } catch(e) { console.error('renderBgpStatusPill error:', e); }
  7938. try { renderBgpPeers(); } catch(e) { console.error('renderBgpPeers error:', e); }
  7939. try { renderBgpNetworks(); } catch(e) { console.error('renderBgpNetworks error:', e); }
  7940. try { renderBgpRoutes(); } catch(e) { console.error('renderBgpRoutes error:', e); }
  7941. try { renderOspfInstances(); } catch(e) { console.error('renderOspfInstances error:', e); }
  7942. try { renderOspfAreas(); } catch(e) { console.error('renderOspfAreas error:', e); }
  7943. try { renderOspfAreaRanges(); } catch(e) { console.error('renderOspfAreaRanges error:', e); }
  7944. try { renderOspfTemplates(); } catch(e) { console.error('renderOspfTemplates error:', e); }
  7945. try { renderOspfLiveInterfaces(); } catch(e) { console.error('renderOspfLiveInterfaces error:', e); }
  7946. try { renderOspfStaticNbrs(); } catch(e) { console.error('renderOspfStaticNbrs error:', e); }
  7947. try { renderOspfNeighbors(); } catch(e) { console.error('renderOspfNeighbors error:', e); }
  7948. try { renderOspfLSA(); } catch(e) { console.error('renderOspfLSA error:', e); }
  7949. try { renderRoutingFilters(); } catch(e) { console.error('renderRoutingFilters error:', e); }
  7950. try { updateBadges(); } catch(e) { console.error('updateBadges error:', e); }
  7951. if (showToastMsg) showToast('Refreshed', 'Dynamic routing telemetry updated', 'info');
  7952. } catch (err) {
  7953. console.error('Failed to load dynamic routing:', err);
  7954. if (showToastMsg) showToast('Notice', 'Unable to refresh dynamic routing telemetry', 'warning');
  7955. }
  7956. }
  7957. async function loadOspfAll() {
  7958. await loadDynamicRouting(true);
  7959. }
  7960. function renderBgpStatusPill() {
  7961. const pills = document.querySelectorAll('.bgp-live-status-pill');
  7962. pills.forEach(pill => {
  7963. const inst = state.bgpInstance;
  7964. if (!inst || !inst.enabled) {
  7965. 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';
  7966. pill.innerText = 'BGP DISABLED';
  7967. } else if (inst.running) {
  7968. 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';
  7969. pill.innerText = `BGP ACTIVE (AS ${inst.as})`;
  7970. } else {
  7971. 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';
  7972. pill.innerText = 'BGP STARTING...';
  7973. }
  7974. });
  7975. }
  7976. function renderBgpPeers() {
  7977. const tbody = document.getElementById('bgp-peers-table-body');
  7978. if (!tbody) return;
  7979. const empty = document.getElementById('bgp-peers-empty');
  7980. const countBadge = document.getElementById('bgp-peers-count-badge');
  7981. const navBadge = document.getElementById('dyn-badge-bgp-peers');
  7982. const peers = state.bgpPeers || [];
  7983. if (countBadge) countBadge.innerText = `${peers.length} Peers`;
  7984. if (navBadge) navBadge.innerText = peers.length;
  7985. if (peers.length === 0) {
  7986. tbody.innerHTML = '';
  7987. if (empty) empty.classList.remove('hidden');
  7988. return;
  7989. }
  7990. if (empty) empty.classList.add('hidden');
  7991. const sig = peers.map(p => `${p.name}:${p.state}:${p.uptime}:${p.prefix_received}:${p.prefix_sent}:${p.disabled}`).join(';');
  7992. if (tbody.dataset.sig === sig) return;
  7993. tbody.dataset.sig = sig;
  7994. tbody.innerHTML = peers.map(p => {
  7995. let flagA = !p.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  7996. let flagE = p.state === 'Established' ? '<span class="text-emerald-400 font-bold ml-1" title="Established">E</span>' : '';
  7997. let flagX = p.disabled ? '<span class="text-rose-400 font-bold ml-1" title="Disabled">X</span>' : '';
  7998. let stateBadge = '';
  7999. if (p.disabled) {
  8000. 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>';
  8001. } else if (p.state === 'Established') {
  8002. 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>';
  8003. } else if (p.state === 'Connect' || p.state === 'Active') {
  8004. 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>`;
  8005. } else {
  8006. 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>`;
  8007. }
  8008. return `
  8009. <tr class="hover:bg-slate-800/40 transition">
  8010. <td class="py-2.5 px-3 text-center tracking-wider">${flagA}${flagE}${flagX}</td>
  8011. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(p.name)}</td>
  8012. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(p.remote_address)}</td>
  8013. <td class="py-2.5 px-3">
  8014. <div class="font-bold text-slate-200">AS ${p.remote_as}</div>
  8015. ${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>`}
  8016. </td>
  8017. <td class="py-2.5 px-3">${stateBadge}</td>
  8018. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(p.uptime || '-')}</td>
  8019. <td class="py-2.5 px-3 text-slate-300">
  8020. <span class="text-emerald-400 font-bold">↓ ${p.prefix_received || 0}</span> /
  8021. <span class="text-blue-400 font-bold">↑ ${p.prefix_sent || 0}</span>
  8022. </td>
  8023. <td class="py-2.5 px-3 font-mono text-[11px] whitespace-nowrap">
  8024. ${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> ` : ''}
  8025. ${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>` : ''}
  8026. ${!p.in_filter && !p.out_filter ? '<span class="text-slate-600">-</span>' : ''}
  8027. </td>
  8028. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(p.comment || '')}</td>
  8029. <td class="py-2.5 px-3 text-right space-x-1.5 whitespace-nowrap font-sans">
  8030. <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'}">
  8031. ${p.disabled ? 'Enable' : 'Disable'}
  8032. </button>
  8033. <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">
  8034. Edit
  8035. </button>
  8036. <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">
  8037. Delete
  8038. </button>
  8039. </td>
  8040. </tr>
  8041. `;
  8042. }).join('');
  8043. }
  8044. function renderBgpNetworks() {
  8045. const tbody = document.getElementById('bgp-nets-table-body');
  8046. if (!tbody) return;
  8047. const empty = document.getElementById('bgp-nets-empty');
  8048. const countBadge = document.getElementById('bgp-nets-count-badge');
  8049. const navBadge = document.getElementById('dyn-badge-bgp-nets');
  8050. const nets = state.bgpNets || [];
  8051. if (countBadge) countBadge.innerText = `${nets.length} Networks`;
  8052. if (navBadge) navBadge.innerText = nets.length;
  8053. if (nets.length === 0) {
  8054. tbody.innerHTML = '';
  8055. if (empty) empty.classList.remove('hidden');
  8056. return;
  8057. }
  8058. if (empty) empty.classList.add('hidden');
  8059. const sig = nets.map(n => `${n.network}:${n.disabled}:${n.comment}`).join(';');
  8060. if (tbody.dataset.sig === sig) return;
  8061. tbody.dataset.sig = sig;
  8062. tbody.innerHTML = nets.map(n => `
  8063. <tr class="hover:bg-slate-800/40 transition">
  8064. <td class="py-2.5 px-3 font-semibold text-purple-300 font-mono">${escapeHtml(n.network)}</td>
  8065. <td class="py-2.5 px-3">
  8066. ${n.disabled
  8067. ? '<span class="px-2 py-0.5 rounded-full text-[10px] bg-slate-800 text-slate-400 border border-slate-700">Disabled</span>'
  8068. : '<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>'}
  8069. </td>
  8070. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(n.comment || '')}</td>
  8071. <td class="py-2.5 px-3 text-right space-x-1 font-sans">
  8072. <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">
  8073. Delete
  8074. </button>
  8075. </td>
  8076. </tr>
  8077. `).join('');
  8078. }
  8079. function renderBgpRoutes() {
  8080. const tbody = document.getElementById('bgp-routes-table-body');
  8081. if (!tbody) return;
  8082. const empty = document.getElementById('bgp-routes-empty');
  8083. const countBadge = document.getElementById('bgp-routes-count-badge');
  8084. const navBadge = document.getElementById('dyn-badge-bgp-routes');
  8085. const routes = state.bgpRoutes || [];
  8086. if (countBadge) countBadge.innerText = `${routes.length} Routes`;
  8087. if (navBadge) navBadge.innerText = routes.length;
  8088. if (routes.length === 0) {
  8089. tbody.innerHTML = '';
  8090. if (empty) empty.classList.remove('hidden');
  8091. return;
  8092. }
  8093. if (empty) empty.classList.add('hidden');
  8094. const sig = routes.map(r => `${r.prefix}:${r.next_hop}:${r.metric}:${r.path}`).join(';');
  8095. if (tbody.dataset.sig === sig) return;
  8096. tbody.dataset.sig = sig;
  8097. tbody.innerHTML = routes.map(r => `
  8098. <tr class="hover:bg-slate-800/40 transition">
  8099. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.prefix)}</td>
  8100. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(r.next_hop || '-')}</td>
  8101. <td class="py-2.5 px-3 text-slate-300">${r.metric}</td>
  8102. <td class="py-2.5 px-3 text-slate-300">${r.weight}</td>
  8103. <td class="py-2.5 px-3 text-amber-300">${escapeHtml(r.path || 'i')}</td>
  8104. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.origin || 'IGP')}</td>
  8105. </tr>
  8106. `).join('');
  8107. }
  8108. // =========================================================================
  8109. // DEBTIK v7 OSPF TABLE RENDERING & SORTING
  8110. // =========================================================================
  8111. function sortOspfTable(tab, col) {
  8112. if (!state.ospfSort) state.ospfSort = {};
  8113. if (!state.ospfSort[tab]) state.ospfSort[tab] = { col: col, asc: true };
  8114. if (state.ospfSort[tab].col === col) {
  8115. state.ospfSort[tab].asc = !state.ospfSort[tab].asc;
  8116. } else {
  8117. state.ospfSort[tab].col = col;
  8118. state.ospfSort[tab].asc = true;
  8119. }
  8120. const asc = state.ospfSort[tab].asc;
  8121. let list = [];
  8122. if (tab === 'instances') list = state.ospfInstances || [];
  8123. else if (tab === 'areas') list = state.ospfAreas || [];
  8124. else if (tab === 'ranges') list = state.ospfAreaRanges || [];
  8125. else if (tab === 'templates') list = state.ospfTemplates || [];
  8126. else if (tab === 'live_ifaces') list = state.ospfLiveInterfaces || [];
  8127. else if (tab === 'snbrs') list = state.ospfStaticNbrs || [];
  8128. else if (tab === 'neighbors') list = state.ospfNeighbors || [];
  8129. else if (tab === 'lsa') list = state.ospfLSA || [];
  8130. list.sort((a, b) => {
  8131. let valA = a[col] ?? '';
  8132. let valB = b[col] ?? '';
  8133. if (typeof valA === 'number' && typeof valB === 'number') {
  8134. return asc ? valA - valB : valB - valA;
  8135. }
  8136. return asc ? String(valA).localeCompare(String(valB)) : String(valB).localeCompare(String(valA));
  8137. });
  8138. if (tab === 'instances') renderOspfInstances();
  8139. else if (tab === 'areas') renderOspfAreas();
  8140. else if (tab === 'ranges') renderOspfAreaRanges();
  8141. else if (tab === 'templates') renderOspfTemplates();
  8142. else if (tab === 'live_ifaces') renderOspfLiveInterfaces();
  8143. else if (tab === 'snbrs') renderOspfStaticNbrs();
  8144. else if (tab === 'neighbors') renderOspfNeighbors();
  8145. else if (tab === 'lsa') renderOspfLSA();
  8146. }
  8147. function selectOspfRow(tab, id) {
  8148. if (!state.selectedOspfRow) state.selectedOspfRow = {};
  8149. state.selectedOspfRow[tab] = id;
  8150. if (tab === 'instances') {
  8151. renderOspfInstances();
  8152. const btnEn = document.getElementById('btn-ospf-inst-enable');
  8153. const btnDis = document.getElementById('btn-ospf-inst-disable');
  8154. const btnRem = document.getElementById('btn-ospf-inst-remove');
  8155. const btnCom = document.getElementById('btn-ospf-inst-comment');
  8156. if (btnEn) btnEn.disabled = false;
  8157. if (btnDis) btnDis.disabled = false;
  8158. if (btnRem) btnRem.disabled = false;
  8159. if (btnCom) btnCom.disabled = false;
  8160. } else if (tab === 'areas') {
  8161. renderOspfAreas();
  8162. const btnEn = document.getElementById('btn-ospf-area-enable');
  8163. const btnDis = document.getElementById('btn-ospf-area-disable');
  8164. const btnRem = document.getElementById('btn-ospf-area-remove');
  8165. const btnCom = document.getElementById('btn-ospf-area-comment');
  8166. if (btnEn) btnEn.disabled = false;
  8167. if (btnDis) btnDis.disabled = false;
  8168. if (btnRem) btnRem.disabled = false;
  8169. if (btnCom) btnCom.disabled = false;
  8170. } else if (tab === 'ranges') {
  8171. renderOspfAreaRanges();
  8172. const btnEn = document.getElementById('btn-ospf-range-enable');
  8173. const btnDis = document.getElementById('btn-ospf-range-disable');
  8174. const btnRem = document.getElementById('btn-ospf-range-remove');
  8175. const btnCom = document.getElementById('btn-ospf-range-comment');
  8176. if (btnEn) btnEn.disabled = false;
  8177. if (btnDis) btnDis.disabled = false;
  8178. if (btnRem) btnRem.disabled = false;
  8179. if (btnCom) btnCom.disabled = false;
  8180. } else if (tab === 'templates') {
  8181. renderOspfTemplates();
  8182. const btnEn = document.getElementById('btn-ospf-tmpl-enable');
  8183. const btnDis = document.getElementById('btn-ospf-tmpl-disable');
  8184. const btnRem = document.getElementById('btn-ospf-tmpl-remove');
  8185. const btnCom = document.getElementById('btn-ospf-tmpl-comment');
  8186. if (btnEn) btnEn.disabled = false;
  8187. if (btnDis) btnDis.disabled = false;
  8188. if (btnRem) btnRem.disabled = false;
  8189. if (btnCom) btnCom.disabled = false;
  8190. } else if (tab === 'snbrs') {
  8191. renderOspfStaticNbrs();
  8192. const btnEn = document.getElementById('btn-ospf-snbr-enable');
  8193. const btnDis = document.getElementById('btn-ospf-snbr-disable');
  8194. const btnRem = document.getElementById('btn-ospf-snbr-remove');
  8195. const btnCom = document.getElementById('btn-ospf-snbr-comment');
  8196. if (btnEn) btnEn.disabled = false;
  8197. if (btnDis) btnDis.disabled = false;
  8198. if (btnRem) btnRem.disabled = false;
  8199. if (btnCom) btnCom.disabled = false;
  8200. }
  8201. }
  8202. // TAB 1: INSTANCES
  8203. function renderOspfInstances() {
  8204. const tbody = document.getElementById('ospf-instances-table-body');
  8205. if (!tbody) return;
  8206. const countEl = document.getElementById('ospf-instances-footer-count');
  8207. const filter = (document.getElementById('filter-ospf-instances')?.value || '').toLowerCase();
  8208. let list = state.ospfInstances || [];
  8209. if (filter) {
  8210. list = list.filter(i => (i.name || '').toLowerCase().includes(filter) || (i.router_id || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  8211. }
  8212. if (countEl) countEl.innerText = list.length;
  8213. const selId = state.selectedOspfRow?.instances;
  8214. tbody.innerHTML = list.map((inst, idx) => {
  8215. const isSel = inst.id === selId;
  8216. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  8217. const flagD = inst.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  8218. return `
  8219. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('instances', '${inst.id}')" ondblclick="openEditOspfInstanceModal('${inst.id}')">
  8220. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  8221. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🔀'}</td>
  8222. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(inst.comment || '')}</td>
  8223. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  8224. <span class="text-sky-400">↳</span> <span>${escapeHtml(inst.name || 'Default')}</span>
  8225. </td>
  8226. <td class="py-1.5 px-3">${inst.version || 2}</td>
  8227. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(inst.vrf || 'main')}</td>
  8228. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(inst.router_id || '192.168.131.56')}</td>
  8229. </tr>
  8230. `;
  8231. }).join('');
  8232. }
  8233. // TAB 2: AREAS
  8234. function renderOspfAreas() {
  8235. const tbody = document.getElementById('ospf-areas-table-body');
  8236. if (!tbody) return;
  8237. const countEl = document.getElementById('ospf-areas-footer-count');
  8238. const filter = (document.getElementById('filter-ospf-areas')?.value || '').toLowerCase();
  8239. let list = state.ospfAreas || [];
  8240. if (filter) {
  8241. list = list.filter(a => (a.name || '').toLowerCase().includes(filter) || (a.area_id || '').toLowerCase().includes(filter) || (a.comment || '').toLowerCase().includes(filter));
  8242. }
  8243. if (countEl) countEl.innerText = list.length;
  8244. const selId = state.selectedOspfRow?.areas;
  8245. tbody.innerHTML = list.map((a, idx) => {
  8246. const isSel = a.id === selId;
  8247. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  8248. const flagD = a.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  8249. return `
  8250. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('areas', '${a.id}')" ondblclick="openEditOspfAreaModal('${a.id}')">
  8251. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  8252. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🌐'}</td>
  8253. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(a.comment || '')}</td>
  8254. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  8255. <span class="text-sky-400">↳</span> <span>${escapeHtml(a.name || 'Default')}</span>
  8256. </td>
  8257. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(a.instance || 'Default')}</td>
  8258. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(a.area_id || '0.0.0.0')}</td>
  8259. <td class="py-1.5 px-3 font-mono text-slate-400">${escapeHtml(a.area_type || 'default')}</td>
  8260. </tr>
  8261. `;
  8262. }).join('');
  8263. }
  8264. // TAB 3: AREA RANGES
  8265. function renderOspfAreaRanges() {
  8266. const tbody = document.getElementById('ospf-ranges-table-body');
  8267. if (!tbody) return;
  8268. const countEl = document.getElementById('ospf-ranges-footer-count');
  8269. const filter = (document.getElementById('filter-ospf-area-ranges')?.value || '').toLowerCase();
  8270. let list = state.ospfAreaRanges || [];
  8271. if (filter) {
  8272. list = list.filter(r => (r.prefix || '').toLowerCase().includes(filter) || (r.area || '').toLowerCase().includes(filter) || (r.comment || '').toLowerCase().includes(filter));
  8273. }
  8274. if (countEl) countEl.innerText = list.length;
  8275. const selId = state.selectedOspfRow?.['area-ranges'];
  8276. tbody.innerHTML = list.map((r, idx) => {
  8277. const isSel = r.id === selId;
  8278. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  8279. const flagD = r.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  8280. return `
  8281. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('ranges', '${r.id}')" ondblclick="openEditOspfAreaRangeModal('${r.id}')">
  8282. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  8283. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🏷'}</td>
  8284. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(r.comment || '')}</td>
  8285. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(r.area || 'Default')}</td>
  8286. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(r.prefix || '')}</td>
  8287. <td class="py-1.5 px-3">${r.cost || 1}</td>
  8288. <td class="py-1.5 px-3">${r.advertise !== false ? 'yes' : 'no'}</td>
  8289. </tr>
  8290. `;
  8291. }).join('');
  8292. }
  8293. // TAB 4: INTERFACE TEMPLATES
  8294. function renderOspfTemplates() {
  8295. const tbody = document.getElementById('ospf-templates-table-body');
  8296. if (!tbody) return;
  8297. const countEl = document.getElementById('ospf-templates-footer-count');
  8298. const filter = (document.getElementById('filter-ospf-templates')?.value || '').toLowerCase();
  8299. let list = state.ospfTemplates || [];
  8300. if (filter) {
  8301. list = list.filter(t => (t.interfaces || t.interface || '').toLowerCase().includes(filter) || (t.networks || t.network || '').toLowerCase().includes(filter) || (t.comment || '').toLowerCase().includes(filter));
  8302. }
  8303. if (countEl) countEl.innerText = list.length;
  8304. const selId = state.selectedOspfRow?.templates;
  8305. tbody.innerHTML = list.map((t, idx) => {
  8306. const isSel = t.id === selId;
  8307. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  8308. const ifaces = t.interfaces || t.interface || 'all';
  8309. const nets = t.networks || t.network || '';
  8310. const flagD = t.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  8311. return `
  8312. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('templates', '${t.id}')" ondblclick="openEditOspfTemplateModal('${t.id}')">
  8313. <td class="py-1.5 px-3 w-8 text-center text-slate-500 font-bold">${idx}</td>
  8314. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🔀'}</td>
  8315. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(t.comment || '')}</td>
  8316. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  8317. <span class="text-sky-400">↳</span> <span>${escapeHtml(ifaces)}</span>
  8318. </td>
  8319. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(t.area || 'Default')}</td>
  8320. <td class="py-1.5 px-3 font-mono text-sky-300">${escapeHtml(nets)}</td>
  8321. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(t.network_type || 'broadcast')}</td>
  8322. <td class="py-1.5 px-3">${t.cost || 1}</td>
  8323. <td class="py-1.5 px-3">${t.priority || 128}</td>
  8324. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(t.auth || t.auth_type || '')}</td>
  8325. </tr>
  8326. `;
  8327. }).join('');
  8328. }
  8329. // TAB 5: LIVE INTERFACES
  8330. function renderOspfLiveInterfaces() {
  8331. const tbody = document.getElementById('ospf-live-interfaces-table-body');
  8332. if (!tbody) return;
  8333. const countEl = document.getElementById('ospf-live-interfaces-footer-count');
  8334. const filter = (document.getElementById('filter-ospf-interfaces')?.value || '').toLowerCase();
  8335. let list = state.ospfLiveInterfaces || [];
  8336. if (filter) {
  8337. list = list.filter(i => (i.interface || '').toLowerCase().includes(filter) || (i.address || '').toLowerCase().includes(filter) || (i.state || '').toLowerCase().includes(filter));
  8338. }
  8339. if (countEl) countEl.innerText = list.length;
  8340. tbody.innerHTML = list.map(i => `
  8341. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  8342. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(i.flags || 'D')}</td>
  8343. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(i.interface || '')}</td>
  8344. <td class="py-1.5 px-3 font-mono text-sky-300 font-medium">${escapeHtml(i.address || '')}</td>
  8345. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(i.area || 'Default')}</td>
  8346. <td class="py-1.5 px-3 text-center text-slate-400">${i.instance_id || 0}</td>
  8347. <td class="py-1.5 px-3 font-mono text-amber-300 lowercase">${escapeHtml(i.state || 'waiting')}</td>
  8348. <td class="py-1.5 px-3">${i.cost || 1}</td>
  8349. <td class="py-1.5 px-3">${i.priority || 128}</td>
  8350. </tr>
  8351. `).join('');
  8352. }
  8353. // TAB 6: STATIC NEIGHBORS
  8354. function renderOspfStaticNbrs() {
  8355. const tbody = document.getElementById('ospf-snbrs-table-body');
  8356. if (!tbody) return;
  8357. const countEl = document.getElementById('ospf-snbrs-footer-count');
  8358. const filter = (document.getElementById('filter-ospf-static-nbrs')?.value || '').toLowerCase();
  8359. let list = state.ospfStaticNbrs || [];
  8360. if (filter) {
  8361. list = list.filter(n => (n.address || '').toLowerCase().includes(filter) || (n.area || '').toLowerCase().includes(filter) || (n.comment || '').toLowerCase().includes(filter));
  8362. }
  8363. if (countEl) countEl.innerText = list.length;
  8364. const selId = state.selectedOspfRow?.['static-nbrs'];
  8365. tbody.innerHTML = list.map((n, idx) => {
  8366. const isSel = n.id === selId;
  8367. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  8368. const flagD = n.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  8369. return `
  8370. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('snbrs', '${n.id}')" ondblclick="openEditOspfStaticNbrModal('${n.id}')">
  8371. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  8372. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '📡'}</td>
  8373. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(n.comment || '')}</td>
  8374. <td class="py-1.5 px-3 font-semibold font-mono text-sky-300">${escapeHtml(n.address || '')}</td>
  8375. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(n.area || 'Default')}</td>
  8376. <td class="py-1.5 px-3">${n.poll_interval || 120}s</td>
  8377. <td class="py-1.5 px-3">${n.cost || 1}</td>
  8378. </tr>
  8379. `;
  8380. }).join('');
  8381. }
  8382. // TAB 7: LIVE NEIGHBORS
  8383. function renderOspfNeighbors() {
  8384. const tbody = document.getElementById('ospf-neighbors-table-body');
  8385. if (!tbody) return;
  8386. const countEl = document.getElementById('ospf-neighbors-footer-count');
  8387. const filter = (document.getElementById('filter-ospf-neighbors')?.value || '').toLowerCase();
  8388. let list = state.ospfNeighbors || [];
  8389. if (filter) {
  8390. list = list.filter(n => (n.address || '').toLowerCase().includes(filter) || (n.state || '').toLowerCase().includes(filter) || (n.instance || '').toLowerCase().includes(filter));
  8391. }
  8392. if (countEl) countEl.innerText = list.length;
  8393. tbody.innerHTML = list.map(n => `
  8394. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  8395. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(n.flags || 'D')}</td>
  8396. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(n.comment || '')}</td>
  8397. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  8398. <span class="text-sky-400">↳</span> <span>${escapeHtml(n.instance || 'Default')}</span>
  8399. </td>
  8400. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(n.area || 'Default')}</td>
  8401. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(n.address || '')}</td>
  8402. <td class="py-1.5 px-3 font-mono font-bold text-emerald-400">${escapeHtml(n.state || 'Full')}</td>
  8403. <td class="py-1.5 px-3 text-slate-400">${n.state_changes ?? 6}</td>
  8404. </tr>
  8405. `).join('');
  8406. }
  8407. // TAB 8: LINK-STATE DATABASE (LSA)
  8408. function renderOspfLSA() {
  8409. const tbody = document.getElementById('ospf-lsa-table-body');
  8410. if (!tbody) return;
  8411. const countEl = document.getElementById('ospf-lsa-footer-count');
  8412. const filter = (document.getElementById('filter-ospf-lsa')?.value || '').toLowerCase();
  8413. let list = state.ospfLSA || [];
  8414. if (filter) {
  8415. list = list.filter(l => (l.type || '').toLowerCase().includes(filter) || (l.originator || '').toLowerCase().includes(filter) || (l.id || '').toLowerCase().includes(filter));
  8416. }
  8417. if (countEl) countEl.innerText = list.length;
  8418. tbody.innerHTML = list.map(l => `
  8419. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  8420. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(l.flags || 'D')}</td>
  8421. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  8422. <span class="text-sky-400">↳</span> <span>${escapeHtml(l.instance || 'Default')}</span>
  8423. </td>
  8424. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(l.area || 'Default')}</td>
  8425. <td class="py-1.5 px-3 font-mono text-amber-300">${escapeHtml(l.type || 'router')}</td>
  8426. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(l.originator || '')}</td>
  8427. <td class="py-1.5 px-3 font-mono text-sky-300 font-medium">${escapeHtml(l.id || '')}</td>
  8428. <td class="py-1.5 px-3 text-slate-500">${escapeHtml(l.link || '')}</td>
  8429. <td class="py-1.5 px-3 text-slate-500">${l.link_index ?? 0}</td>
  8430. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(l.sequence || '')}</td>
  8431. <td class="py-1.5 px-3 text-slate-400">${l.age ?? 0}</td>
  8432. </tr>
  8433. `).join('');
  8434. }
  8435. function renderOspfStatusPill() {
  8436. // Maintained for backward compatibility
  8437. const pill = document.getElementById('ospf-live-status-pill');
  8438. if (!pill) return;
  8439. 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';
  8440. pill.innerText = 'OSPF ACTIVE';
  8441. }
  8442. function renderOspfInterfaces() {
  8443. renderOspfTemplates();
  8444. }
  8445. function renderOspfRoutes() {
  8446. // Routes retained in background
  8447. }
  8448. // BGP Modals & Actions
  8449. function openBgpInstanceModal() {
  8450. const inst = state.bgpInstance || { enabled: false, as: 65001, router_id: '192.168.131.56', hold_time: 180, keepalive_time: 60 };
  8451. document.getElementById('modal-bgp-enabled').checked = !!inst.enabled;
  8452. document.getElementById('modal-bgp-as').value = inst.as || 65001;
  8453. document.getElementById('modal-bgp-router-id').value = inst.router_id || '';
  8454. document.getElementById('modal-bgp-keepalive').value = inst.keepalive_time || 60;
  8455. document.getElementById('modal-bgp-holdtime').value = inst.hold_time || 180;
  8456. document.getElementById('modal-bgp-redist-conn').checked = !!inst.redistribute_connected;
  8457. document.getElementById('modal-bgp-redist-static').checked = !!inst.redistribute_static;
  8458. document.getElementById('modal-bgp-redist-ospf').checked = !!inst.redistribute_ospf;
  8459. document.getElementById('bgp-instance-modal').classList.remove('hidden');
  8460. }
  8461. function closeBgpInstanceModal() {
  8462. document.getElementById('bgp-instance-modal').classList.add('hidden');
  8463. }
  8464. async function submitBgpInstance(e) {
  8465. e.preventDefault();
  8466. const payload = {
  8467. enabled: document.getElementById('modal-bgp-enabled').checked,
  8468. as: parseInt(document.getElementById('modal-bgp-as').value, 10),
  8469. router_id: document.getElementById('modal-bgp-router-id').value.trim(),
  8470. keepalive_time: parseInt(document.getElementById('modal-bgp-keepalive').value, 10),
  8471. hold_time: parseInt(document.getElementById('modal-bgp-holdtime').value, 10),
  8472. redistribute_connected: document.getElementById('modal-bgp-redist-conn').checked,
  8473. redistribute_static: document.getElementById('modal-bgp-redist-static').checked,
  8474. redistribute_ospf: document.getElementById('modal-bgp-redist-ospf').checked
  8475. };
  8476. try {
  8477. const res = await fetch(`${API_BASE}/routing/bgp/instance`, {
  8478. method: 'POST',
  8479. headers: { 'Content-Type': 'application/json' },
  8480. body: JSON.stringify(payload)
  8481. });
  8482. if (res.ok) {
  8483. closeBgpInstanceModal();
  8484. showToast('Success', 'BGP instance configuration updated', 'success');
  8485. loadDynamicRouting();
  8486. } else {
  8487. const err = await res.json();
  8488. showToast('Error', err.error || 'Failed to update BGP instance', 'error');
  8489. }
  8490. } catch (err) {
  8491. showToast('Error', err.message, 'error');
  8492. }
  8493. }
  8494. // ----------------- BGP Peer Connection Modal (DebTik v7) -----------------
  8495. function switchBgpPeerModalTab(tab) {
  8496. const tabs = ['general', 'extra', 'attributes', 'filter'];
  8497. tabs.forEach(t => {
  8498. const pane = document.getElementById(`bgp-peer-tab-${t}`);
  8499. const btn = document.getElementById(`bgp-peer-tab-btn-${t}`);
  8500. if (t === tab) {
  8501. if (pane) pane.classList.remove('hidden');
  8502. if (btn) btn.className = 'px-4 py-2 text-xs font-bold border-b-2 border-cyan-500 text-white transition';
  8503. } else {
  8504. if (pane) pane.classList.add('hidden');
  8505. 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';
  8506. }
  8507. });
  8508. }
  8509. function addOutputNetworkRow(val = '') {
  8510. const container = document.getElementById('modal-bgp-output-networks-container');
  8511. if (!container) return;
  8512. const row = document.createElement('div');
  8513. row.className = 'flex items-center gap-2 output-net-row';
  8514. row.innerHTML = `
  8515. <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">
  8516. <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>
  8517. `;
  8518. container.appendChild(row);
  8519. }
  8520. function parseBgpTime(val) {
  8521. if (!val) return 0;
  8522. val = String(val).trim();
  8523. if (val.includes(':')) {
  8524. const parts = val.split(':').map(x => parseInt(x, 10) || 0);
  8525. if (parts.length === 3) return parts[0] * 3600 + parts[1] * 60 + parts[2];
  8526. if (parts.length === 2) return parts[0] * 60 + parts[1];
  8527. }
  8528. return parseInt(val, 10) || 0;
  8529. }
  8530. function formatBgpTime(secs) {
  8531. if (!secs || secs <= 0) return '00:00:00';
  8532. const h = Math.floor(secs / 3600);
  8533. const m = Math.floor((secs % 3600) / 60);
  8534. const s = secs % 60;
  8535. return `${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`;
  8536. }
  8537. function populateBgpRoutingTables() {
  8538. const sel = document.getElementById('modal-bgp-peer-routing-table');
  8539. if (!sel) return;
  8540. const cur = sel.value || 'main';
  8541. sel.innerHTML = '<option value="main">main</option>';
  8542. (state.routingTables || []).forEach(t => {
  8543. if (t.name !== 'main') {
  8544. const opt = document.createElement('option');
  8545. opt.value = t.name;
  8546. opt.innerText = t.name;
  8547. sel.appendChild(opt);
  8548. }
  8549. });
  8550. sel.value = cur;
  8551. }
  8552. function openAddBgpPeerModal() {
  8553. document.getElementById('bgp-peer-form').reset();
  8554. document.getElementById('modal-bgp-peer-id').value = '';
  8555. document.getElementById('bgp-peer-modal-title').innerText = 'New...';
  8556. // General Tab
  8557. document.getElementById('modal-bgp-peer-enabled').checked = true;
  8558. document.getElementById('modal-bgp-peer-comment').value = '';
  8559. document.getElementById('modal-bgp-peer-name').value = '';
  8560. if (document.getElementById('modal-bgp-peer-instance')) document.getElementById('modal-bgp-peer-instance').value = 'bgp-instance-1';
  8561. if (document.getElementById('modal-bgp-peer-template')) document.getElementById('modal-bgp-peer-template').value = '';
  8562. document.getElementById('modal-bgp-peer-local-as').value = '';
  8563. document.getElementById('modal-bgp-peer-afi-ip').checked = true;
  8564. document.getElementById('modal-bgp-peer-afi-ipv6').checked = false;
  8565. if (document.getElementById('modal-bgp-peer-afi-l2vpn')) document.getElementById('modal-bgp-peer-afi-l2vpn').checked = false;
  8566. if (document.getElementById('modal-bgp-peer-afi-vpnv4')) document.getElementById('modal-bgp-peer-afi-vpnv4').checked = false;
  8567. if (document.getElementById('modal-bgp-peer-afi-l2vpn-cisco')) document.getElementById('modal-bgp-peer-afi-l2vpn-cisco').checked = false;
  8568. document.getElementById('modal-bgp-peer-router-id').value = '';
  8569. document.getElementById('modal-bgp-peer-remote-addr').value = '';
  8570. document.getElementById('modal-bgp-peer-remote-port').value = '';
  8571. document.getElementById('modal-bgp-peer-remote-as').value = '';
  8572. if (document.getElementById('modal-bgp-peer-remote-allow-as')) document.getElementById('modal-bgp-peer-remote-allow-as').value = '';
  8573. document.getElementById('modal-bgp-peer-local-addr').value = '';
  8574. document.getElementById('modal-bgp-peer-local-port').value = '';
  8575. document.getElementById('modal-bgp-peer-local-role').value = 'ebgp';
  8576. document.getElementById('modal-bgp-peer-password').value = '';
  8577. document.getElementById('modal-bgp-peer-multihop').checked = false;
  8578. if (document.getElementById('modal-bgp-peer-tx-ttl')) document.getElementById('modal-bgp-peer-tx-ttl').value = '';
  8579. if (document.getElementById('modal-bgp-peer-rx-min-ttl')) document.getElementById('modal-bgp-peer-rx-min-ttl').value = '';
  8580. document.getElementById('modal-bgp-peer-connect').checked = true;
  8581. document.getElementById('modal-bgp-peer-listen').checked = true;
  8582. // Extra Tab
  8583. document.getElementById('modal-bgp-peer-holdtime').value = '00:00:30';
  8584. document.getElementById('modal-bgp-peer-keepalive').value = '00:00:10';
  8585. if (document.getElementById('modal-bgp-peer-use-bfd')) document.getElementById('modal-bgp-peer-use-bfd').checked = false;
  8586. if (document.getElementById('modal-bgp-peer-vrf')) document.getElementById('modal-bgp-peer-vrf').value = 'main';
  8587. if (document.getElementById('modal-bgp-peer-no-client-reflect')) document.getElementById('modal-bgp-peer-no-client-reflect').checked = true;
  8588. document.getElementById('modal-bgp-peer-redist-conn').checked = false;
  8589. document.getElementById('modal-bgp-peer-redist-static').checked = true;
  8590. if (document.getElementById('modal-bgp-peer-redist-rip')) document.getElementById('modal-bgp-peer-redist-rip').checked = false;
  8591. document.getElementById('modal-bgp-peer-redist-ospf').checked = false;
  8592. document.getElementById('modal-bgp-peer-redist-bgp').checked = false;
  8593. if (document.getElementById('modal-bgp-peer-redist-vpn')) document.getElementById('modal-bgp-peer-redist-vpn').checked = false;
  8594. if (document.getElementById('modal-bgp-peer-redist-dhcp')) document.getElementById('modal-bgp-peer-redist-dhcp').checked = false;
  8595. if (document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn')) document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn').checked = false;
  8596. if (document.getElementById('modal-bgp-peer-redist-slaac')) document.getElementById('modal-bgp-peer-redist-slaac').checked = false;
  8597. document.getElementById('modal-bgp-peer-default-orig').checked = false;
  8598. if (document.getElementById('modal-bgp-peer-network-blackhole')) document.getElementById('modal-bgp-peer-network-blackhole').checked = false;
  8599. if (document.getElementById('modal-bgp-peer-no-early-cut')) document.getElementById('modal-bgp-peer-no-early-cut').checked = false;
  8600. if (document.getElementById('modal-bgp-peer-keep-sent-attrs')) document.getElementById('modal-bgp-peer-keep-sent-attrs').checked = false;
  8601. if (document.getElementById('modal-bgp-peer-input-affinity')) document.getElementById('modal-bgp-peer-input-affinity').value = '';
  8602. if (document.getElementById('modal-bgp-peer-output-affinity')) document.getElementById('modal-bgp-peer-output-affinity').value = '';
  8603. // Attributes Tab
  8604. document.getElementById('modal-bgp-peer-nexthop-choice').value = 'force-self';
  8605. document.getElementById('modal-bgp-peer-default-prepend').value = 0;
  8606. document.getElementById('modal-bgp-peer-allow-as-in').value = 0;
  8607. if (document.getElementById('modal-bgp-peer-ignore-as-path-len')) document.getElementById('modal-bgp-peer-ignore-as-path-len').checked = false;
  8608. document.getElementById('modal-bgp-peer-remove-priv-as').checked = false;
  8609. document.getElementById('modal-bgp-peer-as-override').checked = false;
  8610. // Filter Tab
  8611. populateFilterChainsDatalist();
  8612. document.getElementById('modal-bgp-peer-in-filter').value = '';
  8613. if (document.getElementById('modal-bgp-peer-in-accept-nlri')) document.getElementById('modal-bgp-peer-in-accept-nlri').value = '';
  8614. if (document.getElementById('modal-bgp-peer-in-accept-comm')) document.getElementById('modal-bgp-peer-in-accept-comm').value = '';
  8615. if (document.getElementById('modal-bgp-peer-in-accept-ext-comm')) document.getElementById('modal-bgp-peer-in-accept-ext-comm').value = '';
  8616. if (document.getElementById('modal-bgp-peer-in-accept-large-comm')) document.getElementById('modal-bgp-peer-in-accept-large-comm').value = '';
  8617. if (document.getElementById('modal-bgp-peer-in-filter-comm')) document.getElementById('modal-bgp-peer-in-filter-comm').value = '';
  8618. if (document.getElementById('modal-bgp-peer-in-filter-ext-comm')) document.getElementById('modal-bgp-peer-in-filter-ext-comm').value = '';
  8619. if (document.getElementById('modal-bgp-peer-in-filter-large-comm')) document.getElementById('modal-bgp-peer-in-filter-large-comm').value = '';
  8620. if (document.getElementById('modal-bgp-peer-in-filter-unknown')) document.getElementById('modal-bgp-peer-in-filter-unknown').checked = false;
  8621. document.getElementById('modal-bgp-peer-out-filter').value = '';
  8622. if (document.getElementById('modal-bgp-peer-out-selection-policy')) document.getElementById('modal-bgp-peer-out-selection-policy').value = 'disabled';
  8623. if (document.getElementById('modal-bgp-peer-out-network-name')) document.getElementById('modal-bgp-peer-out-network-name').value = '';
  8624. populateBgpRoutingTables();
  8625. const container = document.getElementById('modal-bgp-output-networks-container');
  8626. if (container) {
  8627. container.innerHTML = '';
  8628. addOutputNetworkRow('');
  8629. }
  8630. const removeBtn = document.getElementById('modal-btn-remove-peer');
  8631. if (removeBtn) removeBtn.classList.add('hidden');
  8632. switchBgpPeerModalTab('general');
  8633. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  8634. }
  8635. function populateFilterChainsDatalist() {
  8636. const dl = document.getElementById('filter-chains-list');
  8637. if (!dl) return;
  8638. const chains = new Set();
  8639. (state.routingFilters || []).forEach(f => {
  8640. if (f.chain) chains.add(f.chain);
  8641. });
  8642. if (chains.size === 0) {
  8643. chains.add('awmn');
  8644. chains.add('bgp-in');
  8645. chains.add('bgp-out');
  8646. }
  8647. dl.innerHTML = '';
  8648. chains.forEach(c => {
  8649. const opt = document.createElement('option');
  8650. opt.value = c;
  8651. dl.appendChild(opt);
  8652. });
  8653. }
  8654. function openEditBgpPeerModal(id) {
  8655. const p = (state.bgpPeers || []).find(item => item.id === id);
  8656. if (!p) return;
  8657. populateBgpRoutingTables();
  8658. populateFilterChainsDatalist();
  8659. document.getElementById('modal-bgp-peer-id').value = p.id;
  8660. document.getElementById('bgp-peer-modal-title').innerText = p.name || p.id;
  8661. // General Tab
  8662. document.getElementById('modal-bgp-peer-enabled').checked = p.enabled !== false && !p.disabled;
  8663. document.getElementById('modal-bgp-peer-comment').value = p.comment || '';
  8664. document.getElementById('modal-bgp-peer-name').value = p.name || '';
  8665. if (document.getElementById('modal-bgp-peer-instance')) document.getElementById('modal-bgp-peer-instance').value = p.instance || 'bgp-instance-1';
  8666. if (document.getElementById('modal-bgp-peer-template')) document.getElementById('modal-bgp-peer-template').value = p.template || '';
  8667. document.getElementById('modal-bgp-peer-local-as').value = p.local_as || '';
  8668. document.getElementById('modal-bgp-peer-router-id').value = p.router_id || '';
  8669. document.getElementById('modal-bgp-peer-afi-ip').checked = true;
  8670. document.getElementById('modal-bgp-peer-afi-ipv6').checked = p.afi === 'ipv6';
  8671. document.getElementById('modal-bgp-peer-remote-addr').value = p.remote_address || '';
  8672. document.getElementById('modal-bgp-peer-remote-port').value = p.remote_port || '';
  8673. document.getElementById('modal-bgp-peer-remote-as').value = p.remote_as || '';
  8674. if (document.getElementById('modal-bgp-peer-remote-allow-as')) document.getElementById('modal-bgp-peer-remote-allow-as').value = p.remote_allow_as || '';
  8675. document.getElementById('modal-bgp-peer-local-addr').value = p.local_address || '';
  8676. document.getElementById('modal-bgp-peer-local-port').value = p.local_port || '';
  8677. document.getElementById('modal-bgp-peer-local-role').value = p.local_role || 'ebgp';
  8678. document.getElementById('modal-bgp-peer-password').value = p.password || '';
  8679. document.getElementById('modal-bgp-peer-multihop').checked = !!p.multihop;
  8680. if (document.getElementById('modal-bgp-peer-tx-ttl')) document.getElementById('modal-bgp-peer-tx-ttl').value = p.tx_ttl || '';
  8681. if (document.getElementById('modal-bgp-peer-rx-min-ttl')) document.getElementById('modal-bgp-peer-rx-min-ttl').value = p.rx_min_ttl || '';
  8682. document.getElementById('modal-bgp-peer-connect').checked = p.connect !== false;
  8683. document.getElementById('modal-bgp-peer-listen').checked = p.listen !== false;
  8684. // Extra Tab
  8685. document.getElementById('modal-bgp-peer-holdtime').value = p.hold_time ? formatBgpTime(p.hold_time) : '00:00:30';
  8686. document.getElementById('modal-bgp-peer-keepalive').value = p.keepalive_time ? formatBgpTime(p.keepalive_time) : '00:00:10';
  8687. if (document.getElementById('modal-bgp-peer-use-bfd')) document.getElementById('modal-bgp-peer-use-bfd').checked = !!p.use_bfd;
  8688. document.getElementById('modal-bgp-peer-routing-table').value = p.routing_table || 'main';
  8689. if (document.getElementById('modal-bgp-peer-vrf')) document.getElementById('modal-bgp-peer-vrf').value = p.vrf || 'main';
  8690. if (document.getElementById('modal-bgp-peer-no-client-reflect')) document.getElementById('modal-bgp-peer-no-client-reflect').checked = p.no_client_reflect !== false;
  8691. document.getElementById('modal-bgp-peer-redist-conn').checked = !!p.redist_connected;
  8692. document.getElementById('modal-bgp-peer-redist-static').checked = p.redist_static !== false;
  8693. if (document.getElementById('modal-bgp-peer-redist-rip')) document.getElementById('modal-bgp-peer-redist-rip').checked = !!p.redist_rip;
  8694. document.getElementById('modal-bgp-peer-redist-ospf').checked = !!p.redist_ospf;
  8695. document.getElementById('modal-bgp-peer-redist-bgp').checked = !!p.redist_bgp;
  8696. if (document.getElementById('modal-bgp-peer-redist-vpn')) document.getElementById('modal-bgp-peer-redist-vpn').checked = !!p.redist_vpn;
  8697. if (document.getElementById('modal-bgp-peer-redist-dhcp')) document.getElementById('modal-bgp-peer-redist-dhcp').checked = !!p.redist_dhcp;
  8698. 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;
  8699. if (document.getElementById('modal-bgp-peer-redist-slaac')) document.getElementById('modal-bgp-peer-redist-slaac').checked = !!p.redist_slaac;
  8700. document.getElementById('modal-bgp-peer-default-orig').checked = !!p.default_originate;
  8701. if (document.getElementById('modal-bgp-peer-network-blackhole')) document.getElementById('modal-bgp-peer-network-blackhole').checked = !!p.network_blackhole;
  8702. if (document.getElementById('modal-bgp-peer-no-early-cut')) document.getElementById('modal-bgp-peer-no-early-cut').checked = !!p.no_early_cut;
  8703. if (document.getElementById('modal-bgp-peer-keep-sent-attrs')) document.getElementById('modal-bgp-peer-keep-sent-attrs').checked = !!p.keep_sent_attrs;
  8704. if (document.getElementById('modal-bgp-peer-input-affinity')) document.getElementById('modal-bgp-peer-input-affinity').value = p.input_affinity || '';
  8705. if (document.getElementById('modal-bgp-peer-output-affinity')) document.getElementById('modal-bgp-peer-output-affinity').value = p.output_affinity || '';
  8706. // Attributes Tab
  8707. document.getElementById('modal-bgp-peer-nexthop-choice').value = p.nexthop_choice || (p.nexthop_self ? 'force-self' : 'default');
  8708. document.getElementById('modal-bgp-peer-default-prepend').value = p.default_prepend || 0;
  8709. document.getElementById('modal-bgp-peer-allow-as-in').value = p.allow_as_in || 0;
  8710. 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;
  8711. document.getElementById('modal-bgp-peer-remove-priv-as').checked = !!p.remove_private_as;
  8712. document.getElementById('modal-bgp-peer-as-override').checked = !!p.as_override;
  8713. // Filter Tab
  8714. document.getElementById('modal-bgp-peer-in-filter').value = p.in_filter || '';
  8715. if (document.getElementById('modal-bgp-peer-in-accept-nlri')) document.getElementById('modal-bgp-peer-in-accept-nlri').value = p.in_accept_nlri || '';
  8716. if (document.getElementById('modal-bgp-peer-in-accept-comm')) document.getElementById('modal-bgp-peer-in-accept-comm').value = p.in_accept_communities || '';
  8717. 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 || '';
  8718. 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 || '';
  8719. if (document.getElementById('modal-bgp-peer-in-filter-comm')) document.getElementById('modal-bgp-peer-in-filter-comm').value = p.in_filter_communities || '';
  8720. 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 || '';
  8721. 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 || '';
  8722. if (document.getElementById('modal-bgp-peer-in-filter-unknown')) document.getElementById('modal-bgp-peer-in-filter-unknown').checked = !!p.in_filter_unknown;
  8723. document.getElementById('modal-bgp-peer-out-filter').value = p.out_filter || '';
  8724. if (document.getElementById('modal-bgp-peer-out-selection-policy')) document.getElementById('modal-bgp-peer-out-selection-policy').value = p.out_selection_policy || 'disabled';
  8725. if (document.getElementById('modal-bgp-peer-out-network-name')) document.getElementById('modal-bgp-peer-out-network-name').value = p.output_network || '';
  8726. // Output Networks
  8727. const container = document.getElementById('modal-bgp-output-networks-container');
  8728. if (container) {
  8729. container.innerHTML = '';
  8730. if (p.output_networks && p.output_networks.length > 0) {
  8731. p.output_networks.forEach(net => addOutputNetworkRow(net));
  8732. } else {
  8733. addOutputNetworkRow('');
  8734. }
  8735. }
  8736. const removeBtn = document.getElementById('modal-btn-remove-peer');
  8737. if (removeBtn) removeBtn.classList.remove('hidden');
  8738. switchBgpPeerModalTab('general');
  8739. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  8740. }
  8741. function copyCurrentBgpPeer() {
  8742. document.getElementById('modal-bgp-peer-id').value = '';
  8743. const nameEl = document.getElementById('modal-bgp-peer-name');
  8744. if (nameEl) nameEl.value = (nameEl.value || 'peer') + '-copy';
  8745. document.getElementById('bgp-peer-modal-title').innerText = 'New...';
  8746. const removeBtn = document.getElementById('modal-btn-remove-peer');
  8747. if (removeBtn) removeBtn.classList.add('hidden');
  8748. showToast('Cloned', 'BGP connection copied to new draft', 'info');
  8749. }
  8750. function removeCurrentBgpPeer() {
  8751. const id = document.getElementById('modal-bgp-peer-id')?.value;
  8752. if (!id) return;
  8753. deleteBgpPeer(id);
  8754. closeBgpPeerModal();
  8755. }
  8756. function closeBgpPeerModal() {
  8757. document.getElementById('bgp-peer-modal').classList.add('hidden');
  8758. }
  8759. function getBgpPeerFormData() {
  8760. const netInputs = document.querySelectorAll('#modal-bgp-output-networks-container .output-net-row input');
  8761. const outputNetworks = [];
  8762. netInputs.forEach(inp => {
  8763. const v = inp.value.trim();
  8764. if (v) outputNetworks.push(v);
  8765. });
  8766. const enabled = document.getElementById('modal-bgp-peer-enabled').checked;
  8767. return {
  8768. id: document.getElementById('modal-bgp-peer-id').value,
  8769. name: document.getElementById('modal-bgp-peer-name').value.trim(),
  8770. enabled: enabled,
  8771. disabled: !enabled,
  8772. comment: document.getElementById('modal-bgp-peer-comment').value.trim(),
  8773. instance: document.getElementById('modal-bgp-peer-instance')?.value.trim() || 'bgp-instance-1',
  8774. template: document.getElementById('modal-bgp-peer-template')?.value.trim() || '',
  8775. local_as: parseInt(document.getElementById('modal-bgp-peer-local-as')?.value, 10) || 0,
  8776. router_id: document.getElementById('modal-bgp-peer-router-id').value.trim(),
  8777. afi: document.getElementById('modal-bgp-peer-afi-ipv6').checked ? 'ipv6' : 'ip',
  8778. remote_address: document.getElementById('modal-bgp-peer-remote-addr').value.trim(),
  8779. remote_port: parseInt(document.getElementById('modal-bgp-peer-remote-port').value, 10) || 0,
  8780. remote_as: parseInt(document.getElementById('modal-bgp-peer-remote-as').value, 10) || 0,
  8781. remote_allow_as: document.getElementById('modal-bgp-peer-remote-allow-as')?.value.trim() || '',
  8782. local_address: document.getElementById('modal-bgp-peer-local-addr').value.trim(),
  8783. local_port: parseInt(document.getElementById('modal-bgp-peer-local-port').value, 10) || 0,
  8784. local_role: document.getElementById('modal-bgp-peer-local-role').value,
  8785. password: document.getElementById('modal-bgp-peer-password').value,
  8786. multihop: document.getElementById('modal-bgp-peer-multihop').checked,
  8787. tx_ttl: parseInt(document.getElementById('modal-bgp-peer-tx-ttl')?.value, 10) || 0,
  8788. rx_min_ttl: parseInt(document.getElementById('modal-bgp-peer-rx-min-ttl')?.value, 10) || 0,
  8789. connect: document.getElementById('modal-bgp-peer-connect').checked,
  8790. listen: document.getElementById('modal-bgp-peer-listen').checked,
  8791. hold_time: parseBgpTime(document.getElementById('modal-bgp-peer-holdtime').value),
  8792. keepalive_time: parseBgpTime(document.getElementById('modal-bgp-peer-keepalive').value),
  8793. use_bfd: document.getElementById('modal-bgp-peer-use-bfd')?.checked || false,
  8794. routing_table: document.getElementById('modal-bgp-peer-routing-table').value,
  8795. vrf: document.getElementById('modal-bgp-peer-vrf')?.value.trim() || 'main',
  8796. no_client_reflect: document.getElementById('modal-bgp-peer-no-client-reflect')?.checked || false,
  8797. redist_connected: document.getElementById('modal-bgp-peer-redist-conn').checked,
  8798. redist_static: document.getElementById('modal-bgp-peer-redist-static').checked,
  8799. redist_rip: document.getElementById('modal-bgp-peer-redist-rip')?.checked || false,
  8800. redist_ospf: document.getElementById('modal-bgp-peer-redist-ospf').checked,
  8801. redist_bgp: document.getElementById('modal-bgp-peer-redist-bgp').checked,
  8802. redist_vpn: document.getElementById('modal-bgp-peer-redist-vpn')?.checked || false,
  8803. redist_dhcp: document.getElementById('modal-bgp-peer-redist-dhcp')?.checked || false,
  8804. redist_bgp_mpls_vpn: document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn')?.checked || false,
  8805. redist_slaac: document.getElementById('modal-bgp-peer-redist-slaac')?.checked || false,
  8806. default_originate: document.getElementById('modal-bgp-peer-default-orig').checked,
  8807. network_blackhole: document.getElementById('modal-bgp-peer-network-blackhole')?.checked || false,
  8808. no_early_cut: document.getElementById('modal-bgp-peer-no-early-cut')?.checked || false,
  8809. keep_sent_attrs: document.getElementById('modal-bgp-peer-keep-sent-attrs')?.checked || false,
  8810. input_affinity: (document.getElementById('modal-bgp-peer-input-affinity')?.value || '').trim(),
  8811. output_affinity: (document.getElementById('modal-bgp-peer-output-affinity')?.value || '').trim(),
  8812. nexthop_choice: document.getElementById('modal-bgp-peer-nexthop-choice').value,
  8813. nexthop_self: document.getElementById('modal-bgp-peer-nexthop-choice').value === 'force-self',
  8814. default_prepend: parseInt(document.getElementById('modal-bgp-peer-default-prepend').value, 10) || 0,
  8815. allow_as_in: parseInt(document.getElementById('modal-bgp-peer-allow-as-in').value, 10) || 0,
  8816. ignore_as_path_len: document.getElementById('modal-bgp-peer-ignore-as-path-len')?.checked || false,
  8817. remove_private_as: document.getElementById('modal-bgp-peer-remove-priv-as').checked,
  8818. as_override: document.getElementById('modal-bgp-peer-as-override').checked,
  8819. in_filter: (document.getElementById('modal-bgp-peer-in-filter')?.value || '').trim(),
  8820. in_accept_nlri: (document.getElementById('modal-bgp-peer-in-accept-nlri')?.value || '').trim(),
  8821. in_accept_communities: (document.getElementById('modal-bgp-peer-in-accept-comm')?.value || '').trim(),
  8822. in_accept_ext_communities: (document.getElementById('modal-bgp-peer-in-accept-ext-comm')?.value || '').trim(),
  8823. in_accept_large_communities: (document.getElementById('modal-bgp-peer-in-accept-large-comm')?.value || '').trim(),
  8824. in_filter_communities: (document.getElementById('modal-bgp-peer-in-filter-comm')?.value || '').trim(),
  8825. in_filter_ext_communities: (document.getElementById('modal-bgp-peer-in-filter-ext-comm')?.value || '').trim(),
  8826. in_filter_large_communities: (document.getElementById('modal-bgp-peer-in-filter-large-comm')?.value || '').trim(),
  8827. in_filter_unknown: document.getElementById('modal-bgp-peer-in-filter-unknown')?.checked || false,
  8828. out_filter: (document.getElementById('modal-bgp-peer-out-filter')?.value || '').trim(),
  8829. out_selection_policy: document.getElementById('modal-bgp-peer-out-selection-policy')?.value || 'disabled',
  8830. output_network: (document.getElementById('modal-bgp-peer-out-network-name')?.value || '').trim(),
  8831. output_networks: outputNetworks
  8832. };
  8833. }
  8834. async function submitBgpPeer(e) {
  8835. if (e) e.preventDefault();
  8836. const payload = getBgpPeerFormData();
  8837. try {
  8838. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  8839. method: 'POST',
  8840. headers: { 'Content-Type': 'application/json' },
  8841. body: JSON.stringify(payload)
  8842. });
  8843. if (res.ok) {
  8844. closeBgpPeerModal();
  8845. showToast('Success', 'BGP Connection saved', 'success');
  8846. loadDynamicRouting();
  8847. } else {
  8848. const err = await res.json();
  8849. showToast('Error', err.error || 'Failed to save peer', 'error');
  8850. }
  8851. } catch (err) {
  8852. showToast('Error', err.message, 'error');
  8853. }
  8854. }
  8855. async function applyBgpPeerModal(e) {
  8856. if (e) e.preventDefault();
  8857. const payload = getBgpPeerFormData();
  8858. try {
  8859. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  8860. method: 'POST',
  8861. headers: { 'Content-Type': 'application/json' },
  8862. body: JSON.stringify(payload)
  8863. });
  8864. if (res.ok) {
  8865. const data = await res.json();
  8866. if (data.peer && data.peer.id) {
  8867. document.getElementById('modal-bgp-peer-id').value = data.peer.id;
  8868. document.getElementById('bgp-peer-modal-title').innerText = data.peer.name || data.peer.id;
  8869. document.getElementById('modal-btn-remove-peer')?.classList.remove('hidden');
  8870. }
  8871. showToast('Applied', 'BGP Connection applied', 'success');
  8872. loadDynamicRouting();
  8873. } else {
  8874. const err = await res.json();
  8875. showToast('Error', err.error || 'Failed to apply peer', 'error');
  8876. }
  8877. } catch (err) {
  8878. showToast('Error', err.message, 'error');
  8879. }
  8880. }
  8881. async function deleteBgpPeer(id) {
  8882. if (!confirm('Are you sure you want to delete this BGP peer connection?')) return;
  8883. try {
  8884. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8885. if (res.ok) {
  8886. showToast('Deleted', 'BGP peer removed', 'success');
  8887. loadDynamicRouting();
  8888. }
  8889. } catch (err) {
  8890. showToast('Error', err.message, 'error');
  8891. }
  8892. }
  8893. async function toggleBgpPeerState(id, disabled) {
  8894. try {
  8895. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}/state`, {
  8896. method: 'POST',
  8897. headers: { 'Content-Type': 'application/json' },
  8898. body: JSON.stringify({ disabled })
  8899. });
  8900. if (res.ok) {
  8901. showToast('Updated', `Peer ${disabled ? 'disabled' : 'enabled'}`, 'success');
  8902. loadDynamicRouting();
  8903. }
  8904. } catch (err) {
  8905. showToast('Error', err.message, 'error');
  8906. }
  8907. }
  8908. function openAddBgpNetworkModal() {
  8909. document.getElementById('bgp-network-form').reset();
  8910. document.getElementById('modal-bgp-net-id').value = '';
  8911. document.getElementById('bgp-network-modal').classList.remove('hidden');
  8912. }
  8913. function closeBgpNetworkModal() {
  8914. document.getElementById('bgp-network-modal').classList.add('hidden');
  8915. }
  8916. async function submitBgpNetwork(e) {
  8917. e.preventDefault();
  8918. const payload = {
  8919. id: document.getElementById('modal-bgp-net-id').value,
  8920. network: document.getElementById('modal-bgp-net-cidr').value.trim(),
  8921. comment: document.getElementById('modal-bgp-net-comment').value.trim(),
  8922. disabled: document.getElementById('modal-bgp-net-disabled').checked
  8923. };
  8924. try {
  8925. const res = await fetch(`${API_BASE}/routing/bgp/networks`, {
  8926. method: 'POST',
  8927. headers: { 'Content-Type': 'application/json' },
  8928. body: JSON.stringify(payload)
  8929. });
  8930. if (res.ok) {
  8931. closeBgpNetworkModal();
  8932. showToast('Success', 'BGP network advertisement saved', 'success');
  8933. loadDynamicRouting();
  8934. } else {
  8935. const err = await res.json();
  8936. showToast('Error', err.error || 'Failed to save network', 'error');
  8937. }
  8938. } catch (err) {
  8939. showToast('Error', err.message, 'error');
  8940. }
  8941. }
  8942. async function deleteBgpNetwork(id) {
  8943. if (!confirm('Are you sure you want to stop announcing this network?')) return;
  8944. try {
  8945. const res = await fetch(`${API_BASE}/routing/bgp/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8946. if (res.ok) {
  8947. showToast('Deleted', 'Network advertisement removed', 'success');
  8948. loadDynamicRouting();
  8949. }
  8950. } catch (err) {
  8951. showToast('Error', err.message, 'error');
  8952. }
  8953. }
  8954. // =========================================================================
  8955. // DEBTIK v7 OSPF MODALS & ACTIONS
  8956. // =========================================================================
  8957. // --- 1. OSPF INSTANCE ---
  8958. function openOspfInstanceModal(id = null) {
  8959. const isEdit = !!id;
  8960. const inst = (state.ospfInstances || []).find(i => i.id === id) || {
  8961. id: '',
  8962. name: 'Default',
  8963. version: 2,
  8964. vrf: 'main',
  8965. router_id: '192.168.131.56',
  8966. routing_table: 'main',
  8967. enabled: true,
  8968. redistribute_connected: false,
  8969. redistribute_static: true,
  8970. redistribute_bgp: false,
  8971. comment: ''
  8972. };
  8973. document.getElementById('ospf-instance-modal-title').innerText = isEdit ? inst.name : 'New...';
  8974. document.getElementById('modal-ospf-inst-id').value = isEdit ? inst.id : '';
  8975. document.getElementById('modal-ospf-inst-enabled').checked = !inst.disabled;
  8976. document.getElementById('modal-ospf-inst-comment').value = inst.comment || '';
  8977. document.getElementById('modal-ospf-inst-name').value = inst.name || 'Default';
  8978. document.getElementById('modal-ospf-inst-version').value = inst.version || 2;
  8979. document.getElementById('modal-ospf-inst-vrf').value = inst.vrf || 'main';
  8980. document.getElementById('modal-ospf-inst-router-id').value = inst.router_id || '';
  8981. document.getElementById('modal-ospf-inst-routing-table').value = inst.routing_table || 'main';
  8982. document.getElementById('modal-ospf-inst-redist-conn').checked = !!inst.redistribute_connected;
  8983. document.getElementById('modal-ospf-inst-redist-static').checked = inst.redistribute_static !== false;
  8984. document.getElementById('modal-ospf-inst-redist-bgp').checked = !!inst.redistribute_bgp;
  8985. const btnRem = document.getElementById('btn-ospf-inst-modal-remove');
  8986. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  8987. document.getElementById('ospf-instance-modal').classList.remove('hidden');
  8988. }
  8989. function openEditOspfInstanceModal(id) {
  8990. openOspfInstanceModal(id);
  8991. }
  8992. function closeOspfInstanceModal() {
  8993. document.getElementById('ospf-instance-modal').classList.add('hidden');
  8994. }
  8995. async function submitOspfInstance(e) {
  8996. if (e) e.preventDefault();
  8997. const payload = {
  8998. id: document.getElementById('modal-ospf-inst-id').value,
  8999. name: document.getElementById('modal-ospf-inst-name').value.trim() || 'Default',
  9000. version: parseInt(document.getElementById('modal-ospf-inst-version').value, 10) || 2,
  9001. vrf: document.getElementById('modal-ospf-inst-vrf').value.trim() || 'main',
  9002. router_id: document.getElementById('modal-ospf-inst-router-id').value.trim(),
  9003. routing_table: document.getElementById('modal-ospf-inst-routing-table').value.trim() || 'main',
  9004. enabled: document.getElementById('modal-ospf-inst-enabled').checked,
  9005. disabled: !document.getElementById('modal-ospf-inst-enabled').checked,
  9006. comment: document.getElementById('modal-ospf-inst-comment').value.trim(),
  9007. redistribute_connected: document.getElementById('modal-ospf-inst-redist-conn').checked,
  9008. redistribute_static: document.getElementById('modal-ospf-inst-redist-static').checked,
  9009. redistribute_bgp: document.getElementById('modal-ospf-inst-redist-bgp').checked
  9010. };
  9011. try {
  9012. const res = await fetch(`${API_BASE}/routing/ospf/instances`, {
  9013. method: 'POST',
  9014. headers: { 'Content-Type': 'application/json' },
  9015. body: JSON.stringify(payload)
  9016. });
  9017. if (res.ok) {
  9018. closeOspfInstanceModal();
  9019. showToast('Saved', 'OSPF instance updated', 'success');
  9020. loadDynamicRouting();
  9021. } else {
  9022. const err = await res.json();
  9023. showToast('Error', err.error || 'Failed to save OSPF instance', 'error');
  9024. }
  9025. } catch (err) {
  9026. showToast('Error', err.message, 'error');
  9027. }
  9028. }
  9029. function applyOspfInstanceForm() {
  9030. submitOspfInstance(null);
  9031. }
  9032. function copyOspfInstance() {
  9033. document.getElementById('modal-ospf-inst-id').value = '';
  9034. document.getElementById('modal-ospf-inst-name').value += '-copy';
  9035. document.getElementById('ospf-instance-modal-title').innerText = 'New...';
  9036. showToast('Copied', 'Duplicated as new OSPF instance', 'info');
  9037. }
  9038. async function deleteCurrentOspfInstance() {
  9039. const id = document.getElementById('modal-ospf-inst-id').value;
  9040. if (!id) return;
  9041. if (!confirm('Are you sure you want to remove this OSPF instance?')) return;
  9042. try {
  9043. const res = await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9044. if (res.ok) {
  9045. closeOspfInstanceModal();
  9046. showToast('Removed', 'OSPF instance deleted', 'success');
  9047. loadDynamicRouting();
  9048. }
  9049. } catch (err) {
  9050. showToast('Error', err.message, 'error');
  9051. }
  9052. }
  9053. async function enableSelectedOspfInstance() {
  9054. const id = state.selectedOspfRow?.instances;
  9055. if (!id) return;
  9056. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}/state`, {
  9057. method: 'POST',
  9058. headers: { 'Content-Type': 'application/json' },
  9059. body: JSON.stringify({ disabled: false })
  9060. });
  9061. loadDynamicRouting();
  9062. }
  9063. async function disableSelectedOspfInstance() {
  9064. const id = state.selectedOspfRow?.instances;
  9065. if (!id) return;
  9066. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}/state`, {
  9067. method: 'POST',
  9068. headers: { 'Content-Type': 'application/json' },
  9069. body: JSON.stringify({ disabled: true })
  9070. });
  9071. loadDynamicRouting();
  9072. }
  9073. async function removeSelectedOspfInstance() {
  9074. const id = state.selectedOspfRow?.instances;
  9075. if (!id) return;
  9076. if (!confirm('Delete selected OSPF instance?')) return;
  9077. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9078. loadDynamicRouting();
  9079. }
  9080. async function promptCommentOspfInstance() {
  9081. const id = state.selectedOspfRow?.instances;
  9082. if (!id) return;
  9083. const inst = (state.ospfInstances || []).find(i => i.id === id);
  9084. if (!inst) return;
  9085. const comment = prompt('Enter comment for OSPF instance:', inst.comment || '');
  9086. if (comment === null) return;
  9087. inst.comment = comment;
  9088. await fetch(`${API_BASE}/routing/ospf/instances`, {
  9089. method: 'POST',
  9090. headers: { 'Content-Type': 'application/json' },
  9091. body: JSON.stringify(inst)
  9092. });
  9093. loadDynamicRouting();
  9094. }
  9095. // --- 2. OSPF AREA ---
  9096. function populateOspfAreaDropdowns() {
  9097. const instSelect = document.getElementById('modal-ospf-area-instance');
  9098. if (instSelect) {
  9099. const cur = instSelect.value;
  9100. instSelect.innerHTML = (state.ospfInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)}</option>`).join('');
  9101. if (instSelect.innerHTML === '') instSelect.innerHTML = '<option value="Default">Default</option>';
  9102. if (cur) instSelect.value = cur;
  9103. }
  9104. }
  9105. function openOspfAreaModal(id = null) {
  9106. const isEdit = !!id;
  9107. populateOspfAreaDropdowns();
  9108. const area = (state.ospfAreas || []).find(a => a.id === id) || {
  9109. id: '',
  9110. name: 'Default',
  9111. instance: 'Default',
  9112. area_id: '0.0.0.0',
  9113. area_type: 'default',
  9114. default_cost: 1,
  9115. no_summaries: false,
  9116. disabled: false,
  9117. comment: ''
  9118. };
  9119. document.getElementById('ospf-area-modal-title').innerText = isEdit ? area.name : 'New...';
  9120. document.getElementById('modal-ospf-area-id').value = isEdit ? area.id : '';
  9121. document.getElementById('modal-ospf-area-enabled').checked = !area.disabled;
  9122. document.getElementById('modal-ospf-area-comment').value = area.comment || '';
  9123. document.getElementById('modal-ospf-area-name').value = area.name || 'Default';
  9124. document.getElementById('modal-ospf-area-instance').value = area.instance || 'Default';
  9125. document.getElementById('modal-ospf-area-areaid').value = area.area_id || '0.0.0.0';
  9126. document.getElementById('modal-ospf-area-type').value = area.area_type || 'default';
  9127. document.getElementById('modal-ospf-area-default-cost').value = area.default_cost || 1;
  9128. document.getElementById('modal-ospf-area-no-summaries').checked = !!area.no_summaries;
  9129. const btnRem = document.getElementById('btn-ospf-area-modal-remove');
  9130. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  9131. document.getElementById('ospf-area-modal').classList.remove('hidden');
  9132. }
  9133. function openEditOspfAreaModal(id) {
  9134. openOspfAreaModal(id);
  9135. }
  9136. function closeOspfAreaModal() {
  9137. document.getElementById('ospf-area-modal').classList.add('hidden');
  9138. }
  9139. async function submitOspfArea(e) {
  9140. if (e) e.preventDefault();
  9141. const payload = {
  9142. id: document.getElementById('modal-ospf-area-id').value,
  9143. name: document.getElementById('modal-ospf-area-name').value.trim() || 'Default',
  9144. instance: document.getElementById('modal-ospf-area-instance').value.trim() || 'Default',
  9145. area_id: document.getElementById('modal-ospf-area-areaid').value.trim() || '0.0.0.0',
  9146. area_type: document.getElementById('modal-ospf-area-type').value,
  9147. default_cost: parseInt(document.getElementById('modal-ospf-area-default-cost').value, 10) || 1,
  9148. no_summaries: document.getElementById('modal-ospf-area-no-summaries').checked,
  9149. disabled: !document.getElementById('modal-ospf-area-enabled').checked,
  9150. comment: document.getElementById('modal-ospf-area-comment').value.trim()
  9151. };
  9152. try {
  9153. const res = await fetch(`${API_BASE}/routing/ospf/areas`, {
  9154. method: 'POST',
  9155. headers: { 'Content-Type': 'application/json' },
  9156. body: JSON.stringify(payload)
  9157. });
  9158. if (res.ok) {
  9159. closeOspfAreaModal();
  9160. showToast('Saved', 'OSPF area saved', 'success');
  9161. loadDynamicRouting();
  9162. } else {
  9163. const err = await res.json();
  9164. showToast('Error', err.error || 'Failed to save area', 'error');
  9165. }
  9166. } catch (err) {
  9167. showToast('Error', err.message, 'error');
  9168. }
  9169. }
  9170. function applyOspfAreaForm() {
  9171. submitOspfArea(null);
  9172. }
  9173. function copyOspfArea() {
  9174. document.getElementById('modal-ospf-area-id').value = '';
  9175. document.getElementById('modal-ospf-area-name').value += '-copy';
  9176. document.getElementById('ospf-area-modal-title').innerText = 'New...';
  9177. showToast('Copied', 'Duplicated as new OSPF area', 'info');
  9178. }
  9179. async function deleteCurrentOspfArea() {
  9180. const id = document.getElementById('modal-ospf-area-id').value;
  9181. if (!id) return;
  9182. if (!confirm('Are you sure you want to remove this OSPF area?')) return;
  9183. try {
  9184. const res = await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9185. if (res.ok) {
  9186. closeOspfAreaModal();
  9187. showToast('Removed', 'OSPF area deleted', 'success');
  9188. loadDynamicRouting();
  9189. }
  9190. } catch (err) {
  9191. showToast('Error', err.message, 'error');
  9192. }
  9193. }
  9194. async function enableSelectedOspfArea() {
  9195. const id = state.selectedOspfRow?.areas;
  9196. if (!id) return;
  9197. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}/state`, {
  9198. method: 'POST',
  9199. headers: { 'Content-Type': 'application/json' },
  9200. body: JSON.stringify({ disabled: false })
  9201. });
  9202. loadDynamicRouting();
  9203. }
  9204. async function disableSelectedOspfArea() {
  9205. const id = state.selectedOspfRow?.areas;
  9206. if (!id) return;
  9207. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}/state`, {
  9208. method: 'POST',
  9209. headers: { 'Content-Type': 'application/json' },
  9210. body: JSON.stringify({ disabled: true })
  9211. });
  9212. loadDynamicRouting();
  9213. }
  9214. async function removeSelectedOspfArea() {
  9215. const id = state.selectedOspfRow?.areas;
  9216. if (!id) return;
  9217. if (!confirm('Delete selected OSPF area?')) return;
  9218. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9219. loadDynamicRouting();
  9220. }
  9221. async function promptCommentOspfArea() {
  9222. const id = state.selectedOspfRow?.areas;
  9223. if (!id) return;
  9224. const area = (state.ospfAreas || []).find(a => a.id === id);
  9225. if (!area) return;
  9226. const comment = prompt('Enter comment for OSPF area:', area.comment || '');
  9227. if (comment === null) return;
  9228. area.comment = comment;
  9229. await fetch(`${API_BASE}/routing/ospf/areas`, {
  9230. method: 'POST',
  9231. headers: { 'Content-Type': 'application/json' },
  9232. body: JSON.stringify(area)
  9233. });
  9234. loadDynamicRouting();
  9235. }
  9236. // --- 3. OSPF AREA RANGE ---
  9237. function populateAreaRangeDropdowns() {
  9238. const select = document.getElementById('modal-ospf-range-area');
  9239. if (select) {
  9240. const cur = select.value;
  9241. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  9242. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  9243. if (cur) select.value = cur;
  9244. }
  9245. }
  9246. function openOspfAreaRangeModal(id = null) {
  9247. const isEdit = !!id;
  9248. populateAreaRangeDropdowns();
  9249. const r = (state.ospfAreaRanges || []).find(it => it.id === id) || {
  9250. id: '',
  9251. area: 'Default',
  9252. prefix: '',
  9253. cost: 1,
  9254. advertise: true,
  9255. disabled: false,
  9256. comment: ''
  9257. };
  9258. document.getElementById('ospf-area-range-modal-title').innerText = isEdit ? r.prefix : 'New...';
  9259. document.getElementById('modal-ospf-range-id').value = isEdit ? r.id : '';
  9260. document.getElementById('modal-ospf-range-enabled').checked = !r.disabled;
  9261. document.getElementById('modal-ospf-range-comment').value = r.comment || '';
  9262. document.getElementById('modal-ospf-range-area').value = r.area || 'Default';
  9263. document.getElementById('modal-ospf-range-prefix').value = r.prefix || '';
  9264. document.getElementById('modal-ospf-range-cost').value = r.cost || 1;
  9265. document.getElementById('modal-ospf-range-advertise').checked = r.advertise !== false;
  9266. const btnRem = document.getElementById('btn-ospf-range-modal-remove');
  9267. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  9268. document.getElementById('ospf-area-range-modal').classList.remove('hidden');
  9269. }
  9270. function openEditOspfAreaRangeModal(id) {
  9271. openOspfAreaRangeModal(id);
  9272. }
  9273. function closeOspfAreaRangeModal() {
  9274. document.getElementById('ospf-area-range-modal').classList.add('hidden');
  9275. }
  9276. async function submitOspfAreaRange(e) {
  9277. if (e) e.preventDefault();
  9278. const payload = {
  9279. id: document.getElementById('modal-ospf-range-id').value,
  9280. area: document.getElementById('modal-ospf-range-area').value,
  9281. prefix: document.getElementById('modal-ospf-range-prefix').value.trim(),
  9282. cost: parseInt(document.getElementById('modal-ospf-range-cost').value, 10) || 1,
  9283. advertise: document.getElementById('modal-ospf-range-advertise').checked,
  9284. disabled: !document.getElementById('modal-ospf-range-enabled').checked,
  9285. comment: document.getElementById('modal-ospf-range-comment').value.trim()
  9286. };
  9287. try {
  9288. const res = await fetch(`${API_BASE}/routing/ospf/area-ranges`, {
  9289. method: 'POST',
  9290. headers: { 'Content-Type': 'application/json' },
  9291. body: JSON.stringify(payload)
  9292. });
  9293. if (res.ok) {
  9294. closeOspfAreaRangeModal();
  9295. showToast('Saved', 'Area range saved', 'success');
  9296. loadDynamicRouting();
  9297. } else {
  9298. const err = await res.json();
  9299. showToast('Error', err.error || 'Failed to save area range', 'error');
  9300. }
  9301. } catch (err) {
  9302. showToast('Error', err.message, 'error');
  9303. }
  9304. }
  9305. function applyOspfAreaRangeForm() {
  9306. submitOspfAreaRange(null);
  9307. }
  9308. async function deleteCurrentOspfAreaRange() {
  9309. const id = document.getElementById('modal-ospf-range-id').value;
  9310. if (!id) return;
  9311. if (!confirm('Delete this area range?')) return;
  9312. try {
  9313. await fetch(`${API_BASE}/routing/ospf/area-ranges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9314. closeOspfAreaRangeModal();
  9315. showToast('Removed', 'Area range removed', 'success');
  9316. loadDynamicRouting();
  9317. } catch (err) {
  9318. showToast('Error', err.message, 'error');
  9319. }
  9320. }
  9321. async function enableSelectedOspfAreaRange() {
  9322. const id = state.selectedOspfRow?.['area-ranges'];
  9323. if (!id) return;
  9324. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  9325. if (!r) return;
  9326. r.disabled = false;
  9327. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  9328. loadDynamicRouting();
  9329. }
  9330. async function disableSelectedOspfAreaRange() {
  9331. const id = state.selectedOspfRow?.['area-ranges'];
  9332. if (!id) return;
  9333. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  9334. if (!r) return;
  9335. r.disabled = true;
  9336. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  9337. loadDynamicRouting();
  9338. }
  9339. async function removeSelectedOspfAreaRange() {
  9340. const id = state.selectedOspfRow?.['area-ranges'];
  9341. if (!id) return;
  9342. if (!confirm('Delete selected area range?')) return;
  9343. await fetch(`${API_BASE}/routing/ospf/area-ranges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9344. loadDynamicRouting();
  9345. }
  9346. async function promptCommentOspfAreaRange() {
  9347. const id = state.selectedOspfRow?.['area-ranges'];
  9348. if (!id) return;
  9349. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  9350. if (!r) return;
  9351. const comment = prompt('Enter comment for area range:', r.comment || '');
  9352. if (comment === null) return;
  9353. r.comment = comment;
  9354. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  9355. loadDynamicRouting();
  9356. }
  9357. // --- 4. OSPF INTERFACE TEMPLATE ---
  9358. function switchOspfTemplateTab(tab) {
  9359. const tabGen = document.getElementById('ospf-tmpl-tab-general');
  9360. const tabAuth = document.getElementById('ospf-tmpl-tab-auth');
  9361. const btnGen = document.getElementById('ospf-tmpl-tab-btn-general');
  9362. const btnAuth = document.getElementById('ospf-tmpl-tab-btn-auth');
  9363. if (tab === 'general') {
  9364. if (tabGen) tabGen.classList.remove('hidden');
  9365. if (tabAuth) tabAuth.classList.add('hidden');
  9366. if (btnGen) btnGen.className = 'px-4 py-2 text-xs font-bold border-b-2 border-sky-500 text-white transition';
  9367. 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';
  9368. } else {
  9369. if (tabGen) tabGen.classList.add('hidden');
  9370. if (tabAuth) tabAuth.classList.remove('hidden');
  9371. 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';
  9372. if (btnAuth) btnAuth.className = 'px-4 py-2 text-xs font-bold border-b-2 border-sky-500 text-white transition';
  9373. }
  9374. }
  9375. function populateTemplateAreaDropdowns() {
  9376. const select = document.getElementById('modal-ospf-tmpl-area');
  9377. if (select) {
  9378. const cur = select.value;
  9379. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  9380. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  9381. if (cur) select.value = cur;
  9382. }
  9383. }
  9384. function openOspfTemplateModal(id = null) {
  9385. const isEdit = !!id;
  9386. populateTemplateAreaDropdowns();
  9387. switchOspfTemplateTab('general');
  9388. const tmpl = (state.ospfTemplates || []).find(t => t.id === id) || {
  9389. id: '',
  9390. interfaces: '',
  9391. area: 'Default',
  9392. networks: '',
  9393. network_type: 'broadcast',
  9394. cost: 1,
  9395. priority: 128,
  9396. passive: false,
  9397. hello_interval: 10,
  9398. dead_interval: 40,
  9399. auth: 'none',
  9400. auth_key: '',
  9401. disabled: false,
  9402. comment: ''
  9403. };
  9404. document.getElementById('ospf-template-modal-title').innerText = isEdit ? (tmpl.interfaces || tmpl.networks || 'Template') : 'New...';
  9405. document.getElementById('modal-ospf-tmpl-id').value = isEdit ? tmpl.id : '';
  9406. document.getElementById('modal-ospf-tmpl-enabled').checked = !tmpl.disabled;
  9407. document.getElementById('modal-ospf-tmpl-comment').value = tmpl.comment || '';
  9408. document.getElementById('modal-ospf-tmpl-interfaces').value = tmpl.interfaces || tmpl.interface || '';
  9409. document.getElementById('modal-ospf-tmpl-area').value = tmpl.area || 'Default';
  9410. document.getElementById('modal-ospf-tmpl-networks').value = tmpl.networks || tmpl.network || '';
  9411. document.getElementById('modal-ospf-tmpl-net-type').value = tmpl.network_type || 'broadcast';
  9412. document.getElementById('modal-ospf-tmpl-cost').value = tmpl.cost || 1;
  9413. document.getElementById('modal-ospf-tmpl-priority').value = tmpl.priority || 128;
  9414. document.getElementById('modal-ospf-tmpl-passive').checked = !!tmpl.passive;
  9415. document.getElementById('modal-ospf-tmpl-hello').value = tmpl.hello_interval || 10;
  9416. document.getElementById('modal-ospf-tmpl-dead').value = tmpl.dead_interval || 40;
  9417. document.getElementById('modal-ospf-tmpl-auth').value = tmpl.auth || tmpl.auth_type || 'none';
  9418. document.getElementById('modal-ospf-tmpl-auth-key').value = tmpl.auth_key || '';
  9419. const btnRem = document.getElementById('btn-ospf-tmpl-modal-remove');
  9420. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  9421. document.getElementById('ospf-template-modal').classList.remove('hidden');
  9422. }
  9423. function openEditOspfTemplateModal(id) {
  9424. openOspfTemplateModal(id);
  9425. }
  9426. function closeOspfTemplateModal() {
  9427. document.getElementById('ospf-template-modal').classList.add('hidden');
  9428. }
  9429. async function submitOspfTemplate(e) {
  9430. if (e) e.preventDefault();
  9431. const payload = {
  9432. id: document.getElementById('modal-ospf-tmpl-id').value,
  9433. interfaces: document.getElementById('modal-ospf-tmpl-interfaces').value.trim(),
  9434. interface: document.getElementById('modal-ospf-tmpl-interfaces').value.trim(),
  9435. area: document.getElementById('modal-ospf-tmpl-area').value,
  9436. networks: document.getElementById('modal-ospf-tmpl-networks').value.trim(),
  9437. network: document.getElementById('modal-ospf-tmpl-networks').value.trim(),
  9438. network_type: document.getElementById('modal-ospf-tmpl-net-type').value,
  9439. cost: parseInt(document.getElementById('modal-ospf-tmpl-cost').value, 10) || 1,
  9440. priority: parseInt(document.getElementById('modal-ospf-tmpl-priority').value, 10) || 128,
  9441. passive: document.getElementById('modal-ospf-tmpl-passive').checked,
  9442. hello_interval: parseInt(document.getElementById('modal-ospf-tmpl-hello').value, 10) || 10,
  9443. dead_interval: parseInt(document.getElementById('modal-ospf-tmpl-dead').value, 10) || 40,
  9444. auth: document.getElementById('modal-ospf-tmpl-auth').value,
  9445. auth_type: document.getElementById('modal-ospf-tmpl-auth').value,
  9446. auth_key: document.getElementById('modal-ospf-tmpl-auth-key').value,
  9447. disabled: !document.getElementById('modal-ospf-tmpl-enabled').checked,
  9448. comment: document.getElementById('modal-ospf-tmpl-comment').value.trim()
  9449. };
  9450. try {
  9451. const res = await fetch(`${API_BASE}/routing/ospf/templates`, {
  9452. method: 'POST',
  9453. headers: { 'Content-Type': 'application/json' },
  9454. body: JSON.stringify(payload)
  9455. });
  9456. if (res.ok) {
  9457. closeOspfTemplateModal();
  9458. showToast('Saved', 'Interface template saved', 'success');
  9459. loadDynamicRouting();
  9460. } else {
  9461. const err = await res.json();
  9462. showToast('Error', err.error || 'Failed to save interface template', 'error');
  9463. }
  9464. } catch (err) {
  9465. showToast('Error', err.message, 'error');
  9466. }
  9467. }
  9468. function applyOspfTemplateForm() {
  9469. submitOspfTemplate(null);
  9470. }
  9471. function copyOspfTemplate() {
  9472. document.getElementById('modal-ospf-tmpl-id').value = '';
  9473. document.getElementById('ospf-template-modal-title').innerText = 'New...';
  9474. showToast('Copied', 'Duplicated as new template', 'info');
  9475. }
  9476. async function deleteCurrentOspfTemplate() {
  9477. const id = document.getElementById('modal-ospf-tmpl-id').value;
  9478. if (!id) return;
  9479. if (!confirm('Delete this interface template?')) return;
  9480. try {
  9481. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9482. closeOspfTemplateModal();
  9483. showToast('Removed', 'Interface template deleted', 'success');
  9484. loadDynamicRouting();
  9485. } catch (err) {
  9486. showToast('Error', err.message, 'error');
  9487. }
  9488. }
  9489. async function enableSelectedOspfTemplate() {
  9490. const id = state.selectedOspfRow?.templates;
  9491. if (!id) return;
  9492. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  9493. method: 'POST',
  9494. headers: { 'Content-Type': 'application/json' },
  9495. body: JSON.stringify({ disabled: false })
  9496. });
  9497. loadDynamicRouting();
  9498. }
  9499. async function disableSelectedOspfTemplate() {
  9500. const id = state.selectedOspfRow?.templates;
  9501. if (!id) return;
  9502. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  9503. method: 'POST',
  9504. headers: { 'Content-Type': 'application/json' },
  9505. body: JSON.stringify({ disabled: true })
  9506. });
  9507. loadDynamicRouting();
  9508. }
  9509. async function removeSelectedOspfTemplate() {
  9510. const id = state.selectedOspfRow?.templates;
  9511. if (!id) return;
  9512. if (!confirm('Delete selected interface template?')) return;
  9513. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9514. loadDynamicRouting();
  9515. }
  9516. async function promptCommentOspfTemplate() {
  9517. const id = state.selectedOspfRow?.templates;
  9518. if (!id) return;
  9519. const tmpl = (state.ospfTemplates || []).find(t => t.id === id);
  9520. if (!tmpl) return;
  9521. const comment = prompt('Enter comment for template:', tmpl.comment || '');
  9522. if (comment === null) return;
  9523. tmpl.comment = comment;
  9524. await fetch(`${API_BASE}/routing/ospf/templates`, {
  9525. method: 'POST',
  9526. headers: { 'Content-Type': 'application/json' },
  9527. body: JSON.stringify(tmpl)
  9528. });
  9529. loadDynamicRouting();
  9530. }
  9531. // --- 5. OSPF STATIC NEIGHBOR ---
  9532. function populateStaticNbrAreaDropdowns() {
  9533. const select = document.getElementById('modal-ospf-snbr-area');
  9534. if (select) {
  9535. const cur = select.value;
  9536. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  9537. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  9538. if (cur) select.value = cur;
  9539. }
  9540. }
  9541. function openOspfStaticNbrModal(id = null) {
  9542. const isEdit = !!id;
  9543. populateStaticNbrAreaDropdowns();
  9544. const nbr = (state.ospfStaticNbrs || []).find(n => n.id === id) || {
  9545. id: '',
  9546. address: '',
  9547. area: 'Default',
  9548. poll_interval: 120,
  9549. cost: 1,
  9550. disabled: false,
  9551. comment: ''
  9552. };
  9553. document.getElementById('ospf-static-nbr-modal-title').innerText = isEdit ? nbr.address : 'New...';
  9554. document.getElementById('modal-ospf-snbr-id').value = isEdit ? nbr.id : '';
  9555. document.getElementById('modal-ospf-snbr-enabled').checked = !nbr.disabled;
  9556. document.getElementById('modal-ospf-snbr-comment').value = nbr.comment || '';
  9557. document.getElementById('modal-ospf-snbr-address').value = nbr.address || '';
  9558. document.getElementById('modal-ospf-snbr-area').value = nbr.area || 'Default';
  9559. document.getElementById('modal-ospf-snbr-poll').value = nbr.poll_interval || 120;
  9560. document.getElementById('modal-ospf-snbr-cost').value = nbr.cost || 1;
  9561. const btnRem = document.getElementById('btn-ospf-snbr-modal-remove');
  9562. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  9563. document.getElementById('ospf-static-nbr-modal').classList.remove('hidden');
  9564. }
  9565. function openEditOspfStaticNbrModal(id) {
  9566. openOspfStaticNbrModal(id);
  9567. }
  9568. function closeOspfStaticNbrModal() {
  9569. document.getElementById('ospf-static-nbr-modal').classList.add('hidden');
  9570. }
  9571. async function submitOspfStaticNbr(e) {
  9572. if (e) e.preventDefault();
  9573. const payload = {
  9574. id: document.getElementById('modal-ospf-snbr-id').value,
  9575. address: document.getElementById('modal-ospf-snbr-address').value.trim(),
  9576. area: document.getElementById('modal-ospf-snbr-area').value,
  9577. poll_interval: parseInt(document.getElementById('modal-ospf-snbr-poll').value, 10) || 120,
  9578. cost: parseInt(document.getElementById('modal-ospf-snbr-cost').value, 10) || 1,
  9579. disabled: !document.getElementById('modal-ospf-snbr-enabled').checked,
  9580. comment: document.getElementById('modal-ospf-snbr-comment').value.trim()
  9581. };
  9582. try {
  9583. const res = await fetch(`${API_BASE}/routing/ospf/static-neighbors`, {
  9584. method: 'POST',
  9585. headers: { 'Content-Type': 'application/json' },
  9586. body: JSON.stringify(payload)
  9587. });
  9588. if (res.ok) {
  9589. closeOspfStaticNbrModal();
  9590. showToast('Saved', 'Static neighbor saved', 'success');
  9591. loadDynamicRouting();
  9592. } else {
  9593. const err = await res.json();
  9594. showToast('Error', err.error || 'Failed to save static neighbor', 'error');
  9595. }
  9596. } catch (err) {
  9597. showToast('Error', err.message, 'error');
  9598. }
  9599. }
  9600. function applyOspfStaticNbrForm() {
  9601. submitOspfStaticNbr(null);
  9602. }
  9603. async function deleteCurrentOspfStaticNbr() {
  9604. const id = document.getElementById('modal-ospf-snbr-id').value;
  9605. if (!id) return;
  9606. if (!confirm('Delete this static neighbor?')) return;
  9607. try {
  9608. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9609. closeOspfStaticNbrModal();
  9610. showToast('Removed', 'Static neighbor removed', 'success');
  9611. loadDynamicRouting();
  9612. } catch (err) {
  9613. showToast('Error', err.message, 'error');
  9614. }
  9615. }
  9616. async function enableSelectedOspfStaticNbr() {
  9617. const id = state.selectedOspfRow?.['static-nbrs'];
  9618. if (!id) return;
  9619. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  9620. if (!n) return;
  9621. n.disabled = false;
  9622. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  9623. loadDynamicRouting();
  9624. }
  9625. async function disableSelectedOspfStaticNbr() {
  9626. const id = state.selectedOspfRow?.['static-nbrs'];
  9627. if (!id) return;
  9628. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  9629. if (!n) return;
  9630. n.disabled = true;
  9631. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  9632. loadDynamicRouting();
  9633. }
  9634. async function removeSelectedOspfStaticNbr() {
  9635. const id = state.selectedOspfRow?.['static-nbrs'];
  9636. if (!id) return;
  9637. if (!confirm('Delete selected static neighbor?')) return;
  9638. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9639. loadDynamicRouting();
  9640. }
  9641. async function promptCommentOspfStaticNbr() {
  9642. const id = state.selectedOspfRow?.['static-nbrs'];
  9643. if (!id) return;
  9644. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  9645. if (!n) return;
  9646. const comment = prompt('Enter comment for static neighbor:', n.comment || '');
  9647. if (comment === null) return;
  9648. n.comment = comment;
  9649. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  9650. loadDynamicRouting();
  9651. }
  9652. // Backward-compat aliases
  9653. function openAddOspfInterfaceModal() { openOspfTemplateModal(); }
  9654. function openEditOspfInterfaceModal(id) { openEditOspfTemplateModal(id); }
  9655. function closeOspfInterfaceModal() { closeOspfTemplateModal(); }
  9656. function submitOspfInterface(e) { submitOspfTemplate(e); }
  9657. function deleteOspfInterface(id) {
  9658. fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' }).then(() => loadDynamicRouting());
  9659. }
  9660. function toggleOspfInterfaceState(id, disabled) {
  9661. fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  9662. method: 'POST',
  9663. headers: { 'Content-Type': 'application/json' },
  9664. body: JSON.stringify({ disabled })
  9665. }).then(() => loadDynamicRouting());
  9666. }
  9667. function openAddOspfAreaModal() { openOspfAreaModal(); }
  9668. function deleteOspfArea(id) {
  9669. fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' }).then(() => loadDynamicRouting());
  9670. }
  9671. // ============================================================================
  9672. // ==================== MIKROTIK BRIDGE SUBSYSTEM ==============================
  9673. // ============================================================================
  9674. function switchBridgeSubTab(tab) {
  9675. state.bridgeSubTab = tab;
  9676. const tabs = ['bridges', 'ports', 'vlans', 'hosts'];
  9677. tabs.forEach(t => {
  9678. const panel = document.getElementById(`bridge-subtab-${t}`);
  9679. const btn = document.getElementById(`bridge-subtab-btn-${t}`);
  9680. if (panel) {
  9681. if (t === tab) panel.classList.remove('hidden');
  9682. else panel.classList.add('hidden');
  9683. }
  9684. if (btn) {
  9685. if (t === tab) {
  9686. 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';
  9687. } else {
  9688. 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';
  9689. }
  9690. }
  9691. });
  9692. const addBtn = document.getElementById('bridge-top-action-btn');
  9693. if (addBtn) {
  9694. if (tab === 'bridges') addBtn.innerHTML = '<span>+ Add Bridge</span>';
  9695. else if (tab === 'ports') addBtn.innerHTML = '<span>+ Add Port</span>';
  9696. else if (tab === 'vlans') addBtn.innerHTML = '<span>+ Add VLAN Entry</span>';
  9697. else if (tab === 'hosts') addBtn.innerHTML = '<span>🔄 Refresh MACs</span>';
  9698. }
  9699. if (tab === 'hosts') loadBridgeHosts();
  9700. setTimeout(initTableSorting, 50);
  9701. }
  9702. function openCurrentBridgeModal() {
  9703. if (state.bridgeSubTab === 'bridges') openAddBridgeModal();
  9704. else if (state.bridgeSubTab === 'ports') openAddBridgePortModal();
  9705. else if (state.bridgeSubTab === 'vlans') openAddBridgeVLANModal();
  9706. else if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  9707. }
  9708. async function loadBridge() {
  9709. try {
  9710. const [bridgesRes, portsRes, vlansRes, summaryRes, eoipRes, vlanIfacesRes] = await Promise.all([
  9711. fetch(`${API_BASE}/bridge/bridges`),
  9712. fetch(`${API_BASE}/bridge/ports`),
  9713. fetch(`${API_BASE}/bridge/vlans`),
  9714. fetch(`${API_BASE}/bridge/summary`),
  9715. fetch(`${API_BASE}/vpn/eoip`),
  9716. fetch(`${API_BASE}/vlans`)
  9717. ]);
  9718. if (bridgesRes.ok) state.bridges = await bridgesRes.json();
  9719. if (portsRes.ok) state.bridgePorts = await portsRes.json();
  9720. if (vlansRes.ok) state.bridgeVLANs = await vlansRes.json();
  9721. if (summaryRes.ok) state.bridgeSummary = await summaryRes.json();
  9722. if (eoipRes && eoipRes.ok) state.eoipTunnels = await eoipRes.json();
  9723. if (vlanIfacesRes && vlanIfacesRes.ok) state.vlans = await vlanIfacesRes.json();
  9724. // Badges & Stats
  9725. const bBridges = document.getElementById('bridge-badge-bridges');
  9726. if (bBridges) bBridges.innerText = (state.bridges || []).length;
  9727. const bPorts = document.getElementById('bridge-badge-ports');
  9728. if (bPorts) bPorts.innerText = (state.bridgePorts || []).length;
  9729. const bVlans = document.getElementById('bridge-badge-vlans');
  9730. if (bVlans) bVlans.innerText = (state.bridgeVLANs || []).length;
  9731. const bHosts = document.getElementById('bridge-badge-hosts');
  9732. if (bHosts) bHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  9733. const sBr = document.getElementById('bridge-stat-bridges');
  9734. if (sBr) sBr.innerText = (state.bridges || []).length;
  9735. const sPorts = document.getElementById('bridge-stat-ports');
  9736. if (sPorts) sPorts.innerText = (state.bridgePorts || []).length;
  9737. const sHosts = document.getElementById('bridge-stat-hosts');
  9738. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  9739. renderBridges();
  9740. renderBridgePorts();
  9741. renderBridgeVLANs();
  9742. if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  9743. } catch (err) {
  9744. console.error('Failed to load bridge subsystem:', err);
  9745. }
  9746. }
  9747. // ----------------- Bridges -----------------
  9748. function renderBridges() {
  9749. const tbody = document.getElementById('bridge-table-body');
  9750. const empty = document.getElementById('bridge-empty-bridges');
  9751. const countBadge = document.getElementById('bridge-count-badge');
  9752. if (!tbody) return;
  9753. tbody.innerHTML = '';
  9754. const bridges = state.bridges || [];
  9755. if (countBadge) countBadge.innerText = `${bridges.length} Bridges`;
  9756. if (bridges.length === 0) {
  9757. empty?.classList.remove('hidden');
  9758. return;
  9759. }
  9760. empty?.classList.add('hidden');
  9761. bridges.forEach((b, idx) => {
  9762. const tr = document.createElement('tr');
  9763. tr.className = `hover:bg-slate-800/40 transition text-xs ${b.disabled ? 'opacity-50' : ''}`;
  9764. // Format IP addresses pill list
  9765. let ipsHtml = '<span class="text-slate-600 font-sans">None</span>';
  9766. if (b.ip_addresses && b.ip_addresses.length > 0) {
  9767. ipsHtml = b.ip_addresses.map(ip => `
  9768. <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">
  9769. <span>${ip}</span>
  9770. <button onclick="deleteBridgeIP('${b.id}', '${ip}')" class="text-slate-500 hover:text-rose-400 font-bold ml-0.5">×</button>
  9771. </span>
  9772. `).join(' ');
  9773. }
  9774. const runningFlag = b.running ? '<span class="text-emerald-400 font-bold" title="Running (R)">R</span>' : '<span class="text-slate-600">-</span>';
  9775. const disabledFlag = b.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '';
  9776. const flagDisplay = `${runningFlag}${disabledFlag ? ' ' + disabledFlag : ''}`;
  9777. tr.innerHTML = `
  9778. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  9779. <td class="py-2.5 px-3 text-center font-mono">${flagDisplay}</td>
  9780. <td class="py-2.5 px-3 font-bold text-white text-sm">
  9781. <span class="text-sky-400 mr-1.5">🌉</span>${b.name}
  9782. </td>
  9783. <td class="py-2.5 px-3 text-slate-300">${b.mtu}</td>
  9784. <td class="py-2.5 px-3 font-mono text-slate-300 text-[11px]">${b.mac_address || '-'}</td>
  9785. <td class="py-2.5 px-3">
  9786. <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>
  9787. </td>
  9788. <td class="py-2.5 px-3 text-center">
  9789. ${b.vlan_filtering ? '<span class="text-emerald-400 font-bold">yes</span>' : '<span class="text-slate-500">no</span>'}
  9790. </td>
  9791. <td class="py-2.5 px-3 font-mono">${b.pvid || 1}</td>
  9792. <td class="py-2.5 px-3">
  9793. <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>
  9794. </td>
  9795. <td class="py-2.5 px-3">
  9796. <div class="flex items-center gap-1.5 flex-wrap">
  9797. ${ipsHtml}
  9798. <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>
  9799. </div>
  9800. </td>
  9801. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  9802. <span class="text-emerald-400">↓ ${b.rx_human || '0 B'}</span> / <span class="text-cyan-400">↑ ${b.tx_human || '0 B'}</span>
  9803. </td>
  9804. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${b.comment || ''}">${b.comment || '-'}</td>
  9805. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  9806. <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>
  9807. <button onclick="openEditBridgeModal('${b.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  9808. <button onclick="deleteBridge('${b.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  9809. </td>
  9810. `;
  9811. tbody.appendChild(tr);
  9812. });
  9813. }
  9814. function openAddBridgeModal() {
  9815. document.getElementById('bridge-modal-title').innerText = 'Add Bridge Interface';
  9816. document.getElementById('bridge-modal-id').value = '';
  9817. document.getElementById('bridge-modal-name').value = 'bridge1';
  9818. document.getElementById('bridge-modal-name').disabled = false;
  9819. document.getElementById('bridge-modal-mtu').value = '1500';
  9820. document.getElementById('bridge-modal-mac').value = '';
  9821. document.getElementById('bridge-modal-stp').value = 'rstp';
  9822. document.getElementById('bridge-modal-priority').value = '32768';
  9823. document.getElementById('bridge-modal-vlanfiltering').checked = false;
  9824. document.getElementById('bridge-modal-pvid').value = '1';
  9825. document.getElementById('bridge-modal-fastforward').checked = true;
  9826. document.getElementById('bridge-modal-comment').value = '';
  9827. document.getElementById('bridge-modal-disabled').checked = false;
  9828. toggleBridgeModalVlanFiltering();
  9829. document.getElementById('bridge-modal').classList.remove('hidden');
  9830. }
  9831. function openEditBridgeModal(id) {
  9832. const b = (state.bridges || []).find(x => x.id === id);
  9833. if (!b) return;
  9834. document.getElementById('bridge-modal-title').innerText = `Edit Bridge (${b.name})`;
  9835. document.getElementById('bridge-modal-id').value = b.id;
  9836. document.getElementById('bridge-modal-name').value = b.name;
  9837. document.getElementById('bridge-modal-name').disabled = true;
  9838. document.getElementById('bridge-modal-mtu').value = b.mtu || 1500;
  9839. document.getElementById('bridge-modal-mac').value = b.mac_address || '';
  9840. document.getElementById('bridge-modal-stp').value = b.stp || 'rstp';
  9841. document.getElementById('bridge-modal-priority').value = b.priority || 32768;
  9842. document.getElementById('bridge-modal-vlanfiltering').checked = !!b.vlan_filtering;
  9843. document.getElementById('bridge-modal-pvid').value = b.pvid || 1;
  9844. document.getElementById('bridge-modal-fastforward').checked = b.fast_forward !== false;
  9845. document.getElementById('bridge-modal-comment').value = b.comment || '';
  9846. document.getElementById('bridge-modal-disabled').checked = !!b.disabled;
  9847. toggleBridgeModalVlanFiltering();
  9848. document.getElementById('bridge-modal').classList.remove('hidden');
  9849. }
  9850. function closeBridgeModal() {
  9851. document.getElementById('bridge-modal').classList.add('hidden');
  9852. }
  9853. function toggleBridgeModalVlanFiltering() {
  9854. const chk = document.getElementById('bridge-modal-vlanfiltering').checked;
  9855. const pvidBox = document.getElementById('bridge-modal-pvid-box');
  9856. if (pvidBox) {
  9857. if (chk) pvidBox.classList.remove('opacity-40');
  9858. else pvidBox.classList.add('opacity-40');
  9859. }
  9860. }
  9861. async function submitSaveBridge(e) {
  9862. e.preventDefault();
  9863. const id = document.getElementById('bridge-modal-id').value;
  9864. const name = document.getElementById('bridge-modal-name').value.trim();
  9865. const mtu = parseInt(document.getElementById('bridge-modal-mtu').value, 10) || 1500;
  9866. const mac = document.getElementById('bridge-modal-mac').value.trim();
  9867. const stp = document.getElementById('bridge-modal-stp').value;
  9868. const priority = parseInt(document.getElementById('bridge-modal-priority').value, 10) || 32768;
  9869. const vlanFiltering = document.getElementById('bridge-modal-vlanfiltering').checked;
  9870. const pvid = parseInt(document.getElementById('bridge-modal-pvid').value, 10) || 1;
  9871. const fastForward = document.getElementById('bridge-modal-fastforward').checked;
  9872. const comment = document.getElementById('bridge-modal-comment').value.trim();
  9873. const disabled = document.getElementById('bridge-modal-disabled').checked;
  9874. try {
  9875. const res = await fetch(`${API_BASE}/bridge/bridges`, {
  9876. method: 'POST',
  9877. headers: { 'Content-Type': 'application/json' },
  9878. body: JSON.stringify({
  9879. id,
  9880. name,
  9881. mtu,
  9882. mac_address: mac,
  9883. stp,
  9884. priority,
  9885. vlan_filtering: vlanFiltering,
  9886. pvid,
  9887. fast_forward: fastForward,
  9888. comment,
  9889. disabled
  9890. })
  9891. });
  9892. if (res.ok) {
  9893. showToast('Bridge Saved', `Bridge ${name} configured`, 'success');
  9894. closeBridgeModal();
  9895. loadBridge();
  9896. fetchData(false);
  9897. } else {
  9898. const err = await res.json();
  9899. showToast('Error', err.error || err.message || 'Failed to save bridge', 'error');
  9900. }
  9901. } catch (err) {
  9902. showToast('Error', err.message, 'error');
  9903. }
  9904. }
  9905. async function toggleBridgeState(id, disabled) {
  9906. try {
  9907. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/state`, {
  9908. method: 'POST',
  9909. headers: { 'Content-Type': 'application/json' },
  9910. body: JSON.stringify({ disabled })
  9911. });
  9912. if (res.ok) {
  9913. loadBridge();
  9914. fetchData(false);
  9915. }
  9916. } catch (err) {
  9917. showToast('Error', err.message, 'error');
  9918. }
  9919. }
  9920. async function deleteBridge(id) {
  9921. const b = (state.bridges || []).find(x => x.id === id);
  9922. const name = b ? b.name : id;
  9923. if (!confirm(`Are you sure you want to delete bridge '${name}'? All member ports will be detached.`)) return;
  9924. try {
  9925. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9926. if (res.ok) {
  9927. showToast('Deleted', `Bridge ${name} deleted`, 'success');
  9928. loadBridge();
  9929. fetchData(false);
  9930. } else {
  9931. const err = await res.json();
  9932. showToast('Error', err.error || err.message || 'Failed to delete bridge', 'error');
  9933. }
  9934. } catch (err) {
  9935. showToast('Error', err.message, 'error');
  9936. }
  9937. }
  9938. // ----------------- Bridge IP Assignments -----------------
  9939. function openAddBridgeIPModal(id, name) {
  9940. document.getElementById('bridge-ip-modal-id').value = id;
  9941. document.getElementById('bridge-ip-modal-sub').innerText = name;
  9942. document.getElementById('bridge-ip-modal-cidr').value = '';
  9943. document.getElementById('bridge-ip-modal').classList.remove('hidden');
  9944. }
  9945. function closeBridgeIPModal() {
  9946. document.getElementById('bridge-ip-modal').classList.add('hidden');
  9947. }
  9948. async function submitAddBridgeIP(e) {
  9949. e.preventDefault();
  9950. const id = document.getElementById('bridge-ip-modal-id').value;
  9951. const ip = document.getElementById('bridge-ip-modal-cidr').value.trim();
  9952. try {
  9953. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  9954. method: 'POST',
  9955. headers: { 'Content-Type': 'application/json' },
  9956. body: JSON.stringify({ ip })
  9957. });
  9958. if (res.ok) {
  9959. showToast('IP Assigned', `${ip} assigned to bridge`, 'success');
  9960. closeBridgeIPModal();
  9961. loadBridge();
  9962. fetchData(false);
  9963. } else {
  9964. const err = await res.json();
  9965. showToast('Error', err.error || err.message || 'Failed to add IP', 'error');
  9966. }
  9967. } catch (err) {
  9968. showToast('Error', err.message, 'error');
  9969. }
  9970. }
  9971. async function deleteBridgeIP(id, ip) {
  9972. if (!confirm(`Remove IP address ${ip} from bridge?`)) return;
  9973. try {
  9974. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  9975. method: 'DELETE',
  9976. headers: { 'Content-Type': 'application/json' },
  9977. body: JSON.stringify({ ip })
  9978. });
  9979. if (res.ok) {
  9980. showToast('IP Removed', `${ip} removed from bridge`, 'success');
  9981. loadBridge();
  9982. fetchData(false);
  9983. }
  9984. } catch (err) {
  9985. showToast('Error', err.message, 'error');
  9986. }
  9987. }
  9988. // ----------------- Bridge Ports -----------------
  9989. function renderBridgePorts() {
  9990. const tbody = document.getElementById('bridge-ports-table-body');
  9991. const empty = document.getElementById('bridge-empty-ports');
  9992. const countBadge = document.getElementById('bridge-ports-count-badge');
  9993. const filterBridge = document.getElementById('bridge-ports-filter-bridge')?.value || '';
  9994. if (!tbody) return;
  9995. tbody.innerHTML = '';
  9996. // Update filter select
  9997. populateBridgeSelect('bridge-ports-filter-bridge', filterBridge, true);
  9998. const ports = (state.bridgePorts || []).filter(p => !filterBridge || p.bridge === filterBridge);
  9999. if (countBadge) countBadge.innerText = `${ports.length} Ports`;
  10000. if (ports.length === 0) {
  10001. empty?.classList.remove('hidden');
  10002. return;
  10003. }
  10004. empty?.classList.add('hidden');
  10005. ports.forEach((p, idx) => {
  10006. const tr = document.createElement('tr');
  10007. tr.className = `hover:bg-slate-800/40 transition text-xs ${p.disabled ? 'opacity-50' : ''}`;
  10008. const disabledFlag = p.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  10009. tr.innerHTML = `
  10010. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  10011. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  10012. <td class="py-2.5 px-3 font-bold text-white text-sm">
  10013. <span class="text-emerald-400 mr-1.5">🔌</span>${p.interface}
  10014. </td>
  10015. <td class="py-2.5 px-3 font-semibold text-sky-400">${p.bridge}</td>
  10016. <td class="py-2.5 px-3 font-mono">${p.pvid || 1}</td>
  10017. <td class="py-2.5 px-3 text-slate-300">${p.frame_types}</td>
  10018. <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>
  10019. <td class="py-2.5 px-3">
  10020. ${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>'}
  10021. </td>
  10022. <td class="py-2.5 px-3">
  10023. <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>
  10024. </td>
  10025. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${p.comment || ''}">${p.comment || '-'}</td>
  10026. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  10027. <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>
  10028. <button onclick="openEditBridgePortModal('${p.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  10029. <button onclick="deleteBridgePort('${p.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  10030. </td>
  10031. `;
  10032. tbody.appendChild(tr);
  10033. });
  10034. }
  10035. function openAddBridgePortModal() {
  10036. document.getElementById('bridge-port-modal-title').innerText = 'Add Port to Bridge';
  10037. document.getElementById('bridge-port-modal-id').value = '';
  10038. populateBridgeSelect('bridge-port-modal-bridge');
  10039. populateBridgePortCandidateSelect('bridge-port-modal-interface');
  10040. document.getElementById('bridge-port-modal-pvid').value = '1';
  10041. document.getElementById('bridge-port-modal-frametypes').value = 'admit-all';
  10042. document.getElementById('bridge-port-modal-ingressfiltering').checked = false;
  10043. document.getElementById('bridge-port-modal-horizon').value = '0';
  10044. document.getElementById('bridge-port-modal-pathcost').value = '10';
  10045. document.getElementById('bridge-port-modal-priority').value = '128';
  10046. document.getElementById('bridge-port-modal-learn').checked = true;
  10047. document.getElementById('bridge-port-modal-comment').value = '';
  10048. document.getElementById('bridge-port-modal-disabled').checked = false;
  10049. document.getElementById('bridge-port-modal').classList.remove('hidden');
  10050. }
  10051. function openEditBridgePortModal(id) {
  10052. const p = (state.bridgePorts || []).find(x => x.id === id);
  10053. if (!p) return;
  10054. document.getElementById('bridge-port-modal-title').innerText = `Edit Bridge Port (${p.interface})`;
  10055. document.getElementById('bridge-port-modal-id').value = p.id;
  10056. populateBridgeSelect('bridge-port-modal-bridge', p.bridge);
  10057. populateBridgePortCandidateSelect('bridge-port-modal-interface', p.interface);
  10058. document.getElementById('bridge-port-modal-pvid').value = p.pvid || 1;
  10059. document.getElementById('bridge-port-modal-frametypes').value = p.frame_types || 'admit-all';
  10060. document.getElementById('bridge-port-modal-ingressfiltering').checked = !!p.ingress_filtering;
  10061. document.getElementById('bridge-port-modal-horizon').value = p.horizon || 0;
  10062. document.getElementById('bridge-port-modal-pathcost').value = p.path_cost || 10;
  10063. document.getElementById('bridge-port-modal-priority').value = p.priority || 128;
  10064. document.getElementById('bridge-port-modal-learn').checked = p.learn !== false;
  10065. document.getElementById('bridge-port-modal-comment').value = p.comment || '';
  10066. document.getElementById('bridge-port-modal-disabled').checked = !!p.disabled;
  10067. document.getElementById('bridge-port-modal').classList.remove('hidden');
  10068. }
  10069. function closeBridgePortModal() {
  10070. document.getElementById('bridge-port-modal').classList.add('hidden');
  10071. }
  10072. async function submitSaveBridgePort(e) {
  10073. e.preventDefault();
  10074. const id = document.getElementById('bridge-port-modal-id').value;
  10075. const bridge = document.getElementById('bridge-port-modal-bridge').value;
  10076. const iface = document.getElementById('bridge-port-modal-interface').value;
  10077. const pvid = parseInt(document.getElementById('bridge-port-modal-pvid').value, 10) || 1;
  10078. const frameTypes = document.getElementById('bridge-port-modal-frametypes').value;
  10079. const ingressFiltering = document.getElementById('bridge-port-modal-ingressfiltering').checked;
  10080. const horizon = parseInt(document.getElementById('bridge-port-modal-horizon').value, 10) || 0;
  10081. const pathCost = parseInt(document.getElementById('bridge-port-modal-pathcost').value, 10) || 10;
  10082. const priority = parseInt(document.getElementById('bridge-port-modal-priority').value, 10) || 128;
  10083. const learn = document.getElementById('bridge-port-modal-learn').checked;
  10084. const comment = document.getElementById('bridge-port-modal-comment').value.trim();
  10085. const disabled = document.getElementById('bridge-port-modal-disabled').checked;
  10086. try {
  10087. const res = await fetch(`${API_BASE}/bridge/ports`, {
  10088. method: 'POST',
  10089. headers: { 'Content-Type': 'application/json' },
  10090. body: JSON.stringify({
  10091. id,
  10092. bridge,
  10093. interface: iface,
  10094. pvid,
  10095. frame_types: frameTypes,
  10096. ingress_filtering: ingressFiltering,
  10097. horizon,
  10098. path_cost: pathCost,
  10099. priority,
  10100. learn,
  10101. comment,
  10102. disabled
  10103. })
  10104. });
  10105. if (res.ok) {
  10106. showToast('Port Attached', `${iface} added to ${bridge}`, 'success');
  10107. closeBridgePortModal();
  10108. loadBridge();
  10109. fetchData(false);
  10110. } else {
  10111. const err = await res.json();
  10112. showToast('Error', err.error || err.message || 'Failed to save port', 'error');
  10113. }
  10114. } catch (err) {
  10115. showToast('Error', err.message, 'error');
  10116. }
  10117. }
  10118. async function toggleBridgePortState(id, disabled) {
  10119. try {
  10120. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}/state`, {
  10121. method: 'POST',
  10122. headers: { 'Content-Type': 'application/json' },
  10123. body: JSON.stringify({ disabled })
  10124. });
  10125. if (res.ok) {
  10126. loadBridge();
  10127. fetchData(false);
  10128. }
  10129. } catch (err) {
  10130. showToast('Error', err.message, 'error');
  10131. }
  10132. }
  10133. async function deleteBridgePort(id) {
  10134. const p = (state.bridgePorts || []).find(x => x.id === id);
  10135. const iface = p ? p.interface : id;
  10136. if (!confirm(`Detach interface '${iface}' from bridge?`)) return;
  10137. try {
  10138. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10139. if (res.ok) {
  10140. showToast('Port Detached', `${iface} removed from bridge`, 'success');
  10141. loadBridge();
  10142. fetchData(false);
  10143. }
  10144. } catch (err) {
  10145. showToast('Error', err.message, 'error');
  10146. }
  10147. }
  10148. // ----------------- Bridge VLANs -----------------
  10149. function renderBridgeVLANs() {
  10150. const tbody = document.getElementById('bridge-vlans-table-body');
  10151. const empty = document.getElementById('bridge-empty-vlans');
  10152. const countBadge = document.getElementById('bridge-vlans-count-badge');
  10153. const filterBridge = document.getElementById('bridge-vlans-filter-bridge')?.value || '';
  10154. if (!tbody) return;
  10155. tbody.innerHTML = '';
  10156. populateBridgeSelect('bridge-vlans-filter-bridge', filterBridge, true);
  10157. const vlans = (state.bridgeVLANs || []).filter(v => !filterBridge || v.bridge === filterBridge);
  10158. if (countBadge) countBadge.innerText = `${vlans.length} Entries`;
  10159. if (vlans.length === 0) {
  10160. empty?.classList.remove('hidden');
  10161. return;
  10162. }
  10163. empty?.classList.add('hidden');
  10164. vlans.forEach((v, idx) => {
  10165. const tr = document.createElement('tr');
  10166. tr.className = `hover:bg-slate-800/40 transition text-xs ${v.disabled ? 'opacity-50' : ''}`;
  10167. const taggedHtml = (v.tagged && v.tagged.length > 0)
  10168. ? 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(' ')
  10169. : '<span class="text-slate-600">none</span>';
  10170. const untaggedHtml = (v.untagged && v.untagged.length > 0)
  10171. ? 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(' ')
  10172. : '<span class="text-slate-600">none</span>';
  10173. const disabledFlag = v.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  10174. tr.innerHTML = `
  10175. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  10176. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  10177. <td class="py-2.5 px-3 font-semibold text-sky-400">${v.bridge}</td>
  10178. <td class="py-2.5 px-3 font-bold text-white font-mono text-sm">${v.vlan_ids}</td>
  10179. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${taggedHtml}</div></td>
  10180. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${untaggedHtml}</div></td>
  10181. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${v.comment || ''}">${v.comment || '-'}</td>
  10182. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  10183. <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>
  10184. <button onclick="openEditBridgeVLANModal('${v.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  10185. <button onclick="deleteBridgeVLAN('${v.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  10186. </td>
  10187. `;
  10188. tbody.appendChild(tr);
  10189. });
  10190. }
  10191. function openAddBridgeVLANModal() {
  10192. document.getElementById('bridge-vlan-modal-title').innerText = 'Add Bridge VLAN Entry';
  10193. document.getElementById('bridge-vlan-modal-id').value = '';
  10194. populateBridgeSelect('bridge-vlan-modal-bridge');
  10195. document.getElementById('bridge-vlan-modal-vlanids').value = '';
  10196. document.getElementById('bridge-vlan-modal-comment').value = '';
  10197. document.getElementById('bridge-vlan-modal-disabled').checked = false;
  10198. updateBridgeVlanPortCheckboxes();
  10199. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  10200. }
  10201. function openEditBridgeVLANModal(id) {
  10202. const v = (state.bridgeVLANs || []).find(x => x.id === id);
  10203. if (!v) return;
  10204. document.getElementById('bridge-vlan-modal-title').innerText = `Edit Bridge VLAN (${v.vlan_ids})`;
  10205. document.getElementById('bridge-vlan-modal-id').value = v.id;
  10206. populateBridgeSelect('bridge-vlan-modal-bridge', v.bridge);
  10207. document.getElementById('bridge-vlan-modal-vlanids').value = v.vlan_ids;
  10208. document.getElementById('bridge-vlan-modal-comment').value = v.comment || '';
  10209. document.getElementById('bridge-vlan-modal-disabled').checked = !!v.disabled;
  10210. updateBridgeVlanPortCheckboxes(v.tagged || [], v.untagged || []);
  10211. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  10212. }
  10213. function closeBridgeVlanModal() {
  10214. document.getElementById('bridge-vlan-modal').classList.add('hidden');
  10215. }
  10216. function updateBridgeVlanPortCheckboxes(taggedSelected = [], untaggedSelected = []) {
  10217. const selBridge = document.getElementById('bridge-vlan-modal-bridge')?.value || '';
  10218. const taggedBox = document.getElementById('bridge-vlan-tagged-ports');
  10219. const untaggedBox = document.getElementById('bridge-vlan-untagged-ports');
  10220. if (!taggedBox || !untaggedBox) return;
  10221. // Ports belonging to the selected bridge
  10222. const memberPorts = (state.bridgePorts || []).filter(p => !selBridge || p.bridge === selBridge);
  10223. if (memberPorts.length === 0) {
  10224. taggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  10225. untaggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  10226. return;
  10227. }
  10228. taggedBox.innerHTML = memberPorts.map(p => `
  10229. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  10230. <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">
  10231. <span>${p.interface}</span>
  10232. </label>
  10233. `).join('');
  10234. untaggedBox.innerHTML = memberPorts.map(p => `
  10235. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  10236. <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">
  10237. <span>${p.interface}</span>
  10238. </label>
  10239. `).join('');
  10240. }
  10241. async function submitSaveBridgeVLAN(e) {
  10242. e.preventDefault();
  10243. const id = document.getElementById('bridge-vlan-modal-id').value;
  10244. const bridge = document.getElementById('bridge-vlan-modal-bridge').value;
  10245. const vlanIDs = document.getElementById('bridge-vlan-modal-vlanids').value.trim();
  10246. const comment = document.getElementById('bridge-vlan-modal-comment').value.trim();
  10247. const disabled = document.getElementById('bridge-vlan-modal-disabled').checked;
  10248. const tagged = Array.from(document.querySelectorAll('input[name="bvlan-tagged"]:checked')).map(x => x.value);
  10249. const untagged = Array.from(document.querySelectorAll('input[name="bvlan-untagged"]:checked')).map(x => x.value);
  10250. try {
  10251. const res = await fetch(`${API_BASE}/bridge/vlans`, {
  10252. method: 'POST',
  10253. headers: { 'Content-Type': 'application/json' },
  10254. body: JSON.stringify({
  10255. id,
  10256. bridge,
  10257. vlan_ids: vlanIDs,
  10258. tagged,
  10259. untagged,
  10260. comment,
  10261. disabled
  10262. })
  10263. });
  10264. if (res.ok) {
  10265. showToast('VLAN Entry Saved', `VLAN ${vlanIDs} configured on ${bridge}`, 'success');
  10266. closeBridgeVlanModal();
  10267. loadBridge();
  10268. } else {
  10269. const err = await res.json();
  10270. showToast('Error', err.error || err.message || 'Failed to save VLAN entry', 'error');
  10271. }
  10272. } catch (err) {
  10273. showToast('Error', err.message, 'error');
  10274. }
  10275. }
  10276. async function toggleBridgeVLANState(id, disabled) {
  10277. try {
  10278. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}/state`, {
  10279. method: 'POST',
  10280. headers: { 'Content-Type': 'application/json' },
  10281. body: JSON.stringify({ disabled })
  10282. });
  10283. if (res.ok) loadBridge();
  10284. } catch (err) {
  10285. showToast('Error', err.message, 'error');
  10286. }
  10287. }
  10288. async function deleteBridgeVLAN(id) {
  10289. if (!confirm('Delete this bridge VLAN entry?')) return;
  10290. try {
  10291. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10292. if (res.ok) {
  10293. showToast('Deleted', 'VLAN entry removed from bridge', 'success');
  10294. loadBridge();
  10295. }
  10296. } catch (err) {
  10297. showToast('Error', err.message, 'error');
  10298. }
  10299. }
  10300. // ----------------- Hosts / MAC Table -----------------
  10301. async function loadBridgeHosts() {
  10302. const filterBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || '';
  10303. populateBridgeSelect('bridge-hosts-filter-bridge', filterBridge, true);
  10304. try {
  10305. const url = filterBridge ? `${API_BASE}/bridge/hosts?bridge=${encodeURIComponent(filterBridge)}` : `${API_BASE}/bridge/hosts`;
  10306. const res = await fetch(url);
  10307. if (res.ok) {
  10308. state.bridgeHosts = await res.json();
  10309. renderBridgeHosts();
  10310. }
  10311. } catch (err) {
  10312. console.error('Failed to load bridge hosts:', err);
  10313. }
  10314. }
  10315. function renderBridgeHosts() {
  10316. const tbody = document.getElementById('bridge-hosts-table-body');
  10317. const empty = document.getElementById('bridge-empty-hosts');
  10318. const countBadge = document.getElementById('bridge-hosts-count-badge');
  10319. const search = (document.getElementById('bridge-hosts-search')?.value || '').toLowerCase().trim();
  10320. if (!tbody) return;
  10321. tbody.innerHTML = '';
  10322. const hosts = (state.bridgeHosts || []).filter(h => {
  10323. if (!search) return true;
  10324. return (h.mac || '').toLowerCase().includes(search) || (h.interface || '').toLowerCase().includes(search) || (h.bridge || '').toLowerCase().includes(search);
  10325. });
  10326. if (countBadge) countBadge.innerText = `${hosts.length} Hosts`;
  10327. if (hosts.length === 0) {
  10328. empty?.classList.remove('hidden');
  10329. return;
  10330. }
  10331. empty?.classList.add('hidden');
  10332. hosts.forEach(h => {
  10333. const tr = document.createElement('tr');
  10334. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  10335. let flagBadges = '';
  10336. 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>';
  10337. 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>';
  10338. 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>';
  10339. tr.innerHTML = `
  10340. <td class="py-2.5 px-3 font-mono font-bold text-white text-sm">${h.mac}</td>
  10341. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${h.interface || '-'}</td>
  10342. <td class="py-2.5 px-3 font-mono text-sky-400">${h.bridge || '-'}</td>
  10343. <td class="py-2.5 px-3 font-mono">${h.vlan_id || 1}</td>
  10344. <td class="py-2.5 px-3 font-mono text-slate-400">${h.age ? h.age.toFixed(1) + 's' : '-'}</td>
  10345. <td class="py-2.5 px-3">${flagBadges}</td>
  10346. `;
  10347. tbody.appendChild(tr);
  10348. });
  10349. }
  10350. async function flushBridgeHosts() {
  10351. const selBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || (state.bridges[0] ? state.bridges[0].name : '');
  10352. if (!selBridge) {
  10353. showToast('Notice', 'Please select a bridge to flush dynamic MACs', 'info');
  10354. return;
  10355. }
  10356. if (!confirm(`Flush all dynamic learned MAC addresses on bridge '${selBridge}'?`)) return;
  10357. try {
  10358. const res = await fetch(`${API_BASE}/bridge/hosts/flush`, {
  10359. method: 'POST',
  10360. headers: { 'Content-Type': 'application/json' },
  10361. body: JSON.stringify({ bridge: selBridge })
  10362. });
  10363. if (res.ok) {
  10364. showToast('FDB Flushed', `Dynamic MACs flushed on ${selBridge}`, 'success');
  10365. loadBridgeHosts();
  10366. }
  10367. } catch (err) {
  10368. showToast('Error', err.message, 'error');
  10369. }
  10370. }
  10371. // ----------------- Helpers -----------------
  10372. function populateBridgeSelect(selectId, currentVal = '', includeAll = false) {
  10373. const sel = document.getElementById(selectId);
  10374. if (!sel) return;
  10375. const prevVal = currentVal || sel.value;
  10376. sel.innerHTML = includeAll ? '<option value="">All Bridges</option>' : '';
  10377. (state.bridges || []).forEach(b => {
  10378. const opt = document.createElement('option');
  10379. opt.value = b.name;
  10380. opt.innerText = `${b.name} (${b.ports_count} ports)`;
  10381. if (b.name === prevVal) opt.selected = true;
  10382. sel.appendChild(opt);
  10383. });
  10384. }
  10385. function populateBridgePortCandidateSelect(selectId, currentVal = '') {
  10386. const sel = document.getElementById(selectId);
  10387. if (!sel) return;
  10388. sel.innerHTML = '<option value="">(Select Interface...)</option>';
  10389. // 1. Physical Interfaces
  10390. const grpPhys = document.createElement('optgroup');
  10391. grpPhys.label = 'Physical Interfaces';
  10392. (state.interfaces || []).filter(i => i.type !== 'bridge' && i.type !== 'vlan' && i.type !== 'loopback').forEach(i => {
  10393. const opt = document.createElement('option');
  10394. opt.value = i.name;
  10395. opt.innerText = `${i.name} (${i.role || i.type})`;
  10396. if (i.name === currentVal) opt.selected = true;
  10397. grpPhys.appendChild(opt);
  10398. });
  10399. if (grpPhys.children.length > 0) sel.appendChild(grpPhys);
  10400. // 2. VLAN Sub-interfaces
  10401. const grpVlans = document.createElement('optgroup');
  10402. grpVlans.label = 'VLAN Sub-interfaces (802.1Q)';
  10403. (state.vlans || []).forEach(v => {
  10404. const opt = document.createElement('option');
  10405. opt.value = v.name;
  10406. opt.innerText = `${v.name} (VLAN ${v.vlan_id})`;
  10407. if (v.name === currentVal) opt.selected = true;
  10408. grpVlans.appendChild(opt);
  10409. });
  10410. if (grpVlans.children.length > 0) sel.appendChild(grpVlans);
  10411. // 3. EoIP Tunnels (MikroTik EoIP bridging!)
  10412. const grpEoip = document.createElement('optgroup');
  10413. grpEoip.label = 'EoIP Tunnels (Layer 2 VPN)';
  10414. (state.eoipTunnels || []).forEach(t => {
  10415. const opt = document.createElement('option');
  10416. opt.value = t.name;
  10417. opt.innerText = `${t.name} (Tunnel ID: ${t.tunnel_id} -> ${t.remote_address})`;
  10418. if (t.name === currentVal) opt.selected = true;
  10419. grpEoip.appendChild(opt);
  10420. });
  10421. if (grpEoip.children.length > 0) sel.appendChild(grpEoip);
  10422. }
  10423. // -------------------------------------------------------------
  10424. // DebTik Routing Filters Management (/routing filter)
  10425. // -------------------------------------------------------------
  10426. if (!state.activeRoutingFilterTab) state.activeRoutingFilterTab = 'rules';
  10427. if (!state.selectedFilterRow) state.selectedFilterRow = {};
  10428. if (!state.rfSort) state.rfSort = {};
  10429. function switchRoutingFilterTab(tab) {
  10430. state.activeRoutingFilterTab = tab;
  10431. const tabs = ['rules', 'select-rules', 'community-lists', 'as-lists'];
  10432. tabs.forEach(t => {
  10433. const btn = document.getElementById(`tab-rf-${t}`);
  10434. const content = document.getElementById(`tab-content-rf-${t}`);
  10435. if (btn) {
  10436. if (t === tab) {
  10437. 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';
  10438. } else {
  10439. btn.className = 'px-3 py-1 text-xs font-semibold rounded text-slate-400 hover:text-white hover:bg-slate-800 transition';
  10440. }
  10441. }
  10442. if (content) {
  10443. if (t === tab) content.classList.remove('hidden');
  10444. else content.classList.add('hidden');
  10445. }
  10446. });
  10447. const chainContainer = document.getElementById('rf-chain-filter-container');
  10448. if (chainContainer) {
  10449. if (tab === 'rules' || tab === 'select-rules') chainContainer.classList.remove('hidden');
  10450. else chainContainer.classList.add('hidden');
  10451. }
  10452. renderRoutingFilters();
  10453. }
  10454. function selectFilterRow(tab, id) {
  10455. if (state.selectedFilterRow[tab] === id) {
  10456. delete state.selectedFilterRow[tab];
  10457. } else {
  10458. state.selectedFilterRow[tab] = id;
  10459. }
  10460. if (tab === 'rules') renderRoutingFilterRules();
  10461. else if (tab === 'select-rules') renderRoutingFilterSelectRules();
  10462. else if (tab === 'community-lists') renderRoutingFilterCommunityLists();
  10463. else if (tab === 'as-lists') renderRoutingFilterASLists();
  10464. }
  10465. function openRoutingFilterNewModal() {
  10466. const tab = state.activeRoutingFilterTab || 'rules';
  10467. if (tab === 'rules') openAddRoutingFilterModal();
  10468. else if (tab === 'select-rules') openAddSelectRuleModal();
  10469. else if (tab === 'community-lists') openAddCommunityListModal();
  10470. else if (tab === 'as-lists') openAddASListModal();
  10471. }
  10472. function toggleSelectedRoutingFilter(disabled) {
  10473. const tab = state.activeRoutingFilterTab || 'rules';
  10474. const id = state.selectedFilterRow[tab];
  10475. if (!id) {
  10476. showToast('Select Row', 'Please click on a row to select it first', 'info');
  10477. return;
  10478. }
  10479. if (tab === 'rules') toggleRoutingFilterState(id, disabled);
  10480. else if (tab === 'select-rules') toggleSelectRuleState(id, disabled);
  10481. else if (tab === 'community-lists') toggleCommunityListState(id, disabled);
  10482. else if (tab === 'as-lists') toggleASListState(id, disabled);
  10483. }
  10484. function removeSelectedRoutingFilter() {
  10485. const tab = state.activeRoutingFilterTab || 'rules';
  10486. const id = state.selectedFilterRow[tab];
  10487. if (!id) {
  10488. showToast('Select Row', 'Please click on a row to select it first', 'info');
  10489. return;
  10490. }
  10491. if (tab === 'rules') deleteRoutingFilter(id);
  10492. else if (tab === 'select-rules') deleteSelectRule(id);
  10493. else if (tab === 'community-lists') deleteCommunityList(id);
  10494. else if (tab === 'as-lists') deleteASList(id);
  10495. }
  10496. function searchRoutingFilters(q) {
  10497. state.rfSearchQuery = (q || '').trim().toLowerCase();
  10498. renderRoutingFilters();
  10499. }
  10500. function sortFilterTable(tab, col) {
  10501. if (!state.rfSort) state.rfSort = {};
  10502. if (!state.rfSort[tab]) state.rfSort[tab] = { col: col, asc: true };
  10503. if (state.rfSort[tab].col === col) {
  10504. state.rfSort[tab].asc = !state.rfSort[tab].asc;
  10505. } else {
  10506. state.rfSort[tab].col = col;
  10507. state.rfSort[tab].asc = true;
  10508. }
  10509. const asc = state.rfSort[tab].asc;
  10510. let list = [];
  10511. if (tab === 'rules') list = state.routingFilters || [];
  10512. else if (tab === 'select-rules') list = state.routingSelectRules || [];
  10513. else if (tab === 'community-lists') list = state.routingCommunityLists || [];
  10514. else if (tab === 'as-lists') list = state.routingASLists || [];
  10515. list.sort((a, b) => {
  10516. let valA = a[col] ?? '';
  10517. let valB = b[col] ?? '';
  10518. if (col === 'flags') {
  10519. valA = a.disabled ? 'X' : 'A';
  10520. valB = b.disabled ? 'X' : 'A';
  10521. }
  10522. if (typeof valA === 'number' && typeof valB === 'number') {
  10523. return asc ? valA - valB : valB - valA;
  10524. }
  10525. return asc ? String(valA).localeCompare(String(valB)) : String(valB).localeCompare(String(valA));
  10526. });
  10527. const allCols = ['flags', 'rule_order', 'chain', 'rule', 'name', 'communities', 'range', 'regexp', 'comment'];
  10528. allCols.forEach(c => {
  10529. const el = document.getElementById(`sort-icon-${tab}-${c}`);
  10530. if (el) el.innerText = (c === col) ? (asc ? '▲' : '▼') : '';
  10531. });
  10532. if (tab === 'rules') renderRoutingFilterRules();
  10533. else if (tab === 'select-rules') renderRoutingFilterSelectRules();
  10534. else if (tab === 'community-lists') renderRoutingFilterCommunityLists();
  10535. else if (tab === 'as-lists') renderRoutingFilterASLists();
  10536. }
  10537. function renderRoutingFilters() {
  10538. const navBadge = document.getElementById('badge-filters-count');
  10539. const allRules = state.routingFilters || [];
  10540. if (navBadge) navBadge.innerText = allRules.length;
  10541. // Populate chain filter select options and datalist
  10542. const chainSelect = document.getElementById('routing-filter-chain-select');
  10543. const chainDatalist = document.getElementById('dl-routing-chains');
  10544. const uniqueChains = Array.from(new Set(allRules.map(r => r.chain).filter(Boolean))).sort();
  10545. if (chainSelect) {
  10546. const currentVal = state.filterChainSelected || 'all';
  10547. chainSelect.innerHTML = `<option value="all">All Chains (${allRules.length})</option>` +
  10548. uniqueChains.map(ch => {
  10549. const count = allRules.filter(r => r.chain === ch).length;
  10550. return `<option value="${escapeHtml(ch)}"${currentVal === ch ? ' selected' : ''}>${escapeHtml(ch)} (${count})</option>`;
  10551. }).join('');
  10552. chainSelect.value = currentVal;
  10553. }
  10554. if (chainDatalist) {
  10555. chainDatalist.innerHTML = uniqueChains.map(ch => `<option value="${escapeHtml(ch)}">`).join('');
  10556. }
  10557. renderRoutingFilterRules();
  10558. renderRoutingFilterSelectRules();
  10559. renderRoutingFilterCommunityLists();
  10560. renderRoutingFilterASLists();
  10561. }
  10562. function filterRoutingFiltersByChain(chain) {
  10563. state.filterChainSelected = chain;
  10564. renderRoutingFilters();
  10565. }
  10566. // -------------------------------------------------------------
  10567. // TAB 1: RULES (/routing filter rule)
  10568. // -------------------------------------------------------------
  10569. function renderRoutingFilterRules() {
  10570. const tbody = document.getElementById('routing-filter-rules-tbody');
  10571. if (!tbody) return;
  10572. const empty = document.getElementById('rf-rules-empty');
  10573. const statusCount = document.getElementById('rf-status-count');
  10574. let list = (state.routingFilters || []).slice();
  10575. if (state.filterChainSelected && state.filterChainSelected !== 'all') {
  10576. list = list.filter(r => r.chain === state.filterChainSelected);
  10577. }
  10578. const q = state.rfSearchQuery;
  10579. if (q) {
  10580. list = list.filter(r =>
  10581. (r.chain && r.chain.toLowerCase().includes(q)) ||
  10582. (r.rule && r.rule.toLowerCase().includes(q)) ||
  10583. (r.prefix && r.prefix.toLowerCase().includes(q)) ||
  10584. (r.comment && r.comment.toLowerCase().includes(q))
  10585. );
  10586. }
  10587. if (!state.rfSort?.['rules']) {
  10588. list.sort((a, b) => {
  10589. if (a.chain !== b.chain) return (a.chain || '').localeCompare(b.chain || '');
  10590. return (a.rule_order || 0) - (b.rule_order || 0);
  10591. });
  10592. }
  10593. if (statusCount && (state.activeRoutingFilterTab === 'rules' || !state.activeRoutingFilterTab)) {
  10594. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  10595. }
  10596. if (list.length === 0) {
  10597. tbody.innerHTML = '';
  10598. if (empty) empty.classList.remove('hidden');
  10599. return;
  10600. }
  10601. if (empty) empty.classList.add('hidden');
  10602. tbody.innerHTML = list.map(r => {
  10603. const isSelected = state.selectedFilterRow?.['rules'] === r.id;
  10604. const flagA = !r.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  10605. const flagX = r.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  10606. const flagC = r.comment ? '<span class="text-amber-400 font-bold ml-1" title="Comment">C</span>' : '';
  10607. let ruleDisplay = '';
  10608. if (r.rule && r.rule.trim() !== '') {
  10609. ruleDisplay = `<span class="text-emerald-400 font-mono font-medium">${escapeHtml(r.rule)}</span>`;
  10610. } else {
  10611. let conds = [];
  10612. if (r.prefix) conds.push(`dst in ${escapeHtml(r.prefix)}`);
  10613. if (r.match_protocol && r.match_protocol !== 'any') conds.push(`protocol ${escapeHtml(r.match_protocol)}`);
  10614. let act = r.action || 'accept';
  10615. ruleDisplay = `<span class="text-slate-300 font-mono">if (${conds.length ? conds.join(' && ') : 'true'}) { ${escapeHtml(act)}; }</span>`;
  10616. }
  10617. return `
  10618. <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'}">
  10619. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}${flagC}</td>
  10620. <td class="py-2 px-2 font-mono text-slate-400 font-bold">${r.rule_order || 10}</td>
  10621. <td class="py-2 px-3">
  10622. <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>
  10623. </td>
  10624. <td class="py-2 px-3 break-all max-w-xl">${ruleDisplay}</td>
  10625. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(r.comment || '')}</td>
  10626. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  10627. <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>
  10628. <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>
  10629. <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'}">
  10630. ${r.disabled ? 'Enable' : 'Disable'}
  10631. </button>
  10632. <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">
  10633. Edit
  10634. </button>
  10635. <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">
  10636. ✕
  10637. </button>
  10638. </td>
  10639. </tr>
  10640. `;
  10641. }).join('');
  10642. }
  10643. // -------------------------------------------------------------
  10644. // TAB 2: SELECT RULES (/routing filter select-rule)
  10645. // -------------------------------------------------------------
  10646. function renderRoutingFilterSelectRules() {
  10647. const tbody = document.getElementById('routing-filter-select-rules-tbody');
  10648. if (!tbody) return;
  10649. const empty = document.getElementById('rf-select-rules-empty');
  10650. const statusCount = document.getElementById('rf-status-count');
  10651. let list = (state.routingSelectRules || []).slice();
  10652. if (state.filterChainSelected && state.filterChainSelected !== 'all') {
  10653. list = list.filter(r => r.chain === state.filterChainSelected);
  10654. }
  10655. const q = state.rfSearchQuery;
  10656. if (q) {
  10657. list = list.filter(r =>
  10658. (r.chain && r.chain.toLowerCase().includes(q)) ||
  10659. (r.rule && r.rule.toLowerCase().includes(q)) ||
  10660. (r.comment && r.comment.toLowerCase().includes(q))
  10661. );
  10662. }
  10663. if (statusCount && state.activeRoutingFilterTab === 'select-rules') {
  10664. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  10665. }
  10666. if (list.length === 0) {
  10667. tbody.innerHTML = '';
  10668. if (empty) empty.classList.remove('hidden');
  10669. return;
  10670. }
  10671. if (empty) empty.classList.add('hidden');
  10672. tbody.innerHTML = list.map(r => {
  10673. const isSelected = state.selectedFilterRow?.['select-rules'] === r.id;
  10674. const flagA = !r.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  10675. const flagX = r.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  10676. return `
  10677. <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'}">
  10678. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  10679. <td class="py-2 px-2 font-mono text-slate-400 font-bold">${r.rule_order || 10}</td>
  10680. <td class="py-2 px-3">
  10681. <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>
  10682. </td>
  10683. <td class="py-2 px-3 break-all max-w-xl font-mono text-emerald-400">${escapeHtml(r.rule || '')}</td>
  10684. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(r.comment || '')}</td>
  10685. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  10686. <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'}">
  10687. ${r.disabled ? 'Enable' : 'Disable'}
  10688. </button>
  10689. <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">
  10690. Edit
  10691. </button>
  10692. <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">
  10693. ✕
  10694. </button>
  10695. </td>
  10696. </tr>
  10697. `;
  10698. }).join('');
  10699. }
  10700. // -------------------------------------------------------------
  10701. // TAB 3: COMMUNITY LISTS (/routing filter community-list)
  10702. // -------------------------------------------------------------
  10703. function renderRoutingFilterCommunityLists() {
  10704. const tbody = document.getElementById('routing-filter-comm-lists-tbody');
  10705. if (!tbody) return;
  10706. const empty = document.getElementById('rf-comm-lists-empty');
  10707. const statusCount = document.getElementById('rf-status-count');
  10708. let list = (state.routingCommunityLists || []).slice();
  10709. const q = state.rfSearchQuery;
  10710. if (q) {
  10711. list = list.filter(cl =>
  10712. (cl.name && cl.name.toLowerCase().includes(q)) ||
  10713. (cl.comment && cl.comment.toLowerCase().includes(q)) ||
  10714. (cl.communities && cl.communities.some(c => c.toLowerCase().includes(q)))
  10715. );
  10716. }
  10717. if (statusCount && state.activeRoutingFilterTab === 'community-lists') {
  10718. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  10719. }
  10720. if (list.length === 0) {
  10721. tbody.innerHTML = '';
  10722. if (empty) empty.classList.remove('hidden');
  10723. return;
  10724. }
  10725. if (empty) empty.classList.add('hidden');
  10726. tbody.innerHTML = list.map(cl => {
  10727. const isSelected = state.selectedFilterRow?.['community-lists'] === cl.id;
  10728. const flagA = !cl.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  10729. const flagX = cl.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  10730. const commBadges = (cl.communities || []).map(c =>
  10731. `<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>`
  10732. ).join(' ');
  10733. return `
  10734. <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'}">
  10735. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  10736. <td class="py-2 px-3 font-mono font-bold text-white">${escapeHtml(cl.name)}</td>
  10737. <td class="py-2 px-3 space-x-1">${commBadges || '<span class="text-slate-600">-</span>'}</td>
  10738. <td class="py-2 px-3 font-mono text-slate-400">${escapeHtml(cl.regexp || '-')}</td>
  10739. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(cl.comment || '')}</td>
  10740. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  10741. <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'}">
  10742. ${cl.disabled ? 'Enable' : 'Disable'}
  10743. </button>
  10744. <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">
  10745. Edit
  10746. </button>
  10747. <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">
  10748. ✕
  10749. </button>
  10750. </td>
  10751. </tr>
  10752. `;
  10753. }).join('');
  10754. }
  10755. // -------------------------------------------------------------
  10756. // TAB 4: AS LISTS (/routing filter num-list)
  10757. // -------------------------------------------------------------
  10758. function renderRoutingFilterASLists() {
  10759. const tbody = document.getElementById('routing-filter-as-lists-tbody');
  10760. if (!tbody) return;
  10761. const empty = document.getElementById('rf-as-lists-empty');
  10762. const statusCount = document.getElementById('rf-status-count');
  10763. let list = (state.routingASLists || []).slice();
  10764. const q = state.rfSearchQuery;
  10765. if (q) {
  10766. list = list.filter(al =>
  10767. (al.name && al.name.toLowerCase().includes(q)) ||
  10768. (al.range && al.range.toLowerCase().includes(q)) ||
  10769. (al.comment && al.comment.toLowerCase().includes(q))
  10770. );
  10771. }
  10772. if (statusCount && state.activeRoutingFilterTab === 'as-lists') {
  10773. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  10774. }
  10775. if (list.length === 0) {
  10776. tbody.innerHTML = '';
  10777. if (empty) empty.classList.remove('hidden');
  10778. return;
  10779. }
  10780. if (empty) empty.classList.add('hidden');
  10781. tbody.innerHTML = list.map(al => {
  10782. const isSelected = state.selectedFilterRow?.['as-lists'] === al.id;
  10783. const flagA = !al.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  10784. const flagX = al.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  10785. return `
  10786. <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'}">
  10787. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  10788. <td class="py-2 px-3 font-mono font-bold text-white">${escapeHtml(al.name)}</td>
  10789. <td class="py-2 px-3 font-mono text-purple-300">${escapeHtml(al.range)}</td>
  10790. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(al.comment || '')}</td>
  10791. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  10792. <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'}">
  10793. ${al.disabled ? 'Enable' : 'Disable'}
  10794. </button>
  10795. <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">
  10796. Edit
  10797. </button>
  10798. <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">
  10799. ✕
  10800. </button>
  10801. </td>
  10802. </tr>
  10803. `;
  10804. }).join('');
  10805. }
  10806. // -------------------------------------------------------------
  10807. // SNIPPETS & WIZARD HELPERS
  10808. // -------------------------------------------------------------
  10809. function insertRuleSnippet(type) {
  10810. const textarea = document.getElementById('modal-rf-rule');
  10811. if (!textarea) return;
  10812. let snippet = '';
  10813. switch (type) {
  10814. case 'accept-default':
  10815. snippet = 'if (dst in 0.0.0.0/0) { accept; }';
  10816. break;
  10817. case 'drop-rfc1918':
  10818. snippet = 'if (dst in 10.0.0.0/8 || dst in 172.16.0.0/12 || dst in 192.168.0.0/16) { reject; }';
  10819. break;
  10820. case 'len-24':
  10821. snippet = 'if (dst-len > 24) { reject; }';
  10822. break;
  10823. case 'local-pref-150':
  10824. snippet = 'if (dst in 10.0.0.0/8) { set bgp-local-pref 150; accept; }';
  10825. break;
  10826. case 'as-prepend-2':
  10827. snippet = 'set bgp-path-prepend 2; accept;';
  10828. break;
  10829. case 'set-comm':
  10830. snippet = 'set bgp-communities.add 65000:100; accept;';
  10831. break;
  10832. case 'match-comm':
  10833. snippet = 'if (bgp-communities includes 65000:100) { accept; }';
  10834. break;
  10835. case 'reject-all':
  10836. snippet = 'reject;';
  10837. break;
  10838. }
  10839. if (!snippet) return;
  10840. if (!textarea.value.trim()) {
  10841. textarea.value = snippet;
  10842. } else {
  10843. textarea.value = textarea.value.trim() + '\n' + snippet;
  10844. }
  10845. }
  10846. function generateScriptFromWizard() {
  10847. const pfx = (document.getElementById('modal-rf-prefix')?.value || '').trim();
  10848. const pfxLen = (document.getElementById('modal-rf-prefix-len')?.value || '').trim();
  10849. const proto = document.getElementById('modal-rf-protocol')?.value || 'any';
  10850. const asp = (document.getElementById('modal-rf-as-path')?.value || '').trim();
  10851. const comm = (document.getElementById('modal-rf-community')?.value || '').trim();
  10852. const act = document.getElementById('modal-rf-action')?.value || 'accept';
  10853. const lp = parseInt(document.getElementById('modal-rf-set-local-pref')?.value, 10) || 0;
  10854. const prep = parseInt(document.getElementById('modal-rf-set-as-prepend')?.value, 10) || 0;
  10855. const conds = [];
  10856. if (pfx) {
  10857. if (pfxLen) {
  10858. if (pfxLen.includes('-')) {
  10859. const parts = pfxLen.split('-');
  10860. conds.push(`dst in ${pfx}{${parts[0].trim()},${parts[1].trim()}}`);
  10861. } else {
  10862. conds.push(`dst in ${pfx} && dst-len >= ${pfxLen}`);
  10863. }
  10864. } else {
  10865. conds.push(`dst in ${pfx}`);
  10866. }
  10867. }
  10868. if (proto && proto !== 'any') {
  10869. conds.push(`protocol ${proto}`);
  10870. }
  10871. if (asp) {
  10872. conds.push(`bgp-as-path "${asp}"`);
  10873. }
  10874. if (comm) {
  10875. conds.push(`bgp-communities includes ${comm}`);
  10876. }
  10877. const actions = [];
  10878. if (lp > 0) actions.push(`set bgp-local-pref ${lp};`);
  10879. if (prep > 0) actions.push(`set bgp-path-prepend ${prep};`);
  10880. actions.push(`${act};`);
  10881. let code = '';
  10882. if (conds.length > 0) {
  10883. code = `if (${conds.join(' && ')}) {\n ${actions.join(' ')}\n}`;
  10884. } else {
  10885. code = actions.join(' ');
  10886. }
  10887. const textarea = document.getElementById('modal-rf-rule');
  10888. if (textarea) textarea.value = code;
  10889. }
  10890. // -------------------------------------------------------------
  10891. // MODAL CRUD: RULES (/routing filter rule)
  10892. // -------------------------------------------------------------
  10893. function openAddRoutingFilterModal(defaultChain = '') {
  10894. const form = document.getElementById('routing-filter-form');
  10895. if (form) form.reset();
  10896. const idEl = document.getElementById('modal-rf-id');
  10897. if (idEl) idEl.value = '';
  10898. const titleEl = document.getElementById('modal-rf-title');
  10899. if (titleEl) titleEl.innerText = 'Add Routing Filter Rule';
  10900. const chainEl = document.getElementById('modal-rf-chain');
  10901. if (chainEl) chainEl.value = defaultChain || (state.filterChainSelected && state.filterChainSelected !== 'all' ? state.filterChainSelected : 'bgp-in');
  10902. const orderEl = document.getElementById('modal-rf-order');
  10903. if (orderEl) orderEl.value = ((state.routingFilters || []).length + 1) * 10;
  10904. const ruleEl = document.getElementById('modal-rf-rule');
  10905. if (ruleEl) ruleEl.value = 'if (dst in 10.0.0.0/8) { set bgp-local-pref 150; accept; }';
  10906. const disEl = document.getElementById('modal-rf-disabled');
  10907. if (disEl) disEl.checked = false;
  10908. const modal = document.getElementById('modal-routing-filter');
  10909. if (modal) modal.classList.remove('hidden');
  10910. }
  10911. function openEditRoutingFilterModal(id) {
  10912. const r = (state.routingFilters || []).find(item => item.id === id);
  10913. if (!r) return;
  10914. const idEl = document.getElementById('modal-rf-id');
  10915. if (idEl) idEl.value = r.id;
  10916. const titleEl = document.getElementById('modal-rf-title');
  10917. if (titleEl) titleEl.innerText = 'Edit Routing Filter Rule';
  10918. const chainEl = document.getElementById('modal-rf-chain');
  10919. if (chainEl) chainEl.value = r.chain || '';
  10920. const orderEl = document.getElementById('modal-rf-order');
  10921. if (orderEl) orderEl.value = r.rule_order || 10;
  10922. const ruleEl = document.getElementById('modal-rf-rule');
  10923. if (ruleEl) {
  10924. if (r.rule) {
  10925. ruleEl.value = r.rule;
  10926. } else {
  10927. let conds = [];
  10928. if (r.prefix) conds.push(`dst in ${r.prefix}`);
  10929. if (r.match_protocol && r.match_protocol !== 'any') conds.push(`protocol ${r.match_protocol}`);
  10930. let act = r.action || 'accept';
  10931. ruleEl.value = `if (${conds.length ? conds.join(' && ') : 'true'}) { ${act}; }`;
  10932. }
  10933. }
  10934. const comEl = document.getElementById('modal-rf-comment');
  10935. if (comEl) comEl.value = r.comment || '';
  10936. const disEl = document.getElementById('modal-rf-disabled');
  10937. if (disEl) disEl.checked = !!r.disabled;
  10938. const modal = document.getElementById('modal-routing-filter');
  10939. if (modal) modal.classList.remove('hidden');
  10940. }
  10941. function closeRoutingFilterModal() {
  10942. const modal = document.getElementById('modal-routing-filter');
  10943. if (modal) modal.classList.add('hidden');
  10944. }
  10945. async function submitRoutingFilter(e) {
  10946. if (e) e.preventDefault();
  10947. const payload = {
  10948. id: document.getElementById('modal-rf-id').value,
  10949. chain: document.getElementById('modal-rf-chain').value.trim(),
  10950. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  10951. rule: document.getElementById('modal-rf-rule').value.trim(),
  10952. comment: document.getElementById('modal-rf-comment').value.trim(),
  10953. disabled: document.getElementById('modal-rf-disabled').checked
  10954. };
  10955. try {
  10956. const res = await fetch(`${API_BASE}/routing/filters`, {
  10957. method: 'POST',
  10958. headers: { 'Content-Type': 'application/json' },
  10959. body: JSON.stringify(payload)
  10960. });
  10961. if (res.ok) {
  10962. closeRoutingFilterModal();
  10963. showToast('Success', 'Routing filter rule saved', 'success');
  10964. loadDynamicRouting();
  10965. } else {
  10966. const err = await res.json();
  10967. showToast('Error', err.error || 'Failed to save filter rule', 'error');
  10968. }
  10969. } catch (err) {
  10970. showToast('Error', err.message, 'error');
  10971. }
  10972. }
  10973. async function applyRoutingFilterForm() {
  10974. const payload = {
  10975. id: document.getElementById('modal-rf-id').value,
  10976. chain: document.getElementById('modal-rf-chain').value.trim(),
  10977. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  10978. rule: document.getElementById('modal-rf-rule').value.trim(),
  10979. comment: document.getElementById('modal-rf-comment').value.trim(),
  10980. disabled: document.getElementById('modal-rf-disabled').checked
  10981. };
  10982. try {
  10983. const res = await fetch(`${API_BASE}/routing/filters`, {
  10984. method: 'POST',
  10985. headers: { 'Content-Type': 'application/json' },
  10986. body: JSON.stringify(payload)
  10987. });
  10988. if (res.ok) {
  10989. const data = await res.json();
  10990. if (data.id) document.getElementById('modal-rf-id').value = data.id;
  10991. showToast('Applied', 'Routing filter configuration applied', 'success');
  10992. loadDynamicRouting();
  10993. } else {
  10994. const err = await res.json();
  10995. showToast('Error', err.error || 'Failed to apply filter rule', 'error');
  10996. }
  10997. } catch (err) {
  10998. showToast('Error', err.message, 'error');
  10999. }
  11000. }
  11001. async function moveRoutingFilterOrder(id, delta) {
  11002. const list = state.routingFilters || [];
  11003. const idx = list.findIndex(r => r.id === id);
  11004. if (idx < 0) return;
  11005. const targetIdx = idx + delta;
  11006. if (targetIdx < 0 || targetIdx >= list.length) return;
  11007. const currentOrder = list[idx].rule_order || 10;
  11008. const targetOrder = list[targetIdx].rule_order || 20;
  11009. list[idx].rule_order = targetOrder;
  11010. list[targetIdx].rule_order = currentOrder;
  11011. try {
  11012. await fetch(`${API_BASE}/routing/filters`, {
  11013. method: 'POST',
  11014. headers: { 'Content-Type': 'application/json' },
  11015. body: JSON.stringify(list[idx])
  11016. });
  11017. await fetch(`${API_BASE}/routing/filters`, {
  11018. method: 'POST',
  11019. headers: { 'Content-Type': 'application/json' },
  11020. body: JSON.stringify(list[targetIdx])
  11021. });
  11022. loadDynamicRouting();
  11023. } catch (e) {
  11024. console.error('Reorder error:', e);
  11025. }
  11026. }
  11027. async function deleteRoutingFilter(id) {
  11028. if (!confirm('Are you sure you want to delete this routing filter rule?')) return;
  11029. try {
  11030. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11031. if (res.ok) {
  11032. showToast('Deleted', 'Routing filter rule removed', 'info');
  11033. loadDynamicRouting();
  11034. } else {
  11035. const err = await res.json();
  11036. showToast('Error', err.error || 'Failed to delete rule', 'error');
  11037. }
  11038. } catch (err) {
  11039. showToast('Error', err.message, 'error');
  11040. }
  11041. }
  11042. async function toggleRoutingFilterState(id, disabled) {
  11043. try {
  11044. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}/state`, {
  11045. method: 'POST',
  11046. headers: { 'Content-Type': 'application/json' },
  11047. body: JSON.stringify({ disabled })
  11048. });
  11049. if (res.ok) {
  11050. showToast('Status Updated', `Rule ${disabled ? 'disabled' : 'enabled'}`, 'info');
  11051. loadDynamicRouting();
  11052. } else {
  11053. const err = await res.json();
  11054. showToast('Error', err.error || 'Failed to toggle rule state', 'error');
  11055. }
  11056. } catch (err) {
  11057. showToast('Error', err.message, 'error');
  11058. }
  11059. }
  11060. // -------------------------------------------------------------
  11061. // MODAL CRUD: SELECT RULES (/routing filter select-rule)
  11062. // -------------------------------------------------------------
  11063. function openAddSelectRuleModal() {
  11064. document.getElementById('modal-rf-sr-id').value = '';
  11065. document.getElementById('modal-rf-sr-title').innerText = 'Add Routing Select Rule';
  11066. document.getElementById('modal-rf-sr-chain').value = state.filterChainSelected && state.filterChainSelected !== 'all' ? state.filterChainSelected : 'bgp-out';
  11067. document.getElementById('modal-rf-sr-order').value = ((state.routingSelectRules || []).length + 1) * 10;
  11068. document.getElementById('modal-rf-sr-rule').value = 'if (protocol bgp && dst in 10.0.0.0/8) { accept; }';
  11069. document.getElementById('modal-rf-sr-comment').value = '';
  11070. document.getElementById('modal-rf-sr-disabled').checked = false;
  11071. document.getElementById('modal-rf-select-rule').classList.remove('hidden');
  11072. }
  11073. function openEditSelectRuleModal(id) {
  11074. const r = (state.routingSelectRules || []).find(item => item.id === id);
  11075. if (!r) return;
  11076. document.getElementById('modal-rf-sr-id').value = r.id;
  11077. document.getElementById('modal-rf-sr-title').innerText = 'Edit Routing Select Rule';
  11078. document.getElementById('modal-rf-sr-chain').value = r.chain || '';
  11079. document.getElementById('modal-rf-sr-order').value = r.rule_order || 10;
  11080. document.getElementById('modal-rf-sr-rule').value = r.rule || '';
  11081. document.getElementById('modal-rf-sr-comment').value = r.comment || '';
  11082. document.getElementById('modal-rf-sr-disabled').checked = !!r.disabled;
  11083. document.getElementById('modal-rf-select-rule').classList.remove('hidden');
  11084. }
  11085. function closeSelectRuleModal() {
  11086. document.getElementById('modal-rf-select-rule').classList.add('hidden');
  11087. }
  11088. async function submitSelectRule(e) {
  11089. e.preventDefault();
  11090. const payload = {
  11091. id: document.getElementById('modal-rf-sr-id').value,
  11092. chain: document.getElementById('modal-rf-sr-chain').value.trim(),
  11093. rule_order: parseInt(document.getElementById('modal-rf-sr-order').value, 10) || 10,
  11094. rule: document.getElementById('modal-rf-sr-rule').value.trim(),
  11095. comment: document.getElementById('modal-rf-sr-comment').value.trim(),
  11096. disabled: document.getElementById('modal-rf-sr-disabled').checked
  11097. };
  11098. try {
  11099. const res = await fetch(`${API_BASE}/routing/filters/select-rules`, {
  11100. method: 'POST',
  11101. headers: { 'Content-Type': 'application/json' },
  11102. body: JSON.stringify(payload)
  11103. });
  11104. if (res.ok) {
  11105. closeSelectRuleModal();
  11106. showToast('Success', 'Select rule saved', 'success');
  11107. loadDynamicRouting();
  11108. } else {
  11109. const err = await res.json();
  11110. showToast('Error', err.error || 'Failed to save select rule', 'error');
  11111. }
  11112. } catch (err) {
  11113. showToast('Error', err.message, 'error');
  11114. }
  11115. }
  11116. async function deleteSelectRule(id) {
  11117. if (!confirm('Are you sure you want to delete this select rule?')) return;
  11118. try {
  11119. const res = await fetch(`${API_BASE}/routing/filters/select-rules/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11120. if (res.ok) {
  11121. showToast('Deleted', 'Select rule removed', 'info');
  11122. loadDynamicRouting();
  11123. } else {
  11124. const err = await res.json();
  11125. showToast('Error', err.error || 'Failed to delete select rule', 'error');
  11126. }
  11127. } catch (err) {
  11128. showToast('Error', err.message, 'error');
  11129. }
  11130. }
  11131. async function toggleSelectRuleState(id, disabled) {
  11132. try {
  11133. const res = await fetch(`${API_BASE}/routing/filters/select-rules/${encodeURIComponent(id)}/state`, {
  11134. method: 'POST',
  11135. headers: { 'Content-Type': 'application/json' },
  11136. body: JSON.stringify({ disabled })
  11137. });
  11138. if (res.ok) {
  11139. showToast('Status Updated', `Select rule ${disabled ? 'disabled' : 'enabled'}`, 'info');
  11140. loadDynamicRouting();
  11141. } else {
  11142. const err = await res.json();
  11143. showToast('Error', err.error || 'Failed to update select rule state', 'error');
  11144. }
  11145. } catch (err) {
  11146. showToast('Error', err.message, 'error');
  11147. }
  11148. }
  11149. // -------------------------------------------------------------
  11150. // MODAL CRUD: COMMUNITY LISTS (/routing filter community-list)
  11151. // -------------------------------------------------------------
  11152. function openAddCommunityListModal() {
  11153. document.getElementById('modal-rf-cl-id').value = '';
  11154. document.getElementById('modal-rf-cl-title').innerText = 'Add BGP Community List';
  11155. document.getElementById('modal-rf-cl-name').value = '';
  11156. document.getElementById('modal-rf-cl-communities').value = '';
  11157. document.getElementById('modal-rf-cl-regexp').value = '';
  11158. document.getElementById('modal-rf-cl-comment').value = '';
  11159. document.getElementById('modal-rf-cl-disabled').checked = false;
  11160. document.getElementById('modal-rf-community-list').classList.remove('hidden');
  11161. }
  11162. function openEditCommunityListModal(id) {
  11163. const cl = (state.routingCommunityLists || []).find(item => item.id === id);
  11164. if (!cl) return;
  11165. document.getElementById('modal-rf-cl-id').value = cl.id;
  11166. document.getElementById('modal-rf-cl-title').innerText = 'Edit BGP Community List';
  11167. document.getElementById('modal-rf-cl-name').value = cl.name || '';
  11168. document.getElementById('modal-rf-cl-communities').value = (cl.communities || []).join(', ');
  11169. document.getElementById('modal-rf-cl-regexp').value = cl.regexp || '';
  11170. document.getElementById('modal-rf-cl-comment').value = cl.comment || '';
  11171. document.getElementById('modal-rf-cl-disabled').checked = !!cl.disabled;
  11172. document.getElementById('modal-rf-community-list').classList.remove('hidden');
  11173. }
  11174. function closeCommunityListModal() {
  11175. document.getElementById('modal-rf-community-list').classList.add('hidden');
  11176. }
  11177. async function submitCommunityList(e) {
  11178. e.preventDefault();
  11179. const rawComms = document.getElementById('modal-rf-cl-communities').value;
  11180. const comms = rawComms.split(',').map(c => c.trim()).filter(Boolean);
  11181. const payload = {
  11182. id: document.getElementById('modal-rf-cl-id').value,
  11183. name: document.getElementById('modal-rf-cl-name').value.trim(),
  11184. communities: comms,
  11185. regexp: document.getElementById('modal-rf-cl-regexp').value.trim(),
  11186. comment: document.getElementById('modal-rf-cl-comment').value.trim(),
  11187. disabled: document.getElementById('modal-rf-cl-disabled').checked
  11188. };
  11189. try {
  11190. const res = await fetch(`${API_BASE}/routing/filters/community-lists`, {
  11191. method: 'POST',
  11192. headers: { 'Content-Type': 'application/json' },
  11193. body: JSON.stringify(payload)
  11194. });
  11195. if (res.ok) {
  11196. closeCommunityListModal();
  11197. showToast('Success', 'Community list saved', 'success');
  11198. loadDynamicRouting();
  11199. } else {
  11200. const err = await res.json();
  11201. showToast('Error', err.error || 'Failed to save community list', 'error');
  11202. }
  11203. } catch (err) {
  11204. showToast('Error', err.message, 'error');
  11205. }
  11206. }
  11207. async function deleteCommunityList(id) {
  11208. if (!confirm('Are you sure you want to delete this community list?')) return;
  11209. try {
  11210. const res = await fetch(`${API_BASE}/routing/filters/community-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11211. if (res.ok) {
  11212. showToast('Deleted', 'Community list removed', 'info');
  11213. loadDynamicRouting();
  11214. } else {
  11215. const err = await res.json();
  11216. showToast('Error', err.error || 'Failed to delete community list', 'error');
  11217. }
  11218. } catch (err) {
  11219. showToast('Error', err.message, 'error');
  11220. }
  11221. }
  11222. async function toggleCommunityListState(id, disabled) {
  11223. try {
  11224. const res = await fetch(`${API_BASE}/routing/filters/community-lists/${encodeURIComponent(id)}/state`, {
  11225. method: 'POST',
  11226. headers: { 'Content-Type': 'application/json' },
  11227. body: JSON.stringify({ disabled })
  11228. });
  11229. if (res.ok) {
  11230. showToast('Status Updated', `Community list ${disabled ? 'disabled' : 'enabled'}`, 'info');
  11231. loadDynamicRouting();
  11232. } else {
  11233. const err = await res.json();
  11234. showToast('Error', err.error || 'Failed to update community list state', 'error');
  11235. }
  11236. } catch (err) {
  11237. showToast('Error', err.message, 'error');
  11238. }
  11239. }
  11240. // -------------------------------------------------------------
  11241. // MODAL CRUD: AS LISTS (/routing filter num-list)
  11242. // -------------------------------------------------------------
  11243. function openAddASListModal() {
  11244. document.getElementById('modal-rf-al-id').value = '';
  11245. document.getElementById('modal-rf-al-title').innerText = 'Add AS Number List';
  11246. document.getElementById('modal-rf-al-name').value = '';
  11247. document.getElementById('modal-rf-al-range').value = '';
  11248. document.getElementById('modal-rf-al-comment').value = '';
  11249. document.getElementById('modal-rf-al-disabled').checked = false;
  11250. document.getElementById('modal-rf-as-list').classList.remove('hidden');
  11251. }
  11252. function openEditASListModal(id) {
  11253. const al = (state.routingASLists || []).find(item => item.id === id);
  11254. if (!al) return;
  11255. document.getElementById('modal-rf-al-id').value = al.id;
  11256. document.getElementById('modal-rf-al-title').innerText = 'Edit AS Number List';
  11257. document.getElementById('modal-rf-al-name').value = al.name || '';
  11258. document.getElementById('modal-rf-al-range').value = al.range || '';
  11259. document.getElementById('modal-rf-al-comment').value = al.comment || '';
  11260. document.getElementById('modal-rf-al-disabled').checked = !!al.disabled;
  11261. document.getElementById('modal-rf-as-list').classList.remove('hidden');
  11262. }
  11263. function closeASListModal() {
  11264. document.getElementById('modal-rf-as-list').classList.add('hidden');
  11265. }
  11266. async function submitASList(e) {
  11267. e.preventDefault();
  11268. const payload = {
  11269. id: document.getElementById('modal-rf-al-id').value,
  11270. name: document.getElementById('modal-rf-al-name').value.trim(),
  11271. range: document.getElementById('modal-rf-al-range').value.trim(),
  11272. comment: document.getElementById('modal-rf-al-comment').value.trim(),
  11273. disabled: document.getElementById('modal-rf-al-disabled').checked
  11274. };
  11275. try {
  11276. const res = await fetch(`${API_BASE}/routing/filters/as-lists`, {
  11277. method: 'POST',
  11278. headers: { 'Content-Type': 'application/json' },
  11279. body: JSON.stringify(payload)
  11280. });
  11281. if (res.ok) {
  11282. closeASListModal();
  11283. showToast('Success', 'AS number list saved', 'success');
  11284. loadDynamicRouting();
  11285. } else {
  11286. const err = await res.json();
  11287. showToast('Error', err.error || 'Failed to save AS list', 'error');
  11288. }
  11289. } catch (err) {
  11290. showToast('Error', err.message, 'error');
  11291. }
  11292. }
  11293. async function deleteASList(id) {
  11294. if (!confirm('Are you sure you want to delete this AS list?')) return;
  11295. try {
  11296. const res = await fetch(`${API_BASE}/routing/filters/as-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11297. if (res.ok) {
  11298. showToast('Deleted', 'AS list removed', 'info');
  11299. loadDynamicRouting();
  11300. } else {
  11301. const err = await res.json();
  11302. showToast('Error', err.error || 'Failed to delete AS list', 'error');
  11303. }
  11304. } catch (err) {
  11305. showToast('Error', err.message, 'error');
  11306. }
  11307. }
  11308. async function toggleASListState(id, disabled) {
  11309. try {
  11310. const res = await fetch(`${API_BASE}/routing/filters/as-lists/${encodeURIComponent(id)}/state`, {
  11311. method: 'POST',
  11312. headers: { 'Content-Type': 'application/json' },
  11313. body: JSON.stringify({ disabled })
  11314. });
  11315. if (res.ok) {
  11316. showToast('Status Updated', `AS list ${disabled ? 'disabled' : 'enabled'}`, 'info');
  11317. loadDynamicRouting();
  11318. } else {
  11319. const err = await res.json();
  11320. showToast('Error', err.error || 'Failed to update AS list state', 'error');
  11321. }
  11322. } catch (err) {
  11323. showToast('Error', err.message, 'error');
  11324. }
  11325. }
  11326. // ==========================================
  11327. // TROUBLESHOOT & DIAGNOSTIC TOOLS (/tool)
  11328. // ==========================================
  11329. function loadToolsView() {
  11330. populateToolsInterfaces();
  11331. switchToolsSubTab(state.activeToolsSubTab || 'ping');
  11332. }
  11333. function populateToolsInterfaces() {
  11334. const pingSel = document.getElementById('tools-ping-iface');
  11335. const traceSel = document.getElementById('tools-tr-iface');
  11336. let opts = '<option value="">Auto (Default Route)</option>';
  11337. if (Array.isArray(state.interfaces)) {
  11338. state.interfaces.forEach(iface => {
  11339. if (iface.name) {
  11340. opts += `<option value="${escapeHtml(iface.name)}">${escapeHtml(iface.name)}${iface.ip_address ? ' (' + escapeHtml(iface.ip_address) + ')' : ''}</option>`;
  11341. }
  11342. });
  11343. }
  11344. if (pingSel) {
  11345. const cur = pingSel.value;
  11346. pingSel.innerHTML = opts;
  11347. if (cur) pingSel.value = cur;
  11348. }
  11349. if (traceSel) {
  11350. const cur = traceSel.value;
  11351. traceSel.innerHTML = opts;
  11352. if (cur) traceSel.value = cur;
  11353. }
  11354. }
  11355. function switchToolsSubTab(subTab) {
  11356. state.activeToolsSubTab = subTab;
  11357. const tabs = ['ping', 'traceroute', 'mtr', 'dns', 'port'];
  11358. tabs.forEach(t => {
  11359. const btn = document.getElementById(`tools-subtab-btn-${t}`);
  11360. const view = document.getElementById(`tools-view-${t}`);
  11361. if (btn) {
  11362. if (t === subTab) {
  11363. 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';
  11364. } else {
  11365. 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';
  11366. }
  11367. }
  11368. if (view) {
  11369. if (t === subTab) {
  11370. view.classList.remove('hidden');
  11371. } else {
  11372. view.classList.add('hidden');
  11373. }
  11374. }
  11375. });
  11376. }
  11377. function setPortPreset(port) {
  11378. const input = document.getElementById('tools-port-num');
  11379. if (input) input.value = port;
  11380. }
  11381. let pingAbortController = null;
  11382. let tracerouteAbortController = null;
  11383. function clearPingTable() {
  11384. const tbody = document.getElementById('tools-ping-tbody');
  11385. if (tbody) tbody.innerHTML = '';
  11386. const rawEl = document.getElementById('tools-ping-raw');
  11387. if (rawEl) rawEl.innerText = '';
  11388. const sentEl = document.getElementById('tools-ping-stat-sent');
  11389. if (sentEl) sentEl.innerText = '0';
  11390. const recvEl = document.getElementById('tools-ping-stat-recv');
  11391. if (recvEl) recvEl.innerText = '0';
  11392. const lossEl = document.getElementById('tools-ping-stat-loss');
  11393. if (lossEl) lossEl.innerText = '0%';
  11394. const avgEl = document.getElementById('tools-ping-stat-avg');
  11395. if (avgEl) avgEl.innerText = '0 ms';
  11396. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  11397. if (minMaxEl) minMaxEl.innerText = '-';
  11398. const badge = document.getElementById('tools-ping-status-badge');
  11399. if (badge) {
  11400. badge.className = '';
  11401. badge.innerText = '';
  11402. }
  11403. }
  11404. function clearTracerouteTable() {
  11405. const tbody = document.getElementById('tools-tr-tbody');
  11406. if (tbody) tbody.innerHTML = '';
  11407. const rawEl = document.getElementById('tools-tr-raw');
  11408. if (rawEl) rawEl.innerText = '';
  11409. const statHops = document.getElementById('tools-tr-hops-count');
  11410. if (statHops) statHops.innerText = '0 Hops';
  11411. }
  11412. function resetPingButton() {
  11413. const btn = document.getElementById('tools-ping-btn');
  11414. const btnText = document.getElementById('tools-ping-btn-text');
  11415. const spinner = document.getElementById('tools-ping-spinner');
  11416. if (btn) {
  11417. btn.disabled = false;
  11418. 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';
  11419. }
  11420. if (btnText) btnText.innerText = 'Start Ping';
  11421. if (spinner) spinner.classList.add('hidden');
  11422. }
  11423. function setPingRunningButton() {
  11424. const btn = document.getElementById('tools-ping-btn');
  11425. const btnText = document.getElementById('tools-ping-btn-text');
  11426. const spinner = document.getElementById('tools-ping-spinner');
  11427. if (btn) {
  11428. btn.disabled = false;
  11429. 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';
  11430. }
  11431. if (btnText) btnText.innerText = 'Stop Ping';
  11432. if (spinner) spinner.classList.remove('hidden');
  11433. }
  11434. function resetTracerouteButton() {
  11435. const btn = document.getElementById('tools-tr-btn');
  11436. const btnText = document.getElementById('tools-tr-btn-text');
  11437. const spinner = document.getElementById('tools-tr-spinner');
  11438. if (btn) {
  11439. btn.disabled = false;
  11440. 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';
  11441. }
  11442. if (btnText) btnText.innerText = 'Start Traceroute';
  11443. if (spinner) spinner.classList.add('hidden');
  11444. }
  11445. function setTracerouteRunningButton() {
  11446. const btn = document.getElementById('tools-tr-btn');
  11447. const btnText = document.getElementById('tools-tr-btn-text');
  11448. const spinner = document.getElementById('tools-tr-spinner');
  11449. if (btn) {
  11450. btn.disabled = false;
  11451. 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';
  11452. }
  11453. if (btnText) btnText.innerText = 'Stop Traceroute';
  11454. if (spinner) spinner.classList.remove('hidden');
  11455. }
  11456. async function executePing(e) {
  11457. if (e) e.preventDefault();
  11458. // If already running, clicking the button stops the stream!
  11459. if (pingAbortController) {
  11460. pingAbortController.abort();
  11461. pingAbortController = null;
  11462. resetPingButton();
  11463. showToast('Ping Stopped', 'Live ping stopped by user', 'info');
  11464. return;
  11465. }
  11466. const target = document.getElementById('tools-ping-target')?.value?.trim();
  11467. const count = parseInt(document.getElementById('tools-ping-count')?.value || '4', 10);
  11468. const size = parseInt(document.getElementById('tools-ping-size')?.value || '56', 10);
  11469. const timeout = parseInt(document.getElementById('tools-ping-timeout')?.value || '3', 10);
  11470. const iface = document.getElementById('tools-ping-iface')?.value || '';
  11471. const dontFrag = document.getElementById('tools-ping-df')?.checked || false;
  11472. if (!target) {
  11473. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  11474. return;
  11475. }
  11476. clearPingTable();
  11477. const resCard = document.getElementById('tools-ping-results');
  11478. if (resCard) resCard.classList.remove('hidden');
  11479. pingAbortController = new AbortController();
  11480. setPingRunningButton();
  11481. try {
  11482. const res = await fetch(`${API_BASE}/tools/ping/stream`, {
  11483. method: 'POST',
  11484. headers: { 'Content-Type': 'application/json' },
  11485. body: JSON.stringify({
  11486. target,
  11487. count,
  11488. size,
  11489. timeout,
  11490. interface: iface,
  11491. dont_frag: dontFrag
  11492. }),
  11493. signal: pingAbortController.signal
  11494. });
  11495. if (!res.ok) {
  11496. const errText = await res.text();
  11497. showToast('Ping Error', errText || 'Failed to start live ping', 'error');
  11498. resetPingButton();
  11499. pingAbortController = null;
  11500. return;
  11501. }
  11502. const reader = res.body.getReader();
  11503. const decoder = new TextDecoder('utf-8');
  11504. let buffer = '';
  11505. while (true) {
  11506. const { done, value } = await reader.read();
  11507. if (done) break;
  11508. buffer += decoder.decode(value, { stream: true });
  11509. const blocks = buffer.split('\n\n');
  11510. buffer = blocks.pop() || '';
  11511. for (const block of blocks) {
  11512. const trimmed = block.trim();
  11513. if (!trimmed) continue;
  11514. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  11515. try {
  11516. const evt = JSON.parse(line);
  11517. handleLivePingEvent(evt);
  11518. } catch (parseErr) {
  11519. console.warn('Ping SSE parse error:', parseErr, line);
  11520. }
  11521. }
  11522. }
  11523. } catch (err) {
  11524. if (err.name === 'AbortError') {
  11525. // User aborted normally
  11526. } else {
  11527. showToast('Ping Error', err.message, 'error');
  11528. }
  11529. } finally {
  11530. pingAbortController = null;
  11531. resetPingButton();
  11532. }
  11533. }
  11534. function handleLivePingEvent(evt) {
  11535. const sentEl = document.getElementById('tools-ping-stat-sent');
  11536. const recvEl = document.getElementById('tools-ping-stat-recv');
  11537. const lossEl = document.getElementById('tools-ping-stat-loss');
  11538. const avgEl = document.getElementById('tools-ping-stat-avg');
  11539. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  11540. const badge = document.getElementById('tools-ping-status-badge');
  11541. const tbody = document.getElementById('tools-ping-tbody');
  11542. const rawEl = document.getElementById('tools-ping-raw');
  11543. if (evt.raw && rawEl) {
  11544. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  11545. rawEl.scrollTop = rawEl.scrollHeight;
  11546. }
  11547. if (evt.type === 'reply') {
  11548. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  11549. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  11550. if (lossEl && evt.packet_loss_pct !== undefined) {
  11551. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  11552. lossEl.className = evt.packet_loss_pct === 0
  11553. ? 'text-base font-bold font-mono text-emerald-400 mt-1'
  11554. : (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');
  11555. }
  11556. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  11557. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  11558. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  11559. }
  11560. if (badge) {
  11561. if (evt.packet_loss_pct === 0) {
  11562. 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';
  11563. badge.innerText = '100% OK';
  11564. } else {
  11565. 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';
  11566. badge.innerText = `${evt.packet_loss_pct.toFixed(0)}% LOSS`;
  11567. }
  11568. }
  11569. if (tbody) {
  11570. const tr = document.createElement('tr');
  11571. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  11572. tr.innerHTML = `
  11573. <td class="py-2 px-3 text-slate-300">#${evt.seq}</td>
  11574. <td class="py-2 px-3 font-semibold text-white">${escapeHtml(evt.from)}</td>
  11575. <td class="py-2 px-3 text-slate-400">${evt.bytes} bytes</td>
  11576. <td class="py-2 px-3 text-slate-300">${evt.ttl}</td>
  11577. <td class="py-2 px-3 font-bold text-amber-300">${evt.time_ms.toFixed(2)} ms</td>
  11578. <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>
  11579. `;
  11580. tbody.appendChild(tr);
  11581. }
  11582. } else if (evt.type === 'timeout') {
  11583. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  11584. if (lossEl && evt.packet_loss_pct !== undefined) {
  11585. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  11586. 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';
  11587. }
  11588. if (badge) {
  11589. 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';
  11590. badge.innerText = `${evt.packet_loss_pct?.toFixed(0) || 100}% LOSS`;
  11591. }
  11592. if (tbody) {
  11593. const tr = document.createElement('tr');
  11594. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs opacity-75';
  11595. tr.innerHTML = `
  11596. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  11597. <td class="py-2 px-3 font-semibold text-slate-500 italic">Request timed out</td>
  11598. <td class="py-2 px-3 text-slate-600">--</td>
  11599. <td class="py-2 px-3 text-slate-600">--</td>
  11600. <td class="py-2 px-3 font-bold text-slate-500">* * *</td>
  11601. <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>
  11602. `;
  11603. tbody.appendChild(tr);
  11604. }
  11605. } else if (evt.type === 'unreach') {
  11606. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  11607. if (lossEl && evt.packet_loss_pct !== undefined) {
  11608. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  11609. lossEl.className = 'text-base font-bold font-mono text-rose-400 mt-1';
  11610. }
  11611. if (badge) {
  11612. 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';
  11613. badge.innerText = 'UNREACHABLE';
  11614. }
  11615. if (tbody) {
  11616. const tr = document.createElement('tr');
  11617. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  11618. tr.innerHTML = `
  11619. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  11620. <td class="py-2 px-3 font-semibold text-rose-400">${escapeHtml(evt.from || 'Gateway')}</td>
  11621. <td class="py-2 px-3 text-slate-600">--</td>
  11622. <td class="py-2 px-3 text-slate-600">--</td>
  11623. <td class="py-2 px-3 font-bold text-rose-400 text-xs">${escapeHtml(evt.message || 'Unreachable')}</td>
  11624. <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>
  11625. `;
  11626. tbody.appendChild(tr);
  11627. }
  11628. } else if (evt.type === 'stats') {
  11629. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  11630. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  11631. if (lossEl && evt.packet_loss_pct !== undefined) lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  11632. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  11633. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  11634. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  11635. }
  11636. } else if (evt.type === 'done') {
  11637. 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');
  11638. }
  11639. }
  11640. async function executeTraceroute(e) {
  11641. if (e) e.preventDefault();
  11642. if (tracerouteAbortController) {
  11643. tracerouteAbortController.abort();
  11644. tracerouteAbortController = null;
  11645. resetTracerouteButton();
  11646. showToast('Traceroute Stopped', 'Traceroute stopped by user', 'info');
  11647. return;
  11648. }
  11649. const target = document.getElementById('tools-tr-target')?.value?.trim();
  11650. const maxHops = parseInt(document.getElementById('tools-tr-maxhops')?.value || '15', 10);
  11651. const protocol = document.getElementById('tools-tr-proto')?.value || 'icmp';
  11652. const iface = document.getElementById('tools-tr-iface')?.value || '';
  11653. const resolve = document.getElementById('tools-tr-resolve')?.checked || false;
  11654. if (!target) {
  11655. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  11656. return;
  11657. }
  11658. clearTracerouteTable();
  11659. const resCard = document.getElementById('tools-tr-results');
  11660. if (resCard) resCard.classList.remove('hidden');
  11661. tracerouteAbortController = new AbortController();
  11662. setTracerouteRunningButton();
  11663. try {
  11664. const res = await fetch(`${API_BASE}/tools/traceroute/stream`, {
  11665. method: 'POST',
  11666. headers: { 'Content-Type': 'application/json' },
  11667. body: JSON.stringify({
  11668. target,
  11669. max_hops: maxHops,
  11670. protocol,
  11671. interface: iface,
  11672. resolve
  11673. }),
  11674. signal: tracerouteAbortController.signal
  11675. });
  11676. if (!res.ok) {
  11677. const errText = await res.text();
  11678. showToast('Traceroute Error', errText || 'Failed to start traceroute', 'error');
  11679. resetTracerouteButton();
  11680. tracerouteAbortController = null;
  11681. return;
  11682. }
  11683. const reader = res.body.getReader();
  11684. const decoder = new TextDecoder('utf-8');
  11685. let buffer = '';
  11686. while (true) {
  11687. const { done, value } = await reader.read();
  11688. if (done) break;
  11689. buffer += decoder.decode(value, { stream: true });
  11690. const blocks = buffer.split('\n\n');
  11691. buffer = blocks.pop() || '';
  11692. for (const block of blocks) {
  11693. const trimmed = block.trim();
  11694. if (!trimmed) continue;
  11695. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  11696. try {
  11697. const evt = JSON.parse(line);
  11698. handleLiveTracerouteEvent(evt);
  11699. } catch (parseErr) {
  11700. console.warn('Traceroute SSE parse error:', parseErr, line);
  11701. }
  11702. }
  11703. }
  11704. } catch (err) {
  11705. if (err.name === 'AbortError') {
  11706. // User aborted normally
  11707. } else {
  11708. showToast('Traceroute Error', err.message, 'error');
  11709. }
  11710. } finally {
  11711. tracerouteAbortController = null;
  11712. resetTracerouteButton();
  11713. }
  11714. }
  11715. function handleLiveTracerouteEvent(evt) {
  11716. const statHops = document.getElementById('tools-tr-hops-count');
  11717. const tbody = document.getElementById('tools-tr-tbody');
  11718. const rawEl = document.getElementById('tools-tr-raw');
  11719. if (evt.raw && rawEl) {
  11720. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  11721. rawEl.scrollTop = rawEl.scrollHeight;
  11722. }
  11723. if (evt.hops_count !== undefined && statHops) {
  11724. statHops.innerText = `${evt.hops_count} Hops`;
  11725. }
  11726. if (evt.type === 'hop' && evt.hop && tbody) {
  11727. const h = evt.hop;
  11728. const isTimeout = h.status === 'timeout' || (!h.ip && !h.host);
  11729. const rtt1 = Array.isArray(h.times_ms) && h.times_ms[0] ? `${h.times_ms[0]} ms` : (isTimeout ? '*' : '--');
  11730. const rtt2 = Array.isArray(h.times_ms) && h.times_ms[1] ? `${h.times_ms[1]} ms` : (isTimeout ? '*' : '--');
  11731. const displayHost = h.host && h.host !== h.ip ? `${escapeHtml(h.host)} (${escapeHtml(h.ip || '')})` : escapeHtml(h.ip || (isTimeout ? 'Request timed out' : '--'));
  11732. const tr = document.createElement('tr');
  11733. tr.className = `hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs ${isTimeout ? 'opacity-60' : ''}`;
  11734. tr.innerHTML = `
  11735. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  11736. <td class="py-2.5 px-3 font-semibold ${isTimeout ? 'text-slate-500 italic' : 'text-cyan-300'}">${displayHost}</td>
  11737. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt1)}</td>
  11738. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt2)}</td>
  11739. <td class="py-2.5 px-3 text-right">
  11740. ${isTimeout
  11741. ? '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-slate-800 text-slate-400 border border-slate-700">TIMEOUT</span>'
  11742. : '<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>'}
  11743. </td>
  11744. `;
  11745. tbody.appendChild(tr);
  11746. } else if (evt.type === 'done') {
  11747. showToast('Traceroute Finished', `Traced ${evt.hops_count || 0} hops`, 'info');
  11748. }
  11749. }
  11750. async function executeMTR(e) {
  11751. if (e) e.preventDefault();
  11752. const target = document.getElementById('tools-mtr-target')?.value?.trim();
  11753. const cycles = parseInt(document.getElementById('tools-mtr-count')?.value || '3', 10);
  11754. if (!target) {
  11755. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  11756. return;
  11757. }
  11758. const btn = document.getElementById('tools-mtr-btn');
  11759. const spinner = document.getElementById('tools-mtr-spinner');
  11760. if (btn) btn.disabled = true;
  11761. if (spinner) spinner.classList.remove('hidden');
  11762. try {
  11763. const res = await fetch(`${API_BASE}/tools/mtr`, {
  11764. method: 'POST',
  11765. headers: { 'Content-Type': 'application/json' },
  11766. body: JSON.stringify({ target, count: cycles })
  11767. });
  11768. const data = await res.json();
  11769. if (!res.ok) {
  11770. showToast('MTR Error', data.error || 'Failed to execute MTR', 'error');
  11771. return;
  11772. }
  11773. const resCard = document.getElementById('tools-mtr-results');
  11774. if (resCard) resCard.classList.remove('hidden');
  11775. const hopsCount = Array.isArray(data.hops) ? data.hops.length : 0;
  11776. const statHops = document.getElementById('tools-mtr-hops-count');
  11777. if (statHops) statHops.innerText = `${hopsCount} Hops`;
  11778. const tbody = document.getElementById('tools-mtr-tbody');
  11779. if (tbody) {
  11780. if (hopsCount > 0) {
  11781. tbody.innerHTML = data.hops.map(h => {
  11782. 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');
  11783. return `
  11784. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  11785. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  11786. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(h.host || '--')}</td>
  11787. <td class="py-2.5 px-3 ${lossClass}">${h.loss_pct.toFixed(1)}%</td>
  11788. <td class="py-2.5 px-3 text-slate-300">${h.sent}</td>
  11789. <td class="py-2.5 px-3 text-slate-300">${h.last_ms.toFixed(1)}</td>
  11790. <td class="py-2.5 px-3 font-bold text-amber-300">${h.avg_ms.toFixed(1)}</td>
  11791. <td class="py-2.5 px-3 text-emerald-400">${h.best_ms.toFixed(1)}</td>
  11792. <td class="py-2.5 px-3 text-rose-400">${h.wrst_ms.toFixed(1)}</td>
  11793. <td class="py-2.5 px-3 text-slate-400">${h.stdev_ms.toFixed(1)}</td>
  11794. </tr>
  11795. `;
  11796. }).join('');
  11797. } else {
  11798. tbody.innerHTML = `<tr><td colspan="9" class="p-4 text-center text-xs text-rose-400 font-mono">No MTR data collected</td></tr>`;
  11799. }
  11800. }
  11801. const rawEl = document.getElementById('tools-mtr-raw');
  11802. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  11803. showToast('MTR Finished', `Report completed (${hopsCount} hops discovered)`, 'info');
  11804. } catch (err) {
  11805. showToast('MTR Error', err.message, 'error');
  11806. } finally {
  11807. if (btn) btn.disabled = false;
  11808. if (spinner) spinner.classList.add('hidden');
  11809. }
  11810. }
  11811. async function executeDNS(e) {
  11812. if (e) e.preventDefault();
  11813. const domain = document.getElementById('tools-dns-domain')?.value?.trim();
  11814. const type = document.getElementById('tools-dns-type')?.value || 'A';
  11815. const server = document.getElementById('tools-dns-server')?.value?.trim() || '';
  11816. if (!domain) {
  11817. showToast('Input Required', 'Please enter a hostname or domain', 'warning');
  11818. return;
  11819. }
  11820. const btn = document.getElementById('tools-dns-btn');
  11821. const spinner = document.getElementById('tools-dns-spinner');
  11822. if (btn) btn.disabled = true;
  11823. if (spinner) spinner.classList.remove('hidden');
  11824. try {
  11825. const res = await fetch(`${API_BASE}/tools/dns`, {
  11826. method: 'POST',
  11827. headers: { 'Content-Type': 'application/json' },
  11828. body: JSON.stringify({ domain, type, server })
  11829. });
  11830. const data = await res.json();
  11831. if (!res.ok) {
  11832. showToast('DNS Error', data.error || 'Failed to resolve DNS query', 'error');
  11833. return;
  11834. }
  11835. const resCard = document.getElementById('tools-dns-results');
  11836. if (resCard) resCard.classList.remove('hidden');
  11837. const metaEl = document.getElementById('tools-dns-meta');
  11838. if (metaEl) metaEl.innerText = `Resolved in ${data.query_time_ms ?? 0} ms via ${escapeHtml(data.server || 'System DNS')}`;
  11839. const tbody = document.getElementById('tools-dns-tbody');
  11840. if (tbody) {
  11841. if (Array.isArray(data.records) && data.records.length > 0) {
  11842. tbody.innerHTML = data.records.map(r => `
  11843. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  11844. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.name)}</td>
  11845. <td class="py-2.5 px-3 text-slate-400">${r.ttl}s</td>
  11846. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.class || 'IN')}</td>
  11847. <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>
  11848. <td class="py-2.5 px-3 font-bold text-amber-300 break-all">${escapeHtml(r.value)}</td>
  11849. </tr>
  11850. `).join('');
  11851. } else {
  11852. 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>`;
  11853. }
  11854. }
  11855. const rawEl = document.getElementById('tools-dns-raw');
  11856. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  11857. showToast('DNS Lookup Done', `Resolved ${domain} in ${data.query_time_ms} ms`, 'success');
  11858. } catch (err) {
  11859. showToast('DNS Error', err.message, 'error');
  11860. } finally {
  11861. if (btn) btn.disabled = false;
  11862. if (spinner) spinner.classList.add('hidden');
  11863. }
  11864. }
  11865. async function executePortProbe(e) {
  11866. if (e) e.preventDefault();
  11867. const target = document.getElementById('tools-port-target')?.value?.trim();
  11868. const port = parseInt(document.getElementById('tools-port-num')?.value || '80', 10);
  11869. const timeout = parseInt(document.getElementById('tools-port-timeout')?.value || '3', 10);
  11870. if (!target || !port) {
  11871. showToast('Input Required', 'Please enter a target host and TCP port', 'warning');
  11872. return;
  11873. }
  11874. const btn = document.getElementById('tools-port-btn');
  11875. const spinner = document.getElementById('tools-port-spinner');
  11876. if (btn) btn.disabled = true;
  11877. if (spinner) spinner.classList.remove('hidden');
  11878. try {
  11879. const res = await fetch(`${API_BASE}/tools/port-probe`, {
  11880. method: 'POST',
  11881. headers: { 'Content-Type': 'application/json' },
  11882. body: JSON.stringify({ target, port, timeout })
  11883. });
  11884. const data = await res.json();
  11885. if (!res.ok) {
  11886. showToast('Probe Error', data.error || 'Failed to probe TCP port', 'error');
  11887. return;
  11888. }
  11889. const resCard = document.getElementById('tools-port-results');
  11890. if (resCard) resCard.classList.remove('hidden');
  11891. const banner = document.getElementById('tools-port-banner');
  11892. const icon = document.getElementById('tools-port-icon');
  11893. const title = document.getElementById('tools-port-title');
  11894. const sub = document.getElementById('tools-port-sub');
  11895. const latency = document.getElementById('tools-port-latency');
  11896. if (data.open) {
  11897. if (banner) banner.className = 'rounded-xl p-5 border bg-emerald-950/30 border-emerald-800/50 flex items-center justify-between';
  11898. if (icon) {
  11899. 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';
  11900. icon.innerText = '✓';
  11901. }
  11902. if (title) {
  11903. title.className = 'text-sm font-bold text-emerald-300';
  11904. title.innerText = `PORT ${port} OPEN / LISTENING`;
  11905. }
  11906. if (sub) {
  11907. sub.className = 'text-xs mt-0.5 font-mono text-emerald-400/80';
  11908. sub.innerText = `TCP 3-way handshake established with ${escapeHtml(target)}:${port}${data.service ? ' (' + escapeHtml(data.service) + ')' : ''}`;
  11909. }
  11910. if (latency) {
  11911. latency.className = 'text-base font-bold font-mono text-emerald-300';
  11912. latency.innerText = `${data.latency_ms.toFixed(2)} ms`;
  11913. }
  11914. } else {
  11915. if (banner) banner.className = 'rounded-xl p-5 border bg-rose-950/30 border-rose-800/50 flex items-center justify-between';
  11916. if (icon) {
  11917. 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';
  11918. icon.innerText = '✕';
  11919. }
  11920. if (title) {
  11921. title.className = 'text-sm font-bold text-rose-300';
  11922. title.innerText = `PORT ${port} CLOSED / FILTERED`;
  11923. }
  11924. if (sub) {
  11925. sub.className = 'text-xs mt-0.5 font-mono text-rose-400/80';
  11926. sub.innerText = `Connection failed or timed out to ${escapeHtml(target)}:${port}`;
  11927. }
  11928. if (latency) {
  11929. latency.className = 'text-base font-bold font-mono text-slate-500';
  11930. latency.innerText = '--';
  11931. }
  11932. }
  11933. const rawEl = document.getElementById('tools-port-raw');
  11934. 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'}`);
  11935. showToast('Probe Complete', `Port ${port} is ${data.open ? 'OPEN' : 'CLOSED'}`, data.open ? 'success' : 'warning');
  11936. } catch (err) {
  11937. showToast('Probe Error', err.message, 'error');
  11938. } finally {
  11939. if (btn) btn.disabled = false;
  11940. if (spinner) spinner.classList.add('hidden');
  11941. }
  11942. }
  11943. // ==========================================
  11944. // DHCP CLIENT (/ip dhcp-client) CONTROLLER
  11945. // ==========================================
  11946. async function loadDHCPClients(showToastMsg = false) {
  11947. try {
  11948. const [clientsRes, sumRes] = await Promise.all([
  11949. fetch(`${API_BASE}/dhcp/clients`),
  11950. fetch(`${API_BASE}/dhcp/clients/summary`)
  11951. ]);
  11952. if (clientsRes.ok) {
  11953. state.dhcpClients = await clientsRes.json();
  11954. }
  11955. if (sumRes.ok) {
  11956. state.dhcpSummary = await sumRes.json();
  11957. }
  11958. renderDHCPClients();
  11959. updateDHCPSummaryCards();
  11960. const bDhcp = document.getElementById('badge-dhcp-client-count');
  11961. if (bDhcp && state.dhcpSummary) {
  11962. bDhcp.innerText = state.dhcpSummary.total_clients || 0;
  11963. }
  11964. if (showToastMsg) {
  11965. showToast('Refreshed', 'DHCP Client telemetry updated', 'info');
  11966. }
  11967. } catch (err) {
  11968. console.error('Failed to load DHCP clients:', err);
  11969. if (showToastMsg) {
  11970. showToast('Notice', 'Unable to fetch DHCP client status', 'warning');
  11971. }
  11972. }
  11973. }
  11974. function updateDHCPSummaryCards() {
  11975. const sum = state.dhcpSummary || {
  11976. total_clients: (state.dhcpClients || []).length,
  11977. bound_clients: (state.dhcpClients || []).filter(c => c.status === 'bound').length,
  11978. searching_clients: (state.dhcpClients || []).filter(c => c.status === 'searching').length,
  11979. disabled_clients: (state.dhcpClients || []).filter(c => !c.enabled).length
  11980. };
  11981. const totalEl = document.getElementById('dhcp-stat-total');
  11982. const boundEl = document.getElementById('dhcp-stat-bound');
  11983. const searchEl = document.getElementById('dhcp-stat-searching');
  11984. const disEl = document.getElementById('dhcp-stat-disabled');
  11985. if (totalEl) totalEl.innerText = sum.total_clients ?? 0;
  11986. if (boundEl) boundEl.innerText = sum.bound_clients ?? 0;
  11987. if (searchEl) searchEl.innerText = sum.searching_clients ?? 0;
  11988. if (disEl) disEl.innerText = sum.disabled_clients ?? 0;
  11989. }
  11990. function renderDHCPClients() {
  11991. const tbody = document.getElementById('dhcp-clients-tbody');
  11992. const emptyState = document.getElementById('dhcp-clients-empty');
  11993. if (!tbody) return;
  11994. const clients = Array.isArray(state.dhcpClients) ? state.dhcpClients : [];
  11995. if (clients.length === 0) {
  11996. tbody.innerHTML = '';
  11997. if (emptyState) emptyState.classList.remove('hidden');
  11998. return;
  11999. }
  12000. if (emptyState) emptyState.classList.add('hidden');
  12001. const sig = clients.map(c => `${c.id}:${c.status}:${c.ip_address}:${c.gateway}:${c.enabled}`).join(';');
  12002. if (tbody.dataset.sig === sig) return;
  12003. tbody.dataset.sig = sig;
  12004. tbody.innerHTML = clients.map(c => {
  12005. let statusBadge = '';
  12006. if (!c.enabled) {
  12007. 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>';
  12008. } else if (c.status === 'bound') {
  12009. 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>';
  12010. } else if (c.status === 'searching') {
  12011. 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>';
  12012. } else if (c.status === 'stopped') {
  12013. 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>';
  12014. } else {
  12015. 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>`;
  12016. }
  12017. 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>';
  12018. const gwDisplay = c.gateway ? `<span class="text-slate-300">${escapeHtml(c.gateway)}</span>` : '<span class="text-slate-600">--</span>';
  12019. const srvDisplay = c.dhcp_server ? `<span class="text-slate-300">${escapeHtml(c.dhcp_server)}</span>` : '<span class="text-slate-600">--</span>';
  12020. 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>';
  12021. const expDisplay = c.expires_in ? `<span class="text-purple-300">${escapeHtml(c.expires_in)}</span>` : '<span class="text-slate-600">--</span>';
  12022. // Option flags
  12023. const flags = [];
  12024. 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>');
  12025. 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>');
  12026. 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>');
  12027. 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>`);
  12028. return `
  12029. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 text-xs transition">
  12030. <td class="py-3 px-4">
  12031. <div class="flex items-center gap-2">
  12032. <span class="font-bold text-white text-sm">${escapeHtml(c.interface)}</span>
  12033. ${c.comment ? `<span class="text-[11px] text-slate-400 font-sans italic">(${escapeHtml(c.comment)})</span>` : ''}
  12034. </div>
  12035. </td>
  12036. <td class="py-3 px-4">${statusBadge}</td>
  12037. <td class="py-3 px-4 font-mono">${ipDisplay}</td>
  12038. <td class="py-3 px-4 font-mono">${gwDisplay}</td>
  12039. <td class="py-3 px-4 font-mono">${srvDisplay}</td>
  12040. <td class="py-3 px-4 font-mono text-[11px]">${dnsDisplay}</td>
  12041. <td class="py-3 px-4 font-mono text-[11px]">${expDisplay}</td>
  12042. <td class="py-3 px-4">
  12043. <div class="flex flex-wrap gap-1 font-mono">${flags.join('')}</div>
  12044. </td>
  12045. <td class="py-3 px-4 text-right space-x-1.5 font-sans whitespace-nowrap">
  12046. ${c.enabled ? `
  12047. <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>
  12048. <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>
  12049. <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>
  12050. ` : `
  12051. <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>
  12052. `}
  12053. <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>
  12054. <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>
  12055. </td>
  12056. </tr>
  12057. `;
  12058. }).join('');
  12059. }
  12060. function openDHCPClientModal(clientId = null) {
  12061. const modal = document.getElementById('modal-dhcp-client');
  12062. if (!modal) return;
  12063. const title = document.getElementById('modal-dhcp-title');
  12064. const idInput = document.getElementById('modal-dhcp-id');
  12065. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  12066. const distInput = document.getElementById('modal-dhcp-distance');
  12067. const commentInput = document.getElementById('modal-dhcp-comment');
  12068. const defRouteCheck = document.getElementById('modal-dhcp-def-route');
  12069. const peerDnsCheck = document.getElementById('modal-dhcp-peer-dns');
  12070. const peerNtpCheck = document.getElementById('modal-dhcp-peer-ntp');
  12071. const enabledCheck = document.getElementById('modal-dhcp-enabled');
  12072. // Populate interfaces
  12073. if (ifaceSelect) {
  12074. let opts = '<option value="">Select interface...</option>';
  12075. const allIfaces = state.interfaces || [];
  12076. const allVlans = state.vlans || [];
  12077. const usedIfaces = new Set((state.dhcpClients || []).map(c => c.interface));
  12078. // Group 1: Physical & Bridge Interfaces
  12079. opts += '<optgroup label="Physical & Bridge Interfaces">';
  12080. allIfaces.filter(i => supportsDHCPClient(i)).forEach(i => {
  12081. const isConfigured = usedIfaces.has(i.name) ? ' (Configured)' : '';
  12082. opts += `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)} [${escapeHtml(i.role || i.type)}]${isConfigured}</option>`;
  12083. });
  12084. opts += '</optgroup>';
  12085. // Group 2: VLAN Interfaces
  12086. if (allVlans.length > 0) {
  12087. opts += '<optgroup label="802.1Q VLAN Sub-interfaces">';
  12088. allVlans.forEach(v => {
  12089. const isConfigured = usedIfaces.has(v.name) ? ' (Configured)' : '';
  12090. opts += `<option value="${escapeHtml(v.name)}">${escapeHtml(v.name)} (VLAN ${v.vlan_id})${isConfigured}</option>`;
  12091. });
  12092. opts += '</optgroup>';
  12093. }
  12094. ifaceSelect.innerHTML = opts;
  12095. }
  12096. if (clientId) {
  12097. const client = (state.dhcpClients || []).find(c => c.id === clientId);
  12098. if (client) {
  12099. if (title) title.innerText = `Edit DHCP Client: ${client.interface}`;
  12100. if (idInput) idInput.value = client.id;
  12101. if (ifaceSelect) {
  12102. ifaceSelect.value = client.interface;
  12103. ifaceSelect.disabled = true; // interface cannot be changed on edit
  12104. }
  12105. if (distInput) distInput.value = client.default_route_distance || 1;
  12106. if (commentInput) commentInput.value = client.comment || '';
  12107. if (defRouteCheck) defRouteCheck.checked = client.add_default_route !== false;
  12108. if (peerDnsCheck) peerDnsCheck.checked = client.use_peer_dns !== false;
  12109. if (peerNtpCheck) peerNtpCheck.checked = client.use_peer_ntp !== false;
  12110. if (enabledCheck) enabledCheck.checked = client.enabled !== false;
  12111. }
  12112. } else {
  12113. if (title) title.innerText = 'Add DHCP Client';
  12114. if (idInput) idInput.value = '';
  12115. if (ifaceSelect) {
  12116. ifaceSelect.value = '';
  12117. ifaceSelect.disabled = false;
  12118. }
  12119. if (distInput) distInput.value = 1;
  12120. if (commentInput) commentInput.value = '';
  12121. if (defRouteCheck) defRouteCheck.checked = true;
  12122. if (peerDnsCheck) peerDnsCheck.checked = true;
  12123. if (peerNtpCheck) peerNtpCheck.checked = true;
  12124. if (enabledCheck) enabledCheck.checked = true;
  12125. }
  12126. modal.classList.remove('hidden');
  12127. }
  12128. function openDHCPClientModalForIface(ifaceName) {
  12129. openDHCPClientModal();
  12130. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  12131. if (ifaceSelect && ifaceName) {
  12132. ifaceSelect.value = ifaceName;
  12133. }
  12134. }
  12135. function closeDHCPClientModal() {
  12136. const modal = document.getElementById('modal-dhcp-client');
  12137. if (modal) modal.classList.add('hidden');
  12138. }
  12139. async function submitSaveDHCPClient(e) {
  12140. if (e) e.preventDefault();
  12141. const id = document.getElementById('modal-dhcp-id')?.value;
  12142. const iface = document.getElementById('modal-dhcp-iface')?.value?.trim();
  12143. const distance = parseInt(document.getElementById('modal-dhcp-distance')?.value || '1', 10);
  12144. const comment = document.getElementById('modal-dhcp-comment')?.value?.trim() || '';
  12145. const defRoute = document.getElementById('modal-dhcp-def-route')?.checked ?? true;
  12146. const peerDns = document.getElementById('modal-dhcp-peer-dns')?.checked ?? true;
  12147. const peerNtp = document.getElementById('modal-dhcp-peer-ntp')?.checked ?? true;
  12148. const enabled = document.getElementById('modal-dhcp-enabled')?.checked ?? true;
  12149. if (!id && !iface) {
  12150. showToast('Input Required', 'Please select an interface for the DHCP client', 'warning');
  12151. return;
  12152. }
  12153. try {
  12154. let res;
  12155. if (id) {
  12156. // PUT update
  12157. res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  12158. method: 'PUT',
  12159. headers: { 'Content-Type': 'application/json' },
  12160. body: JSON.stringify({
  12161. enabled,
  12162. add_default_route: defRoute,
  12163. default_route_distance: distance,
  12164. use_peer_dns: peerDns,
  12165. use_peer_ntp: peerNtp,
  12166. comment
  12167. })
  12168. });
  12169. } else {
  12170. // POST create
  12171. res = await fetch(`${API_BASE}/dhcp/clients`, {
  12172. method: 'POST',
  12173. headers: { 'Content-Type': 'application/json' },
  12174. body: JSON.stringify({
  12175. interface: iface,
  12176. enabled,
  12177. add_default_route: defRoute,
  12178. default_route_distance: distance,
  12179. use_peer_dns: peerDns,
  12180. use_peer_ntp: peerNtp,
  12181. comment
  12182. })
  12183. });
  12184. }
  12185. const data = await res.json();
  12186. if (!res.ok) {
  12187. showToast('Error', data.error || 'Failed to save DHCP client', 'error');
  12188. return;
  12189. }
  12190. closeDHCPClientModal();
  12191. showToast('Success', id ? 'DHCP Client updated successfully' : `DHCP Client activated on ${iface}`, 'success');
  12192. await loadDHCPClients();
  12193. fetchData(); // refresh interfaces list with new lease/status
  12194. } catch (err) {
  12195. showToast('Error', err.message, 'error');
  12196. }
  12197. }
  12198. async function toggleDHCPClientState(id, enabled) {
  12199. try {
  12200. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/state`, {
  12201. method: 'POST',
  12202. headers: { 'Content-Type': 'application/json' },
  12203. body: JSON.stringify({ enabled })
  12204. });
  12205. const data = await res.json();
  12206. if (!res.ok) {
  12207. showToast('Error', data.error || 'Failed to toggle client state', 'error');
  12208. return;
  12209. }
  12210. showToast('Updated', `DHCP client ${enabled ? 'enabled' : 'disabled'}`, 'info');
  12211. await loadDHCPClients();
  12212. fetchData();
  12213. } catch (err) {
  12214. showToast('Error', err.message, 'error');
  12215. }
  12216. }
  12217. async function renewDHCPClient(id) {
  12218. try {
  12219. showToast('Renewing...', 'Requesting DHCP lease renewal from upstream server', 'info');
  12220. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/renew`, {
  12221. method: 'POST'
  12222. });
  12223. const data = await res.json();
  12224. if (!res.ok) {
  12225. showToast('Error', data.error || 'Failed to renew lease', 'error');
  12226. return;
  12227. }
  12228. showToast('Lease Renewed', 'DHCP renewal signal sent successfully', 'success');
  12229. setTimeout(() => {
  12230. loadDHCPClients();
  12231. fetchData();
  12232. }, 1500);
  12233. } catch (err) {
  12234. showToast('Error', err.message, 'error');
  12235. }
  12236. }
  12237. async function releaseDHCPClient(id) {
  12238. try {
  12239. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/release`, {
  12240. method: 'POST'
  12241. });
  12242. const data = await res.json();
  12243. if (!res.ok) {
  12244. showToast('Error', data.error || 'Failed to release lease', 'error');
  12245. return;
  12246. }
  12247. showToast('Lease Released', 'DHCP lease released from upstream server', 'info');
  12248. await loadDHCPClients();
  12249. fetchData();
  12250. } catch (err) {
  12251. showToast('Error', err.message, 'error');
  12252. }
  12253. }
  12254. async function deleteDHCPClient(id, ifaceName) {
  12255. if (!confirm(`Are you sure you want to remove the DHCP Client on ${ifaceName}? The interface will release its dynamic IP.`)) {
  12256. return;
  12257. }
  12258. try {
  12259. const res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  12260. method: 'DELETE'
  12261. });
  12262. const data = await res.json();
  12263. if (!res.ok) {
  12264. showToast('Error', data.error || 'Failed to delete DHCP client', 'error');
  12265. return;
  12266. }
  12267. showToast('Deleted', `DHCP client removed from ${ifaceName}`, 'info');
  12268. await loadDHCPClients();
  12269. fetchData();
  12270. } catch (err) {
  12271. showToast('Error', err.message, 'error');
  12272. }
  12273. }
  12274. // ==================== DHCP SERVER (/ip dhcp-server) ====================
  12275. async function loadDHCPServer(populate = true) {
  12276. try {
  12277. const [sumRes, srvRes, netRes, leaseRes, optRes] = await Promise.all([
  12278. fetch(`${API_BASE}/dhcp-server/summary`),
  12279. fetch(`${API_BASE}/dhcp-server/servers`),
  12280. fetch(`${API_BASE}/dhcp-server/networks`),
  12281. fetch(`${API_BASE}/dhcp-server/leases`),
  12282. fetch(`${API_BASE}/dhcp-server/options`)
  12283. ]);
  12284. if (sumRes.ok) state.dhcpServerSummary = await sumRes.json();
  12285. if (srvRes.ok) state.dhcpServers = await srvRes.json();
  12286. if (netRes.ok) state.dhcpNetworks = await netRes.json();
  12287. if (leaseRes.ok) state.dhcpLeases = await leaseRes.json();
  12288. if (optRes.ok) state.dhcpOptions = await optRes.json();
  12289. const sum = state.dhcpServerSummary || {};
  12290. const srvs = state.dhcpServers || [];
  12291. const nets = state.dhcpNetworks || [];
  12292. const leases = state.dhcpLeases || [];
  12293. const opts = state.dhcpOptions || [];
  12294. // KPI Cards
  12295. const statActive = document.getElementById('dhcp-server-stat-active');
  12296. if (statActive) {
  12297. const activeCount = srvs.filter(s => s.running).length;
  12298. statActive.innerText = `${activeCount} / ${srvs.length}`;
  12299. }
  12300. const statLeases = document.getElementById('dhcp-server-stat-leases');
  12301. if (statLeases) {
  12302. statLeases.innerText = leases.length;
  12303. }
  12304. const statLeasesSub = document.getElementById('dhcp-server-stat-leases-sub');
  12305. if (statLeasesSub) {
  12306. const dyn = leases.filter(l => l.dynamic).length;
  12307. const st = leases.filter(l => !l.dynamic).length;
  12308. statLeasesSub.innerText = `${dyn} dynamic, ${st} static`;
  12309. }
  12310. const statNetworks = document.getElementById('dhcp-server-stat-networks');
  12311. if (statNetworks) {
  12312. statNetworks.innerText = nets.length;
  12313. }
  12314. // Subtab Badges
  12315. const bSrv = document.getElementById('dhcp-server-tab-badge-servers');
  12316. if (bSrv) bSrv.innerText = srvs.length;
  12317. const bNet = document.getElementById('dhcp-server-tab-badge-networks');
  12318. if (bNet) bNet.innerText = nets.length;
  12319. const bLease = document.getElementById('dhcp-server-tab-badge-leases');
  12320. if (bLease) bLease.innerText = leases.length;
  12321. const bOpt = document.getElementById('dhcp-server-tab-badge-options');
  12322. if (bOpt) bOpt.innerText = opts.length;
  12323. // Sidebar Badge
  12324. const sideBadge = document.getElementById('badge-dhcp-server-count');
  12325. if (sideBadge) sideBadge.innerText = leases.length || srvs.length;
  12326. renderCurrentDHCPServerTab();
  12327. } catch (err) {
  12328. console.error('Failed to load DHCP Server:', err);
  12329. }
  12330. }
  12331. function switchDHCPServerTab(tab) {
  12332. state.dhcpServerTab = tab;
  12333. const tabs = ['servers', 'networks', 'leases', 'options'];
  12334. tabs.forEach(t => {
  12335. const panel = document.getElementById(`dhcp-server-subtab-${t}`);
  12336. const btn = document.getElementById(`dhcp-server-tab-btn-${t}`);
  12337. if (panel) {
  12338. if (t === tab) panel.classList.remove('hidden');
  12339. else panel.classList.add('hidden');
  12340. }
  12341. if (btn) {
  12342. if (t === tab) {
  12343. 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';
  12344. } else {
  12345. 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';
  12346. }
  12347. }
  12348. });
  12349. const addBtn = document.getElementById('dhcp-server-primary-add-btn');
  12350. if (addBtn) {
  12351. if (tab === 'servers') addBtn.innerHTML = '<span>+ Add Server</span>';
  12352. else if (tab === 'networks') addBtn.innerHTML = '<span>+ Add Network</span>';
  12353. else if (tab === 'leases') addBtn.innerHTML = '<span>+ Add Static Lease</span>';
  12354. else if (tab === 'options') addBtn.innerHTML = '<span>+ Add Option</span>';
  12355. }
  12356. renderCurrentDHCPServerTab();
  12357. }
  12358. function handleDHCPServerPrimaryAdd() {
  12359. const tab = state.dhcpServerTab || 'servers';
  12360. if (tab === 'servers') openAddDHCPServerModal();
  12361. else if (tab === 'networks') openAddDHCPNetworkModal();
  12362. else if (tab === 'leases') openAddDHCPStaticLeaseModal();
  12363. else if (tab === 'options') openAddDHCPOptionModal();
  12364. }
  12365. function renderCurrentDHCPServerTab() {
  12366. const tab = state.dhcpServerTab || 'servers';
  12367. if (tab === 'servers') renderDHCPServers();
  12368. else if (tab === 'networks') renderDHCPNetworks();
  12369. else if (tab === 'leases') renderDHCPLeases();
  12370. else if (tab === 'options') renderDHCPOptions();
  12371. }
  12372. function renderDHCPServers() {
  12373. const tbody = document.getElementById('dhcp-server-tbody');
  12374. const empty = document.getElementById('dhcp-server-empty');
  12375. if (!tbody) return;
  12376. const servers = state.dhcpServers || [];
  12377. if (servers.length === 0) {
  12378. tbody.innerHTML = '';
  12379. empty?.classList.remove('hidden');
  12380. return;
  12381. }
  12382. empty?.classList.add('hidden');
  12383. const sig = servers.map(s => `${s.id}:${s.running}:${s.disabled}:${s.active_leases}:${s.interface}`).join(';');
  12384. if (tbody.dataset.sig === sig) return;
  12385. tbody.dataset.sig = sig;
  12386. tbody.innerHTML = '';
  12387. servers.forEach(s => {
  12388. const tr = document.createElement('tr');
  12389. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  12390. tr.innerHTML = `
  12391. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(s.running, s.disabled)}</td>
  12392. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(s.name)}</td>
  12393. <td class="py-2.5 px-3 font-mono text-cyan-400 font-semibold">${escapeHtml(s.interface)}</td>
  12394. <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>
  12395. <td class="py-2.5 px-3 font-mono text-emerald-400">${escapeHtml(s.address_pool)}</td>
  12396. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(s.lease_time || '12h')}</td>
  12397. <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>
  12398. <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>
  12399. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]" title="${escapeHtml(s.comment || '')}">${escapeHtml(s.comment || '-')}</td>
  12400. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  12401. <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>
  12402. <button onclick="openEditDHCPServerModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  12403. <button onclick="deleteDHCPServer('${s.id}', '${escapeHtml(s.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  12404. </td>
  12405. `;
  12406. tbody.appendChild(tr);
  12407. });
  12408. }
  12409. function renderDHCPNetworks() {
  12410. const tbody = document.getElementById('dhcp-networks-tbody');
  12411. const empty = document.getElementById('dhcp-networks-empty');
  12412. if (!tbody) return;
  12413. tbody.innerHTML = '';
  12414. const networks = state.dhcpNetworks || [];
  12415. if (networks.length === 0) {
  12416. empty?.classList.remove('hidden');
  12417. return;
  12418. }
  12419. empty?.classList.add('hidden');
  12420. networks.forEach(n => {
  12421. const tr = document.createElement('tr');
  12422. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  12423. const dnsStr = (n.dns_servers || []).join(', ') || '-';
  12424. const optionsChips = (n.dhcp_options || []).map(optId => {
  12425. const opt = (state.dhcpOptions || []).find(o => o.id === optId);
  12426. if (!opt) return '';
  12427. 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>`;
  12428. }).filter(Boolean).join('');
  12429. tr.innerHTML = `
  12430. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${escapeHtml(n.address)}</td>
  12431. <td class="py-2.5 px-3 font-mono text-cyan-300 font-semibold">${escapeHtml(n.gateway || '-')}</td>
  12432. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(n.netmask || '-')}</td>
  12433. <td class="py-2.5 px-3 font-mono text-slate-300 truncate max-w-[140px]" title="${escapeHtml(dnsStr)}">${escapeHtml(dnsStr)}</td>
  12434. <td class="py-2.5 px-3 font-mono text-slate-400">${escapeHtml(n.domain || '-')}</td>
  12435. <td class="py-2.5 px-3 font-mono">${optionsChips || '<span class="text-slate-600 font-sans">-</span>'}</td>
  12436. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(n.comment || '')}">${escapeHtml(n.comment || '-')}</td>
  12437. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  12438. <button onclick="openEditDHCPNetworkModal('${n.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  12439. <button onclick="deleteDHCPNetwork('${n.id}', '${escapeHtml(n.address)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  12440. </td>
  12441. `;
  12442. tbody.appendChild(tr);
  12443. });
  12444. }
  12445. function renderDHCPLeases() {
  12446. const tbody = document.getElementById('dhcp-leases-tbody');
  12447. const empty = document.getElementById('dhcp-leases-empty');
  12448. if (!tbody) return;
  12449. tbody.innerHTML = '';
  12450. const leases = state.dhcpLeases || [];
  12451. if (leases.length === 0) {
  12452. empty?.classList.remove('hidden');
  12453. return;
  12454. }
  12455. empty?.classList.add('hidden');
  12456. leases.forEach(l => {
  12457. const tr = document.createElement('tr');
  12458. tr.className = `hover:bg-slate-800/40 transition text-xs ${l.disabled ? 'opacity-50' : ''}`;
  12459. 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>';
  12460. const statusBadge = l.status === 'bound'
  12461. ? '<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>'
  12462. : l.status === 'static'
  12463. ? '<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>'
  12464. : '<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>';
  12465. const makeStaticBtn = l.dynamic
  12466. ? `<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>`
  12467. : `<button onclick="deleteDHCPStaticLease('${l.id}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Remove</button>`;
  12468. tr.innerHTML = `
  12469. <td class="py-2.5 px-3 text-center">${flag}</td>
  12470. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(l.address)}</td>
  12471. <td class="py-2.5 px-3 font-mono text-cyan-300">${escapeHtml(l.mac_address)}</td>
  12472. <td class="py-2.5 px-3 font-sans text-slate-200 font-medium">${escapeHtml(l.hostname || '*')}</td>
  12473. <td class="py-2.5 px-3 font-mono text-slate-400">${escapeHtml(l.server || 'all')}</td>
  12474. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(l.expires_in || 'never')}</td>
  12475. <td class="py-2.5 px-3">${statusBadge}</td>
  12476. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(l.comment || '')}">${escapeHtml(l.comment || '-')}</td>
  12477. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  12478. ${makeStaticBtn}
  12479. </td>
  12480. `;
  12481. tbody.appendChild(tr);
  12482. });
  12483. }
  12484. function renderDHCPOptions() {
  12485. const tbody = document.getElementById('dhcp-options-tbody');
  12486. const empty = document.getElementById('dhcp-options-empty');
  12487. if (!tbody) return;
  12488. tbody.innerHTML = '';
  12489. const options = state.dhcpOptions || [];
  12490. if (options.length === 0) {
  12491. empty?.classList.remove('hidden');
  12492. return;
  12493. }
  12494. empty?.classList.add('hidden');
  12495. options.forEach(o => {
  12496. const tr = document.createElement('tr');
  12497. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  12498. tr.innerHTML = `
  12499. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(o.name)}</td>
  12500. <td class="py-2.5 px-3 font-bold text-cyan-400 font-mono">${o.code}</td>
  12501. <td class="py-2.5 px-3 font-mono text-emerald-400 break-all max-w-xs">${escapeHtml(o.value)}</td>
  12502. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-xs" title="${escapeHtml(o.comment || '')}">${escapeHtml(o.comment || '-')}</td>
  12503. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  12504. <button onclick="openEditDHCPOptionModal('${o.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  12505. <button onclick="deleteDHCPOption('${o.id}', '${escapeHtml(o.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  12506. </td>
  12507. `;
  12508. tbody.appendChild(tr);
  12509. });
  12510. }
  12511. // ==================== MODALS & ACTIONS: SERVER ====================
  12512. function populateDHCPNetworkSelect(elemId, selectedVal) {
  12513. const sel = document.getElementById(elemId);
  12514. if (!sel) return;
  12515. sel.innerHTML = '<option value="">Select network subnet...</option>';
  12516. const networks = state.dhcpNetworks || [];
  12517. networks.forEach(n => {
  12518. const opt = document.createElement('option');
  12519. opt.value = n.address;
  12520. opt.innerText = `${n.address} (Gateway: ${n.gateway || 'None'}${n.comment ? ' - ' + n.comment : ''})`;
  12521. if (selectedVal && (selectedVal === n.address || selectedVal === n.id)) {
  12522. opt.selected = true;
  12523. }
  12524. sel.appendChild(opt);
  12525. });
  12526. }
  12527. function onDHCPServerNetworkChange() {
  12528. const netSel = document.getElementById('dhcp-server-modal-network');
  12529. if (!netSel) return;
  12530. const netVal = netSel.value;
  12531. if (!netVal) return;
  12532. const poolInput = document.getElementById('dhcp-server-modal-pool');
  12533. if (!poolInput) return;
  12534. // Auto-calculate suggested address pool based on subnet CIDR
  12535. const parts = netVal.split('/');
  12536. const ip = parts[0];
  12537. const cidr = parseInt(parts[1] || '24', 10);
  12538. if (cidr === 24) {
  12539. const octets = ip.split('.');
  12540. if (octets.length === 4) {
  12541. const base = `${octets[0]}.${octets[1]}.${octets[2]}`;
  12542. poolInput.value = `${base}.10-${base}.254`;
  12543. }
  12544. }
  12545. }
  12546. function openAddDHCPServerModal() {
  12547. document.getElementById('dhcp-server-modal-title').innerText = 'Add DHCP Server';
  12548. document.getElementById('dhcp-server-modal-id').value = '';
  12549. document.getElementById('dhcp-server-modal-name').value = `dhcp${(state.dhcpServers || []).length + 1}`;
  12550. document.getElementById('dhcp-server-modal-pool').value = '192.168.88.10-192.168.88.254';
  12551. document.getElementById('dhcp-server-modal-leasetime').value = '12h';
  12552. document.getElementById('dhcp-server-modal-comment').value = '';
  12553. document.getElementById('dhcp-server-modal-authoritative').checked = true;
  12554. document.getElementById('dhcp-server-modal-disabled').checked = false;
  12555. populateDHCPIfaceSelect('dhcp-server-modal-iface', '');
  12556. const networks = state.dhcpNetworks || [];
  12557. const defaultNet = networks.length > 0 ? networks[0].address : '';
  12558. populateDHCPNetworkSelect('dhcp-server-modal-network', defaultNet);
  12559. if (defaultNet) {
  12560. onDHCPServerNetworkChange();
  12561. }
  12562. document.getElementById('dhcp-server-instance-modal').classList.remove('hidden');
  12563. }
  12564. function openEditDHCPServerModal(id) {
  12565. const s = (state.dhcpServers || []).find(item => item.id === id);
  12566. if (!s) return;
  12567. document.getElementById('dhcp-server-modal-title').innerText = `Edit DHCP Server (${s.name})`;
  12568. document.getElementById('dhcp-server-modal-id').value = s.id;
  12569. document.getElementById('dhcp-server-modal-name').value = s.name;
  12570. document.getElementById('dhcp-server-modal-pool').value = s.address_pool;
  12571. document.getElementById('dhcp-server-modal-leasetime').value = s.lease_time || '12h';
  12572. document.getElementById('dhcp-server-modal-comment').value = s.comment || '';
  12573. document.getElementById('dhcp-server-modal-authoritative').checked = s.authoritative !== false;
  12574. document.getElementById('dhcp-server-modal-disabled').checked = !!s.disabled;
  12575. populateDHCPIfaceSelect('dhcp-server-modal-iface', s.interface);
  12576. populateDHCPNetworkSelect('dhcp-server-modal-network', s.network || '');
  12577. document.getElementById('dhcp-server-instance-modal').classList.remove('hidden');
  12578. }
  12579. function closeDHCPServerModal() {
  12580. document.getElementById('dhcp-server-instance-modal').classList.add('hidden');
  12581. }
  12582. async function submitSaveDHCPServer(e) {
  12583. e.preventDefault();
  12584. const id = document.getElementById('dhcp-server-modal-id').value;
  12585. const name = document.getElementById('dhcp-server-modal-name').value.trim();
  12586. const iface = document.getElementById('dhcp-server-modal-iface').value;
  12587. const network = document.getElementById('dhcp-server-modal-network').value.trim();
  12588. const pool = document.getElementById('dhcp-server-modal-pool').value.trim();
  12589. const leaseTime = document.getElementById('dhcp-server-modal-leasetime').value.trim() || '12h';
  12590. const comment = document.getElementById('dhcp-server-modal-comment').value.trim();
  12591. const authoritative = document.getElementById('dhcp-server-modal-authoritative').checked;
  12592. const disabled = document.getElementById('dhcp-server-modal-disabled').checked;
  12593. try {
  12594. const res = await fetch(`${API_BASE}/dhcp-server/servers`, {
  12595. method: 'POST',
  12596. headers: { 'Content-Type': 'application/json' },
  12597. body: JSON.stringify({
  12598. id,
  12599. name,
  12600. interface: iface,
  12601. network,
  12602. address_pool: pool,
  12603. lease_time: leaseTime,
  12604. authoritative,
  12605. disabled,
  12606. comment
  12607. })
  12608. });
  12609. if (res.ok) {
  12610. showToast('DHCP Server Saved', `Server ${name} configured successfully`, 'success');
  12611. closeDHCPServerModal();
  12612. loadDHCPServer(false);
  12613. fetchData(false);
  12614. } else {
  12615. const err = await res.text();
  12616. showToast('Error', err, 'error');
  12617. }
  12618. } catch (err) {
  12619. showToast('Error', err.message, 'error');
  12620. }
  12621. }
  12622. async function toggleDHCPServerState(id, disabled) {
  12623. try {
  12624. const res = await fetch(`${API_BASE}/dhcp-server/servers/${encodeURIComponent(id)}/state`, {
  12625. method: 'POST',
  12626. headers: { 'Content-Type': 'application/json' },
  12627. body: JSON.stringify({ disabled })
  12628. });
  12629. if (res.ok) {
  12630. showToast('State Updated', disabled ? 'Server disabled' : 'Server enabled', 'info');
  12631. loadDHCPServer(false);
  12632. fetchData(false);
  12633. }
  12634. } catch (err) {
  12635. showToast('Error', err.message, 'error');
  12636. }
  12637. }
  12638. async function deleteDHCPServer(id, name) {
  12639. if (!confirm(`Are you sure you want to delete DHCP Server "${name}"?`)) return;
  12640. try {
  12641. const res = await fetch(`${API_BASE}/dhcp-server/servers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12642. if (res.ok) {
  12643. showToast('Deleted', `DHCP Server ${name} removed`, 'success');
  12644. loadDHCPServer(false);
  12645. fetchData(false);
  12646. }
  12647. } catch (err) {
  12648. showToast('Error', err.message, 'error');
  12649. }
  12650. }
  12651. // ==================== MODALS & ACTIONS: NETWORKS ====================
  12652. function openAddDHCPNetworkModal() {
  12653. document.getElementById('dhcp-network-modal-title').innerText = 'Add DHCP Network';
  12654. document.getElementById('dhcp-network-modal-id').value = '';
  12655. document.getElementById('dhcp-network-modal-address').value = '192.168.88.0/24';
  12656. document.getElementById('dhcp-network-modal-gateway').value = '192.168.88.1';
  12657. document.getElementById('dhcp-network-modal-dns').value = '192.168.88.1, 1.1.1.1, 8.8.8.8';
  12658. document.getElementById('dhcp-network-modal-domain').value = 'lan';
  12659. document.getElementById('dhcp-network-modal-netmask').value = '';
  12660. document.getElementById('dhcp-network-modal-comment').value = '';
  12661. renderDHCPNetworkOptionsCheckboxes([]);
  12662. document.getElementById('dhcp-network-modal').classList.remove('hidden');
  12663. }
  12664. function openEditDHCPNetworkModal(id) {
  12665. const n = (state.dhcpNetworks || []).find(item => item.id === id);
  12666. if (!n) return;
  12667. document.getElementById('dhcp-network-modal-title').innerText = `Edit DHCP Network (${n.address})`;
  12668. document.getElementById('dhcp-network-modal-id').value = n.id;
  12669. document.getElementById('dhcp-network-modal-address').value = n.address;
  12670. document.getElementById('dhcp-network-modal-gateway').value = n.gateway || '';
  12671. document.getElementById('dhcp-network-modal-dns').value = (n.dns_servers || []).join(', ');
  12672. document.getElementById('dhcp-network-modal-domain').value = n.domain || '';
  12673. document.getElementById('dhcp-network-modal-netmask').value = n.netmask || '';
  12674. document.getElementById('dhcp-network-modal-comment').value = n.comment || '';
  12675. renderDHCPNetworkOptionsCheckboxes(n.dhcp_options || []);
  12676. document.getElementById('dhcp-network-modal').classList.remove('hidden');
  12677. }
  12678. function renderDHCPNetworkOptionsCheckboxes(selectedIds) {
  12679. const container = document.getElementById('dhcp-network-modal-options-list');
  12680. if (!container) return;
  12681. container.innerHTML = '';
  12682. const opts = state.dhcpOptions || [];
  12683. if (opts.length === 0) {
  12684. container.innerHTML = '<span class="text-slate-500 text-[11px] col-span-2">No custom options configured. Add some in the "Options" tab.</span>';
  12685. return;
  12686. }
  12687. opts.forEach(o => {
  12688. const isChecked = selectedIds.includes(o.id);
  12689. const label = document.createElement('label');
  12690. label.className = 'flex items-center space-x-2 text-slate-300 hover:text-white cursor-pointer';
  12691. label.innerHTML = `
  12692. <input type="checkbox" name="dhcp-net-opt" value="${o.id}" ${isChecked ? 'checked' : ''} class="rounded bg-slate-800 border-slate-700 text-emerald-600">
  12693. <span class="truncate" title="${escapeHtml(o.name)} (Code ${o.code})">${escapeHtml(o.name)} <span class="text-cyan-400">#${o.code}</span></span>
  12694. `;
  12695. container.appendChild(label);
  12696. });
  12697. }
  12698. function closeDHCPNetworkModal() {
  12699. document.getElementById('dhcp-network-modal').classList.add('hidden');
  12700. }
  12701. async function submitSaveDHCPNetwork(e) {
  12702. e.preventDefault();
  12703. const id = document.getElementById('dhcp-network-modal-id').value;
  12704. const address = document.getElementById('dhcp-network-modal-address').value.trim();
  12705. const gateway = document.getElementById('dhcp-network-modal-gateway').value.trim();
  12706. const dnsStr = document.getElementById('dhcp-network-modal-dns').value.trim();
  12707. const domain = document.getElementById('dhcp-network-modal-domain').value.trim();
  12708. const netmask = document.getElementById('dhcp-network-modal-netmask').value.trim();
  12709. const comment = document.getElementById('dhcp-network-modal-comment').value.trim();
  12710. const selectedOpts = [];
  12711. document.querySelectorAll('input[name="dhcp-net-opt"]:checked').forEach(cb => selectedOpts.push(cb.value));
  12712. const dnsServers = dnsStr ? dnsStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  12713. try {
  12714. const res = await fetch(`${API_BASE}/dhcp-server/networks`, {
  12715. method: 'POST',
  12716. headers: { 'Content-Type': 'application/json' },
  12717. body: JSON.stringify({
  12718. id,
  12719. address,
  12720. gateway,
  12721. netmask,
  12722. dns_servers: dnsServers,
  12723. domain,
  12724. dhcp_options: selectedOpts,
  12725. comment
  12726. })
  12727. });
  12728. if (res.ok) {
  12729. showToast('Network Saved', `Subnet ${address} configured successfully`, 'success');
  12730. closeDHCPNetworkModal();
  12731. loadDHCPServer(false);
  12732. fetchData(false);
  12733. } else {
  12734. const err = await res.text();
  12735. showToast('Error', err, 'error');
  12736. }
  12737. } catch (err) {
  12738. showToast('Error', err.message, 'error');
  12739. }
  12740. }
  12741. async function deleteDHCPNetwork(id, addr) {
  12742. if (!confirm(`Are you sure you want to delete DHCP Network "${addr}"?`)) return;
  12743. try {
  12744. const res = await fetch(`${API_BASE}/dhcp-server/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12745. if (res.ok) {
  12746. showToast('Deleted', `Network ${addr} removed`, 'success');
  12747. loadDHCPServer(false);
  12748. fetchData(false);
  12749. }
  12750. } catch (err) {
  12751. showToast('Error', err.message, 'error');
  12752. }
  12753. }
  12754. // ==================== MODALS & ACTIONS: LEASES ====================
  12755. function openAddDHCPStaticLeaseModal() {
  12756. document.getElementById('dhcp-static-lease-modal-title').innerText = 'Add Static Lease Reservation';
  12757. document.getElementById('dhcp-static-lease-modal-id').value = '';
  12758. document.getElementById('dhcp-static-lease-modal-mac').value = '';
  12759. document.getElementById('dhcp-static-lease-modal-ip').value = '';
  12760. document.getElementById('dhcp-static-lease-modal-hostname').value = '';
  12761. document.getElementById('dhcp-static-lease-modal-server').value = 'all';
  12762. document.getElementById('dhcp-static-lease-modal-comment').value = '';
  12763. document.getElementById('dhcp-static-lease-modal-disabled').checked = false;
  12764. document.getElementById('dhcp-static-lease-modal').classList.remove('hidden');
  12765. }
  12766. function closeDHCPStaticLeaseModal() {
  12767. document.getElementById('dhcp-static-lease-modal').classList.add('hidden');
  12768. }
  12769. async function submitSaveDHCPStaticLease(e) {
  12770. e.preventDefault();
  12771. const id = document.getElementById('dhcp-static-lease-modal-id').value;
  12772. const mac = document.getElementById('dhcp-static-lease-modal-mac').value.trim();
  12773. const ip = document.getElementById('dhcp-static-lease-modal-ip').value.trim();
  12774. const hostname = document.getElementById('dhcp-static-lease-modal-hostname').value.trim();
  12775. const server = document.getElementById('dhcp-static-lease-modal-server').value.trim() || 'all';
  12776. const comment = document.getElementById('dhcp-static-lease-modal-comment').value.trim();
  12777. const disabled = document.getElementById('dhcp-static-lease-modal-disabled').checked;
  12778. try {
  12779. const res = await fetch(`${API_BASE}/dhcp-server/leases/static`, {
  12780. method: 'POST',
  12781. headers: { 'Content-Type': 'application/json' },
  12782. body: JSON.stringify({
  12783. id,
  12784. mac_address: mac,
  12785. address: ip,
  12786. hostname,
  12787. server,
  12788. comment,
  12789. disabled
  12790. })
  12791. });
  12792. if (res.ok) {
  12793. showToast('Static Lease Saved', `IP ${ip} reserved for ${mac}`, 'success');
  12794. closeDHCPStaticLeaseModal();
  12795. loadDHCPServer(false);
  12796. fetchData(false);
  12797. } else {
  12798. const err = await res.text();
  12799. showToast('Error', err, 'error');
  12800. }
  12801. } catch (err) {
  12802. showToast('Error', err.message, 'error');
  12803. }
  12804. }
  12805. async function deleteDHCPStaticLease(id) {
  12806. if (!confirm('Are you sure you want to remove this static reservation?')) return;
  12807. try {
  12808. const res = await fetch(`${API_BASE}/dhcp-server/leases/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12809. if (res.ok) {
  12810. showToast('Deleted', 'Static lease removed', 'success');
  12811. loadDHCPServer(false);
  12812. fetchData(false);
  12813. }
  12814. } catch (err) {
  12815. showToast('Error', err.message, 'error');
  12816. }
  12817. }
  12818. async function makeDHCPLeaseStatic(mac, ip, hostname, comment) {
  12819. try {
  12820. const res = await fetch(`${API_BASE}/dhcp-server/leases/make-static`, {
  12821. method: 'POST',
  12822. headers: { 'Content-Type': 'application/json' },
  12823. body: JSON.stringify({
  12824. mac_address: mac,
  12825. address: ip,
  12826. hostname,
  12827. comment: comment || 'Converted to static'
  12828. })
  12829. });
  12830. if (res.ok) {
  12831. showToast('Lease Made Static', `IP ${ip} permanently reserved for ${mac}`, 'success');
  12832. loadDHCPServer(false);
  12833. fetchData(false);
  12834. } else {
  12835. const err = await res.text();
  12836. showToast('Error', err, 'error');
  12837. }
  12838. } catch (err) {
  12839. showToast('Error', err.message, 'error');
  12840. }
  12841. }
  12842. // ==================== MODALS & ACTIONS: OPTIONS ====================
  12843. function openAddDHCPOptionModal() {
  12844. document.getElementById('dhcp-option-modal-title').innerText = 'Add DHCP Option';
  12845. document.getElementById('dhcp-option-modal-id').value = '';
  12846. document.getElementById('dhcp-option-modal-name').value = '';
  12847. document.getElementById('dhcp-option-modal-code').value = '';
  12848. document.getElementById('dhcp-option-modal-value').value = '';
  12849. document.getElementById('dhcp-option-modal-comment').value = '';
  12850. document.getElementById('dhcp-option-modal').classList.remove('hidden');
  12851. }
  12852. function openEditDHCPOptionModal(id) {
  12853. const o = (state.dhcpOptions || []).find(item => item.id === id);
  12854. if (!o) return;
  12855. document.getElementById('dhcp-option-modal-title').innerText = `Edit DHCP Option (${o.name})`;
  12856. document.getElementById('dhcp-option-modal-id').value = o.id;
  12857. document.getElementById('dhcp-option-modal-name').value = o.name;
  12858. document.getElementById('dhcp-option-modal-code').value = o.code;
  12859. document.getElementById('dhcp-option-modal-value').value = o.value;
  12860. document.getElementById('dhcp-option-modal-comment').value = o.comment || '';
  12861. document.getElementById('dhcp-option-modal').classList.remove('hidden');
  12862. }
  12863. function closeDHCPOptionModal() {
  12864. document.getElementById('dhcp-option-modal').classList.add('hidden');
  12865. }
  12866. async function submitSaveDHCPOption(e) {
  12867. e.preventDefault();
  12868. const id = document.getElementById('dhcp-option-modal-id').value;
  12869. const name = document.getElementById('dhcp-option-modal-name').value.trim();
  12870. const code = parseInt(document.getElementById('dhcp-option-modal-code').value);
  12871. const value = document.getElementById('dhcp-option-modal-value').value.trim();
  12872. const comment = document.getElementById('dhcp-option-modal-comment').value.trim();
  12873. try {
  12874. const res = await fetch(`${API_BASE}/dhcp-server/options`, {
  12875. method: 'POST',
  12876. headers: { 'Content-Type': 'application/json' },
  12877. body: JSON.stringify({ id, name, code, value, comment })
  12878. });
  12879. if (res.ok) {
  12880. showToast('Option Saved', `DHCP option ${name} (#${code}) configured`, 'success');
  12881. closeDHCPOptionModal();
  12882. loadDHCPServer(false);
  12883. fetchData(false);
  12884. } else {
  12885. const err = await res.text();
  12886. showToast('Error', err, 'error');
  12887. }
  12888. } catch (err) {
  12889. showToast('Error', err.message, 'error');
  12890. }
  12891. }
  12892. async function deleteDHCPOption(id, name) {
  12893. if (!confirm(`Are you sure you want to delete DHCP Option "${name}"?`)) return;
  12894. try {
  12895. const res = await fetch(`${API_BASE}/dhcp-server/options/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12896. if (res.ok) {
  12897. showToast('Deleted', `Option ${name} removed`, 'success');
  12898. loadDHCPServer(false);
  12899. fetchData(false);
  12900. }
  12901. } catch (err) {
  12902. showToast('Error', err.message, 'error');
  12903. }
  12904. }
  12905. // ==================== WIZARD: DHCP SETUP (MikroTik style) ====================
  12906. function openDHCPServerSetupModal() {
  12907. populateDHCPIfaceSelect('dhcp-wizard-iface', '');
  12908. onDHCPWizardIfaceChange();
  12909. document.getElementById('dhcp-setup-wizard-modal').classList.remove('hidden');
  12910. }
  12911. function closeDHCPServerSetupModal() {
  12912. document.getElementById('dhcp-setup-wizard-modal').classList.add('hidden');
  12913. }
  12914. function onDHCPWizardIfaceChange() {
  12915. const ifaceName = document.getElementById('dhcp-wizard-iface').value;
  12916. const iface = (state.interfaces || []).find(i => i.name === ifaceName);
  12917. let ip = '192.168.88.1';
  12918. let prefix = '24';
  12919. if (iface && iface.ip_address) {
  12920. const parts = iface.ip_address.split('/');
  12921. ip = parts[0];
  12922. if (parts.length > 1) prefix = parts[1];
  12923. }
  12924. // Calculate subnet base (e.g. 192.168.88.0/24)
  12925. const ipParts = ip.split('.');
  12926. if (ipParts.length === 4) {
  12927. const baseSpace = `${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.0/${prefix}`;
  12928. const pool = `${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.10-${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.254`;
  12929. document.getElementById('dhcp-wizard-space').value = baseSpace;
  12930. document.getElementById('dhcp-wizard-gateway').value = ip;
  12931. document.getElementById('dhcp-wizard-pool').value = pool;
  12932. document.getElementById('dhcp-wizard-dns').value = `${ip}, 1.1.1.1, 8.8.8.8`;
  12933. document.getElementById('dhcp-wizard-ntp').value = `${ip}`;
  12934. }
  12935. }
  12936. async function submitDHCPServerSetupWizard(e) {
  12937. e.preventDefault();
  12938. const iface = document.getElementById('dhcp-wizard-iface').value;
  12939. const space = document.getElementById('dhcp-wizard-space').value.trim();
  12940. const gw = document.getElementById('dhcp-wizard-gateway').value.trim();
  12941. const pool = document.getElementById('dhcp-wizard-pool').value.trim();
  12942. const dnsStr = document.getElementById('dhcp-wizard-dns').value.trim();
  12943. const leaseTime = document.getElementById('dhcp-wizard-leasetime').value.trim() || '12h';
  12944. const ntpStr = document.getElementById('dhcp-wizard-ntp').value.trim();
  12945. const tftp = document.getElementById('dhcp-wizard-tftp').value.trim();
  12946. const dnsServers = dnsStr ? dnsStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  12947. const ntpServers = ntpStr ? ntpStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  12948. try {
  12949. const res = await fetch(`${API_BASE}/dhcp-server/setup`, {
  12950. method: 'POST',
  12951. headers: { 'Content-Type': 'application/json' },
  12952. body: JSON.stringify({
  12953. interface: iface,
  12954. address_space: space,
  12955. gateway: gw,
  12956. address_pool: pool,
  12957. dns_servers: dnsServers,
  12958. lease_time: leaseTime,
  12959. ntp_servers: ntpServers,
  12960. next_server: tftp
  12961. })
  12962. });
  12963. if (res.ok) {
  12964. showToast('DHCP Setup Complete', `DHCP Server setup finished on ${iface}`, 'success');
  12965. closeDHCPServerSetupModal();
  12966. loadDHCPServer(false);
  12967. fetchData(false);
  12968. } else {
  12969. const err = await res.text();
  12970. showToast('Error', err, 'error');
  12971. }
  12972. } catch (err) {
  12973. showToast('Error', err.message, 'error');
  12974. }
  12975. }
  12976. function populateDHCPIfaceSelect(elemId, selectedVal) {
  12977. const sel = document.getElementById(elemId);
  12978. if (!sel) return;
  12979. sel.innerHTML = '<option value="">Select interface...</option>';
  12980. const ifaces = state.interfaces || [];
  12981. ifaces.forEach(i => {
  12982. if (i.name === 'lo') return;
  12983. const opt = document.createElement('option');
  12984. opt.value = i.name;
  12985. const ipStr = i.ip_address ? ` (${i.ip_address})` : '';
  12986. opt.textContent = `${i.name}${ipStr} [${i.role || i.type || 'interface'}]`;
  12987. if (i.name === selectedVal) opt.selected = true;
  12988. sel.appendChild(opt);
  12989. });
  12990. }
  12991. // ==================== UNIVERSAL TABLE ORDERING / SORTING (WINBOX / WEBFIG STYLE) ====================
  12992. function initTableSorting() {
  12993. document.querySelectorAll('table').forEach(setupSortableTable);
  12994. }
  12995. function setupSortableTable(table) {
  12996. const thead = table.querySelector('thead');
  12997. const tbody = table.querySelector('tbody');
  12998. if (!thead || !tbody) return;
  12999. const headerRows = thead.querySelectorAll('tr');
  13000. if (headerRows.length === 0) return;
  13001. const ths = headerRows[headerRows.length - 1].querySelectorAll('th');
  13002. ths.forEach((th, colIdx) => {
  13003. if (th._sortBound) return;
  13004. th._sortBound = true;
  13005. const rawText = th.innerText.trim().toLowerCase();
  13006. const isActionsCol = rawText === 'actions' || (rawText === 'action' && th.classList.contains('text-right'));
  13007. const isCheckboxCol = !!th.querySelector('input[type="checkbox"]');
  13008. const isExpandCol = (th.classList.contains('w-8') || th.classList.contains('w-6')) && !rawText;
  13009. const isExplicitNoSort = th.classList.contains('no-sort') || th.getAttribute('data-sortable') === 'false';
  13010. if (isActionsCol || isCheckboxCol || isExpandCol || isExplicitNoSort) {
  13011. return;
  13012. }
  13013. th.classList.add('table-sortable', 'group');
  13014. if (!th.title) th.title = 'Click to sort (Ascending / Descending / Default)';
  13015. let icon = th.querySelector('.table-sort-icon');
  13016. if (!icon) {
  13017. icon = document.createElement('span');
  13018. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  13019. icon.innerHTML = '⇅';
  13020. th.appendChild(icon);
  13021. }
  13022. th.addEventListener('click', (e) => {
  13023. if (e.target.tagName === 'INPUT' || e.target.tagName === 'BUTTON' || e.target.closest('button, input')) return;
  13024. handleHeaderClick(table, th, colIdx);
  13025. });
  13026. });
  13027. if (!tbody._sortObserved) {
  13028. tbody._sortObserved = true;
  13029. let sortDebounceTimer = null;
  13030. const observer = new MutationObserver((mutations) => {
  13031. if (tbody._isSorting) return;
  13032. const hasChildChanges = mutations.some(m => m.type === 'childList' && m.addedNodes.length > 0);
  13033. if (!hasChildChanges) return;
  13034. clearTimeout(sortDebounceTimer);
  13035. sortDebounceTimer = setTimeout(() => {
  13036. if (tbody._isSorting) return;
  13037. if (table._activeSort && table._activeSort.dir !== 'none') {
  13038. applyTableSort(table, table._activeSort.colIdx, table._activeSort.dir, false);
  13039. } else {
  13040. tagOriginalRowOrder(tbody);
  13041. }
  13042. }, 50);
  13043. });
  13044. tbody._sortObserver = observer;
  13045. observer.observe(tbody, { childList: true });
  13046. }
  13047. tagOriginalRowOrder(tbody);
  13048. }
  13049. function tagOriginalRowOrder(tbody) {
  13050. let idx = 0;
  13051. Array.from(tbody.children).forEach(tr => {
  13052. if (!tr.querySelector('td[colspan]')) {
  13053. if (!tr.hasAttribute('data-orig-idx')) {
  13054. tr.setAttribute('data-orig-idx', idx++);
  13055. }
  13056. }
  13057. });
  13058. }
  13059. function handleHeaderClick(table, th, colIdx) {
  13060. const currentSort = table._activeSort || { colIdx: -1, dir: 'none' };
  13061. let newDir = 'asc';
  13062. if (currentSort.colIdx === colIdx) {
  13063. if (currentSort.dir === 'asc') newDir = 'desc';
  13064. else if (currentSort.dir === 'desc') newDir = 'none';
  13065. else newDir = 'asc';
  13066. } else {
  13067. newDir = 'asc';
  13068. }
  13069. table._activeSort = { colIdx, dir: newDir };
  13070. updateHeaderIcons(table, colIdx, newDir);
  13071. applyTableSort(table, colIdx, newDir, true);
  13072. }
  13073. function updateHeaderIcons(table, activeColIdx, dir) {
  13074. const thead = table.querySelector('thead');
  13075. if (!thead) return;
  13076. const ths = thead.querySelectorAll('th');
  13077. ths.forEach((th, idx) => {
  13078. const icon = th.querySelector('.table-sort-icon');
  13079. if (!icon) return;
  13080. if (idx === activeColIdx && dir !== 'none') {
  13081. icon.innerHTML = dir === 'asc' ? '▲' : '▼';
  13082. icon.className = 'table-sort-icon text-cyan-400 font-bold opacity-100';
  13083. th.classList.add('table-sorted-active');
  13084. } else {
  13085. icon.innerHTML = '⇅';
  13086. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  13087. th.classList.remove('table-sorted-active');
  13088. }
  13089. });
  13090. }
  13091. function applyTableSort(table, colIdx, dir, userInitiated) {
  13092. const tbody = table.querySelector('tbody');
  13093. if (!tbody || tbody.children.length <= 1) return;
  13094. tbody._isSorting = true;
  13095. tagOriginalRowOrder(tbody);
  13096. // Group parent rows and any attached drawer/sub-rows
  13097. const groups = [];
  13098. let currentGroup = null;
  13099. Array.from(tbody.children).forEach(tr => {
  13100. if (tr.querySelector('td[colspan]')) {
  13101. if (currentGroup) {
  13102. currentGroup.subRows.push(tr);
  13103. } else {
  13104. groups.push({ mainRow: tr, subRows: [] });
  13105. }
  13106. } else {
  13107. currentGroup = { mainRow: tr, subRows: [] };
  13108. groups.push(currentGroup);
  13109. }
  13110. });
  13111. if (dir === 'none') {
  13112. groups.sort((a, b) => {
  13113. const idxA = parseInt(a.mainRow.getAttribute('data-orig-idx') || '0', 10);
  13114. const idxB = parseInt(b.mainRow.getAttribute('data-orig-idx') || '0', 10);
  13115. return idxA - idxB;
  13116. });
  13117. } else {
  13118. groups.sort((a, b) => {
  13119. const cellA = a.mainRow.children[colIdx];
  13120. const cellB = b.mainRow.children[colIdx];
  13121. const res = compareTableCells(cellA, cellB);
  13122. return dir === 'asc' ? res : -res;
  13123. });
  13124. }
  13125. // Check if rows are already in correct order to avoid modifying DOM
  13126. let alreadyOrdered = true;
  13127. let childIdx = 0;
  13128. for (const g of groups) {
  13129. if (tbody.children[childIdx] !== g.mainRow) {
  13130. alreadyOrdered = false;
  13131. break;
  13132. }
  13133. childIdx++;
  13134. for (const sub of g.subRows) {
  13135. if (tbody.children[childIdx] !== sub) {
  13136. alreadyOrdered = false;
  13137. break;
  13138. }
  13139. childIdx++;
  13140. }
  13141. }
  13142. if (alreadyOrdered) {
  13143. tbody._isSorting = false;
  13144. return;
  13145. }
  13146. // Disconnect observer while re-ordering to prevent recursion and thrashing
  13147. if (tbody._sortObserver) {
  13148. tbody._sortObserver.disconnect();
  13149. }
  13150. // Re-append rows in sorted order
  13151. groups.forEach(g => {
  13152. tbody.appendChild(g.mainRow);
  13153. g.subRows.forEach(sub => tbody.appendChild(sub));
  13154. });
  13155. // Drain any queued mutations and re-connect observer
  13156. if (tbody._sortObserver) {
  13157. tbody._sortObserver.takeRecords();
  13158. tbody._sortObserver.observe(tbody, { childList: true });
  13159. }
  13160. tbody._isSorting = false;
  13161. }
  13162. function getCellRawText(cell) {
  13163. if (!cell) return '';
  13164. if (cell.hasAttribute('data-sort-value')) return cell.getAttribute('data-sort-value');
  13165. const input = cell.querySelector('input, select');
  13166. if (input) {
  13167. if (input.type === 'checkbox') return input.checked ? '1' : '0';
  13168. return input.value;
  13169. }
  13170. return cell.innerText.trim();
  13171. }
  13172. function parseTrafficToNumber(str) {
  13173. const m = str.match(/^([\d.,]+)\s*([KMGTkmgt]?[iI]?[Bb](?:ps|\/s)?)/);
  13174. if (!m) return null;
  13175. const num = parseFloat(m[1].replace(/,/g, ''));
  13176. if (isNaN(num)) return null;
  13177. const unit = m[2].toUpperCase();
  13178. let mult = 1;
  13179. if (unit.startsWith('K')) mult = 1024;
  13180. else if (unit.startsWith('M')) mult = 1024 * 1024;
  13181. else if (unit.startsWith('G')) mult = 1024 * 1024 * 1024;
  13182. else if (unit.startsWith('T')) mult = 1024 * 1024 * 1024 * 1024;
  13183. return num * mult;
  13184. }
  13185. function parseIpToNumber(str) {
  13186. const clean = str.replace(/^[!~]/, '').trim();
  13187. const m = clean.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(?:\/(\d{1,2}))?/);
  13188. if (!m) return null;
  13189. const o1 = parseInt(m[1], 10);
  13190. const o2 = parseInt(m[2], 10);
  13191. const o3 = parseInt(m[3], 10);
  13192. const o4 = parseInt(m[4], 10);
  13193. if (o1 > 255 || o2 > 255 || o3 > 255 || o4 > 255) return null;
  13194. return ((o1 * 256 + o2) * 256 + o3) * 256 + o4;
  13195. }
  13196. function parseCompoundPackets(str) {
  13197. const m = str.match(/^([\d,]+)p/);
  13198. if (!m) return null;
  13199. return parseInt(m[1].replace(/,/g, ''), 10);
  13200. }
  13201. function compareTableCells(cellA, cellB) {
  13202. const a = getCellRawText(cellA);
  13203. const b = getCellRawText(cellB);
  13204. if (a === '' && b !== '') return 1;
  13205. if (b === '' && a !== '') return -1;
  13206. if (a === b) return 0;
  13207. // 1. IP Addresses / CIDR
  13208. const ipA = parseIpToNumber(a);
  13209. const ipB = parseIpToNumber(b);
  13210. if (ipA !== null && ipB !== null) return ipA - ipB;
  13211. // 2. Packet counts (e.g. "1,250p / 45 KB")
  13212. const pktA = parseCompoundPackets(a);
  13213. const pktB = parseCompoundPackets(b);
  13214. if (pktA !== null && pktB !== null) return pktA - pktB;
  13215. // 3. Traffic / Throughput / Bytes (e.g. "1.2 MB", "500 KiB", "10 Gbps")
  13216. const trafA = parseTrafficToNumber(a);
  13217. const trafB = parseTrafficToNumber(b);
  13218. if (trafA !== null && trafB !== null) return trafA - trafB;
  13219. // 4. Numbers with '#' or formatted with commas (e.g. "#1", "24", "1,200")
  13220. const cleanNumA = a.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  13221. const cleanNumB = b.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  13222. const numA = Number(cleanNumA);
  13223. const numB = Number(cleanNumB);
  13224. if (!isNaN(numA) && !isNaN(numB) && cleanNumA !== '' && cleanNumB !== '') {
  13225. return numA - numB;
  13226. }
  13227. // 5. Natural case-insensitive string compare
  13228. return a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' });
  13229. }
  13230. // ==================== VRRP HIGH AVAILABILITY CONTROLLER ====================
  13231. async function loadVRRP(showToastNotification = false) {
  13232. try {
  13233. const [instRes, sumRes] = await Promise.all([
  13234. fetch(`${API_BASE}/vrrp/instances`),
  13235. fetch(`${API_BASE}/vrrp/summary`)
  13236. ]);
  13237. if (instRes.ok) {
  13238. state.vrrpInstances = await instRes.json();
  13239. renderVRRP();
  13240. }
  13241. if (sumRes.ok) {
  13242. state.vrrpSummary = await sumRes.json();
  13243. renderVRRPSummary();
  13244. }
  13245. if (showToastNotification) {
  13246. showToast('Refreshed', 'VRRP telemetry refreshed', 'info');
  13247. }
  13248. } catch (err) {
  13249. console.error('Failed to load VRRP:', err);
  13250. }
  13251. }
  13252. function renderVRRPSummary() {
  13253. const s = state.vrrpSummary || { total_instances: 0, master_instances: 0, backup_instances: 0 };
  13254. const elTotal = document.getElementById('vrrp-stat-total');
  13255. if (elTotal) elTotal.innerText = s.total_instances || 0;
  13256. const elMaster = document.getElementById('vrrp-stat-master');
  13257. if (elMaster) elMaster.innerText = s.master_instances || 0;
  13258. const elBackup = document.getElementById('vrrp-stat-backup');
  13259. if (elBackup) elBackup.innerText = s.backup_instances || 0;
  13260. const bCount = document.getElementById('badge-vrrp-count');
  13261. if (bCount) bCount.innerText = s.total_instances || 0;
  13262. const dot = document.getElementById('badge-vrrp-dot');
  13263. if (dot) {
  13264. if (s.master_instances > 0) {
  13265. dot.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  13266. } else if (s.backup_instances > 0) {
  13267. dot.className = 'w-2 h-2 rounded-full bg-sky-400';
  13268. } else {
  13269. dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  13270. }
  13271. }
  13272. }
  13273. function renderVRRP() {
  13274. const tbody = document.getElementById('vrrp-table-tbody');
  13275. const empty = document.getElementById('vrrp-table-empty');
  13276. if (!tbody) return;
  13277. tbody.innerHTML = '';
  13278. const instances = state.vrrpInstances || [];
  13279. if (instances.length === 0) {
  13280. empty?.classList.remove('hidden');
  13281. return;
  13282. }
  13283. empty?.classList.add('hidden');
  13284. instances.forEach(inst => {
  13285. const tr = document.createElement('tr');
  13286. tr.className = `hover:bg-slate-800/40 transition text-xs ${inst.disabled ? 'opacity-50' : ''}`;
  13287. // Render Flag: M (Master), B (Backup), F (Fault), X (Disabled)
  13288. 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>`;
  13289. if (inst.disabled) {
  13290. 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>`;
  13291. } else if (inst.state === 'MASTER') {
  13292. 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>`;
  13293. } else if (inst.state === 'BACKUP') {
  13294. 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>`;
  13295. } else if (inst.state === 'FAULT') {
  13296. 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>`;
  13297. }
  13298. // Render State Badge
  13299. let stateBadge = `<span class="px-2 py-0.5 rounded text-[10px] bg-slate-800 text-slate-400 border border-slate-700">DISABLED</span>`;
  13300. if (!inst.disabled) {
  13301. if (inst.state === 'MASTER') {
  13302. 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>`;
  13303. } else if (inst.state === 'BACKUP') {
  13304. 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>`;
  13305. } else if (inst.state === 'FAULT') {
  13306. 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>`;
  13307. }
  13308. }
  13309. const vipsStr = (inst.virtual_ips || []).join(', ') || '-';
  13310. tr.innerHTML = `
  13311. <td class="py-2.5 px-3 text-center">${flagHtml}</td>
  13312. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(inst.name)}</td>
  13313. <td class="py-2.5 px-3 font-mono text-cyan-400 font-semibold">${escapeHtml(inst.interface)}</td>
  13314. <td class="py-2.5 px-3 font-mono font-bold text-center text-white">${inst.vrid}</td>
  13315. <td class="py-2.5 px-3 font-mono text-center text-slate-300 font-semibold">${inst.priority}</td>
  13316. <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>
  13317. <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>
  13318. <td class="py-2.5 px-3 font-mono text-slate-400 text-[11px]">${escapeHtml(inst.virtual_mac || '-')}</td>
  13319. <td class="py-2.5 px-3 text-center">${stateBadge}</td>
  13320. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]" title="${escapeHtml(inst.comment || '')}">${escapeHtml(inst.comment || '-')}</td>
  13321. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  13322. <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>
  13323. <button onclick="openEditVRRPModal('${inst.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  13324. <button onclick="deleteVRRP('${inst.id}', '${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  13325. </td>
  13326. `;
  13327. tbody.appendChild(tr);
  13328. });
  13329. }
  13330. function populateVRRPIfaceSelect(elemId, selectedIface) {
  13331. const sel = document.getElementById(elemId);
  13332. if (!sel) return;
  13333. sel.innerHTML = '<option value="">Select interface...</option>';
  13334. const ifaces = state.interfaces || [];
  13335. ifaces.forEach(i => {
  13336. const opt = document.createElement('option');
  13337. opt.value = i.name;
  13338. opt.innerText = `${i.name} (${i.type || 'net'}${i.ip ? ' - ' + i.ip : ''})`;
  13339. if (selectedIface && selectedIface === i.name) opt.selected = true;
  13340. sel.appendChild(opt);
  13341. });
  13342. }
  13343. function openAddVRRPModal() {
  13344. document.getElementById('modal-vrrp-title').innerText = 'Add VRRP Instance';
  13345. document.getElementById('modal-vrrp-id').value = '';
  13346. document.getElementById('modal-vrrp-name').value = `vrrp${(state.vrrpInstances || []).length + 1}`;
  13347. document.getElementById('modal-vrrp-vrid').value = 10 + (state.vrrpInstances || []).length;
  13348. document.getElementById('modal-vrrp-priority').value = 100;
  13349. document.getElementById('modal-vrrp-vip').value = '192.168.88.254/24';
  13350. document.getElementById('modal-vrrp-version').value = '3';
  13351. document.getElementById('modal-vrrp-interval').value = 1;
  13352. document.getElementById('modal-vrrp-authtype').value = 'none';
  13353. document.getElementById('modal-vrrp-authpass').value = '';
  13354. document.getElementById('modal-vrrp-comment').value = '';
  13355. document.getElementById('modal-vrrp-preempt').checked = true;
  13356. document.getElementById('modal-vrrp-disabled').checked = false;
  13357. populateVRRPIfaceSelect('modal-vrrp-iface', '');
  13358. document.getElementById('modal-vrrp-instance').classList.remove('hidden');
  13359. }
  13360. function openEditVRRPModal(id) {
  13361. const inst = (state.vrrpInstances || []).find(item => item.id === id);
  13362. if (!inst) return;
  13363. document.getElementById('modal-vrrp-title').innerText = `Edit VRRP Instance (${inst.name})`;
  13364. document.getElementById('modal-vrrp-id').value = inst.id;
  13365. document.getElementById('modal-vrrp-name').value = inst.name;
  13366. document.getElementById('modal-vrrp-vrid').value = inst.vrid;
  13367. document.getElementById('modal-vrrp-priority').value = inst.priority;
  13368. document.getElementById('modal-vrrp-vip').value = (inst.virtual_ips || []).join(', ');
  13369. document.getElementById('modal-vrrp-version').value = String(inst.version || 3);
  13370. document.getElementById('modal-vrrp-interval').value = inst.interval || 1;
  13371. document.getElementById('modal-vrrp-authtype').value = inst.auth_type || 'none';
  13372. document.getElementById('modal-vrrp-authpass').value = inst.auth_password || '';
  13373. document.getElementById('modal-vrrp-comment').value = inst.comment || '';
  13374. document.getElementById('modal-vrrp-preempt').checked = inst.preempt !== false;
  13375. document.getElementById('modal-vrrp-disabled').checked = !!inst.disabled;
  13376. populateVRRPIfaceSelect('modal-vrrp-iface', inst.interface);
  13377. document.getElementById('modal-vrrp-instance').classList.remove('hidden');
  13378. }
  13379. function closeVRRPModal() {
  13380. document.getElementById('modal-vrrp-instance').classList.add('hidden');
  13381. }
  13382. async function submitSaveVRRP(e) {
  13383. e.preventDefault();
  13384. const id = document.getElementById('modal-vrrp-id').value;
  13385. const name = document.getElementById('modal-vrrp-name').value.trim();
  13386. const iface = document.getElementById('modal-vrrp-iface').value;
  13387. const vrid = parseInt(document.getElementById('modal-vrrp-vrid').value, 10) || 1;
  13388. const priority = parseInt(document.getElementById('modal-vrrp-priority').value, 10) || 100;
  13389. const vipRaw = document.getElementById('modal-vrrp-vip').value.trim();
  13390. const version = parseInt(document.getElementById('modal-vrrp-version').value, 10) || 3;
  13391. const interval = parseInt(document.getElementById('modal-vrrp-interval').value, 10) || 1;
  13392. const authType = document.getElementById('modal-vrrp-authtype').value;
  13393. const authPass = document.getElementById('modal-vrrp-authpass').value.trim();
  13394. const comment = document.getElementById('modal-vrrp-comment').value.trim();
  13395. const preempt = document.getElementById('modal-vrrp-preempt').checked;
  13396. const disabled = document.getElementById('modal-vrrp-disabled').checked;
  13397. const vips = vipRaw.split(',').map(s => s.trim()).filter(Boolean);
  13398. try {
  13399. const res = await fetch(`${API_BASE}/vrrp/instances`, {
  13400. method: 'POST',
  13401. headers: { 'Content-Type': 'application/json' },
  13402. body: JSON.stringify({
  13403. id,
  13404. name,
  13405. interface: iface,
  13406. vrid,
  13407. priority,
  13408. virtual_ips: vips,
  13409. version,
  13410. interval,
  13411. auth_type: authType,
  13412. auth_password: authPass,
  13413. comment,
  13414. preempt,
  13415. disabled
  13416. })
  13417. });
  13418. if (res.ok) {
  13419. showToast('VRRP Saved', `VRRP instance ${name} configured`, 'success');
  13420. closeVRRPModal();
  13421. loadVRRP(false);
  13422. fetchData(false);
  13423. } else {
  13424. const err = await res.text();
  13425. showToast('Error', err, 'error');
  13426. }
  13427. } catch (err) {
  13428. showToast('Error', err.message, 'error');
  13429. }
  13430. }
  13431. async function deleteVRRP(id, name) {
  13432. if (!confirm(`Delete VRRP instance "${name}"?`)) return;
  13433. try {
  13434. const res = await fetch(`${API_BASE}/vrrp/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  13435. if (res.ok) {
  13436. showToast('Deleted', `VRRP instance ${name} removed`, 'info');
  13437. loadVRRP(false);
  13438. fetchData(false);
  13439. } else {
  13440. const err = await res.text();
  13441. showToast('Error', err, 'error');
  13442. }
  13443. } catch (err) {
  13444. showToast('Error', err.message, 'error');
  13445. }
  13446. }
  13447. async function toggleVRRPState(id, disabled) {
  13448. try {
  13449. const res = await fetch(`${API_BASE}/vrrp/instances/${encodeURIComponent(id)}/state`, {
  13450. method: 'POST',
  13451. headers: { 'Content-Type': 'application/json' },
  13452. body: JSON.stringify({ disabled })
  13453. });
  13454. if (res.ok) {
  13455. showToast('State Updated', disabled ? 'VRRP disabled' : 'VRRP enabled', 'info');
  13456. loadVRRP(false);
  13457. fetchData(false);
  13458. } else {
  13459. const err = await res.text();
  13460. showToast('Error', err, 'error');
  13461. }
  13462. } catch (err) {
  13463. showToast('Error', err.message, 'error');
  13464. }
  13465. }
  13466. // Global observer for dynamically injected tables (e.g. inside modals or drawers)
  13467. if (typeof MutationObserver !== 'undefined' && typeof document !== 'undefined') {
  13468. let docSortDebounce = null;
  13469. const docTableObserver = new MutationObserver((mutations) => {
  13470. let needsInit = false;
  13471. for (const m of mutations) {
  13472. for (const node of m.addedNodes) {
  13473. if (node.nodeType === 1) {
  13474. if (node.tagName === 'TABLE' && !node.closest('tbody, thead')) {
  13475. needsInit = true;
  13476. break;
  13477. } else if (node.querySelector && !node.closest('table') && node.querySelector('table')) {
  13478. needsInit = true;
  13479. break;
  13480. }
  13481. }
  13482. }
  13483. if (needsInit) break;
  13484. }
  13485. if (needsInit) {
  13486. clearTimeout(docSortDebounce);
  13487. docSortDebounce = setTimeout(initTableSorting, 100);
  13488. }
  13489. });
  13490. docTableObserver.observe(document.body || document.documentElement, { childList: true, subtree: true });
  13491. }
  13492. // =========================================================================
  13493. // BANDWIDTH TEST (BwTest) BENCHMARK ENGINE
  13494. // =========================================================================
  13495. const bwtestState = {
  13496. running: false,
  13497. pollTimer: null,
  13498. eventSource: null,
  13499. chartPoints: [],
  13500. maxChartPoints: 60,
  13501. serverConfig: null,
  13502. peakTx: 0,
  13503. peakRx: 0,
  13504. targetDuration: 10,
  13505. lastSampleElapsed: -1,
  13506. sessionID: null
  13507. };
  13508. async function loadBwTestView() {
  13509. resizeBwTestCanvas();
  13510. await Promise.all([fetchBwTestServerStatus(), loadBwTestHistory(), checkActiveBwTest()]);
  13511. }
  13512. async function fetchBwTestServerStatus() {
  13513. try {
  13514. const res = await fetch(`${API_BASE}/tools/bwtest/server`);
  13515. if (!res.ok) return;
  13516. const s = await res.json();
  13517. bwtestState.serverConfig = s;
  13518. // Update indicator and badges
  13519. const indicator = document.getElementById('bwtest-server-indicator');
  13520. const badge = document.getElementById('bwtest-server-badge');
  13521. const sideBadge = document.getElementById('badge-bwtest-server');
  13522. if (s.enabled && s.running) {
  13523. if (indicator) indicator.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  13524. if (badge) {
  13525. badge.innerText = `Port ${s.port} (Active)`;
  13526. badge.className = 'text-emerald-400 font-bold';
  13527. }
  13528. if (sideBadge) {
  13529. sideBadge.innerText = s.port;
  13530. 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';
  13531. }
  13532. } else {
  13533. if (indicator) indicator.className = 'w-2 h-2 rounded-full bg-slate-600';
  13534. if (badge) {
  13535. badge.innerText = `Disabled`;
  13536. badge.className = 'text-slate-500 font-bold';
  13537. }
  13538. if (sideBadge) {
  13539. sideBadge.innerText = 'Off';
  13540. sideBadge.className = 'text-[10px] bg-slate-800 text-slate-500 border border-slate-700 px-1.5 py-0.2 rounded-full font-mono';
  13541. }
  13542. }
  13543. // Modal fields
  13544. const toggle = document.getElementById('bwtest-server-enable-toggle');
  13545. const serverModal = document.getElementById('modal-bwtest-server');
  13546. const editing = serverModal && !serverModal.classList.contains('hidden');
  13547. if (toggle && !editing) toggle.checked = !!s.enabled;
  13548. const portInp = document.getElementById('bwtest-server-port-input');
  13549. if (portInp && !editing) portInp.value = s.port || 2000;
  13550. const actSess = document.getElementById('bwtest-modal-active-sessions');
  13551. if (actSess) actSess.innerText = s.active_sessions || 0;
  13552. const totServ = document.getElementById('bwtest-modal-total-served');
  13553. if (totServ) totServ.innerText = s.total_sessions_served || 0;
  13554. const totBytes = document.getElementById('bwtest-modal-total-bytes');
  13555. if (totBytes) totBytes.innerText = formatBytes(s.total_bytes_processed || 0);
  13556. } catch (err) {
  13557. console.error('Failed to fetch BwTest server status:', err);
  13558. }
  13559. }
  13560. function openBwTestServerModal() {
  13561. const cfg = bwtestState.serverConfig;
  13562. if (cfg) {
  13563. document.getElementById('bwtest-server-enable-toggle').checked = !!cfg.enabled;
  13564. document.getElementById('bwtest-server-port-input').value = cfg.port || 2000;
  13565. }
  13566. fetchBwTestServerStatus();
  13567. document.getElementById('modal-bwtest-server')?.classList.remove('hidden');
  13568. }
  13569. function closeBwTestServerModal() {
  13570. document.getElementById('modal-bwtest-server')?.classList.add('hidden');
  13571. }
  13572. async function submitBwTestServerSettings(e) {
  13573. e.preventDefault();
  13574. const enabled = document.getElementById('bwtest-server-enable-toggle').checked;
  13575. const port = parseInt(document.getElementById('bwtest-server-port-input').value, 10) || 2000;
  13576. try {
  13577. const res = await fetch(`${API_BASE}/tools/bwtest/server`, {
  13578. method: 'POST',
  13579. headers: { 'Content-Type': 'application/json' },
  13580. body: JSON.stringify({ enabled, port, listen_addr: '0.0.0.0', allow_anonymous: true })
  13581. });
  13582. if (!res.ok) {
  13583. const err = await res.json();
  13584. throw new Error(err.error || 'Failed to update server configuration');
  13585. }
  13586. showToast('BwTest Server', `Bandwidth Test server updated (Port ${port})`, 'success');
  13587. closeBwTestServerModal();
  13588. fetchBwTestServerStatus();
  13589. } catch (err) {
  13590. showToast('Server Configuration Error', err.message, 'error');
  13591. }
  13592. }
  13593. function setBwTestTarget(target) {
  13594. const inp = document.getElementById('bwtest-input-target');
  13595. if (inp) inp.value = target;
  13596. }
  13597. function setBwTestProtocol(proto) {
  13598. const hiddenInp = document.getElementById('bwtest-input-protocol');
  13599. if (hiddenInp) hiddenInp.value = proto;
  13600. const btnUdp = document.getElementById('bwtest-proto-udp');
  13601. const btnTcp = document.getElementById('bwtest-proto-tcp');
  13602. const badge = document.getElementById('bwtest-proto-badge');
  13603. const pktField = document.getElementById('bwtest-field-pktsize');
  13604. 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';
  13605. 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';
  13606. 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';
  13607. if (proto === 'udp') {
  13608. if (btnUdp) {
  13609. btnUdp.className = activeUdpCls;
  13610. const dot = btnUdp.querySelector('span');
  13611. if (dot) dot.className = 'w-2 h-2 rounded-full bg-emerald-400';
  13612. }
  13613. if (btnTcp) {
  13614. btnTcp.className = inactiveCls;
  13615. const dot = btnTcp.querySelector('span');
  13616. if (dot) dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  13617. }
  13618. if (badge) {
  13619. badge.innerText = 'UDP Mode (RFC 3550 Jitter + Loss %)';
  13620. badge.className = 'text-[10px] font-mono text-emerald-400 bg-emerald-500/10 px-2 py-0.5 rounded border border-emerald-500/20';
  13621. }
  13622. if (pktField) pktField.classList.remove('opacity-40');
  13623. } else {
  13624. if (btnUdp) {
  13625. btnUdp.className = inactiveCls;
  13626. const dot = btnUdp.querySelector('span');
  13627. if (dot) dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  13628. }
  13629. if (btnTcp) {
  13630. btnTcp.className = activeTcpCls;
  13631. const dot = btnTcp.querySelector('span');
  13632. if (dot) dot.className = 'w-2 h-2 rounded-full bg-blue-400';
  13633. }
  13634. if (badge) {
  13635. badge.innerText = 'TCP Mode (Sliding Window Throughput)';
  13636. badge.className = 'text-[10px] font-mono text-blue-400 bg-blue-500/10 px-2 py-0.5 rounded border border-blue-500/20';
  13637. }
  13638. if (pktField) pktField.classList.add('opacity-40');
  13639. }
  13640. }
  13641. function setBwTestDirection(dir) {
  13642. const hiddenInp = document.getElementById('bwtest-input-direction');
  13643. if (hiddenInp) hiddenInp.value = dir;
  13644. const btnBoth = document.getElementById('bwtest-dir-both');
  13645. const btnTx = document.getElementById('bwtest-dir-tx');
  13646. const btnRx = document.getElementById('bwtest-dir-rx');
  13647. 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';
  13648. 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';
  13649. if (btnBoth) btnBoth.className = dir === 'both' ? activeCls : inactiveCls;
  13650. if (btnTx) btnTx.className = dir === 'tx' ? activeCls : inactiveCls;
  13651. if (btnRx) btnRx.className = dir === 'rx' ? activeCls : inactiveCls;
  13652. }
  13653. function setBwTestLimit(bps) {
  13654. const sel = document.getElementById('bwtest-input-limit');
  13655. if (sel) sel.value = String(bps);
  13656. }
  13657. async function checkActiveBwTest() {
  13658. try {
  13659. const res = await fetch(`${API_BASE}/tools/bwtest/status`);
  13660. if (!res.ok) return;
  13661. const st = await res.json();
  13662. if (st.running) {
  13663. setBwTestRunningUI(true);
  13664. processBwTestStatus(st);
  13665. startBwTestTelemetry();
  13666. }
  13667. } catch (err) {
  13668. console.error('Failed to check active BwTest:', err);
  13669. }
  13670. }
  13671. async function startBwTest(e) {
  13672. if (e && e.preventDefault) e.preventDefault();
  13673. const target = document.getElementById('bwtest-input-target').value.trim() || '127.0.0.1';
  13674. const port = parseInt(document.getElementById('bwtest-input-port').value, 10) || 2000;
  13675. const direction = document.getElementById('bwtest-input-direction').value || 'both';
  13676. const protocol = document.getElementById('bwtest-input-protocol').value || 'udp';
  13677. const bandwidth_limit = parseInt(document.getElementById('bwtest-input-limit').value, 10) || 0;
  13678. const packet_size = parseInt(document.getElementById('bwtest-input-pktsize').value, 10) || 1472;
  13679. const streams = parseInt(document.getElementById('bwtest-input-streams').value, 10) || 1;
  13680. const duration = parseInt(document.getElementById('bwtest-input-duration').value, 10);
  13681. bwtestState.targetDuration = duration;
  13682. bwtestState.chartPoints = [];
  13683. bwtestState.peakTx = 0;
  13684. bwtestState.peakRx = 0;
  13685. bwtestState.lastSampleElapsed = -1;
  13686. bwtestState.sessionID = null;
  13687. // Clear UI elements
  13688. document.getElementById('bwtest-stat-tx-mbps').innerText = '0.00';
  13689. document.getElementById('bwtest-stat-tx-peak').innerText = '0.00 Mbps';
  13690. document.getElementById('bwtest-stat-tx-pkts').innerText = '0';
  13691. document.getElementById('bwtest-stat-rx-mbps').innerText = '0.00';
  13692. document.getElementById('bwtest-stat-rx-peak').innerText = '0.00 Mbps';
  13693. document.getElementById('bwtest-stat-rx-pkts').innerText = '0';
  13694. document.getElementById('bwtest-stat-loss').innerText = '0.0%';
  13695. document.getElementById('bwtest-stat-jitter').innerText = '0.00 ms';
  13696. document.getElementById('bwtest-stat-time').innerText = '0.0s';
  13697. document.getElementById('bwtest-stat-data').innerText = '0.0 MB';
  13698. document.getElementById('bwtest-stat-target-dur').innerText = duration > 0 ? `/ ${duration}s` : '/ ∞';
  13699. const tbody = document.getElementById('bwtest-samples-tbody');
  13700. if (tbody) tbody.innerHTML = '';
  13701. document.getElementById('bwtest-sample-count').innerText = '0 samples';
  13702. setBwTestRunningUI(true);
  13703. try {
  13704. const res = await fetch(`${API_BASE}/tools/bwtest/start`, {
  13705. method: 'POST',
  13706. headers: { 'Content-Type': 'application/json' },
  13707. body: JSON.stringify({
  13708. target,
  13709. port,
  13710. direction,
  13711. protocol,
  13712. bandwidth_limit,
  13713. packet_size,
  13714. streams,
  13715. duration
  13716. })
  13717. });
  13718. if (!res.ok) {
  13719. const err = await res.json();
  13720. throw new Error(err.error || 'Failed to start bandwidth test');
  13721. }
  13722. showToast('Benchmark Started', `Target: ${target}:${port} (${direction.toUpperCase()}, ${protocol.toUpperCase()})`, 'info');
  13723. startBwTestTelemetry();
  13724. } catch (err) {
  13725. setBwTestRunningUI(false);
  13726. showToast('Start Failed', err.message, 'error');
  13727. }
  13728. }
  13729. function setBwTestRunningUI(running) {
  13730. bwtestState.running = running;
  13731. const startBtn = document.getElementById('bwtest-btn-start');
  13732. const stopBtn = document.getElementById('bwtest-btn-stop');
  13733. const badge = document.getElementById('bwtest-run-status-badge');
  13734. const ph = document.getElementById('bwtest-chart-placeholder');
  13735. if (running) {
  13736. if (startBtn) {
  13737. startBtn.disabled = true;
  13738. startBtn.classList.add('opacity-50', 'cursor-not-allowed');
  13739. }
  13740. if (stopBtn) {
  13741. stopBtn.disabled = false;
  13742. stopBtn.classList.remove('opacity-40');
  13743. }
  13744. if (badge) {
  13745. badge.innerText = 'TESTING...';
  13746. 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';
  13747. }
  13748. if (ph) ph.style.display = 'none';
  13749. } else {
  13750. if (startBtn) {
  13751. startBtn.disabled = false;
  13752. startBtn.classList.remove('opacity-50', 'cursor-not-allowed');
  13753. }
  13754. if (stopBtn) {
  13755. stopBtn.disabled = true;
  13756. stopBtn.classList.add('opacity-40');
  13757. }
  13758. if (badge) {
  13759. badge.innerText = 'IDLE';
  13760. badge.className = 'px-2 py-0.5 rounded text-[10px] font-mono bg-slate-800 text-slate-400 border border-slate-700 font-semibold';
  13761. }
  13762. }
  13763. }
  13764. async function stopBwTest() {
  13765. try {
  13766. const res = await fetch(`${API_BASE}/tools/bwtest/stop`, { method: 'POST' });
  13767. if (!res.ok) throw new Error(await responseError(res));
  13768. showToast('Stop Requested', 'Waiting for the bandwidth test to finish', 'info');
  13769. if (!bwtestState.pollTimer) startBwTestTelemetry();
  13770. } catch (err) {
  13771. showToast('Stop Failed', err.message, 'error');
  13772. }
  13773. }
  13774. async function responseError(res) {
  13775. const text = await res.text();
  13776. try { const data = JSON.parse(text); return data.message || (typeof data.error === 'string' ? data.error : null) || `HTTP ${res.status}`; }
  13777. catch { return text || `HTTP ${res.status}`; }
  13778. }
  13779. function processBwTestStatus(st) {
  13780. if (st.session_id && bwtestState.sessionID !== st.session_id) {
  13781. bwtestState.sessionID = st.session_id;
  13782. bwtestState.lastSampleElapsed = -1;
  13783. }
  13784. for (const sample of st.recent_samples || []) {
  13785. if (sample.elapsed_sec > (bwtestState.lastSampleElapsed ?? -1)) {
  13786. handleBwTestSample(sample);
  13787. bwtestState.lastSampleElapsed = sample.elapsed_sec;
  13788. }
  13789. }
  13790. if (!st.running) {
  13791. if (bwtestState.pollTimer) clearInterval(bwtestState.pollTimer);
  13792. bwtestState.pollTimer = null;
  13793. setBwTestRunningUI(false);
  13794. handleBwTestFinish(st.summary, st.error);
  13795. }
  13796. }
  13797. function startBwTestTelemetry() {
  13798. if (!state.currentUser) return;
  13799. if (bwtestState.pollTimer) clearInterval(bwtestState.pollTimer);
  13800. let busy = false;
  13801. const poll = async () => {
  13802. if (busy || !state.currentUser || document.hidden) return;
  13803. busy = true;
  13804. try {
  13805. const res = await fetch(`${API_BASE}/tools/bwtest/status`);
  13806. if (!res.ok) throw new Error(await responseError(res));
  13807. processBwTestStatus(await res.json());
  13808. } catch (err) {
  13809. console.error('BwTest polling error:', err);
  13810. } finally { busy = false; }
  13811. };
  13812. bwtestState.pollTimer = setInterval(poll, 400);
  13813. poll();
  13814. }
  13815. function handleBwTestSample(s) {
  13816. if (!s) return;
  13817. const payloadHint = document.getElementById('bwtest-effective-payload');
  13818. if (payloadHint && s.packet_size) payloadHint.innerText = `Effective datagram: ${s.packet_size} bytes`;
  13819. const txMbps = s.tx_mbps || 0;
  13820. const rxMbps = s.rx_mbps || 0;
  13821. if (txMbps > bwtestState.peakTx) bwtestState.peakTx = txMbps;
  13822. if (rxMbps > bwtestState.peakRx) bwtestState.peakRx = rxMbps;
  13823. // KPI updates
  13824. const elTx = document.getElementById('bwtest-stat-tx-mbps');
  13825. if (elTx) {
  13826. elTx.innerText = txMbps.toFixed(2);
  13827. elTx.title = `Confirmed by peer; locally offered: ${(s.offered_tx_mbps || 0).toFixed(2)} Mbps`;
  13828. }
  13829. const elTxPeak = document.getElementById('bwtest-stat-tx-peak');
  13830. if (elTxPeak) elTxPeak.innerText = `${bwtestState.peakTx.toFixed(2)} Mbps`;
  13831. const elTxPkts = document.getElementById('bwtest-stat-tx-pkts');
  13832. if (elTxPkts) elTxPkts.innerText = s.tx_packets || 0;
  13833. const elRx = document.getElementById('bwtest-stat-rx-mbps');
  13834. if (elRx) elRx.innerText = rxMbps.toFixed(2);
  13835. const elRxPeak = document.getElementById('bwtest-stat-rx-peak');
  13836. if (elRxPeak) elRxPeak.innerText = `${bwtestState.peakRx.toFixed(2)} Mbps`;
  13837. const elRxPkts = document.getElementById('bwtest-stat-rx-pkts');
  13838. if (elRxPkts) elRxPkts.innerText = s.rx_packets || 0;
  13839. const elLoss = document.getElementById('bwtest-stat-loss');
  13840. if (elLoss) {
  13841. elLoss.innerText = `${(s.loss_pct || 0).toFixed(1)}%`;
  13842. elLoss.className = (s.loss_pct > 1.0) ? 'text-2xl font-bold text-rose-400' : 'text-2xl font-bold text-emerald-400';
  13843. }
  13844. const elLostPkts = document.getElementById('bwtest-stat-lost-pkts');
  13845. if (elLostPkts) elLostPkts.innerText = s.lost_packets || 0;
  13846. const elJitter = document.getElementById('bwtest-stat-jitter');
  13847. if (elJitter) elJitter.innerText = `${(s.jitter_ms || 0).toFixed(2)} ms`;
  13848. const elTime = document.getElementById('bwtest-stat-time');
  13849. if (elTime) elTime.innerText = `${(s.elapsed_sec || 0).toFixed(1)}s`;
  13850. const elData = document.getElementById('bwtest-stat-data');
  13851. if (elData) elData.innerText = formatBytes((s.tx_bytes || 0) + (s.rx_bytes || 0));
  13852. const elGraphRate = document.getElementById('bwtest-graph-rate');
  13853. if (elGraphRate) elGraphRate.innerText = `TX: ${txMbps.toFixed(1)} Mbps • RX: ${rxMbps.toFixed(1)} Mbps`;
  13854. // Append point to chart buffer
  13855. bwtestState.chartPoints.push({
  13856. elapsed: s.elapsed_sec || 0,
  13857. tx: txMbps,
  13858. rx: rxMbps
  13859. });
  13860. if (bwtestState.chartPoints.length > bwtestState.maxChartPoints) {
  13861. bwtestState.chartPoints.shift();
  13862. }
  13863. drawBwTestChart();
  13864. // Add row to breakdown table
  13865. const tbody = document.getElementById('bwtest-samples-tbody');
  13866. if (tbody) {
  13867. const tr = document.createElement('tr');
  13868. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  13869. tr.innerHTML = `
  13870. <td class="py-1.5 px-3 font-semibold text-white">${(s.elapsed_sec || 0).toFixed(1)}s</td>
  13871. <td class="py-1.5 px-3 font-bold text-cyan-400">${txMbps.toFixed(2)} Mbps</td>
  13872. <td class="py-1.5 px-3 font-bold text-purple-400">${rxMbps.toFixed(2)} Mbps</td>
  13873. <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>
  13874. <td class="py-1.5 px-3 text-slate-300">${(s.jitter_ms || 0).toFixed(2)} ms</td>
  13875. <td class="py-1.5 px-3 text-slate-400">${formatBytes((s.tx_bytes || 0) + (s.rx_bytes || 0))}</td>
  13876. `;
  13877. tbody.insertBefore(tr, tbody.firstChild);
  13878. const countEl = document.getElementById('bwtest-sample-count');
  13879. if (countEl) countEl.innerText = `${tbody.children.length} samples`;
  13880. }
  13881. }
  13882. function handleBwTestFinish(summary, error) {
  13883. const badge = document.getElementById('bwtest-run-status-badge');
  13884. if (error) {
  13885. showToast('Benchmark Error', error, 'error');
  13886. if (badge) {
  13887. badge.innerText = 'ERROR';
  13888. 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';
  13889. }
  13890. } else if (summary) {
  13891. const avgTx = summary.avg_tx_mbps.toFixed(1);
  13892. const avgRx = summary.avg_rx_mbps.toFixed(1);
  13893. showToast('Benchmark Complete', `Average TX: ${avgTx} Mbps | RX: ${avgRx} Mbps (Loss: ${summary.avg_loss_pct.toFixed(1)}%)`, 'success');
  13894. if (badge) {
  13895. badge.innerText = 'COMPLETED';
  13896. 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';
  13897. }
  13898. }
  13899. loadBwTestHistory();
  13900. fetchBwTestServerStatus();
  13901. }
  13902. function resizeBwTestCanvas() {
  13903. const canvas = document.getElementById('bwtest-chart');
  13904. if (!canvas || !canvas.parentElement) return;
  13905. const rect = canvas.parentElement.getBoundingClientRect();
  13906. const dpr = window.devicePixelRatio || 1;
  13907. canvas.width = rect.width * dpr;
  13908. canvas.height = rect.height * dpr;
  13909. const ctx = canvas.getContext('2d');
  13910. ctx.scale(dpr, dpr);
  13911. drawBwTestChart();
  13912. }
  13913. window.addEventListener('resize', () => {
  13914. if (state.activeTab === 'bwtest') resizeBwTestCanvas();
  13915. });
  13916. function drawBwTestChart() {
  13917. const canvas = document.getElementById('bwtest-chart');
  13918. if (!canvas) return;
  13919. const ctx = canvas.getContext('2d');
  13920. const dpr = window.devicePixelRatio || 1;
  13921. const width = canvas.width / dpr;
  13922. const height = canvas.height / dpr;
  13923. ctx.clearRect(0, 0, width, height);
  13924. const points = bwtestState.chartPoints;
  13925. if (!points || points.length === 0) return;
  13926. // Determine scale ceiling
  13927. let maxRate = 10;
  13928. for (const p of points) {
  13929. if (p.tx > maxRate) maxRate = p.tx;
  13930. if (p.rx > maxRate) maxRate = p.rx;
  13931. }
  13932. maxRate = Math.ceil(maxRate * 1.25); // 25% headroom
  13933. const paddingLeft = 55;
  13934. const paddingBottom = 24;
  13935. const paddingTop = 12;
  13936. const paddingRight = 16;
  13937. const chartW = width - paddingLeft - paddingRight;
  13938. const chartH = height - paddingTop - paddingBottom;
  13939. // Grid Lines and Y-Axis labels
  13940. ctx.strokeStyle = 'rgba(51, 65, 85, 0.4)';
  13941. ctx.lineWidth = 1;
  13942. ctx.fillStyle = '#94a3b8';
  13943. ctx.font = '10px monospace';
  13944. ctx.textAlign = 'right';
  13945. const gridSteps = 4;
  13946. for (let i = 0; i <= gridSteps; i++) {
  13947. const val = (maxRate / gridSteps) * i;
  13948. const y = paddingTop + chartH - (i / gridSteps) * chartH;
  13949. ctx.beginPath();
  13950. ctx.moveTo(paddingLeft, y);
  13951. ctx.lineTo(width - paddingRight, y);
  13952. ctx.stroke();
  13953. ctx.fillText(`${Math.round(val)}M`, paddingLeft - 8, y + 3);
  13954. }
  13955. // Draw TX Line (Cyan #22d3ee)
  13956. drawSeries(ctx, points, p => p.tx, maxRate, paddingLeft, paddingTop, chartW, chartH, '#22d3ee', 'rgba(34, 211, 238, 0.15)');
  13957. // Draw RX Line (Purple #a855f7)
  13958. drawSeries(ctx, points, p => p.rx, maxRate, paddingLeft, paddingTop, chartW, chartH, '#a855f7', 'rgba(168, 85, 247, 0.15)');
  13959. }
  13960. function drawSeries(ctx, points, valFn, maxVal, left, top, w, h, strokeColor, fillColor) {
  13961. if (points.length < 2) return;
  13962. const stepX = w / Math.max(points.length - 1, 1);
  13963. // Gradient area fill
  13964. const grad = ctx.createLinearGradient(0, top, 0, top + h);
  13965. grad.addColorStop(0, fillColor);
  13966. grad.addColorStop(1, 'rgba(0, 0, 0, 0)');
  13967. ctx.beginPath();
  13968. points.forEach((p, idx) => {
  13969. const x = left + idx * stepX;
  13970. const val = valFn(p);
  13971. const y = top + h - (val / maxVal) * h;
  13972. if (idx === 0) {
  13973. ctx.moveTo(x, y);
  13974. } else {
  13975. ctx.lineTo(x, y);
  13976. }
  13977. });
  13978. // Complete path for fill
  13979. ctx.lineTo(left + (points.length - 1) * stepX, top + h);
  13980. ctx.lineTo(left, top + h);
  13981. ctx.closePath();
  13982. ctx.fillStyle = grad;
  13983. ctx.fill();
  13984. // Draw line stroke
  13985. ctx.beginPath();
  13986. ctx.lineWidth = 2.5;
  13987. ctx.strokeStyle = strokeColor;
  13988. points.forEach((p, idx) => {
  13989. const x = left + idx * stepX;
  13990. const val = valFn(p);
  13991. const y = top + h - (val / maxVal) * h;
  13992. if (idx === 0) {
  13993. ctx.moveTo(x, y);
  13994. } else {
  13995. ctx.lineTo(x, y);
  13996. }
  13997. });
  13998. ctx.stroke();
  13999. // Draw end point halo
  14000. const lastP = points[points.length - 1];
  14001. const lastX = left + (points.length - 1) * stepX;
  14002. const lastY = top + h - (valFn(lastP) / maxVal) * h;
  14003. ctx.fillStyle = strokeColor;
  14004. ctx.beginPath();
  14005. ctx.arc(lastX, lastY, 4, 0, 2 * Math.PI);
  14006. ctx.fill();
  14007. }
  14008. async function loadBwTestHistory() {
  14009. try {
  14010. const res = await fetch(`${API_BASE}/tools/bwtest/history`);
  14011. if (!res.ok) return;
  14012. const list = await res.json();
  14013. renderBwTestHistory(Array.isArray(list) ? list : []);
  14014. } catch (err) {
  14015. console.error('Failed to load BwTest history:', err);
  14016. }
  14017. }
  14018. function renderBwTestHistory(list) {
  14019. const tbody = document.getElementById('bwtest-history-tbody');
  14020. if (!tbody) return;
  14021. if (list.length === 0) {
  14022. 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>`;
  14023. return;
  14024. }
  14025. tbody.innerHTML = '';
  14026. list.forEach(item => {
  14027. const s = item.summary || {};
  14028. const tr = document.createElement('tr');
  14029. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  14030. const dirBadge = item.direction === 'both'
  14031. ? `<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>`
  14032. : item.direction === 'tx'
  14033. ? `<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>`
  14034. : `<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>`;
  14035. const protoBadge = item.protocol === 'tcp'
  14036. ? `<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>`
  14037. : `<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>`;
  14038. const dateStr = item.timestamp ? new Date(item.timestamp).toLocaleString() : '-';
  14039. tr.innerHTML = `
  14040. <td class="py-2.5 px-4 font-bold text-white font-mono text-[11px]">${escapeHtml(item.id || '-')}</td>
  14041. <td class="py-2.5 px-4 text-emerald-400 font-mono font-medium">${escapeHtml(item.target || '-')}</td>
  14042. <td class="py-2.5 px-4">${protoBadge}</td>
  14043. <td class="py-2.5 px-4">${dirBadge}</td>
  14044. <td class="py-2.5 px-4 text-slate-300">${(s.duration_sec || 0).toFixed(1)}s</td>
  14045. <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>
  14046. <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>
  14047. <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>
  14048. <td class="py-2.5 px-4 text-slate-300 font-mono">${(s.avg_jitter_ms || 0).toFixed(2)} ms</td>
  14049. <td class="py-2.5 px-4 text-slate-400 text-[11px] font-sans">${escapeHtml(dateStr)}</td>
  14050. `;
  14051. tbody.appendChild(tr);
  14052. });
  14053. }
  14054. // ======================== SETTINGS & ROUTER DNS ========================
  14055. state.settingsSubTab = 'dns';
  14056. state.dnsSettings = null;
  14057. state.dnsStaticRecords = [];
  14058. state.dnsStatus = null;
  14059. function switchSettingsSubTab(sub) {
  14060. state.settingsSubTab = sub;
  14061. const btnDns = document.getElementById('btn-settings-subtab-dns');
  14062. const btnSys = document.getElementById('btn-settings-subtab-system');
  14063. const tabDns = document.getElementById('settings-subtab-dns');
  14064. const tabSys = document.getElementById('settings-subtab-system');
  14065. if (sub === 'dns') {
  14066. if (btnDns) {
  14067. 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';
  14068. }
  14069. if (btnSys) {
  14070. 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';
  14071. }
  14072. tabDns?.classList.remove('hidden');
  14073. tabSys?.classList.add('hidden');
  14074. loadDNSSettings();
  14075. } else {
  14076. if (btnSys) {
  14077. 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';
  14078. }
  14079. if (btnDns) {
  14080. 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';
  14081. }
  14082. tabSys?.classList.remove('hidden');
  14083. tabDns?.classList.add('hidden');
  14084. loadSystemSettings();
  14085. }
  14086. }
  14087. async function loadSettingsData(showLoading = false) {
  14088. if (state.settingsSubTab === 'system') {
  14089. await loadSystemSettings();
  14090. } else {
  14091. await loadDNSSettings();
  14092. }
  14093. }
  14094. async function loadDNSSettings() {
  14095. try {
  14096. const [settingsRes, staticRes, statusRes] = await Promise.all([
  14097. fetch(`${API_BASE}/dns/settings`),
  14098. fetch(`${API_BASE}/dns/static`),
  14099. fetch(`${API_BASE}/dns/status`)
  14100. ]);
  14101. if (settingsRes.ok) {
  14102. state.dnsSettings = await settingsRes.json();
  14103. populateDNSSettingsForm(state.dnsSettings);
  14104. }
  14105. if (staticRes.ok) {
  14106. state.dnsStaticRecords = await staticRes.json();
  14107. renderStaticDNSList();
  14108. }
  14109. if (statusRes.ok) {
  14110. state.dnsStatus = await statusRes.json();
  14111. updateDNSStatusView(state.dnsStatus);
  14112. }
  14113. } catch (err) {
  14114. console.error('Failed to load DNS settings:', err);
  14115. }
  14116. }
  14117. function populateDNSSettingsForm(s) {
  14118. if (!s) return;
  14119. const dnsForm = document.getElementById('form-dns-settings');
  14120. const isEditing = dnsForm && (dnsForm.contains(document.activeElement) || dnsForm.dataset.dirty === 'true');
  14121. const dynamicEl = document.getElementById('dns-dynamic-servers-list');
  14122. if (dynamicEl) {
  14123. if (Array.isArray(s.dynamic_servers) && s.dynamic_servers.length > 0) {
  14124. 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(' ');
  14125. } else {
  14126. dynamicEl.innerText = 'None';
  14127. }
  14128. }
  14129. // If user is actively typing or editing in the form, do not overwrite their inputs!
  14130. if (isEditing) return;
  14131. const serversInput = document.getElementById('dns-servers-input');
  14132. if (serversInput) serversInput.value = (s.servers || []).join(', ');
  14133. const cacheSizeInput = document.getElementById('dns-cache-size-input');
  14134. if (cacheSizeInput) cacheSizeInput.value = s.cache_size || 2048;
  14135. const domainInput = document.getElementById('dns-domain-input');
  14136. if (domainInput) domainInput.value = s.domain || '';
  14137. const allowRemoteInput = document.getElementById('dns-allow-remote-input');
  14138. if (allowRemoteInput) allowRemoteInput.checked = s.allow_remote_requests !== false;
  14139. }
  14140. function updateDNSStatusView(st) {
  14141. if (!st) return;
  14142. const preview = document.getElementById('dns-resolv-preview');
  14143. if (preview) preview.innerText = st.resolv_conf_content || '(empty)';
  14144. const pillText = document.getElementById('dns-live-status-text');
  14145. const pill = document.getElementById('dns-live-status-pill');
  14146. if (pill && pillText) {
  14147. if (st.service_running) {
  14148. 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';
  14149. pillText.innerText = 'DNS Service Active';
  14150. } else {
  14151. 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';
  14152. pillText.innerText = 'DNS Service Inactive';
  14153. }
  14154. }
  14155. }
  14156. function appendDNSPreset(preset) {
  14157. const input = document.getElementById('dns-servers-input');
  14158. if (!input) return;
  14159. const dnsForm = document.getElementById('form-dns-settings');
  14160. if (dnsForm) dnsForm.dataset.dirty = 'true';
  14161. const current = input.value.trim();
  14162. if (!current) {
  14163. input.value = preset;
  14164. } else {
  14165. const existing = current.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  14166. const toAdd = preset.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  14167. toAdd.forEach(ip => {
  14168. if (!existing.includes(ip)) existing.push(ip);
  14169. });
  14170. input.value = existing.join(', ');
  14171. }
  14172. }
  14173. async function saveDNSSettings(e) {
  14174. e.preventDefault();
  14175. const rawServers = document.getElementById('dns-servers-input')?.value || '';
  14176. const servers = rawServers.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  14177. if (servers.length === 0) {
  14178. showToast('Validation Error', 'Please enter at least one upstream DNS server IP', 'error');
  14179. return;
  14180. }
  14181. const cacheSize = parseInt(document.getElementById('dns-cache-size-input')?.value || '2048', 10);
  14182. const domain = (document.getElementById('dns-domain-input')?.value || '').trim();
  14183. const allowRemote = document.getElementById('dns-allow-remote-input')?.checked ?? true;
  14184. try {
  14185. const res = await fetch(`${API_BASE}/dns/settings`, {
  14186. method: 'POST',
  14187. headers: { 'Content-Type': 'application/json' },
  14188. body: JSON.stringify({
  14189. servers: servers,
  14190. cache_size: cacheSize,
  14191. domain: domain,
  14192. allow_remote_requests: allowRemote
  14193. })
  14194. });
  14195. const data = await res.json();
  14196. if (res.ok) {
  14197. const dnsForm = document.getElementById('form-dns-settings');
  14198. if (dnsForm) dnsForm.dataset.dirty = 'false';
  14199. showToast('DNS Applied', 'Router DNS forwarders and resolver settings updated successfully', 'success');
  14200. loadDNSSettings();
  14201. } else {
  14202. showToast('Error', data.error || data.message || 'Failed to save DNS settings', 'error');
  14203. }
  14204. } catch (err) {
  14205. showToast('Error', err.message, 'error');
  14206. }
  14207. }
  14208. async function flushDNSCache() {
  14209. try {
  14210. const res = await fetch(`${API_BASE}/dns/flush`, { method: 'POST' });
  14211. if (res.ok) {
  14212. showToast('Cache Flushed', 'Router DNS cache cleared and static hosts reloaded', 'success');
  14213. loadDNSSettings();
  14214. } else {
  14215. const err = await res.json();
  14216. showToast('Error', err.error || 'Failed to flush cache', 'error');
  14217. }
  14218. } catch (err) {
  14219. showToast('Error', err.message, 'error');
  14220. }
  14221. }
  14222. function renderStaticDNSList() {
  14223. const tbody = document.getElementById('dns-static-tbody');
  14224. const empty = document.getElementById('dns-static-empty');
  14225. const badge = document.getElementById('dns-static-count-badge');
  14226. if (!tbody) return;
  14227. tbody.innerHTML = '';
  14228. const records = state.dnsStaticRecords || [];
  14229. if (badge) badge.innerText = `${records.length} Records`;
  14230. if (records.length === 0) {
  14231. empty?.classList.remove('hidden');
  14232. return;
  14233. }
  14234. empty?.classList.add('hidden');
  14235. records.forEach(rec => {
  14236. const tr = document.createElement('tr');
  14237. tr.className = `hover:bg-slate-800/40 transition text-xs ${rec.disabled ? 'opacity-50' : ''}`;
  14238. tr.innerHTML = `
  14239. <td class="py-2.5 px-4 font-bold text-white">${escapeHtml(rec.name)}</td>
  14240. <td class="py-2.5 px-4">
  14241. <span class="px-2 py-0.5 rounded text-[10px] font-bold ${
  14242. rec.type === 'CNAME' ? 'bg-purple-950 text-purple-300 border border-purple-800' :
  14243. (rec.type === 'AAAA' ? 'bg-blue-950 text-blue-300 border border-blue-800' : 'bg-cyan-950 text-cyan-300 border border-cyan-800')
  14244. }">
  14245. ${rec.type || 'A'}
  14246. </span>
  14247. </td>
  14248. <td class="py-2.5 px-4 text-emerald-400 font-mono">${escapeHtml(rec.address)}</td>
  14249. <td class="py-2.5 px-4 text-slate-400 font-mono">${rec.ttl || 3600}s</td>
  14250. <td class="py-2.5 px-4 text-slate-400 italic truncate max-w-[140px]">${escapeHtml(rec.comment || '-')}</td>
  14251. <td class="py-2.5 px-4">
  14252. <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'}">
  14253. ${rec.disabled ? 'Disabled' : 'Active'}
  14254. </span>
  14255. </td>
  14256. <td class="py-2.5 px-4 text-right space-x-2 font-sans whitespace-nowrap">
  14257. <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>
  14258. <button onclick="openStaticDNSModal('${rec.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold">Edit</button>
  14259. <button onclick="deleteStaticDNS('${rec.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  14260. </td>
  14261. `;
  14262. tbody.appendChild(tr);
  14263. });
  14264. }
  14265. function openStaticDNSModal(id = null) {
  14266. const modal = document.getElementById('modal-static-dns');
  14267. const title = document.getElementById('modal-static-dns-title');
  14268. const form = document.getElementById('form-static-dns');
  14269. if (!modal || !form) return;
  14270. form.reset();
  14271. document.getElementById('modal-static-dns-id').value = '';
  14272. if (id) {
  14273. const rec = (state.dnsStaticRecords || []).find(r => r.id === id);
  14274. if (rec) {
  14275. if (title) title.innerText = 'Edit Static DNS Record';
  14276. document.getElementById('modal-static-dns-id').value = rec.id;
  14277. document.getElementById('modal-static-dns-name').value = rec.name;
  14278. document.getElementById('modal-static-dns-type').value = rec.type || 'A';
  14279. document.getElementById('modal-static-dns-addr').value = rec.address;
  14280. document.getElementById('modal-static-dns-ttl').value = rec.ttl || 3600;
  14281. document.getElementById('modal-static-dns-comment').value = rec.comment || '';
  14282. document.getElementById('modal-static-dns-disabled').checked = !!rec.disabled;
  14283. }
  14284. } else {
  14285. if (title) title.innerText = 'Add Static DNS Record';
  14286. }
  14287. modal.classList.remove('hidden');
  14288. }
  14289. function closeStaticDNSModal() {
  14290. document.getElementById('modal-static-dns')?.classList.add('hidden');
  14291. }
  14292. async function submitSaveStaticDNS(e) {
  14293. e.preventDefault();
  14294. const id = document.getElementById('modal-static-dns-id')?.value || '';
  14295. const name = (document.getElementById('modal-static-dns-name')?.value || '').trim();
  14296. const type = document.getElementById('modal-static-dns-type')?.value || 'A';
  14297. const address = (document.getElementById('modal-static-dns-addr')?.value || '').trim();
  14298. const ttl = parseInt(document.getElementById('modal-static-dns-ttl')?.value || '3600', 10);
  14299. const comment = (document.getElementById('modal-static-dns-comment')?.value || '').trim();
  14300. const disabled = document.getElementById('modal-static-dns-disabled')?.checked ?? false;
  14301. if (!name || !address) {
  14302. showToast('Validation Error', 'Name and Target Address are required', 'error');
  14303. return;
  14304. }
  14305. try {
  14306. const res = await fetch(`${API_BASE}/dns/static`, {
  14307. method: 'POST',
  14308. headers: { 'Content-Type': 'application/json' },
  14309. body: JSON.stringify({ id, name, type, address, ttl, comment, disabled })
  14310. });
  14311. const data = await res.json();
  14312. if (res.ok) {
  14313. showToast('Static DNS Saved', `Saved record ${name} -> ${address}`, 'success');
  14314. closeStaticDNSModal();
  14315. loadDNSSettings();
  14316. } else {
  14317. showToast('Error', data.error || data.message || 'Failed to save record', 'error');
  14318. }
  14319. } catch (err) {
  14320. showToast('Error', err.message, 'error');
  14321. }
  14322. }
  14323. async function deleteStaticDNS(id) {
  14324. if (!confirm('Are you sure you want to delete this static DNS entry?')) return;
  14325. try {
  14326. const res = await fetch(`${API_BASE}/dns/static/${encodeURIComponent(id)}`, { method: 'DELETE' });
  14327. if (res.ok) {
  14328. showToast('Deleted', 'Static DNS record deleted', 'success');
  14329. loadDNSSettings();
  14330. }
  14331. } catch (err) {
  14332. showToast('Error', err.message, 'error');
  14333. }
  14334. }
  14335. async function toggleStaticDNS(id, disabled) {
  14336. try {
  14337. const res = await fetch(`${API_BASE}/dns/static/${encodeURIComponent(id)}/state`, {
  14338. method: 'POST',
  14339. headers: { 'Content-Type': 'application/json' },
  14340. body: JSON.stringify({ disabled })
  14341. });
  14342. if (res.ok) {
  14343. showToast('Updated', `Record ${disabled ? 'disabled' : 'enabled'}`, 'success');
  14344. loadDNSSettings();
  14345. }
  14346. } catch (err) {
  14347. showToast('Error', err.message, 'error');
  14348. }
  14349. }
  14350. async function loadSystemSettings() {
  14351. try {
  14352. const sysForm = document.getElementById('form-system-settings');
  14353. const isEditing = sysForm && (sysForm.contains(document.activeElement) || sysForm.dataset.dirty === 'true');
  14354. const res = await fetch(`${API_BASE}/system/settings`);
  14355. if (res.ok) {
  14356. const data = await res.json();
  14357. if (!isEditing) {
  14358. const hostInput = document.getElementById('system-hostname-input');
  14359. if (hostInput) hostInput.value = data.hostname || '';
  14360. const tzInput = document.getElementById('system-timezone-input');
  14361. if (tzInput && data.timezone) tzInput.value = data.timezone;
  14362. }
  14363. }
  14364. } catch (err) {
  14365. console.error('Failed to load system settings:', err);
  14366. }
  14367. }
  14368. async function saveSystemSettings(e) {
  14369. e.preventDefault();
  14370. const hostname = (document.getElementById('system-hostname-input')?.value || '').trim();
  14371. const timezone = document.getElementById('system-timezone-input')?.value || 'UTC';
  14372. try {
  14373. const res = await fetch(`${API_BASE}/system/settings`, {
  14374. method: 'POST',
  14375. headers: { 'Content-Type': 'application/json' },
  14376. body: JSON.stringify({ hostname, timezone })
  14377. });
  14378. const data = await res.json();
  14379. if (res.ok) {
  14380. const sysForm = document.getElementById('form-system-settings');
  14381. if (sysForm) sysForm.dataset.dirty = 'false';
  14382. showToast('System Updated', 'Hostname and timezone saved successfully', 'success');
  14383. const sideH = document.getElementById('side-hostname');
  14384. if (sideH) sideH.innerText = data.hostname;
  14385. } else {
  14386. showToast('Error', data.error || 'Failed to save system settings', 'error');
  14387. }
  14388. } catch (err) {
  14389. showToast('Error', err.message, 'error');
  14390. }
  14391. }
  14392. // =============================================================================
  14393. // AUTHENTICATION & USER MANAGER
  14394. // =============================================================================
  14395. async function checkAuthStatus() {
  14396. try {
  14397. const res = await originalFetch(`${API_BASE}/auth/me`, {
  14398. headers: {
  14399. 'Authorization': `Bearer ${localStorage.getItem('debtik_token') || ''}`
  14400. }
  14401. });
  14402. if (res.ok) {
  14403. const user = await res.json();
  14404. state.currentUser = user;
  14405. updateUserProfileHeader(user);
  14406. hideLoginScreen();
  14407. state.isPolling = true;
  14408. fetchData();
  14409. initLiveTrafficStream();
  14410. return true;
  14411. } else {
  14412. showLoginScreen(false);
  14413. return false;
  14414. }
  14415. } catch (err) {
  14416. showLoginScreen(false);
  14417. return false;
  14418. }
  14419. }
  14420. function showLoginScreen(isExpired = false) {
  14421. const el = document.getElementById('login-screen');
  14422. if (el) el.classList.remove('hidden');
  14423. const errEl = document.getElementById('login-error');
  14424. const errTxt = document.getElementById('login-error-text');
  14425. if (isExpired && errEl && errTxt) {
  14426. errTxt.innerText = 'Session expired. Please sign in again.';
  14427. errEl.classList.remove('hidden');
  14428. } else if (errEl) {
  14429. errEl.classList.add('hidden');
  14430. }
  14431. const pwInput = document.getElementById('login-password');
  14432. if (pwInput) pwInput.value = '';
  14433. const userInput = document.getElementById('login-username');
  14434. if (userInput && !userInput.value) userInput.focus();
  14435. else if (pwInput) pwInput.focus();
  14436. }
  14437. function hideLoginScreen() {
  14438. const el = document.getElementById('login-screen');
  14439. if (el) el.classList.add('hidden');
  14440. const errEl = document.getElementById('login-error');
  14441. if (errEl) errEl.classList.add('hidden');
  14442. }
  14443. async function handleLoginSubmit(event) {
  14444. event.preventDefault();
  14445. const username = (document.getElementById('login-username')?.value || '').trim();
  14446. const password = document.getElementById('login-password')?.value || '';
  14447. const errEl = document.getElementById('login-error');
  14448. const errTxt = document.getElementById('login-error-text');
  14449. const btn = document.getElementById('login-submit-btn');
  14450. const btnText = document.getElementById('login-btn-text');
  14451. const spinner = document.getElementById('login-btn-spinner');
  14452. if (!username || !password) {
  14453. if (errTxt) errTxt.innerText = 'Username and password are required.';
  14454. if (errEl) errEl.classList.remove('hidden');
  14455. return;
  14456. }
  14457. if (errEl) errEl.classList.add('hidden');
  14458. if (btn) btn.disabled = true;
  14459. if (btnText) btnText.innerText = 'Authenticating...';
  14460. if (spinner) spinner.classList.remove('hidden');
  14461. try {
  14462. const res = await originalFetch(`${API_BASE}/auth/login`, {
  14463. method: 'POST',
  14464. headers: { 'Content-Type': 'application/json' },
  14465. body: JSON.stringify({ username, password })
  14466. });
  14467. const data = await res.json();
  14468. if (res.ok && data.success) {
  14469. localStorage.setItem('debtik_token', data.token);
  14470. state.currentUser = data.user;
  14471. updateUserProfileHeader(data.user);
  14472. hideLoginScreen();
  14473. state.isPolling = true;
  14474. showToast('Authenticated', `Signed in as ${data.user.username}`, 'success');
  14475. const hash = window.location.hash.replace('#', '') || 'dashboard';
  14476. navigate(hash);
  14477. fetchData();
  14478. initLiveTrafficStream();
  14479. // Ensure background telemetry polling is active
  14480. if (!window._telemetryInterval) {
  14481. window._telemetryInterval = setInterval(() => {
  14482. if (state.isPolling && state.currentUser && !document.hidden) {
  14483. fetchData(false);
  14484. }
  14485. }, 5000);
  14486. }
  14487. } else {
  14488. if (errTxt) errTxt.innerText = data.message || 'Invalid username or password';
  14489. if (errEl) errEl.classList.remove('hidden');
  14490. }
  14491. } catch (err) {
  14492. if (errTxt) errTxt.innerText = err.message || 'Failed to connect to router';
  14493. if (errEl) errEl.classList.remove('hidden');
  14494. } finally {
  14495. if (btn) btn.disabled = false;
  14496. if (btnText) btnText.innerText = 'Sign In to Controller';
  14497. if (spinner) spinner.classList.add('hidden');
  14498. }
  14499. }
  14500. async function handleLogoutClick() {
  14501. try {
  14502. await originalFetch(`${API_BASE}/auth/logout`, {
  14503. method: 'POST',
  14504. headers: {
  14505. 'Authorization': `Bearer ${localStorage.getItem('debtik_token') || ''}`
  14506. }
  14507. });
  14508. } catch (e) {}
  14509. stopSessionPolling();
  14510. localStorage.removeItem('debtik_token');
  14511. state.currentUser = null;
  14512. state.isPolling = false;
  14513. if (window._telemetryInterval) {
  14514. clearInterval(window._telemetryInterval);
  14515. window._telemetryInterval = null;
  14516. }
  14517. if (trafficEventSource) {
  14518. trafficEventSource.close();
  14519. trafficEventSource = null;
  14520. }
  14521. if (trafficPollFallback) {
  14522. clearInterval(trafficPollFallback);
  14523. trafficPollFallback = null;
  14524. }
  14525. showLoginScreen(false);
  14526. showToast('Signed Out', 'You have been signed out successfully', 'info');
  14527. }
  14528. function togglePasswordVisibility(id) {
  14529. const input = document.getElementById(id);
  14530. if (!input) return;
  14531. input.type = input.type === 'password' ? 'text' : 'password';
  14532. }
  14533. function toggleUserMenu() {
  14534. const menu = document.getElementById('user-menu-dropdown');
  14535. if (menu) menu.classList.toggle('hidden');
  14536. }
  14537. function closeUserMenu() {
  14538. const menu = document.getElementById('user-menu-dropdown');
  14539. if (menu) menu.classList.add('hidden');
  14540. }
  14541. // Close user menu on outside click
  14542. document.addEventListener('click', (e) => {
  14543. const menu = document.getElementById('user-menu-dropdown');
  14544. if (!menu || menu.classList.contains('hidden')) return;
  14545. if (!e.target.closest('#user-menu-dropdown') && !e.target.closest('button[onclick*="toggleUserMenu"]')) {
  14546. menu.classList.add('hidden');
  14547. }
  14548. });
  14549. function updateUserProfileHeader(user) {
  14550. if (!user) return;
  14551. const navName = document.getElementById('nav-user-name');
  14552. if (navName) navName.innerText = user.username;
  14553. const dropName = document.getElementById('dropdown-user-name');
  14554. if (dropName) dropName.innerText = user.username;
  14555. const navRole = document.getElementById('nav-user-role');
  14556. if (navRole) navRole.innerText = (user.role || 'read').toUpperCase();
  14557. const navAvatar = document.getElementById('nav-user-avatar');
  14558. if (navAvatar) {
  14559. const initials = (user.username || 'AD').slice(0, 2).toUpperCase();
  14560. navAvatar.innerText = initials;
  14561. }
  14562. const statCurUser = document.getElementById('stat-current-user');
  14563. if (statCurUser) statCurUser.innerText = user.username;
  14564. const statCurRole = document.getElementById('stat-current-role');
  14565. if (statCurRole) statCurRole.innerText = (user.role || 'read').toUpperCase();
  14566. // Role permissions UI visibility: hide user management for non-admins
  14567. const isFullAdmin = user.role === 'full';
  14568. const navUsers = document.getElementById('nav-users');
  14569. if (navUsers) {
  14570. if (isFullAdmin) navUsers.classList.remove('hidden');
  14571. else navUsers.classList.add('hidden');
  14572. }
  14573. const dropdownUsers = document.getElementById('dropdown-item-users');
  14574. if (dropdownUsers) {
  14575. if (isFullAdmin) dropdownUsers.classList.remove('hidden');
  14576. else dropdownUsers.classList.add('hidden');
  14577. }
  14578. }
  14579. // ================= User Management CRUD =================
  14580. async function loadUsers(isManual = false) {
  14581. try {
  14582. const res = await fetch(`${API_BASE}/users`);
  14583. if (res.status === 403) {
  14584. const tbody = document.getElementById('users-table-tbody');
  14585. if (tbody) {
  14586. tbody.innerHTML = `
  14587. <tr>
  14588. <td colspan="6" class="p-6 text-center text-amber-400 font-sans">
  14589. <div class="inline-flex items-center gap-2">
  14590. <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>
  14591. <span>Viewing and managing users requires Super Administrator (full) permissions.</span>
  14592. </div>
  14593. </td>
  14594. </tr>
  14595. `;
  14596. }
  14597. return;
  14598. }
  14599. if (res.ok) {
  14600. state.users = await res.json();
  14601. renderUsersTable();
  14602. const totalUsers = document.getElementById('stat-total-users');
  14603. if (totalUsers) totalUsers.innerText = state.users.length;
  14604. const adminCount = state.users.filter(u => u.role === 'full' && !u.disabled).length;
  14605. const adminUsers = document.getElementById('stat-admin-users');
  14606. if (adminUsers) adminUsers.innerText = adminCount;
  14607. const badgeCount = document.getElementById('badge-users-count');
  14608. if (badgeCount) badgeCount.innerText = state.users.length;
  14609. if (isManual) showToast('Refreshed', 'User list updated', 'info');
  14610. }
  14611. } catch (err) {
  14612. console.error('Failed to load users:', err);
  14613. }
  14614. }
  14615. function renderUsersTable() {
  14616. const tbody = document.getElementById('users-table-tbody');
  14617. const emptyState = document.getElementById('users-empty-state');
  14618. if (!tbody) return;
  14619. tbody.innerHTML = '';
  14620. const query = (document.getElementById('users-search-input')?.value || '').trim().toLowerCase();
  14621. const filtered = (state.users || []).filter(u => {
  14622. if (!query) return true;
  14623. return u.username.toLowerCase().includes(query) ||
  14624. (u.role || '').toLowerCase().includes(query) ||
  14625. (u.comment || '').toLowerCase().includes(query);
  14626. });
  14627. if (filtered.length === 0) {
  14628. if (emptyState) emptyState.classList.remove('hidden');
  14629. return;
  14630. }
  14631. if (emptyState) emptyState.classList.add('hidden');
  14632. const currentAuthUser = state.currentUser?.username || '';
  14633. filtered.forEach(u => {
  14634. const isSelf = u.username === currentAuthUser;
  14635. const isFull = u.role === 'full';
  14636. const isWrite = u.role === 'write';
  14637. 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>`;
  14638. if (isFull) {
  14639. 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>`;
  14640. } else if (isWrite) {
  14641. 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>`;
  14642. }
  14643. const statusBadge = u.disabled
  14644. ? `<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>`
  14645. : `<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>`;
  14646. let lastLoginText = 'Never';
  14647. if (u.last_login_at && !u.last_login_at.startsWith('0001-01-01')) {
  14648. const dt = new Date(u.last_login_at);
  14649. lastLoginText = dt.toLocaleString();
  14650. }
  14651. const initials = u.username.slice(0, 2).toUpperCase();
  14652. const tr = document.createElement('tr');
  14653. tr.className = 'hover:bg-slate-800/40 transition group';
  14654. tr.innerHTML = `
  14655. <td class="py-3 px-4">
  14656. <div class="flex items-center gap-3">
  14657. <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">
  14658. ${initials}
  14659. </div>
  14660. <div>
  14661. <div class="font-bold text-white text-xs flex items-center gap-2">
  14662. <span>${escapeHtml(u.username)}</span>
  14663. ${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>' : ''}
  14664. </div>
  14665. <div class="text-[10px] text-slate-500 font-sans">Created: ${u.created_at ? new Date(u.created_at).toLocaleDateString() : '-'}</div>
  14666. </div>
  14667. </div>
  14668. </td>
  14669. <td class="py-3 px-4 font-sans">
  14670. ${roleBadge}
  14671. </td>
  14672. <td class="py-3 px-4 font-sans">
  14673. ${statusBadge}
  14674. </td>
  14675. <td class="py-3 px-4 text-slate-300 font-sans text-xs">
  14676. ${escapeHtml(u.comment) || '<span class="text-slate-600">-</span>'}
  14677. </td>
  14678. <td class="py-3 px-4 text-slate-400 text-xs">
  14679. ${lastLoginText}
  14680. </td>
  14681. <td class="py-3 px-4 text-right space-x-1.5 font-sans">
  14682. <button onclick="openAdminResetPasswordModal('${escapeHtml(u.username)}')"
  14683. class="p-1.5 rounded-lg text-slate-400 hover:text-amber-400 hover:bg-slate-800 transition" title="Reset User Password">
  14684. <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>
  14685. </button>
  14686. <button onclick="openEditUserModal('${escapeHtml(u.username)}')"
  14687. class="p-1.5 rounded-lg text-slate-400 hover:text-cyan-400 hover:bg-slate-800 transition" title="Edit User">
  14688. <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>
  14689. </button>
  14690. ${!isSelf ? `
  14691. <button onclick="deleteUser('${escapeHtml(u.username)}')"
  14692. class="p-1.5 rounded-lg text-slate-400 hover:text-rose-400 hover:bg-slate-800 transition" title="Delete User">
  14693. <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>
  14694. </button>
  14695. ` : ''}
  14696. </td>
  14697. `;
  14698. tbody.appendChild(tr);
  14699. });
  14700. }
  14701. function openAddUserModal() {
  14702. document.getElementById('user-add-username').value = '';
  14703. document.getElementById('user-add-password').value = '';
  14704. document.getElementById('user-add-confirm').value = '';
  14705. document.getElementById('user-add-role').value = 'full';
  14706. document.getElementById('user-add-comment').value = '';
  14707. document.getElementById('modal-add-user')?.classList.remove('hidden');
  14708. document.getElementById('user-add-username')?.focus();
  14709. }
  14710. function closeAddUserModal() {
  14711. document.getElementById('modal-add-user')?.classList.add('hidden');
  14712. }
  14713. async function submitAddUser(event) {
  14714. event.preventDefault();
  14715. const username = (document.getElementById('user-add-username')?.value || '').trim();
  14716. const password = document.getElementById('user-add-password')?.value || '';
  14717. const confirm = document.getElementById('user-add-confirm')?.value || '';
  14718. const role = document.getElementById('user-add-role')?.value || 'full';
  14719. const comment = (document.getElementById('user-add-comment')?.value || '').trim();
  14720. if (password !== confirm) {
  14721. showToast('Validation Error', 'Passwords do not match', 'warning');
  14722. return;
  14723. }
  14724. if (password.length < 4) {
  14725. showToast('Validation Error', 'Password must be at least 4 characters', 'warning');
  14726. return;
  14727. }
  14728. try {
  14729. const res = await fetch(`${API_BASE}/users`, {
  14730. method: 'POST',
  14731. headers: { 'Content-Type': 'application/json' },
  14732. body: JSON.stringify({ username, password, role, comment })
  14733. });
  14734. const data = await res.json();
  14735. if (res.ok) {
  14736. showToast('User Created', `Created user ${username} with ${role.toUpperCase()} permissions`, 'success');
  14737. closeAddUserModal();
  14738. loadUsers(false);
  14739. } else {
  14740. showToast('Error', data.message || 'Failed to create user', 'error');
  14741. }
  14742. } catch (err) {
  14743. showToast('Error', err.message, 'error');
  14744. }
  14745. }
  14746. function openEditUserModal(username) {
  14747. const user = (state.users || []).find(u => u.username === username);
  14748. if (!user) return;
  14749. document.getElementById('user-edit-username').value = user.username;
  14750. document.getElementById('user-edit-username-title').innerText = `@${user.username}`;
  14751. document.getElementById('user-edit-role').value = user.role || 'read';
  14752. document.getElementById('user-edit-comment').value = user.comment || '';
  14753. document.getElementById('user-edit-disabled').checked = !!user.disabled;
  14754. document.getElementById('modal-edit-user')?.classList.remove('hidden');
  14755. }
  14756. function closeEditUserModal() {
  14757. document.getElementById('modal-edit-user')?.classList.add('hidden');
  14758. }
  14759. async function submitEditUser(event) {
  14760. event.preventDefault();
  14761. const username = document.getElementById('user-edit-username')?.value;
  14762. const role = document.getElementById('user-edit-role')?.value || 'read';
  14763. const comment = (document.getElementById('user-edit-comment')?.value || '').trim();
  14764. const disabled = document.getElementById('user-edit-disabled')?.checked || false;
  14765. try {
  14766. const res = await fetch(`${API_BASE}/users/${encodeURIComponent(username)}`, {
  14767. method: 'PUT',
  14768. headers: { 'Content-Type': 'application/json' },
  14769. body: JSON.stringify({ role, comment, disabled })
  14770. });
  14771. const data = await res.json();
  14772. if (res.ok) {
  14773. showToast('User Updated', `Updated settings for ${username}`, 'success');
  14774. closeEditUserModal();
  14775. loadUsers(false);
  14776. // If updated own role/disabled status, refresh self profile
  14777. if (username === state.currentUser?.username) {
  14778. checkAuthStatus();
  14779. }
  14780. } else {
  14781. showToast('Error', data.message || 'Failed to update user', 'error');
  14782. }
  14783. } catch (err) {
  14784. showToast('Error', err.message, 'error');
  14785. }
  14786. }
  14787. function openAdminResetPasswordModal(username) {
  14788. document.getElementById('admin-reset-username').value = username;
  14789. document.getElementById('admin-reset-username-title').innerText = `@${username}`;
  14790. document.getElementById('admin-reset-new-pw').value = '';
  14791. document.getElementById('admin-reset-confirm-pw').value = '';
  14792. document.getElementById('modal-admin-reset-pw')?.classList.remove('hidden');
  14793. document.getElementById('admin-reset-new-pw')?.focus();
  14794. }
  14795. function closeAdminResetPasswordModal() {
  14796. document.getElementById('modal-admin-reset-pw')?.classList.add('hidden');
  14797. }
  14798. async function submitAdminResetPassword(event) {
  14799. event.preventDefault();
  14800. const username = document.getElementById('admin-reset-username')?.value;
  14801. const newPassword = document.getElementById('admin-reset-new-pw')?.value || '';
  14802. const confirm = document.getElementById('admin-reset-confirm-pw')?.value || '';
  14803. if (newPassword !== confirm) {
  14804. showToast('Validation Error', 'Passwords do not match', 'warning');
  14805. return;
  14806. }
  14807. if (newPassword.length < 4) {
  14808. showToast('Validation Error', 'Password must be at least 4 characters', 'warning');
  14809. return;
  14810. }
  14811. try {
  14812. const res = await fetch(`${API_BASE}/users/${encodeURIComponent(username)}/password`, {
  14813. method: 'POST',
  14814. headers: { 'Content-Type': 'application/json' },
  14815. body: JSON.stringify({ new_password: newPassword })
  14816. });
  14817. const data = await res.json();
  14818. if (res.ok) {
  14819. showToast('Password Reset', `Password for user ${username} updated successfully`, 'success');
  14820. closeAdminResetPasswordModal();
  14821. } else {
  14822. showToast('Error', data.message || 'Failed to reset password', 'error');
  14823. }
  14824. } catch (err) {
  14825. showToast('Error', err.message, 'error');
  14826. }
  14827. }
  14828. async function deleteUser(username) {
  14829. if (username === state.currentUser?.username) {
  14830. showToast('Action Forbidden', 'You cannot delete your own account', 'warning');
  14831. return;
  14832. }
  14833. if (!confirm(`Are you sure you want to completely remove user "${username}"?`)) {
  14834. return;
  14835. }
  14836. try {
  14837. const res = await fetch(`${API_BASE}/users/${encodeURIComponent(username)}`, {
  14838. method: 'DELETE'
  14839. });
  14840. const data = await res.json();
  14841. if (res.ok) {
  14842. showToast('User Deleted', `User ${username} has been removed`, 'success');
  14843. loadUsers(false);
  14844. } else {
  14845. showToast('Error', data.message || 'Failed to delete user', 'error');
  14846. }
  14847. } catch (err) {
  14848. showToast('Error', err.message, 'error');
  14849. }
  14850. }
  14851. function openSelfPasswordModal() {
  14852. document.getElementById('self-current-password').value = '';
  14853. document.getElementById('self-new-password').value = '';
  14854. document.getElementById('self-confirm-password').value = '';
  14855. document.getElementById('modal-self-password')?.classList.remove('hidden');
  14856. document.getElementById('self-current-password')?.focus();
  14857. }
  14858. function closeSelfPasswordModal() {
  14859. document.getElementById('modal-self-password')?.classList.add('hidden');
  14860. }
  14861. async function submitSelfPassword(event) {
  14862. event.preventDefault();
  14863. const oldPassword = document.getElementById('self-current-password')?.value || '';
  14864. const newPassword = document.getElementById('self-new-password')?.value || '';
  14865. const confirm = document.getElementById('self-confirm-password')?.value || '';
  14866. if (newPassword !== confirm) {
  14867. showToast('Validation Error', 'New passwords do not match', 'warning');
  14868. return;
  14869. }
  14870. if (newPassword.length < 4) {
  14871. showToast('Validation Error', 'Password must be at least 4 characters', 'warning');
  14872. return;
  14873. }
  14874. try {
  14875. const res = await fetch(`${API_BASE}/auth/change-password`, {
  14876. method: 'POST',
  14877. headers: { 'Content-Type': 'application/json' },
  14878. body: JSON.stringify({ old_password: oldPassword, new_password: newPassword })
  14879. });
  14880. const data = await res.json();
  14881. if (res.ok) {
  14882. showToast('Password Changed', 'Your password has been changed successfully', 'success');
  14883. closeSelfPasswordModal();
  14884. } else {
  14885. showToast('Error', data.message || 'Failed to change password', 'error');
  14886. }
  14887. } catch (err) {
  14888. showToast('Error', err.message, 'error');
  14889. }
  14890. }
  14891. // ==================== MANAGEMENT SERVICES (/ip service) ====================
  14892. state.services = [];
  14893. async function loadServices(manual = false) {
  14894. try {
  14895. const res = await fetch(`${API_BASE}/system/services`);
  14896. if (!res.ok) throw new Error('Failed to load services');
  14897. const data = await res.json();
  14898. state.services = data || [];
  14899. renderServicesTable();
  14900. updateCertificatesBadges();
  14901. if (manual) showToast('Services Updated', 'Service status synchronized', 'success');
  14902. } catch (err) {
  14903. if (manual) showToast('Error', err.message, 'error');
  14904. }
  14905. }
  14906. function renderServicesTable() {
  14907. const tbody = document.getElementById('services-table-body');
  14908. if (!tbody) return;
  14909. if (!state.services || state.services.length === 0) {
  14910. tbody.innerHTML = '<tr><td colspan="5" class="py-6 text-center text-slate-500 text-xs">No services configured.</td></tr>';
  14911. return;
  14912. }
  14913. tbody.innerHTML = state.services.map(s => {
  14914. const isOff = s.disabled;
  14915. const statusBadge = isOff
  14916. ? '<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>'
  14917. : '<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>';
  14918. const toggleBtn = isOff
  14919. ? `<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>`
  14920. : `<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>`;
  14921. let certBadge = '';
  14922. if (s.name === 'www-ssl') {
  14923. if (s.certificate) {
  14924. 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>`;
  14925. } else {
  14926. 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>`;
  14927. }
  14928. }
  14929. const certArg = s.certificate ? `'${escapeHtml(s.certificate)}'` : "''";
  14930. return `
  14931. <tr class="hover:bg-slate-800/40 transition">
  14932. <td class="py-3 px-4 font-bold text-white uppercase">${s.name} ${certBadge}</td>
  14933. <td class="py-3 px-4">
  14934. <div class="flex items-center gap-2">
  14935. <span class="text-cyan-400 font-mono font-bold">${s.port}</span>
  14936. <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">
  14937. <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>
  14938. </button>
  14939. </div>
  14940. </td>
  14941. <td class="py-3 px-4">${statusBadge}</td>
  14942. <td class="py-3 px-4 text-slate-400 text-xs font-sans">${s.comment || '-'}</td>
  14943. <td class="py-3 px-4 text-right">
  14944. <div class="flex items-center justify-end gap-2">
  14945. <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">
  14946. <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>
  14947. <span>Edit</span>
  14948. </button>
  14949. ${toggleBtn}
  14950. </div>
  14951. </td>
  14952. </tr>
  14953. `;
  14954. }).join('');
  14955. }
  14956. function openEditServiceModal(serviceName, currentPort, isDisabled, currentCert = '') {
  14957. document.getElementById('modal-service-name').value = serviceName;
  14958. document.getElementById('modal-service-disabled').value = String(isDisabled);
  14959. document.getElementById('modal-service-display-name').textContent = serviceName.toUpperCase();
  14960. document.getElementById('modal-service-port').value = currentPort;
  14961. const hintEl = document.getElementById('modal-service-port-hint');
  14962. const warnEl = document.getElementById('modal-service-warning');
  14963. const certGroup = document.getElementById('modal-service-cert-group');
  14964. const certSelect = document.getElementById('modal-service-cert-select');
  14965. if (serviceName === 'www') {
  14966. hintEl.textContent = 'Default HTTP web port: 80';
  14967. warnEl.classList.remove('hidden');
  14968. certGroup.classList.add('hidden');
  14969. } else if (serviceName === 'www-ssl') {
  14970. hintEl.textContent = 'Default HTTPS web port: 443';
  14971. warnEl.classList.remove('hidden');
  14972. certGroup.classList.remove('hidden');
  14973. const populateCertOptions = (certs) => {
  14974. certSelect.innerHTML = '<option value="">-- No Certificate Selected --</option>';
  14975. (certs || []).forEach(c => {
  14976. const opt = document.createElement('option');
  14977. opt.value = c.name;
  14978. opt.textContent = `${c.name} (${c.common_name})${c.is_ca ? ' [CA]' : ''}`;
  14979. if (c.name === currentCert) opt.selected = true;
  14980. certSelect.appendChild(opt);
  14981. });
  14982. };
  14983. if (state.certificates && state.certificates.length > 0) {
  14984. populateCertOptions(state.certificates);
  14985. } else {
  14986. loadCertificates(false).then(() => {
  14987. populateCertOptions(state.certificates);
  14988. });
  14989. }
  14990. } else if (serviceName === 'telnet') {
  14991. hintEl.textContent = 'Default Telnet console port: 8282';
  14992. warnEl.classList.add('hidden');
  14993. certGroup.classList.add('hidden');
  14994. } else if (serviceName === 'ssh') {
  14995. hintEl.textContent = 'Default SSH port: 2222';
  14996. warnEl.classList.add('hidden');
  14997. certGroup.classList.add('hidden');
  14998. } else {
  14999. hintEl.textContent = '';
  15000. warnEl.classList.add('hidden');
  15001. certGroup.classList.add('hidden');
  15002. }
  15003. const modal = document.getElementById('modal-service-edit');
  15004. modal.classList.remove('hidden');
  15005. setTimeout(() => document.getElementById('modal-service-port').focus(), 50);
  15006. }
  15007. function closeEditServiceModal() {
  15008. const modal = document.getElementById('modal-service-edit');
  15009. if (modal) modal.classList.add('hidden');
  15010. }
  15011. async function submitSaveServicePort(event) {
  15012. event.preventDefault();
  15013. const name = document.getElementById('modal-service-name').value;
  15014. const disabled = document.getElementById('modal-service-disabled').value === 'true';
  15015. const port = parseInt(document.getElementById('modal-service-port').value, 10);
  15016. if (isNaN(port) || port < 1 || port > 65535) {
  15017. showToast('Invalid Port', 'Port must be a valid number between 1 and 65535', 'error');
  15018. return;
  15019. }
  15020. const certSelect = document.getElementById('modal-service-cert-select');
  15021. const certVal = (name === 'www-ssl' && certSelect) ? certSelect.value : '';
  15022. try {
  15023. const res = await fetch(`${API_BASE}/system/services/${name}`, {
  15024. method: 'POST',
  15025. headers: { 'Content-Type': 'application/json' },
  15026. body: JSON.stringify({ port: port, disabled: disabled, certificate: certVal })
  15027. });
  15028. if (!res.ok) {
  15029. const errData = await res.json();
  15030. throw new Error(errData.message || 'Failed to update service settings');
  15031. }
  15032. closeEditServiceModal();
  15033. showToast('Service Updated', `Service ${name.toUpperCase()} settings saved`, 'success');
  15034. await loadServices();
  15035. } catch (err) {
  15036. showToast('Error', err.message, 'error');
  15037. }
  15038. }
  15039. async function toggleServiceState(serviceName, newDisabled) {
  15040. if (serviceName === 'www' && newDisabled) {
  15041. 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?")) {
  15042. return;
  15043. }
  15044. }
  15045. if (serviceName === 'www-ssl' && !newDisabled) {
  15046. const sslSvc = (state.services || []).find(s => s.name === 'www-ssl');
  15047. if (!sslSvc || !sslSvc.certificate) {
  15048. showToast('Certificate Required', 'Please assign an SSL/TLS certificate to www-ssl before enabling HTTPS.', 'warning');
  15049. openEditServiceModal('www-ssl', sslSvc ? sslSvc.port : 443, false, '');
  15050. return;
  15051. }
  15052. }
  15053. try {
  15054. const res = await fetch(`${API_BASE}/system/services/${serviceName}/state`, {
  15055. method: 'POST',
  15056. headers: { 'Content-Type': 'application/json' },
  15057. body: JSON.stringify({ disabled: newDisabled })
  15058. });
  15059. if (!res.ok) {
  15060. const errData = await res.json();
  15061. throw new Error(errData.message || 'Failed to update service');
  15062. }
  15063. showToast('Service Updated', `Service ${serviceName} is now ${newDisabled ? 'disabled' : 'enabled'}`, 'success');
  15064. await loadServices();
  15065. } catch (err) {
  15066. showToast('Error', err.message, 'error');
  15067. }
  15068. }
  15069. // ==================== SYSTEM LOGS (/log) ====================
  15070. state.logs = [];
  15071. let logsTimer = null;
  15072. async function loadLogs(manual = false) {
  15073. const limitEl = document.getElementById('logs-limit-select');
  15074. const limit = limitEl ? limitEl.value : '100';
  15075. try {
  15076. const res = await fetch(`${API_BASE}/system/logs?limit=${limit}`);
  15077. if (!res.ok) throw new Error('Failed to load logs');
  15078. const data = await res.json();
  15079. state.logs = data.logs || [];
  15080. renderLogsTable();
  15081. if (manual) showToast('Logs Refreshed', `Fetched ${state.logs.length} log records`, 'success');
  15082. } catch (err) {
  15083. if (manual) showToast('Error', err.message, 'error');
  15084. }
  15085. // Setup auto-refresh if enabled and on logs tab
  15086. if (!logsTimer && state.currentUser) {
  15087. logsTimer = setInterval(() => {
  15088. if (state.currentUser && !document.hidden && state.activeTab === 'logs') {
  15089. const auto = document.getElementById('logs-auto-refresh');
  15090. if (auto && auto.checked) {
  15091. loadLogs(false);
  15092. }
  15093. }
  15094. }, 3000);
  15095. }
  15096. }
  15097. function renderLogsTable() {
  15098. const tbody = document.getElementById('logs-table-body');
  15099. if (!tbody) return;
  15100. const search = (document.getElementById('logs-search-input')?.value || '').toLowerCase();
  15101. const topicFilter = (document.getElementById('logs-topic-filter')?.value || '').toLowerCase();
  15102. const filtered = state.logs.filter(entry => {
  15103. if (topicFilter && !entry.topics.toLowerCase().includes(topicFilter)) {
  15104. return false;
  15105. }
  15106. if (search && !entry.message.toLowerCase().includes(search) && !entry.topics.toLowerCase().includes(search)) {
  15107. return false;
  15108. }
  15109. return true;
  15110. });
  15111. if (filtered.length === 0) {
  15112. tbody.innerHTML = '<tr><td colspan="4" class="py-8 text-center text-slate-500 text-xs">No matching log entries found.</td></tr>';
  15113. return;
  15114. }
  15115. tbody.innerHTML = filtered.map(l => {
  15116. let topicColor = 'bg-slate-800 text-slate-300 border-slate-700';
  15117. const topLower = l.topics.toLowerCase();
  15118. if (topLower.includes('auth')) {
  15119. topicColor = 'bg-amber-500/20 text-amber-300 border-amber-500/30';
  15120. } else if (topLower.includes('dhcp')) {
  15121. topicColor = 'bg-cyan-500/20 text-cyan-300 border-cyan-500/30';
  15122. } else if (topLower.includes('route')) {
  15123. topicColor = 'bg-blue-500/20 text-blue-300 border-blue-500/30';
  15124. } else if (topLower.includes('firewall')) {
  15125. topicColor = 'bg-rose-500/20 text-rose-300 border-rose-500/30';
  15126. } else if (topLower.includes('error')) {
  15127. topicColor = 'bg-red-500/20 text-red-300 border-red-500/30';
  15128. } else if (topLower.includes('system')) {
  15129. topicColor = 'bg-emerald-500/20 text-emerald-300 border-emerald-500/30';
  15130. }
  15131. const d = new Date(l.time);
  15132. const timeStr = d.toLocaleDateString('en-US', { month: 'short', day: '2-digit' }) + ' ' + d.toLocaleTimeString('en-US', { hour12: false });
  15133. return `
  15134. <tr class="hover:bg-slate-800/40 transition">
  15135. <td class="py-2 px-3 text-slate-500 font-mono">${l.id}</td>
  15136. <td class="py-2 px-3 text-slate-400 font-mono whitespace-nowrap">${timeStr}</td>
  15137. <td class="py-2 px-3 whitespace-nowrap">
  15138. <span class="px-2 py-0.5 rounded text-[10px] font-bold border ${topicColor}">${l.topics}</span>
  15139. </td>
  15140. <td class="py-2 px-3 text-slate-200 font-mono break-all">${escapeHtml(l.message)}</td>
  15141. </tr>
  15142. `;
  15143. }).join('');
  15144. }
  15145. // ==================== CERTIFICATES & SSL/TLS (/certificate) ====================
  15146. state.certificates = [];
  15147. async function loadCertificates(manual = false) {
  15148. try {
  15149. const res = await fetch(`${API_BASE}/certificates`);
  15150. if (!res.ok) throw new Error('Failed to load certificates');
  15151. state.certificates = await res.json() || [];
  15152. updateCertificatesBadges();
  15153. renderCertificatesTable();
  15154. if (manual) showToast('Certificates Updated', `Loaded ${state.certificates.length} certificates`, 'success');
  15155. } catch (err) {
  15156. if (manual) showToast('Error', err.message, 'error');
  15157. }
  15158. }
  15159. function updateCertificatesBadges() {
  15160. const total = (state.certificates || []).length;
  15161. const caCount = (state.certificates || []).filter(c => c.is_ca).length;
  15162. const bCount = document.getElementById('badge-certs-count');
  15163. if (bCount) bCount.innerText = total;
  15164. const kpiTotal = document.getElementById('kpi-certs-total');
  15165. if (kpiTotal) kpiTotal.innerText = total;
  15166. const kpiCA = document.getElementById('kpi-certs-ca');
  15167. if (kpiCA) kpiCA.innerText = caCount;
  15168. const kpiHttps = document.getElementById('kpi-https-status');
  15169. if (kpiHttps) {
  15170. const sslSvc = (state.services || []).find(s => s.name === 'www-ssl');
  15171. if (sslSvc) {
  15172. if (!sslSvc.disabled) {
  15173. 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>`;
  15174. } else {
  15175. 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>`;
  15176. }
  15177. }
  15178. }
  15179. }
  15180. function renderCertificatesTable() {
  15181. const tbody = document.getElementById('certs-table-body');
  15182. if (!tbody) return;
  15183. if (!state.certificates || state.certificates.length === 0) {
  15184. 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>';
  15185. return;
  15186. }
  15187. tbody.innerHTML = state.certificates.map(c => {
  15188. let typeBadge = '';
  15189. if (c.is_ca) {
  15190. 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>';
  15191. } else if (c.type === 'acme') {
  15192. 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>';
  15193. } else if (c.issuer && c.issuer !== c.common_name) {
  15194. 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>';
  15195. } else {
  15196. 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>';
  15197. }
  15198. const sansHtml = (c.sans && c.sans.length > 0)
  15199. ? 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('')
  15200. : '<span class="text-slate-500">-</span>';
  15201. const validTo = c.valid_to ? new Date(c.valid_to) : null;
  15202. let validStr = '-';
  15203. let validBadge = '';
  15204. if (validTo && !isNaN(validTo.getTime())) {
  15205. const now = new Date();
  15206. const daysLeft = Math.round((validTo - now) / (1000 * 60 * 60 * 24));
  15207. validStr = validTo.toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' });
  15208. if (daysLeft < 0) {
  15209. validBadge = '<span class="ml-1 text-[10px] text-rose-400 font-bold">(Expired)</span>';
  15210. } else if (daysLeft < 30) {
  15211. validBadge = `<span class="ml-1 text-[10px] text-amber-400 font-bold">(${daysLeft}d left)</span>`;
  15212. } else {
  15213. validBadge = `<span class="ml-1 text-[10px] text-slate-400">(${daysLeft}d left)</span>`;
  15214. }
  15215. }
  15216. return `
  15217. <tr class="hover:bg-slate-800/40 transition">
  15218. <td class="py-3 px-4">${typeBadge}</td>
  15219. <td class="py-3 px-4">
  15220. <div class="font-bold text-white">${escapeHtml(c.name)}</div>
  15221. <div class="text-[10px] text-slate-400 font-sans truncate max-w-xs" title="${escapeHtml(c.common_name)}">${escapeHtml(c.common_name)}</div>
  15222. </td>
  15223. <td class="py-3 px-4 text-slate-300 text-xs truncate max-w-xs" title="${escapeHtml(c.issuer || '-')}">${escapeHtml(c.issuer || '-')}</td>
  15224. <td class="py-3 px-4 max-w-xs">${sansHtml}</td>
  15225. <td class="py-3 px-4 whitespace-nowrap text-xs text-slate-300">
  15226. <span>${validStr}</span> ${validBadge}
  15227. <div class="text-[10px] text-slate-500">${c.key_type || ''}</div>
  15228. </td>
  15229. <td class="py-3 px-4 text-right whitespace-nowrap">
  15230. <div class="flex items-center justify-end gap-1.5">
  15231. <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">
  15232. <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>
  15233. <span>View</span>
  15234. </button>
  15235. <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">
  15236. <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>
  15237. </button>
  15238. </div>
  15239. </td>
  15240. </tr>
  15241. `;
  15242. }).join('');
  15243. }
  15244. // Create CA
  15245. function openCreateCAModal() {
  15246. document.getElementById('form-create-ca').reset();
  15247. document.getElementById('ca-days').value = '3650';
  15248. document.getElementById('ca-org').value = 'DebTik Network Appliance';
  15249. document.getElementById('ca-country').value = 'GR';
  15250. document.getElementById('ca-key-type').value = 'RSA-2048';
  15251. document.getElementById('modal-create-ca').classList.remove('hidden');
  15252. setTimeout(() => document.getElementById('ca-name').focus(), 50);
  15253. }
  15254. function closeCreateCAModal() {
  15255. document.getElementById('modal-create-ca').classList.add('hidden');
  15256. }
  15257. async function submitCreateCA(event) {
  15258. event.preventDefault();
  15259. const payload = {
  15260. name: document.getElementById('ca-name').value.trim(),
  15261. common_name: document.getElementById('ca-cn').value.trim(),
  15262. organization: document.getElementById('ca-org').value.trim(),
  15263. country: document.getElementById('ca-country').value.trim(),
  15264. days: parseInt(document.getElementById('ca-days').value, 10) || 3650,
  15265. key_type: document.getElementById('ca-key-type').value
  15266. };
  15267. try {
  15268. const res = await fetch(`${API_BASE}/certificates/ca`, {
  15269. method: 'POST',
  15270. headers: { 'Content-Type': 'application/json' },
  15271. body: JSON.stringify(payload)
  15272. });
  15273. if (!res.ok) {
  15274. const errData = await res.json();
  15275. throw new Error(errData.message || 'Failed to create CA');
  15276. }
  15277. closeCreateCAModal();
  15278. showToast('CA Created', `Root CA ${payload.name} generated successfully`, 'success');
  15279. await loadCertificates();
  15280. } catch (err) {
  15281. showToast('Error', err.message, 'error');
  15282. }
  15283. }
  15284. // Create Cert
  15285. function openCreateCertModal() {
  15286. document.getElementById('form-create-cert').reset();
  15287. document.getElementById('cert-days').value = '730';
  15288. document.getElementById('cert-key-type').value = 'RSA-2048';
  15289. const caSelect = document.getElementById('cert-ca-select');
  15290. caSelect.innerHTML = '<option value="">[ Self-Signed Certificate ]</option>';
  15291. (state.certificates || []).filter(c => c.is_ca).forEach(ca => {
  15292. const opt = document.createElement('option');
  15293. opt.value = ca.name;
  15294. opt.textContent = `${ca.name} (${ca.common_name})`;
  15295. caSelect.appendChild(opt);
  15296. });
  15297. document.getElementById('modal-create-cert').classList.remove('hidden');
  15298. setTimeout(() => document.getElementById('cert-name').focus(), 50);
  15299. }
  15300. function closeCreateCertModal() {
  15301. document.getElementById('modal-create-cert').classList.add('hidden');
  15302. }
  15303. async function submitCreateCert(event) {
  15304. event.preventDefault();
  15305. const rawSans = document.getElementById('cert-sans').value;
  15306. const sansList = rawSans ? rawSans.split(',').map(s => s.trim()).filter(Boolean) : [];
  15307. const caName = document.getElementById('cert-ca-select').value;
  15308. const payload = {
  15309. name: document.getElementById('cert-name').value.trim(),
  15310. common_name: document.getElementById('cert-cn').value.trim(),
  15311. ca_name: caName,
  15312. sans: sansList,
  15313. days: parseInt(document.getElementById('cert-days').value, 10) || 730,
  15314. key_type: document.getElementById('cert-key-type').value,
  15315. is_server: true
  15316. };
  15317. try {
  15318. const res = await fetch(`${API_BASE}/certificates/generate`, {
  15319. method: 'POST',
  15320. headers: { 'Content-Type': 'application/json' },
  15321. body: JSON.stringify(payload)
  15322. });
  15323. if (!res.ok) {
  15324. const errData = await res.json();
  15325. throw new Error(errData.message || 'Failed to issue certificate');
  15326. }
  15327. closeCreateCertModal();
  15328. showToast('Certificate Issued', `Certificate ${payload.name} generated successfully`, 'success');
  15329. await loadCertificates();
  15330. } catch (err) {
  15331. showToast('Error', err.message, 'error');
  15332. }
  15333. }
  15334. // Let's Encrypt
  15335. function openLetsEncryptModal() {
  15336. document.getElementById('form-letsencrypt').reset();
  15337. document.getElementById('modal-letsencrypt').classList.remove('hidden');
  15338. setTimeout(() => document.getElementById('le-domain').focus(), 50);
  15339. }
  15340. function closeLetsEncryptModal() {
  15341. document.getElementById('modal-letsencrypt').classList.add('hidden');
  15342. }
  15343. async function submitLetsEncrypt(event) {
  15344. event.preventDefault();
  15345. const domain = document.getElementById('le-domain').value.trim();
  15346. const email = document.getElementById('le-email').value.trim();
  15347. let name = document.getElementById('le-name').value.trim();
  15348. if (!name) name = domain.replace(/[^a-zA-Z0-9_-]/g, '-');
  15349. const staging = document.getElementById('le-staging').checked;
  15350. const btn = document.getElementById('btn-submit-letsencrypt');
  15351. const origBtnHtml = btn.innerHTML;
  15352. btn.disabled = true;
  15353. 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>`;
  15354. try {
  15355. const res = await fetch(`${API_BASE}/certificates/letsencrypt`, {
  15356. method: 'POST',
  15357. headers: { 'Content-Type': 'application/json' },
  15358. body: JSON.stringify({
  15359. name: name,
  15360. domain: domain,
  15361. email: email,
  15362. staging: staging
  15363. })
  15364. });
  15365. if (!res.ok) {
  15366. const errData = await res.json();
  15367. throw new Error(errData.message || 'Let\'s Encrypt challenge failed');
  15368. }
  15369. closeLetsEncryptModal();
  15370. showToast('Let\'s Encrypt Issued', `Successfully issued trusted certificate for ${domain}`, 'success');
  15371. await loadCertificates();
  15372. } catch (err) {
  15373. showToast('Let\'s Encrypt Error', err.message, 'error');
  15374. } finally {
  15375. btn.disabled = false;
  15376. btn.innerHTML = origBtnHtml;
  15377. }
  15378. }
  15379. // Import Cert
  15380. function openImportCertModal() {
  15381. document.getElementById('form-import-cert').reset();
  15382. document.getElementById('modal-import-cert').classList.remove('hidden');
  15383. setTimeout(() => document.getElementById('import-cert-name').focus(), 50);
  15384. }
  15385. function closeImportCertModal() {
  15386. document.getElementById('modal-import-cert').classList.add('hidden');
  15387. }
  15388. async function submitImportCert(event) {
  15389. event.preventDefault();
  15390. const payload = {
  15391. name: document.getElementById('import-cert-name').value.trim(),
  15392. cert_pem: document.getElementById('import-cert-pem').value.trim(),
  15393. key_pem: document.getElementById('import-key-pem').value.trim()
  15394. };
  15395. try {
  15396. const res = await fetch(`${API_BASE}/certificates/import`, {
  15397. method: 'POST',
  15398. headers: { 'Content-Type': 'application/json' },
  15399. body: JSON.stringify(payload)
  15400. });
  15401. if (!res.ok) {
  15402. const errData = await res.json();
  15403. throw new Error(errData.message || 'Failed to import certificate');
  15404. }
  15405. closeImportCertModal();
  15406. showToast('Certificate Imported', `Imported ${payload.name} successfully`, 'success');
  15407. await loadCertificates();
  15408. } catch (err) {
  15409. showToast('Error', err.message, 'error');
  15410. }
  15411. }
  15412. // View / Export Modal
  15413. async function openViewCertModal(name) {
  15414. const c = (state.certificates || []).find(x => x.name === name);
  15415. if (!c) return;
  15416. document.getElementById('view-cert-modal-title').textContent = `Certificate: ${c.name}`;
  15417. document.getElementById('view-cert-cn').textContent = c.common_name || '-';
  15418. document.getElementById('view-cert-issuer').textContent = c.issuer || '-';
  15419. document.getElementById('view-cert-type').textContent = `${c.is_ca ? 'CA' : 'Server/Client'} (${c.key_type || 'Unknown'})`;
  15420. document.getElementById('view-cert-validto').textContent = c.valid_to ? new Date(c.valid_to).toLocaleString() : '-';
  15421. document.getElementById('view-cert-sans').textContent = (c.sans && c.sans.length > 0) ? c.sans.join(', ') : 'None';
  15422. document.getElementById('view-cert-fp').textContent = c.fingerprint || '-';
  15423. document.getElementById('view-cert-pem-text').value = 'Loading PEM...';
  15424. document.getElementById('view-key-pem-text').value = 'Loading Key...';
  15425. document.getElementById('modal-view-cert').classList.remove('hidden');
  15426. try {
  15427. const res = await fetch(`${API_BASE}/certificates/${encodeURIComponent(name)}/export`);
  15428. if (!res.ok) throw new Error('Failed to export certificate PEM');
  15429. const data = await res.json();
  15430. document.getElementById('view-cert-pem-text').value = data.cert_pem || '';
  15431. document.getElementById('view-key-pem-text').value = data.key_pem || '(Private key not available)';
  15432. } catch (err) {
  15433. document.getElementById('view-cert-pem-text').value = 'Error loading certificate PEM: ' + err.message;
  15434. document.getElementById('view-key-pem-text').value = '';
  15435. }
  15436. }
  15437. function closeViewCertModal() {
  15438. document.getElementById('modal-view-cert').classList.add('hidden');
  15439. }
  15440. function copyCertPEM() {
  15441. const text = document.getElementById('view-cert-pem-text').value;
  15442. if (!text) return;
  15443. navigator.clipboard.writeText(text).then(() => {
  15444. showToast('Copied', 'Certificate PEM copied to clipboard', 'info');
  15445. }).catch(() => {
  15446. showToast('Error', 'Failed to copy to clipboard', 'error');
  15447. });
  15448. }
  15449. function copyKeyPEM() {
  15450. const text = document.getElementById('view-key-pem-text').value;
  15451. if (!text) return;
  15452. navigator.clipboard.writeText(text).then(() => {
  15453. showToast('Copied', 'Private Key PEM copied to clipboard', 'info');
  15454. }).catch(() => {
  15455. showToast('Error', 'Failed to copy to clipboard', 'error');
  15456. });
  15457. }
  15458. async function deleteCertificate(name) {
  15459. if (!confirm(`Are you sure you want to delete certificate "${name}"? This action cannot be undone.`)) {
  15460. return;
  15461. }
  15462. try {
  15463. const res = await fetch(`${API_BASE}/certificates/${encodeURIComponent(name)}`, {
  15464. method: 'DELETE'
  15465. });
  15466. if (!res.ok) {
  15467. const errData = await res.json();
  15468. throw new Error(errData.message || 'Failed to delete certificate');
  15469. }
  15470. showToast('Certificate Deleted', `Certificate "${name}" removed`, 'success');
  15471. await loadCertificates();
  15472. } catch (err) {
  15473. showToast('Error', err.message, 'error');
  15474. }
  15475. }
  15476. // Refresh immediately when returning to a backgrounded controller tab.
  15477. document.addEventListener('visibilitychange', () => {
  15478. if (!state.currentUser) return;
  15479. if (document.hidden) {
  15480. if (trafficEventSource) trafficEventSource.close();
  15481. trafficEventSource = null;
  15482. if (trafficPollFallback) clearInterval(trafficPollFallback);
  15483. trafficPollFallback = null;
  15484. } else {
  15485. fetchData(false);
  15486. initLiveTrafficStream();
  15487. if (state.activeTab === 'bwtest') loadBwTestView();
  15488. }
  15489. });
  15490. async function loadUpdateStatus(populate = true) {
  15491. try {
  15492. const res = await fetch(`${API_BASE}/update/status`);
  15493. if (!res.ok) throw new Error(await responseError(res));
  15494. const data = await res.json();
  15495. if (populate && document.activeElement?.id !== 'update-repository') document.getElementById('update-repository').value = data.repository || '';
  15496. if (populate && document.activeElement?.id !== 'update-tls-pin') document.getElementById('update-tls-pin').value = data.tls_key_pin || '';
  15497. document.getElementById('update-installed').textContent = data.installed_version || 'unknown';
  15498. document.getElementById('update-state').textContent = data.state || 'idle';
  15499. document.getElementById('update-log').textContent = data.log || '';
  15500. } catch (err) { showToast('Update Status', err.message, 'error'); }
  15501. }
  15502. async function saveUpdateConfig() {
  15503. try {
  15504. const repository = document.getElementById('update-repository').value.trim();
  15505. const branch = 'master';
  15506. const tls_key_pin = document.getElementById('update-tls-pin').value.trim();
  15507. const res = await fetch(`${API_BASE}/update/config`, {method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({repository,branch,tls_key_pin})});
  15508. if (!res.ok) throw new Error(await responseError(res));
  15509. document.getElementById('update-install-button').disabled = true;
  15510. document.getElementById('update-available').textContent = '—';
  15511. showToast('Update Source Saved', 'Repository and branch saved', 'success');
  15512. await loadUpdateStatus(false);
  15513. } catch (err) { showToast('Update Source', err.message, 'error'); }
  15514. }
  15515. async function checkUpdate() {
  15516. try {
  15517. const res = await fetch(`${API_BASE}/update/check`, {method:'POST'});
  15518. if (!res.ok) throw new Error(await responseError(res));
  15519. const data = await res.json();
  15520. document.getElementById('update-available').textContent = data.available_version;
  15521. document.getElementById('update-install-button').disabled = !data.update_available;
  15522. showToast('Git Check', data.update_available ? 'An update is available' : 'No newer version available', 'info');
  15523. } catch (err) { showToast('Git Check Failed', err.message, 'error'); }
  15524. }
  15525. async function startUpdate(action) {
  15526. if (!confirm(action === 'rollback' ? 'Restore the previous version and restart DebTik?' : 'Install the newer release version and restart DebTik?')) return;
  15527. try {
  15528. const res = await fetch(`${API_BASE}/update/${action}`, {method:'POST'});
  15529. if (!res.ok) throw new Error(await responseError(res));
  15530. showToast('Update Started', 'The service will restart; reconnect after a few seconds', 'info');
  15531. await loadUpdateStatus(false);
  15532. } catch (err) { showToast('Update Failed', err.message, 'error'); }
  15533. }