app.js 947 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789
  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(), successes: new Map() };
  6. let coreRefreshPromise = null;
  7. let lastSummaryRefresh = 0;
  8. // Map endpoint paths to the views that consume them, so unrelated failures do not
  9. // hide whether the current view has fresh data.
  10. function viewUsesEndpoint(tab, path) {
  11. const endpoints = {
  12. dashboard: ['/system/status', '/interfaces', '/vpn/status', '/firewall/summary'],
  13. interfaces: ['/interfaces', '/vlans', '/roles'],
  14. firewall: ['/firewall/summary', '/firewall/filter', '/firewall/nat', '/firewall/mangle', '/firewall/address-lists'],
  15. routes: ['/routes', '/routing/rules', '/routing/tables'],
  16. 'routing-filters': ['/routing/filters', '/routing/filters/community-lists', '/routing/filters/as-lists'],
  17. bgp: ['/routing/bgp/instance', '/routing/bgp/peers', '/routing/bgp/networks', '/routing/bgp/routes'],
  18. ospf: ['/routing/ospf/instances', '/routing/ospf/areas', '/routing/ospf/templates', '/routing/ospf/neighbors', '/routing/ospf/lsa'],
  19. rip: ['/routing/rip/instances', '/routing/rip/interfaces', '/routing/rip/neighbors-live', '/routing/rip/routes'],
  20. bfd: ['/routing/bfd/instance', '/routing/bfd/interfaces', '/routing/bfd/peers', '/routing/bfd/sessions'],
  21. babel: ['/routing/babel/instances', '/routing/babel/interfaces', '/routing/babel/neighbors', '/routing/babel/routes'],
  22. radv: ['/routing/radv/instances', '/routing/radv/interfaces'],
  23. eigrp: ['/routing/eigrp/instances', '/routing/eigrp/interfaces', '/routing/eigrp/networks', '/routing/eigrp/neighbors', '/routing/eigrp/topology'],
  24. 'dhcp-client': ['/dhcp/clients'], 'dhcp-server': ['/dhcp-server/servers', '/dhcp-server/networks', '/dhcp-server/leases'],
  25. bridge: ['/bridge/summary'], sdwan: ['/sdwan/groups', '/sdwan/telemetry'],
  26. ppp: ['/vpn/ppp/secrets', '/vpn/ppp/profiles', '/vpn/ppp/active'],
  27. aerotun: ['/vpn/aerotun/tunnels', '/vpn/aerotun/stats'], wireguard: ['/vpn/wireguard/interfaces', '/vpn/wireguard/peers'],
  28. eoip: ['/vpn/eoip'], vxlan: ['/vpn/vxlan', '/vpn/vxlan/vteps'], pppoe: ['/vpn/pppoe/clients'],
  29. ipsec: ['/vpn/ipsec/tunnels'], l2tp: ['/vpn/l2tp/clients'], pptp: ['/vpn/pptp/clients'],
  30. vrrp: ['/vrrp/summary'], logs: ['/system/logs'], users: ['/users'],
  31. services: ['/system/services'], certificates: ['/certificates'], settings: ['/dns/settings', '/dns/static', '/dns/status'],
  32. reverse_proxy: ['/proxy/config', '/proxy/rules'], updates: ['/update/status']
  33. };
  34. return (endpoints[tab] || []).some(endpoint => path === '/api' + endpoint);
  35. }
  36. function renderViewDataHealth() {
  37. const el = document.getElementById('view-data-health');
  38. if (!el) return;
  39. const tab = state.activeTab;
  40. el.hidden = !['dashboard','interfaces','firewall','routes','routing-filters','bgp','ospf','rip','bfd','babel','radv','eigrp','dhcp-client','dhcp-server','bridge','sdwan','ppp','aerotun','wireguard','eoip','vxlan','pppoe','ipsec','l2tp','pptp','vrrp','logs','users','services','certificates','settings','reverse_proxy','updates'].includes(tab);
  41. if (el.hidden) return;
  42. const failures = [...telemetryHealth.failures].filter(([path]) => viewUsesEndpoint(tab, path));
  43. const successes = [...telemetryHealth.successes].filter(([path]) => viewUsesEndpoint(tab, path));
  44. if (!failures.length && !successes.length) {
  45. el.textContent = 'View data: waiting';
  46. el.title = 'No successful data request recorded for this view';
  47. } else if (failures.length) {
  48. el.textContent = 'View data: incomplete or unavailable';
  49. el.title = failures.map(([path, error]) => `${path}: ${error}`).join('\n');
  50. } else {
  51. const oldest = Math.min(...successes.map(([, time]) => time));
  52. const seconds = Math.floor((Date.now() - oldest) / 1000);
  53. el.textContent = `Tracked data: oldest update ${seconds}s ago`;
  54. el.title = 'Oldest successful response among tracked requests for this view';
  55. }
  56. el.className = `text-[10px] font-mono ${failures.length || !successes.length || Date.now() - Math.min(...successes.map(([, time]) => time)) > 60000 ? 'text-amber-400' : 'text-emerald-400'}`;
  57. }
  58. function renderTelemetryHealth() {
  59. const el = document.getElementById('telemetry-health');
  60. if (!el) return;
  61. const failures = [...telemetryHealth.failures.entries()];
  62. const seconds = telemetryHealth.lastSuccess ? Math.floor((Date.now() - telemetryHealth.lastSuccess) / 1000) : null;
  63. const stale = seconds === null || seconds > 15;
  64. el.textContent = failures.length ? `Data unavailable / incomplete${seconds === null ? '' : ` · updated ${seconds}s ago`}` : stale ? 'Waiting for fresh data' : `Updated ${seconds}s ago`;
  65. el.className = `text-[10px] font-mono ${failures.length || stale ? 'text-amber-400' : 'text-emerald-400'}`;
  66. 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';
  67. }
  68. function stopSessionPolling() {
  69. if (window._telemetryInterval) clearInterval(window._telemetryInterval);
  70. window._telemetryInterval = null;
  71. if (trafficEventSource) trafficEventSource.close();
  72. trafficEventSource = null;
  73. if (trafficPollFallback) clearInterval(trafficPollFallback);
  74. trafficPollFallback = null;
  75. if (bwtestState.pollTimer) clearInterval(bwtestState.pollTimer);
  76. bwtestState.pollTimer = null;
  77. if (logsTimer) clearInterval(logsTimer);
  78. logsTimer = null;
  79. stopFwStatPolling();
  80. stopNATStatPolling();
  81. stopMangleStatPolling();
  82. telemetryHealth.failures.clear();
  83. telemetryHealth.successes.clear();
  84. telemetryHealth.lastSuccess = 0;
  85. lastSummaryRefresh = 0;
  86. }
  87. window.fetch = async function(resource, options = {}) {
  88. const url = new URL(resource instanceof Request ? resource.url : resource, window.location.href);
  89. const isAPI = url.origin === window.location.origin && url.pathname.startsWith('/api/');
  90. if (!isAPI) return originalFetch(resource, options);
  91. const config = { ...options, headers: new Headers(options.headers || (resource instanceof Request ? resource.headers : undefined)) };
  92. const token = localStorage.getItem('debtik_token');
  93. if (token && !config.headers.has('Authorization')) config.headers.set('Authorization', `Bearer ${token}`);
  94. const method = (config.method || (resource instanceof Request ? resource.method : 'GET')).toUpperCase();
  95. const isRead = method === 'GET' && !url.pathname.includes('/stream') && !url.pathname.startsWith('/api/auth/');
  96. const key = `${url.href}|${JSON.stringify([...config.headers])}`;
  97. if (isRead && pendingAPIReads.has(key)) return (await pendingAPIReads.get(key)).clone();
  98. const perform = async () => {
  99. let timeout;
  100. if (isRead && !config.signal) {
  101. const controller = new AbortController();
  102. config.signal = controller.signal;
  103. timeout = setTimeout(() => controller.abort(), 15000);
  104. }
  105. try {
  106. const response = await originalFetch(resource, config);
  107. if (isRead) {
  108. if (response.ok) {
  109. telemetryHealth.lastSuccess = Date.now();
  110. telemetryHealth.successes.set(url.pathname, telemetryHealth.lastSuccess);
  111. telemetryHealth.failures.delete(url.pathname);
  112. } else {
  113. telemetryHealth.failures.set(url.pathname, `HTTP ${response.status}; displayed values may be old`);
  114. }
  115. renderTelemetryHealth();
  116. renderViewDataHealth();
  117. }
  118. if (response.status === 401 && url.pathname !== '/api/auth/login' && state.currentUser && token === localStorage.getItem('debtik_token')) {
  119. stopSessionPolling();
  120. state.isPolling = false;
  121. state.currentUser = null;
  122. localStorage.removeItem('debtik_token');
  123. showLoginScreen(true);
  124. }
  125. return response;
  126. } catch (err) {
  127. if (isRead) {
  128. telemetryHealth.failures.set(url.pathname, err.name === 'AbortError' ? 'Request timed out' : 'Connection failed; displayed values may be old');
  129. renderTelemetryHealth();
  130. renderViewDataHealth();
  131. }
  132. throw err;
  133. } finally {
  134. if (timeout) clearTimeout(timeout);
  135. }
  136. };
  137. if (!isRead) return perform();
  138. const request = perform();
  139. pendingAPIReads.set(key, request);
  140. try { return (await request).clone(); }
  141. finally { if (pendingAPIReads.get(key) === request) pendingAPIReads.delete(key); }
  142. };
  143. let state = {
  144. currentUser: null,
  145. users: [],
  146. interfaces: [],
  147. vlans: [],
  148. systemStatus: null,
  149. vpnStatus: null,
  150. routes: [],
  151. activeTab: 'dashboard',
  152. fwSubTab: 'filter',
  153. bridgeSubTab: 'bridges',
  154. bridges: [],
  155. bridgePorts: [],
  156. bridgeVLANs: [],
  157. bridgeHosts: [],
  158. bridgeSummary: null,
  159. routesSubTab: 'routes',
  160. pppSubTab: 'secrets',
  161. eoipTunnels: [],
  162. vxlanTunnels: [],
  163. vxlanVteps: [],
  164. pppSecrets: [],
  165. pppProfiles: [],
  166. pppActiveSessions: [],
  167. pppoeServer: null,
  168. pptpServer: null,
  169. l2tpServer: null,
  170. ipsecServer: null,
  171. ifaceFilter: 'all',
  172. currentModalIface: null,
  173. isPolling: false,
  174. expandedParents: new Set(['eth0']),
  175. pppoeData: null,
  176. wgData: null,
  177. ipsecData: null,
  178. l2tpData: null,
  179. pptpData: null,
  180. fwSummary: null,
  181. filterRules: [],
  182. natRules: [],
  183. mangleRules: [],
  184. addressLists: [],
  185. connections: [],
  186. policyRules: [],
  187. routingTables: [],
  188. routingFilters: [],
  189. filterChainSelected: 'all',
  190. activeToolsSubTab: 'ping',
  191. dhcpClients: [],
  192. dhcpSummary: null,
  193. dhcpServerTab: 'servers',
  194. dhcpServers: [],
  195. dhcpNetworks: [],
  196. dhcpLeases: [],
  197. dhcpOptions: [],
  198. dhcpServerSummary: null,
  199. sdwanGroups: [],
  200. sdwanTelemetry: null
  201. };
  202. const API_BASE = '/api';
  203. function escapeHtml(str) {
  204. if (str === null || str === undefined) return '';
  205. return String(str)
  206. .replace(/&/g, '&')
  207. .replace(/</g, '&lt;')
  208. .replace(/>/g, '&gt;')
  209. .replace(/"/g, '&quot;')
  210. .replace(/'/g, '&#039;');
  211. }
  212. function formatBytes(bytes) {
  213. if (bytes === undefined || bytes === null || isNaN(bytes) || bytes === 0) return '0 B';
  214. const k = 1024;
  215. const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
  216. const i = Math.floor(Math.log(bytes) / Math.log(k));
  217. if (i < 0 || i >= sizes.length) return `${bytes} B`;
  218. return `${parseFloat((bytes / Math.pow(k, i)).toFixed(2))} ${sizes[i]}`;
  219. }
  220. // Initialize on page load
  221. document.addEventListener('DOMContentLoaded', async () => {
  222. initTableSorting();
  223. // Verify authentication before bootstrapping telemetry and views
  224. const isAuthenticated = await checkAuthStatus();
  225. if (isAuthenticated) {
  226. const hash = window.location.hash.replace('#', '') || 'dashboard';
  227. navigate(hash);
  228. // Full state telemetry polling every 5 seconds (smooth & flicker-free)
  229. if (!window._telemetryInterval) {
  230. window._telemetryInterval = setInterval(() => {
  231. if (state.isPolling && state.currentUser && !document.hidden) {
  232. fetchData(false);
  233. }
  234. }, 5000);
  235. }
  236. }
  237. });
  238. let trafficEventSource = null;
  239. let trafficPollFallback = null;
  240. function initLiveTrafficStream() {
  241. if (trafficEventSource) {
  242. try { trafficEventSource.close(); } catch(e) {}
  243. trafficEventSource = null;
  244. }
  245. if (trafficPollFallback) {
  246. clearInterval(trafficPollFallback);
  247. trafficPollFallback = null;
  248. }
  249. if (window.EventSource) {
  250. try {
  251. trafficEventSource = new EventSource(`${API_BASE}/interfaces/traffic/stream`);
  252. trafficEventSource.onmessage = (event) => {
  253. try {
  254. const data = JSON.parse(event.data);
  255. updateLiveInterfaceTraffic(data);
  256. } catch (e) {
  257. console.error('Error parsing live traffic event:', e);
  258. }
  259. };
  260. trafficEventSource.onerror = () => {
  261. // Fallback polling if SSE disconnects
  262. if (!trafficPollFallback) {
  263. trafficPollFallback = setInterval(pollLiveTrafficSnapshot, 1000);
  264. }
  265. };
  266. trafficEventSource.onopen = () => {
  267. if (trafficPollFallback) {
  268. clearInterval(trafficPollFallback);
  269. trafficPollFallback = null;
  270. }
  271. };
  272. return;
  273. } catch (e) {
  274. console.warn('EventSource failed, using 1s polling fallback:', e);
  275. }
  276. }
  277. // Fallback if EventSource is unavailable
  278. trafficPollFallback = setInterval(pollLiveTrafficSnapshot, 1000);
  279. }
  280. async function pollLiveTrafficSnapshot() {
  281. try {
  282. const res = await fetch(`${API_BASE}/interfaces/traffic/rates`);
  283. if (res.ok) {
  284. const data = await res.json();
  285. updateLiveInterfaceTraffic(data);
  286. }
  287. } catch (e) {}
  288. }
  289. function updateLiveInterfaceTraffic(data) {
  290. if (!data || !data.interfaces) return;
  291. state.latestTraffic = data;
  292. // 1. Update Top & Dashboard Total Bandwidth Indicators
  293. const rxHuman = data.total_rx_human || '0 B/s';
  294. const txHuman = data.total_tx_human || '0 B/s';
  295. const statRx = document.getElementById('stat-traffic-rx');
  296. if (statRx && statRx.innerText !== rxHuman) statRx.innerText = rxHuman;
  297. const statTx = document.getElementById('stat-traffic-tx');
  298. if (statTx && statTx.innerText !== txHuman) statTx.innerText = txHuman;
  299. // 2. Update state.interfaces rates in-memory
  300. if (Array.isArray(state.interfaces)) {
  301. state.interfaces.forEach(i => {
  302. const live = data.interfaces[i.name];
  303. if (live) {
  304. i.rate = {
  305. rx_bytes_sec: live.rx_bytes_sec,
  306. tx_bytes_sec: live.tx_bytes_sec,
  307. rx_human: live.rx_human,
  308. tx_human: live.tx_human
  309. };
  310. i.stats = {
  311. rx_bytes: live.rx_bytes,
  312. tx_bytes: live.tx_bytes,
  313. rx_packets: live.rx_packets,
  314. tx_packets: live.tx_packets,
  315. rx_errors: live.rx_errors,
  316. tx_errors: live.tx_errors,
  317. rx_dropped: live.rx_dropped,
  318. tx_dropped: live.tx_dropped
  319. };
  320. }
  321. });
  322. }
  323. // 3. Update all live UI rate spans in-place (ZERO flicker)
  324. Object.keys(data.interfaces).forEach(name => {
  325. const live = data.interfaces[name];
  326. // Dashboard Port Matrix Card
  327. const cardRate = document.getElementById(`port-card-rate-${name}`);
  328. if (cardRate && cardRate.innerText !== live.rx_human) {
  329. cardRate.innerText = live.rx_human;
  330. }
  331. // Dashboard Quick Interfaces Table
  332. const quickRx = document.getElementById(`quick-rx-${name}`);
  333. if (quickRx) quickRx.innerText = `↓ ${live.rx_human}`;
  334. const quickTx = document.getElementById(`quick-tx-${name}`);
  335. if (quickTx) quickTx.innerText = `↑ ${live.tx_human}`;
  336. // Main Interfaces Tree Table
  337. const ifaceRx = document.getElementById(`iface-rate-rx-${name}`);
  338. if (ifaceRx) ifaceRx.innerText = `↓ ${live.rx_human}`;
  339. const ifaceTx = document.getElementById(`iface-rate-tx-${name}`);
  340. if (ifaceTx) ifaceTx.innerText = `↑ ${live.tx_human}`;
  341. // VLAN Sub-interfaces Table
  342. const vlanRx = document.getElementById(`vlan-rate-rx-${name}`);
  343. if (vlanRx) vlanRx.innerText = `↓ ${live.rx_human}`;
  344. const vlanTx = document.getElementById(`vlan-rate-tx-${name}`);
  345. if (vlanTx) vlanTx.innerText = `↑ ${live.tx_human}`;
  346. // VLAN Page Table
  347. const vlanPageRx = document.getElementById(`vlan-page-rate-rx-${name}`);
  348. if (vlanPageRx) vlanPageRx.innerText = `↓ ${live.rx_human}`;
  349. const vlanPageTx = document.getElementById(`vlan-page-rate-tx-${name}`);
  350. if (vlanPageTx) vlanPageTx.innerText = `↑ ${live.tx_human}`;
  351. });
  352. }
  353. // Navigation Handler
  354. function navigate(tabName) {
  355. if (tabName === 'dynamic-routing' || tabName === 'routing') {
  356. navigate('bgp');
  357. return;
  358. }
  359. if (tabName === 'vlans') {
  360. navigate('interfaces');
  361. return;
  362. }
  363. if (tabName === 'persistence') {
  364. navigate('dashboard');
  365. return;
  366. }
  367. stopFwStatPolling();
  368. stopNATStatPolling();
  369. stopMangleStatPolling();
  370. state.activeTab = tabName;
  371. renderViewDataHealth();
  372. window.location.hash = tabName;
  373. // Update nav links styling
  374. document.querySelectorAll('.nav-link').forEach(link => {
  375. 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';
  376. });
  377. const activeNav = document.getElementById(`nav-${tabName}`);
  378. if (activeNav) {
  379. 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';
  380. }
  381. // Update page headers
  382. const titles = {
  383. dashboard: { title: 'Dashboard Overview', sub: 'Live router performance and network telemetry' },
  384. interfaces: { title: 'Network Interfaces', sub: 'Interface Table View' },
  385. 'dhcp-client': { title: 'DHCP Client', sub: 'DHCP Client List' },
  386. 'dhcp-server': { title: 'DHCP Server & Subnets', sub: 'DHCP Server instances, subnet networks (NTP, TFTP, DNS), dynamic leases & static reservations' },
  387. bridge: { title: 'Bridge Interfaces', sub: 'IEEE 802.1D / 802.1Q VLAN-aware Layer 2 switching, RSTP & hardware forwarding (FDB)' },
  388. vlans: { title: 'VLAN Virtual Networks', sub: 'IEEE 802.1Q sub-interface segmentation and routing' },
  389. firewall: { title: 'Network Firewall', sub: 'Stateful packet inspection, NAT, traffic mangle, address lists & connection tracking' },
  390. routes: { title: 'Routing & Policy', sub: 'Routing tables, static routes (DAS/DAC), and policy routing rules' },
  391. sdwan: { title: 'Software-Defined WAN (SD-WAN)', sub: 'Multi-link aggregation, traffic load balancing & quality SLA health monitoring' },
  392. bgp: { title: 'BGP Dynamic Routing', sub: 'BGP multi-instance peering sessions, advertised networks, and routing table (RIB)' },
  393. ospf: { title: 'OSPF Dynamic Routing', sub: 'OSPFv2 link-state routing, dynamic neighbor adjacencies, and multi-area topology' },
  394. rip: { title: 'RIP Dynamic Routing', sub: 'Routing Information Protocol (RIPv2 IPv4 & RIPng IPv6) hop-count distance-vector routing' },
  395. bfd: { title: 'BFD Fast Session Detection', sub: 'Bidirectional Forwarding Detection (BFD) sub-second link failure detection for BGP and OSPF' },
  396. babel: { title: 'Babel Dynamic Routing', sub: 'Babel loop-avoiding distance-vector routing for wired and wireless mesh networks (RFC 8966)' },
  397. radv: { title: 'IPv6 Router Advertisements (RAdv)', sub: 'BIRD 2 ICMPv6 Router Advertisement daemon for IPv6 SLAAC autoconfiguration and RDNSS' },
  398. eigrp: { title: 'EIGRP Dynamic Routing', sub: 'Enhanced Interior Gateway Routing Protocol (RFC 7868) DUAL routing, neighbors and topology' },
  399. 'routing-filters': { title: 'Routing Policy Filters', sub: 'Route filter chains, prefix matching, BGP community maps & policy-based path control' },
  400. 'dynamic-routing': { title: 'BGP Dynamic Routing', sub: 'Dynamic routing engine and peering sessions' },
  401. ppp: { title: 'PPP Servers & Secrets', sub: 'Subscriber authentication, dynamic IP pools and VPN access concentrators' },
  402. eoip: { title: 'EoIP Tunnels', sub: 'Ethernet over IP (EoIP / GRETAP) Layer 2 encapsulation & transparent network bridging' },
  403. vxlan: { title: 'VXLAN Tunnels', sub: 'Virtual Extensible LAN (RFC 7348) Layer 2 overlay networks and static VTEPs' },
  404. aerotun: { title: 'AeroTUN High-Speed VPN', sub: 'Layer 3 encrypted tunnel with XChaCha20-Poly1305 and adaptive LZ4 compression' },
  405. pppoe: { title: 'PPPoE Client WAN', sub: 'Point-to-Point Protocol over Ethernet WAN access' },
  406. wireguard: { title: 'WireGuard VPN', sub: 'High-performance cryptographic Layer 3 tunnels with ChaCha20-Poly1305 key exchange' },
  407. ipsec: { title: 'IPSec (IKEv2) strongSwan', sub: 'Enterprise Site-to-Site & Roadwarrior IPSec controller' },
  408. l2tp: { title: 'L2TP VPN Client', sub: 'Layer 2 Tunneling Protocol via xl2tpd' },
  409. pptp: { title: 'PPTP VPN Client', sub: 'Point-to-Point Tunneling Protocol with MPPE-128 encryption' },
  410. vrrp: { title: 'VRRP High Availability', sub: 'Virtual Router Redundancy Protocol, active-backup gateway failover & Virtual IP (VIP) routing' },
  411. bwtest: { title: 'Bandwidth Test Benchmark', sub: 'High-speed line-rate throughput benchmark, token-bucket rate limiting, loss & jitter telemetry' },
  412. tools: { title: 'Diagnostic & Troubleshooting Tools', sub: 'Network latency analysis, ICMP/MTR telemetry, path tracing, DNS resolution and TCP probing' },
  413. settings: { title: 'Router Settings & DNS', sub: 'System DNS forwarder, upstream resolvers, static host mappings, and appliance identity' },
  414. users: { title: 'Local User Manager', sub: 'Manage local system administrator credentials and access permissions' },
  415. certificates: { title: 'Certificates & SSL/TLS', sub: 'Root Certificate Authorities (CA), Server/Client certificates and automated Let\'s Encrypt' },
  416. reverse_proxy: { title: 'Reverse Proxy & Gateway', sub: 'HTTP/HTTPS Path Routing, Domain Forwarding & SSL Termination' },
  417. services: { title: 'Management Services', sub: 'Enable or disable Web, SSH, and Telnet management listeners and listening ports' },
  418. updates: { title: 'Git Updates', sub: 'Check, install and restore appliance software' },
  419. logs: { title: 'System Activity Logs', sub: 'Real-time circular buffer log viewer and topic-based event monitoring' }
  420. };
  421. const header = titles[tabName] || titles.dashboard;
  422. const pTitle = document.getElementById('page-title');
  423. if (pTitle) pTitle.innerText = header.title;
  424. const pSub = document.getElementById('page-subtitle');
  425. if (pSub) pSub.innerText = header.sub;
  426. // Toggle sections dynamically for all section elements
  427. document.querySelectorAll('main section[id^="section-"]').forEach(el => {
  428. if (el.id === `section-${tabName}`) {
  429. el.classList.remove('hidden');
  430. } else {
  431. el.classList.add('hidden');
  432. }
  433. });
  434. if (tabName === 'interfaces') {
  435. loadRoles();
  436. if (state.activeIfaceSubTab === 'roles') switchIfaceSubTab('roles');
  437. else switchIfaceSubTab('tree');
  438. }
  439. if (tabName === 'bridge') loadBridge();
  440. if (tabName === 'firewall') loadFirewall();
  441. if (tabName === 'routes') loadRoutes();
  442. if (tabName === 'sdwan') loadSDWAN();
  443. if (tabName === 'bgp') {
  444. loadDynamicRouting();
  445. switchBgpSubTab(state.activeBgpSubTab || 'bgp-peers');
  446. }
  447. if (tabName === 'ospf') {
  448. loadDynamicRouting();
  449. switchOspfTab(state.activeOspfTab || 'instances');
  450. }
  451. if (tabName === 'rip') {
  452. loadDynamicRouting();
  453. switchRipTab(state.activeRipTab || 'instances');
  454. }
  455. if (tabName === 'bfd') {
  456. loadDynamicRouting();
  457. switchBfdTab(state.activeBfdTab || 'config');
  458. }
  459. if (tabName === 'babel') {
  460. loadDynamicRouting();
  461. switchBabelTab(state.activeBabelTab || 'instances');
  462. }
  463. if (tabName === 'radv') {
  464. loadDynamicRouting();
  465. switchRadvTab(state.activeRadvTab || 'instances');
  466. }
  467. if (tabName === 'eigrp') {
  468. loadDynamicRouting();
  469. switchEigrpTab(state.activeEigrpTab || 'instances');
  470. }
  471. if (tabName === 'routing-filters') loadDynamicRouting();
  472. if (tabName === 'dynamic-routing') loadDynamicRouting();
  473. if (tabName === 'ppp') loadPPP();
  474. if (tabName === 'eoip') loadEoIP();
  475. if (tabName === 'vxlan') loadVXLAN();
  476. if (tabName === 'aerotun') loadAeroTUN();
  477. if (tabName === 'pppoe') loadPPPoE();
  478. if (tabName === 'wireguard') loadWireGuard();
  479. if (tabName === 'ipsec') loadIPSec();
  480. if (tabName === 'l2tp') loadL2TP();
  481. if (tabName === 'pptp') loadPPTP();
  482. if (tabName === 'tools') loadToolsView();
  483. if (tabName === 'dhcp-client') loadDHCPClients();
  484. if (tabName === 'dhcp-server') loadDHCPServer();
  485. if (tabName === 'vrrp') loadVRRP();
  486. if (tabName === 'bwtest') loadBwTestView();
  487. if (tabName === 'settings') loadSettingsData();
  488. if (tabName === 'users') loadUsers();
  489. if (tabName === 'certificates') loadCertificates();
  490. if (tabName === 'reverse_proxy') loadReverseProxy();
  491. if (tabName === 'services') loadServices();
  492. if (tabName === 'updates') loadUpdateStatus();
  493. if (tabName === 'logs') loadLogs();
  494. setTimeout(initTableSorting, 50);
  495. }
  496. // Fetch all core system, network and VPN telemetry
  497. function fetchData(isManual = false) {
  498. if (coreRefreshPromise) return coreRefreshPromise;
  499. coreRefreshPromise = refreshCoreData(isManual).finally(() => { coreRefreshPromise = null; });
  500. return coreRefreshPromise;
  501. }
  502. async function refreshCoreData(isManual = false) {
  503. const spinner = document.getElementById('refresh-spinner');
  504. if (isManual && spinner) spinner.classList.add('animate-spin');
  505. try {
  506. const refreshSummaries = isManual || Date.now() - lastSummaryRefresh > 30000;
  507. const summaryFetch = path => (refreshSummaries || (state.activeTab === 'interfaces' && ['/vlans', '/roles'].includes(path))) ? fetch(`${API_BASE}${path}`).catch(() => ({ ok: false })) : Promise.resolve({ ok: false });
  508. const [statusRes, ifacesRes, vlansRes, vpnRes, fwRes, dynRes, brSummaryRes, dhcpSumRes, dhcpClientsRes, vrrpSumRes, rolesRes] = await Promise.all([
  509. fetch(`${API_BASE}/system/status`).catch(() => ({ ok: false })),
  510. fetch(`${API_BASE}/interfaces`).catch(() => ({ ok: false })),
  511. summaryFetch('/vlans'),
  512. summaryFetch('/vpn/status'),
  513. summaryFetch('/firewall/summary'),
  514. summaryFetch('/routing/dynamic/summary'),
  515. summaryFetch('/bridge/summary'),
  516. summaryFetch('/dhcp/clients/summary'),
  517. summaryFetch('/dhcp/clients'),
  518. summaryFetch('/vrrp/summary').catch(() => null),
  519. summaryFetch('/roles').catch(() => null)
  520. ]);
  521. if (refreshSummaries && [vlansRes, vpnRes, fwRes, dynRes, brSummaryRes, dhcpSumRes, dhcpClientsRes, vrrpSumRes, rolesRes].every(r => r && r.ok)) lastSummaryRefresh = Date.now();
  522. if (rolesRes && rolesRes.ok) {
  523. state.roles = await rolesRes.json();
  524. const countEl = document.getElementById('badge-roles-count');
  525. if (countEl) countEl.innerText = (state.roles || []).length;
  526. }
  527. if (vrrpSumRes && vrrpSumRes.ok) {
  528. state.vrrpSummary = await vrrpSumRes.json();
  529. renderVRRPSummary();
  530. }
  531. if (dhcpSumRes && dhcpSumRes.ok) {
  532. state.dhcpSummary = await dhcpSumRes.json();
  533. const bDhcp = document.getElementById('badge-dhcp-client-count');
  534. if (bDhcp) bDhcp.innerText = state.dhcpSummary?.total_clients || 0;
  535. }
  536. if (dhcpClientsRes && dhcpClientsRes.ok) {
  537. state.dhcpClients = await dhcpClientsRes.json();
  538. }
  539. if (brSummaryRes.ok) {
  540. state.bridgeSummary = await brSummaryRes.json();
  541. const bBridge = document.getElementById('badge-bridge-count');
  542. if (bBridge) bBridge.innerText = state.bridgeSummary?.bridges_count || 0;
  543. const sBr = document.getElementById('bridge-stat-bridges');
  544. if (sBr) sBr.innerText = state.bridgeSummary?.bridges_count || 0;
  545. const sPorts = document.getElementById('bridge-stat-ports');
  546. if (sPorts) sPorts.innerText = state.bridgeSummary?.ports_count || 0;
  547. const sHosts = document.getElementById('bridge-stat-hosts');
  548. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  549. }
  550. if (statusRes.ok) state.systemStatus = await statusRes.json();
  551. if (ifacesRes.ok) {
  552. const ifacesData = await ifacesRes.json();
  553. const rawIfaces = Array.isArray(ifacesData) ? ifacesData : [];
  554. state.interfaces = rawIfaces.filter(i => {
  555. if (!i.name) return false;
  556. if (i.name.startsWith('ep_')) return false;
  557. return !['gre0', 'gretap0', 'erspan0', 'sit0', 'tunl0', 'ip6tnl0', 'ip6gre0', 'ip6erspan0'].includes(i.name);
  558. });
  559. try { populateToolsInterfaces(); } catch (e) {}
  560. }
  561. if (vlansRes.ok) {
  562. const vlansData = await vlansRes.json();
  563. state.vlans = Array.isArray(vlansData) ? vlansData : [];
  564. }
  565. if (vpnRes.ok) state.vpnStatus = await vpnRes.json();
  566. if (fwRes && fwRes.ok) state.fwSummary = await fwRes.json();
  567. if (dynRes && dynRes.ok) state.dynSummary = await dynRes.json();
  568. updateSystemMetrics();
  569. updateBadges();
  570. if (state.activeTab === 'dashboard') renderDashboard();
  571. if (state.activeTab === 'interfaces') {
  572. if (state.activeIfaceSubTab === 'roles') renderRolesTable();
  573. else renderInterfacesList();
  574. }
  575. if (state.activeTab === 'vlans') renderVlansList();
  576. if (state.activeTab === 'firewall') await loadFirewall(false);
  577. if (state.activeTab === 'routes') await loadRoutes(false);
  578. if (state.activeTab === 'dynamic-routing' || state.activeTab === 'bgp' || state.activeTab === 'ospf' || state.activeTab === 'rip' || state.activeTab === 'bfd' || state.activeTab === 'babel' || state.activeTab === 'radv' || state.activeTab === 'eigrp' || state.activeTab === 'routing-filters') await loadDynamicRouting(false);
  579. if (state.activeTab === 'ppp') await loadPPP(false);
  580. if (state.activeTab === 'eoip') await loadEoIP(false);
  581. if (state.activeTab === 'vxlan') await loadVXLAN(false);
  582. if (state.activeTab === 'aerotun') await loadAeroTUN(false);
  583. if (state.activeTab === 'pppoe') await loadPPPoE(false);
  584. if (state.activeTab === 'wireguard') await loadWireGuard(false);
  585. if (state.activeTab === 'ipsec') await loadIPSec(false);
  586. if (state.activeTab === 'l2tp') await loadL2TP(false);
  587. if (state.activeTab === 'pptp') await loadPPTP(false);
  588. if (state.activeTab === 'dhcp-client') await loadDHCPClients(false);
  589. if (state.activeTab === 'dhcp-server') await loadDHCPServer(false);
  590. if (state.activeTab === 'vrrp') await loadVRRP(false);
  591. if (state.activeTab === 'settings') await loadSettingsData(false);
  592. if (state.activeTab === 'users') await loadUsers(false);
  593. if (state.activeTab === 'certificates') await loadCertificates(false);
  594. if (state.activeTab === 'reverse_proxy') await loadReverseProxy(false);
  595. if (state.activeTab === 'sdwan') await loadSDWAN(false);
  596. if (state.activeTab === 'services') await loadServices(false);
  597. if (state.activeTab === 'updates') await loadUpdateStatus(false);
  598. if (state.activeTab === 'bwtest') await fetchBwTestServerStatus();
  599. } catch (err) {
  600. console.error('Failed to fetch router state:', err);
  601. } finally {
  602. if (isManual && spinner) {
  603. setTimeout(() => spinner.classList.remove('animate-spin'), 300);
  604. }
  605. }
  606. }
  607. // Update Top KPI and Sidebar Telemetry
  608. function updateSystemMetrics() {
  609. const s = state.systemStatus;
  610. const v = state.vpnStatus;
  611. if (!s) return;
  612. // Sidebar Host & Uptime
  613. const sideHost = document.getElementById('side-hostname');
  614. if (sideHost) sideHost.innerText = s.hostname || 'debian-lxc';
  615. const sideUp = document.getElementById('side-uptime');
  616. if (sideUp) sideUp.innerText = s.uptime_human || '0m';
  617. const sideGw = document.getElementById('side-gateway-ip');
  618. if (sideGw) sideGw.innerText = s.default_gateway ? `GW: ${s.default_gateway}` : 'GW: Isolated';
  619. // Compute CPU Metrics
  620. let cpuPct = 0;
  621. if (s.cpu_pct !== undefined) {
  622. cpuPct = s.cpu_pct;
  623. } else if (s.cpu_load && s.cpu_load.length > 0) {
  624. const cores = s.cpu_cores || 1;
  625. cpuPct = Math.min(100, Math.round((parseFloat(s.cpu_load[0]) / cores) * 100));
  626. }
  627. const cpuPctStr = `${cpuPct.toFixed(1)}%`;
  628. const cpuWidth = `${Math.max(3, Math.min(100, cpuPct))}%`;
  629. const loadStr = s.cpu_load ? s.cpu_load.join(', ') : '-';
  630. // Sidebar CPU
  631. const sideCpuVal = document.getElementById('side-cpu-val');
  632. if (sideCpuVal) sideCpuVal.innerText = cpuPctStr;
  633. const sideCpuBar = document.getElementById('side-cpu-bar');
  634. if (sideCpuBar) {
  635. sideCpuBar.style.width = cpuWidth;
  636. sideCpuBar.title = `Container: ${cpuPctStr} | Host Loadavg: ${loadStr} (${s.cpu_cores || 1} cores)`;
  637. }
  638. // Dashboard CPU Card
  639. const dashCpuVal = document.getElementById('dash-cpu-val');
  640. if (dashCpuVal) dashCpuVal.innerText = cpuPctStr;
  641. const dashCpuBar = document.getElementById('dash-cpu-bar');
  642. if (dashCpuBar) {
  643. dashCpuBar.style.width = cpuWidth;
  644. if (cpuPct > 85) {
  645. dashCpuBar.className = 'h-full rounded-full bg-rose-500 transition-all duration-500';
  646. } else if (cpuPct > 65) {
  647. dashCpuBar.className = 'h-full rounded-full bg-amber-500 transition-all duration-500';
  648. } else {
  649. dashCpuBar.className = 'h-full rounded-full bg-emerald-500 transition-all duration-500';
  650. }
  651. }
  652. const dashCpuCores = document.getElementById('dash-cpu-cores');
  653. if (dashCpuCores) dashCpuCores.innerText = `${s.cpu_cores || 1} Cores`;
  654. const dashCpuLoad = document.getElementById('dash-cpu-load');
  655. if (dashCpuLoad) dashCpuLoad.innerText = loadStr;
  656. const dashCpuStatus = document.getElementById('dash-cpu-status');
  657. if (dashCpuStatus) {
  658. if (cpuPct > 85) {
  659. dashCpuStatus.innerText = 'High';
  660. dashCpuStatus.className = 'text-[11px] font-semibold text-rose-400 uppercase px-2 py-0.5 rounded bg-rose-500/10';
  661. } else if (cpuPct > 65) {
  662. dashCpuStatus.innerText = 'Heavy';
  663. dashCpuStatus.className = 'text-[11px] font-semibold text-amber-400 uppercase px-2 py-0.5 rounded bg-amber-500/10';
  664. } else {
  665. dashCpuStatus.innerText = 'Normal';
  666. dashCpuStatus.className = 'text-[11px] font-semibold text-emerald-400 uppercase px-2 py-0.5 rounded bg-emerald-500/10';
  667. }
  668. }
  669. // Compute RAM Metrics
  670. const memPct = Math.round(s.mem_usage_pct || 0);
  671. const memPctStr = `${memPct}%`;
  672. const memWidth = `${Math.max(3, Math.min(100, memPct))}%`;
  673. const usedMB = s.mem_used_mb || 0;
  674. const totalMB = s.mem_total_mb || 0;
  675. const freeMB = totalMB > usedMB ? totalMB - usedMB : 0;
  676. function fmtMemMB(mb) {
  677. if (mb >= 1024) {
  678. return `${(mb / 1024).toFixed(1)} GB`;
  679. }
  680. return `${mb} MB`;
  681. }
  682. // Sidebar RAM
  683. const sideRamVal = document.getElementById('side-ram-val');
  684. if (sideRamVal) sideRamVal.innerText = memPctStr;
  685. const sideRamBar = document.getElementById('side-ram-bar');
  686. if (sideRamBar) sideRamBar.style.width = memWidth;
  687. // Dashboard RAM Card
  688. const dashRamVal = document.getElementById('dash-ram-val');
  689. if (dashRamVal) dashRamVal.innerText = memPctStr;
  690. const dashRamBar = document.getElementById('dash-ram-bar');
  691. if (dashRamBar) {
  692. dashRamBar.style.width = memWidth;
  693. if (memPct > 85) {
  694. dashRamBar.className = 'h-full rounded-full bg-rose-500 transition-all duration-500';
  695. } else if (memPct > 70) {
  696. dashRamBar.className = 'h-full rounded-full bg-amber-500 transition-all duration-500';
  697. } else {
  698. dashRamBar.className = 'h-full rounded-full bg-indigo-500 transition-all duration-500';
  699. }
  700. }
  701. const dashRamUsedTotal = document.getElementById('dash-ram-used-total');
  702. if (dashRamUsedTotal) {
  703. dashRamUsedTotal.innerText = `${fmtMemMB(usedMB)} / ${fmtMemMB(totalMB)}`;
  704. }
  705. const dashRamFree = document.getElementById('dash-ram-free');
  706. if (dashRamFree) {
  707. dashRamFree.innerText = fmtMemMB(freeMB);
  708. }
  709. const dashRamStatus = document.getElementById('dash-ram-status');
  710. if (dashRamStatus) {
  711. if (memPct > 85) {
  712. dashRamStatus.innerText = 'High';
  713. dashRamStatus.className = 'text-[11px] font-semibold text-rose-400 uppercase px-2 py-0.5 rounded bg-rose-500/10';
  714. } else {
  715. dashRamStatus.innerText = 'Active';
  716. dashRamStatus.className = 'text-[11px] font-semibold text-indigo-400 uppercase px-2 py-0.5 rounded bg-indigo-500/10';
  717. }
  718. }
  719. // Legacy Dashboard Stats (Safe checks)
  720. const elIfacesUp = document.getElementById('stat-ifaces-up');
  721. if (elIfacesUp) elIfacesUp.innerText = s.up_ifaces || 0;
  722. const elIfacesTot = document.getElementById('stat-ifaces-total');
  723. if (elIfacesTot) elIfacesTot.innerText = `${s.total_ifaces || 0} Total`;
  724. const elIfacesDown = document.getElementById('stat-ifaces-down');
  725. if (elIfacesDown) elIfacesDown.innerText = `${s.down_ifaces || 0} DOWN`;
  726. const elVlans = document.getElementById('stat-vlans-count');
  727. if (elVlans) elVlans.innerText = s.vlan_ifaces || 0;
  728. // VPN Status Indicators
  729. if (v) {
  730. const totalActive = v.total_active_tunnels || 0;
  731. const statVpnActive = document.getElementById('stat-vpn-active');
  732. if (statVpnActive) statVpnActive.innerText = totalActive;
  733. const tunnelsDot = document.getElementById('tunnels-dot');
  734. const tunnelsLabel = document.getElementById('tunnels-label');
  735. if (tunnelsDot && tunnelsLabel) {
  736. if (totalActive > 0) {
  737. tunnelsDot.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  738. tunnelsLabel.innerText = `${totalActive} Active VPN Tunnel${totalActive > 1 ? 's' : ''}`;
  739. } else {
  740. tunnelsDot.className = 'w-2 h-2 rounded-full bg-slate-500';
  741. tunnelsLabel.innerText = '0 Active VPN Tunnels';
  742. }
  743. }
  744. setDotBadge('badge-pppoe-status', (v.active_pppoe || 0) > 0 || v.pppoe_connected);
  745. setDotBadge('badge-wg-status', (v.active_wireguard || 0) > 0 || v.wireguard_active);
  746. setDotBadge('badge-ipsec-status', (v.active_ipsec || 0) > 0 || v.ipsec_active);
  747. setDotBadge('badge-l2tp-status', (v.active_l2tp || 0) > 0 || v.l2tp_connected);
  748. setDotBadge('badge-pptp-status', (v.active_pptp || 0) > 0 || v.pptp_connected);
  749. }
  750. // Total Live Bandwidth Rate
  751. let totalRx = 0;
  752. let totalTx = 0;
  753. (state.interfaces || []).forEach(i => {
  754. if (i.rate) {
  755. totalRx += i.rate.rx_bytes_sec || 0;
  756. totalTx += i.rate.tx_bytes_sec || 0;
  757. }
  758. });
  759. document.getElementById('stat-traffic-rx').innerText = formatTraffic(totalRx);
  760. document.getElementById('stat-traffic-tx').innerText = formatTraffic(totalTx);
  761. }
  762. function setDotBadge(id, active) {
  763. const el = document.getElementById(id);
  764. if (!el) return;
  765. if (active) {
  766. el.className = 'w-2 h-2 rounded-full bg-emerald-400 shadow-sm shadow-emerald-400/80';
  767. } else {
  768. el.className = 'w-2 h-2 rounded-full bg-slate-600';
  769. }
  770. }
  771. function updateBadges() {
  772. const bIfaces = document.getElementById('badge-ifaces-count');
  773. if (bIfaces) bIfaces.innerText = (state.interfaces || []).length;
  774. const bVlans = document.getElementById('badge-vlans-count');
  775. if (bVlans) bVlans.innerText = (state.vlans || []).length;
  776. if (state.fwSummary) {
  777. const totalFwRules = (state.fwSummary.filter_rules_count || 0) + (state.fwSummary.nat_rules_count || 0) + (state.fwSummary.mangle_rules_count || 0);
  778. const badgeFw = document.getElementById('badge-firewall-count');
  779. if (badgeFw) badgeFw.innerText = totalFwRules;
  780. }
  781. if (state.vpnStatus) {
  782. const v = state.vpnStatus;
  783. const bEoIP = document.getElementById('badge-eoip-count');
  784. if (bEoIP) bEoIP.innerText = v.total_eoip || 0;
  785. const bVXLAN = document.getElementById('badge-vxlan-count');
  786. if (bVXLAN) bVXLAN.innerText = v.total_vxlan || 0;
  787. const bAero = document.getElementById('badge-aerotun-count');
  788. if (bAero) bAero.innerText = v.total_aerotun || 0;
  789. const bPPPSess = document.getElementById('badge-ppp-sessions');
  790. if (bPPPSess) bPPPSess.innerText = v.total_ppp_sessions || 0;
  791. setDotBadge('badge-pppoe-status', v.active_pppoe > 0 || v.pppoe_server_running);
  792. setDotBadge('badge-wg-status', v.active_wireguard > 0);
  793. setDotBadge('badge-ipsec-status', v.active_ipsec > 0 || v.ipsec_server_running);
  794. setDotBadge('badge-l2tp-status', v.active_l2tp > 0 || v.l2tp_server_running);
  795. setDotBadge('badge-pptp-status', v.active_pptp > 0 || v.pptp_server_running);
  796. }
  797. if (state.dynSummary) {
  798. const d = state.dynSummary;
  799. setDotBadge('badge-bgp-dot', d.bgp_running);
  800. setDotBadge('badge-ospf-dot', d.ospf_running);
  801. setDotBadge('badge-rip-dot', d.rip_running);
  802. setDotBadge('badge-bfd-dot', d.bfd_running);
  803. setDotBadge('badge-babel-dot', d.babel_running);
  804. setDotBadge('badge-radv-dot', d.radv_running);
  805. setDotBadge('badge-eigrp-dot', d.eigrp_running);
  806. const bBgp = document.getElementById('badge-bgp-count');
  807. if (bBgp) bBgp.innerText = (state.bgpPeers || []).length;
  808. const bOspf = document.getElementById('badge-ospf-count');
  809. if (bOspf) bOspf.innerText = (state.ospfLiveInterfaces || state.ospfTemplates || []).length;
  810. const bRip = document.getElementById('badge-rip-count');
  811. if (bRip) bRip.innerText = (state.ripInterfaces || []).length;
  812. const bBfd = document.getElementById('badge-bfd-count');
  813. if (bBfd) bBfd.innerText = (state.bfdInterfaces || []).length;
  814. const bBabel = document.getElementById('badge-babel-count');
  815. if (bBabel) bBabel.innerText = (state.babelInterfaces || []).length;
  816. const bRadv = document.getElementById('badge-radv-count');
  817. if (bRadv) bRadv.innerText = (state.radvInterfaces || []).length;
  818. const bEigrp = document.getElementById('badge-eigrp-count');
  819. if (bEigrp) bEigrp.innerText = (state.eigrpInterfaces || []).length || (state.eigrpNetworks || []).length || (state.eigrpInstances || []).length;
  820. const bFilters = document.getElementById('badge-filters-count');
  821. if (bFilters) bFilters.innerText = (state.routingFilters || []).length;
  822. }
  823. const bDhcpServer = document.getElementById('badge-dhcp-server-count');
  824. if (bDhcpServer) {
  825. bDhcpServer.innerText = state.dhcpServerSummary ? (state.dhcpServerSummary.active_leases || state.dhcpServerSummary.total_servers || 0) : (state.dhcpServers || []).length;
  826. }
  827. }
  828. // Render Dashboard View
  829. function renderDashboard() {
  830. const matrix = document.getElementById('port-matrix');
  831. if (!matrix) return;
  832. const ifaces = state.interfaces || [];
  833. const sig = ifaces.map(i => `${i.name}:${i.state}:${(i.ipv4 || []).join(',')}:${i.type}:${i.is_vlan}`).join(';');
  834. if (matrix.dataset.sig === sig) {
  835. return; // Structure & link states haven't changed! Do not rebuild or flicker!
  836. }
  837. matrix.dataset.sig = sig;
  838. matrix.innerHTML = '';
  839. (state.interfaces || []).forEach(iface => {
  840. const isUp = iface.state === 'UP';
  841. const isVlan = iface.is_vlan;
  842. const portCard = document.createElement('div');
  843. portCard.className = `p-3 rounded-xl border transition-all cursor-pointer select-none group ${
  844. isUp
  845. ? (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')
  846. : 'bg-slate-900/40 border-slate-800/60 opacity-60 hover:opacity-100 hover:border-slate-700'
  847. }`;
  848. portCard.onclick = () => openIfaceModal(iface.name);
  849. let statusPillClass = isUp ? 'bg-emerald-500 shadow-sm shadow-emerald-500/50' : 'bg-rose-500';
  850. if (isVlan) statusPillClass = isUp ? 'bg-cyan-400 shadow-sm shadow-cyan-400/50' : 'bg-rose-500';
  851. portCard.innerHTML = `
  852. <div class="flex items-center justify-between mb-2">
  853. <span class="font-bold text-xs font-mono text-white group-hover:text-brand-400 transition truncate">${iface.name}</span>
  854. <span class="w-2 h-2 rounded-full ${statusPillClass}"></span>
  855. </div>
  856. <div class="text-[11px] font-mono text-slate-300 truncate">${iface.ipv4 && iface.ipv4.length > 0 ? iface.ipv4[0] : (iface.mac || 'No IP')}</div>
  857. <div class="mt-2 flex items-center justify-between text-[10px] text-slate-400">
  858. <span class="uppercase tracking-wider font-semibold">${isVlan ? `VLAN ${iface.vlan_id}` : iface.type}</span>
  859. <span id="port-card-rate-${iface.name}">${iface.rate?.rx_human || '0 B/s'}</span>
  860. </div>
  861. `;
  862. matrix.appendChild(portCard);
  863. });
  864. const ifaceTbody = document.getElementById('quick-interfaces-table');
  865. if (ifaceTbody) {
  866. ifaceTbody.innerHTML = '';
  867. (state.interfaces || []).forEach(i => {
  868. const isUp = i.state === 'UP';
  869. const tr = document.createElement('tr');
  870. tr.className = 'hover:bg-slate-800/40 transition cursor-pointer';
  871. tr.onclick = () => openIfaceModal(i.name);
  872. const rxStr = i.rate?.rx_human || '0 B/s';
  873. const txStr = i.rate?.tx_human || '0 B/s';
  874. tr.innerHTML = `
  875. <td class="py-2.5 font-bold text-white flex items-center gap-2">
  876. <span class="w-2 h-2 rounded-full ${isUp ? 'bg-emerald-400 shadow-sm shadow-emerald-400/50' : 'bg-rose-400'}"></span>
  877. <span>${i.name}</span>
  878. </td>
  879. <td class="py-2.5 text-slate-300 font-sans">
  880. ${getRoleBadge(i.role || 'LAN')}
  881. </td>
  882. <td class="py-2.5 text-slate-400 text-[11px] font-mono">${i.mac || '-'}</td>
  883. <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>
  884. <td class="py-2.5 text-slate-300 text-[11px] font-mono">
  885. <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>
  886. </td>
  887. <td class="py-2.5 text-right font-sans font-semibold">
  888. <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>
  889. </td>
  890. `;
  891. ifaceTbody.appendChild(tr);
  892. });
  893. }
  894. const vlanTbody = document.getElementById('quick-vlans-table');
  895. if (vlanTbody) {
  896. vlanTbody.innerHTML = '';
  897. }
  898. }
  899. // Expand / Collapse Handlers
  900. function toggleExpand(parentName) {
  901. if (state.expandedParents.has(parentName)) {
  902. state.expandedParents.delete(parentName);
  903. } else {
  904. state.expandedParents.add(parentName);
  905. }
  906. renderInterfacesList();
  907. }
  908. // VLAN Support Checker: 802.1Q sub-interfaces are only supported on physical ethernet, veth, bridge, bond
  909. function supportsVLAN(iface) {
  910. if (!iface) return false;
  911. if (iface.is_vlan) return false;
  912. const name = (iface.name || '').toLowerCase();
  913. const type = (iface.type || '').toLowerCase();
  914. const role = (iface.role || '').toLowerCase();
  915. // Exclude loopback
  916. if (name === 'lo' || type === 'loopback' || role === 'loopback') return false;
  917. // Exclude WireGuard (Layer 3 tunnel, no 802.1Q support)
  918. if (type === 'wireguard' || name.startsWith('wg')) return false;
  919. // Exclude PPP / PPPoE
  920. if (type === 'ppp' || name.startsWith('ppp')) return false;
  921. // Exclude other Layer 3 tunnels and dummy devices
  922. if (type === 'dummy' || type === 'gre' || type === 'sit' || type === 'tun' || type === 'tap' ||
  923. name.startsWith('gre') || name.startsWith('sit') || name.startsWith('ipsec') || name.startsWith('xfrm') || name.startsWith('dummy')) {
  924. return false;
  925. }
  926. // If name already contains a dot, it's already a sub-interface
  927. if (name.includes('.')) return false;
  928. return true;
  929. }
  930. // DHCP Client Support Checker: Only broadcast-capable layer-2 interfaces (Ethernet, veth, VLAN, bridge, bond)
  931. function supportsDHCPClient(iface) {
  932. if (!iface) return false;
  933. const name = (iface.name || '').toLowerCase();
  934. const type = (iface.type || '').toLowerCase();
  935. const role = (iface.role || '').toLowerCase();
  936. // Exclude loopback
  937. if (name === 'lo' || type === 'loopback' || role === 'loopback') return false;
  938. // Exclude WireGuard (Layer 3 point-to-point tunnel, no broadcast/DHCP)
  939. if (type === 'wireguard' || name.startsWith('wg')) return false;
  940. // Exclude PPP / PPPoE / L2TP / PPTP tunnels
  941. if (type === 'ppp' || name.startsWith('ppp') || name.startsWith('l2tp') || name.startsWith('pptp')) return false;
  942. // Exclude other Layer 3 tunnels and dummy devices
  943. if (type === 'dummy' || type === 'gre' || type === 'sit' || type === 'tun' || type === 'tap' ||
  944. name.startsWith('gre') || name.startsWith('sit') || name.startsWith('ipsec') || name.startsWith('xfrm') || name.startsWith('dummy')) {
  945. return false;
  946. }
  947. // Exclude bridge member/slave ports (bridge itself handles IP / DHCP)
  948. const isBridgePort = (state.bridgePorts || []).some(bp => bp.interface === iface.name);
  949. if (isBridgePort) return false;
  950. return true;
  951. }
  952. // Expand / Collapse Handlers
  953. function toggleExpand(parentName) {
  954. const childVlans = (state.vlans || []).filter(v => v.parent_name === parentName || v.name.startsWith(parentName + '.'));
  955. if (childVlans.length === 0) {
  956. // Cannot expand an interface with no VLANs
  957. state.expandedParents.delete(parentName);
  958. return;
  959. }
  960. if (state.expandedParents.has(parentName)) {
  961. state.expandedParents.delete(parentName);
  962. } else {
  963. state.expandedParents.add(parentName);
  964. }
  965. renderInterfacesList();
  966. }
  967. function expandAllIfaces(expand) {
  968. if (expand) {
  969. (state.interfaces || []).forEach(i => {
  970. const hasVlans = (state.vlans || []).some(v => v.parent_name === i.name || v.name.startsWith(i.name + '.'));
  971. if (!i.is_vlan && hasVlans) state.expandedParents.add(i.name);
  972. });
  973. } else {
  974. state.expandedParents.clear();
  975. }
  976. renderInterfacesList();
  977. }
  978. // =========================================================================
  979. // INTERFACE ROLE TAGS MANAGEMENT
  980. // =========================================================================
  981. const ROLE_COLORS = {
  982. amber: { bg: 'bg-amber-500/20', text: 'text-amber-300', border: 'border-amber-500/30' },
  983. blue: { bg: 'bg-blue-500/20', text: 'text-blue-300', border: 'border-blue-500/30' },
  984. cyan: { bg: 'bg-cyan-500/20', text: 'text-cyan-300', border: 'border-cyan-500/30' },
  985. emerald: { bg: 'bg-emerald-500/20', text: 'text-emerald-300', border: 'border-emerald-500/30' },
  986. purple: { bg: 'bg-purple-500/20', text: 'text-purple-300', border: 'border-purple-500/30' },
  987. rose: { bg: 'bg-rose-500/20', text: 'text-rose-300', border: 'border-rose-500/30' },
  988. indigo: { bg: 'bg-indigo-500/20', text: 'text-indigo-300', border: 'border-indigo-500/30' },
  989. sky: { bg: 'bg-sky-500/20', text: 'text-sky-300', border: 'border-sky-500/30' },
  990. slate: { bg: 'bg-slate-800', text: 'text-slate-300', border: 'border-slate-700' }
  991. };
  992. function getRoleBadge(roleName) {
  993. const name = roleName || 'LAN';
  994. const role = (state.roles || []).find(r => r.name.toLowerCase() === name.toLowerCase() || r.id.toLowerCase() === name.toLowerCase());
  995. const colorKey = (role?.color || 'blue').toLowerCase();
  996. const theme = ROLE_COLORS[colorKey] || ROLE_COLORS.blue;
  997. 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>`;
  998. }
  999. function switchIfaceSubTab(subTab) {
  1000. state.activeIfaceSubTab = subTab;
  1001. const treeTab = document.getElementById('ifaces-subtab-tree');
  1002. const rolesTab = document.getElementById('ifaces-subtab-roles');
  1003. const btnTree = document.getElementById('ifaces-subtab-btn-tree');
  1004. const btnRoles = document.getElementById('ifaces-subtab-btn-roles');
  1005. if (subTab === 'roles') {
  1006. treeTab?.classList.add('hidden');
  1007. rolesTab?.classList.remove('hidden');
  1008. if (btnRoles) {
  1009. 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';
  1010. }
  1011. if (btnTree) {
  1012. 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';
  1013. }
  1014. loadRoles();
  1015. } else {
  1016. rolesTab?.classList.add('hidden');
  1017. treeTab?.classList.remove('hidden');
  1018. if (btnTree) {
  1019. 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';
  1020. }
  1021. if (btnRoles) {
  1022. 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';
  1023. }
  1024. renderInterfacesList();
  1025. }
  1026. }
  1027. async function loadRoles() {
  1028. try {
  1029. const res = await fetch(`${API_BASE}/roles`);
  1030. if (res.ok) {
  1031. state.roles = await res.json();
  1032. const countEl = document.getElementById('badge-roles-count');
  1033. if (countEl) countEl.innerText = (state.roles || []).length;
  1034. renderRolesTable();
  1035. populateRoleSelects();
  1036. }
  1037. } catch (err) {
  1038. console.error('Failed to load role tags:', err);
  1039. }
  1040. }
  1041. function renderRolesTable() {
  1042. const tbody = document.getElementById('roles-table-body');
  1043. const empty = document.getElementById('roles-empty-state');
  1044. if (!tbody) return;
  1045. const roles = state.roles || [];
  1046. if (roles.length === 0) {
  1047. tbody.innerHTML = '';
  1048. empty?.classList.remove('hidden');
  1049. return;
  1050. }
  1051. empty?.classList.add('hidden');
  1052. const sig = roles.map(r => `${r.id}:${r.name}:${r.color}:${r.description}:${(r.interfaces||[]).join(',')}`).join(';');
  1053. if (tbody.dataset.sig === sig) return;
  1054. tbody.dataset.sig = sig;
  1055. tbody.innerHTML = roles.map(r => {
  1056. const colorKey = (r.color || 'blue').toLowerCase();
  1057. const theme = ROLE_COLORS[colorKey] || ROLE_COLORS.blue;
  1058. const ifaces = Array.isArray(r.interfaces) ? r.interfaces : [];
  1059. const ifacesChips = ifaces.length > 0
  1060. ? 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('')
  1061. : '<span class="text-slate-600 font-sans text-xs italic">Unassigned (0)</span>';
  1062. return `
  1063. <tr class="hover:bg-slate-800/40 transition">
  1064. <td class="py-3 px-4">
  1065. <span class="px-2.5 py-1 rounded text-xs font-semibold ${theme.bg} ${theme.text} border ${theme.border}">
  1066. ${escapeHtml(r.name)}
  1067. </span>
  1068. </td>
  1069. <td class="py-3 px-4 font-bold text-white font-mono flex items-center gap-2">
  1070. <span>${escapeHtml(r.name)}</span>
  1071. ${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>' : ''}
  1072. </td>
  1073. <td class="py-3 px-4 font-sans capitalize text-slate-300">
  1074. <span class="inline-flex items-center gap-1.5">
  1075. <span class="w-2 h-2 rounded-full ${theme.bg.replace('/20', '')}"></span>
  1076. <span>${escapeHtml(r.color || 'blue')}</span>
  1077. </span>
  1078. </td>
  1079. <td class="py-3 px-4 font-sans text-slate-400 text-xs">${escapeHtml(r.description || '-')}</td>
  1080. <td class="py-3 px-4 font-sans">
  1081. <div class="flex flex-wrap items-center">
  1082. ${ifacesChips}
  1083. </div>
  1084. </td>
  1085. <td class="py-3 px-4 text-right space-x-2 font-sans whitespace-nowrap">
  1086. <button onclick="openRoleModal('${escapeHtml(r.id)}')"
  1087. class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold px-2 py-1 rounded hover:bg-slate-800 transition">
  1088. Edit
  1089. </button>
  1090. <button onclick="deleteRoleTag('${escapeHtml(r.id)}', '${escapeHtml(r.name)}')"
  1091. class="text-xs text-rose-400 hover:text-rose-300 font-semibold px-2 py-1 rounded hover:bg-slate-800 transition">
  1092. Delete
  1093. </button>
  1094. </td>
  1095. </tr>
  1096. `;
  1097. }).join('');
  1098. }
  1099. function openRoleModal(id = null) {
  1100. const modal = document.getElementById('role-modal');
  1101. if (!modal) return;
  1102. const idInput = document.getElementById('role-modal-id');
  1103. const nameInput = document.getElementById('role-modal-name');
  1104. const colorSelect = document.getElementById('role-modal-color');
  1105. const descInput = document.getElementById('role-modal-desc');
  1106. const title = document.getElementById('role-modal-title');
  1107. if (id) {
  1108. const role = (state.roles || []).find(r => r.id === id);
  1109. if (role) {
  1110. if (title) title.innerText = `Edit Role Tag: ${role.name}`;
  1111. if (idInput) idInput.value = role.id;
  1112. if (nameInput) nameInput.value = role.name;
  1113. if (colorSelect) colorSelect.value = role.color || 'blue';
  1114. if (descInput) descInput.value = role.description || '';
  1115. }
  1116. } else {
  1117. if (title) title.innerText = 'Add Role Tag';
  1118. if (idInput) idInput.value = '';
  1119. if (nameInput) nameInput.value = '';
  1120. if (colorSelect) colorSelect.value = 'blue';
  1121. if (descInput) descInput.value = '';
  1122. }
  1123. updateRoleModalPreview();
  1124. modal.classList.remove('hidden');
  1125. }
  1126. function closeRoleModal() {
  1127. const modal = document.getElementById('role-modal');
  1128. if (modal) modal.classList.add('hidden');
  1129. }
  1130. function updateRoleModalPreview() {
  1131. const name = document.getElementById('role-modal-name')?.value.trim() || 'Preview';
  1132. const colorKey = (document.getElementById('role-modal-color')?.value || 'blue').toLowerCase();
  1133. const theme = ROLE_COLORS[colorKey] || ROLE_COLORS.blue;
  1134. const preview = document.getElementById('role-modal-preview');
  1135. if (preview) {
  1136. preview.innerText = name;
  1137. preview.className = `px-2.5 py-1 rounded text-xs font-semibold ${theme.bg} ${theme.text} border ${theme.border}`;
  1138. }
  1139. }
  1140. async function submitSaveRole(e) {
  1141. e.preventDefault();
  1142. const id = document.getElementById('role-modal-id')?.value;
  1143. const name = document.getElementById('role-modal-name')?.value.trim();
  1144. const color = document.getElementById('role-modal-color')?.value;
  1145. const desc = document.getElementById('role-modal-desc')?.value.trim();
  1146. if (!name) return;
  1147. try {
  1148. const payload = { id, name, color, description: desc };
  1149. const method = id ? 'PUT' : 'POST';
  1150. const url = id ? `${API_BASE}/roles/${encodeURIComponent(id)}` : `${API_BASE}/roles`;
  1151. const res = await fetch(url, {
  1152. method,
  1153. headers: { 'Content-Type': 'application/json' },
  1154. body: JSON.stringify(payload)
  1155. });
  1156. if (res.ok) {
  1157. showToast('Role Tag Saved', `Role tag "${name}" saved successfully`, 'success');
  1158. closeRoleModal();
  1159. await loadRoles();
  1160. fetchData(false);
  1161. } else {
  1162. const err = await res.json();
  1163. showToast('Error', err.error || err.message || 'Failed to save role tag', 'error');
  1164. }
  1165. } catch (err) {
  1166. showToast('Error', err.message, 'error');
  1167. }
  1168. }
  1169. async function deleteRoleTag(id, name) {
  1170. if (!confirm(`Are you sure you want to delete role tag "${name}"?\nInterfaces assigned to this role will default to LAN.`)) return;
  1171. try {
  1172. const res = await fetch(`${API_BASE}/roles/${encodeURIComponent(id)}`, {
  1173. method: 'DELETE'
  1174. });
  1175. if (res.ok) {
  1176. showToast('Role Tag Deleted', `Role tag "${name}" removed`, 'success');
  1177. await loadRoles();
  1178. fetchData(false);
  1179. } else {
  1180. const err = await res.json();
  1181. showToast('Error', err.error || err.message || 'Failed to delete role tag', 'error');
  1182. }
  1183. } catch (err) {
  1184. showToast('Error', err.message, 'error');
  1185. }
  1186. }
  1187. function populateRoleSelects(selectedRole = '') {
  1188. const ifaceSelect = document.getElementById('modal-iface-role');
  1189. const vlanSelect = document.getElementById('vlan-role');
  1190. const roles = state.roles || [];
  1191. const optionsHtml = roles.map(r => `<option value="${escapeHtml(r.name)}">${escapeHtml(r.name)}${r.description ? ` (${escapeHtml(r.description)})` : ''}</option>`).join('');
  1192. if (ifaceSelect) {
  1193. const currentVal = selectedRole || ifaceSelect.value || 'LAN';
  1194. if (ifaceSelect.dataset.optionsSig !== optionsHtml) {
  1195. ifaceSelect.innerHTML = optionsHtml;
  1196. ifaceSelect.dataset.optionsSig = optionsHtml;
  1197. }
  1198. if (currentVal) ifaceSelect.value = currentVal;
  1199. }
  1200. if (vlanSelect) {
  1201. const currentVal = selectedRole || vlanSelect.value || 'LAN';
  1202. if (vlanSelect.dataset.optionsSig !== optionsHtml) {
  1203. vlanSelect.innerHTML = optionsHtml;
  1204. vlanSelect.dataset.optionsSig = optionsHtml;
  1205. }
  1206. if (currentVal) vlanSelect.value = currentVal;
  1207. }
  1208. }
  1209. // Filter and Render Hierarchical Interfaces List
  1210. function filterIfaces(filter) {
  1211. state.ifaceFilter = filter || 'all';
  1212. renderInterfacesList();
  1213. }
  1214. function renderInterfacesList() {
  1215. const tbody = document.getElementById('interfaces-tree-tbody');
  1216. const emptyState = document.getElementById('interfaces-empty-state');
  1217. const summary = document.getElementById('ifaces-list-summary');
  1218. const query = (document.getElementById('iface-search')?.value || '').trim().toLowerCase();
  1219. const allIfaces = state.interfaces || [];
  1220. const allVlans = state.vlans || [];
  1221. const parentIfaces = allIfaces.filter(i => !i.is_vlan);
  1222. const filteredParents = parentIfaces.filter(parent => {
  1223. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  1224. if (query) {
  1225. const matchName = parent.name.toLowerCase().includes(query);
  1226. const matchIp = (parent.ipv4 || []).some(ip => ip.toLowerCase().includes(query));
  1227. const matchRole = (parent.role || '').toLowerCase().includes(query);
  1228. const matchType = (parent.type || '').toLowerCase().includes(query);
  1229. const matchVlan = childVlans.some(v =>
  1230. v.name.toLowerCase().includes(query) ||
  1231. String(v.vlan_id).includes(query) ||
  1232. (v.ipv4 || []).some(ip => ip.toLowerCase().includes(query)) ||
  1233. (v.description || '').toLowerCase().includes(query)
  1234. );
  1235. if (!matchName && !matchIp && !matchRole && !matchType && !matchVlan) return false;
  1236. }
  1237. if (state.ifaceFilter === 'has_vlans') return childVlans.length > 0;
  1238. if (state.ifaceFilter === 'physical') return parent.type !== 'loopback';
  1239. if (state.ifaceFilter === 'up') return parent.state === 'UP';
  1240. return true;
  1241. });
  1242. if (summary) {
  1243. summary.innerText = `${parentIfaces.length} Interfaces • ${allVlans.length} Active VLANs`;
  1244. }
  1245. if (filteredParents.length === 0) {
  1246. emptyState?.classList.remove('hidden');
  1247. tbody.innerHTML = '';
  1248. return;
  1249. }
  1250. emptyState?.classList.add('hidden');
  1251. const sig = `${state.ifaceFilter}|${query}|` + filteredParents.map(p => {
  1252. const cVlans = allVlans.filter(v => v.parent_name === p.name || v.name.startsWith(p.name + '.'));
  1253. const dhcp = (state.dhcpClients || []).find(dc => dc.interface === p.name);
  1254. return `${p.name}:${p.state}:${p.role||'LAN'}:${(p.ipv4||[]).join(',')}:${p.mtu}:${cVlans.length}:${state.expandedParents.has(p.name)}:${dhcp?.status || ''}`;
  1255. }).join(';');
  1256. if (tbody.dataset.sig === sig) {
  1257. return; // ZERO changes to structure, links, IPs or VLANs! Do not rebuild DOM!
  1258. }
  1259. tbody.dataset.sig = sig;
  1260. tbody.innerHTML = '';
  1261. filteredParents.forEach(parent => {
  1262. const isUp = parent.state === 'UP';
  1263. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  1264. const hasVlans = childVlans.length > 0;
  1265. const isExpanded = hasVlans && state.expandedParents.has(parent.name);
  1266. const canHaveVlan = supportsVLAN(parent);
  1267. const parentRow = document.createElement('tr');
  1268. parentRow.className = `hover:bg-slate-800/50 transition border-b border-slate-800/80 ${isExpanded ? 'bg-slate-900/80' : ''}`;
  1269. parentRow.innerHTML = `
  1270. <td class="py-3 px-3 text-center">
  1271. ${hasVlans ? `
  1272. <button onclick="toggleExpand('${parent.name}')" title="${isExpanded ? 'Collapse VLANs' : 'Expand VLANs'}"
  1273. class="w-6 h-6 rounded flex items-center justify-center hover:bg-slate-800 text-slate-400 hover:text-white transition">
  1274. <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">
  1275. <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M9 5l7 7-7 7" />
  1276. </svg>
  1277. </button>
  1278. ` : `
  1279. <div class="w-6 h-6 flex items-center justify-center text-slate-700 select-none">
  1280. <span class="w-1.5 h-1.5 rounded-full bg-slate-800"></span>
  1281. </div>
  1282. `}
  1283. </td>
  1284. <td class="py-3 px-4">
  1285. <div class="flex items-center space-x-2.5">
  1286. <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">
  1287. ${parent.type === 'loopback' ? 'LO' : (parent.type === 'wireguard' ? 'WG' : (parent.type === 'bridge' ? 'BR' : 'NIC'))}
  1288. </div>
  1289. <div>
  1290. <div class="flex items-center gap-2">
  1291. <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'}">
  1292. <span>${parent.name}</span>
  1293. <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>
  1294. </span>
  1295. ${hasVlans ? `
  1296. <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>
  1297. ` : `
  1298. <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>
  1299. `}
  1300. </div>
  1301. <div class="text-[10px] text-slate-500 font-sans mt-0.5">${parent.type}</div>
  1302. </div>
  1303. </div>
  1304. </td>
  1305. <td class="py-3 px-4 font-sans">
  1306. <div class="flex items-center gap-1.5">
  1307. ${getRoleBadge(parent.role || 'LAN')}
  1308. <span class="text-xs text-slate-400 truncate max-w-[120px]">${parent.description || '-'}</span>
  1309. </div>
  1310. </td>
  1311. <td class="py-3 px-4">
  1312. ${parent.ipv4 && parent.ipv4.length > 0
  1313. ? `<div class="text-white font-medium">${parent.ipv4[0]}</div>`
  1314. : '<span class="text-slate-600 font-sans">Unassigned</span>'
  1315. }
  1316. ${(() => {
  1317. const c = (state.dhcpClients || []).find(dc => dc.interface === parent.name);
  1318. if (!c) return '';
  1319. 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');
  1320. 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>`;
  1321. })()}
  1322. </td>
  1323. <td class="py-3 px-4 text-slate-400 text-[11px]">
  1324. <div>${parent.mac || 'N/A'}</div>
  1325. <div class="text-[10px] text-slate-500">MTU ${parent.mtu}</div>
  1326. </td>
  1327. <td class="py-3 px-4 text-[11px]">
  1328. <div class="flex items-center space-x-2">
  1329. <span id="iface-rate-rx-${parent.name}" class="text-emerald-400">↓ ${parent.rate?.rx_human || '0 B/s'}</span>
  1330. <span id="iface-rate-tx-${parent.name}" class="text-cyan-400">↑ ${parent.rate?.tx_human || '0 B/s'}</span>
  1331. </div>
  1332. </td>
  1333. <td class="py-3 px-4 font-sans">
  1334. <button onclick="toggleInterfaceState('${parent.name}', '${isUp ? 'down' : 'up'}')"
  1335. class="flex items-center gap-1.5 text-xs font-semibold px-2.5 py-1 rounded-full transition ${
  1336. 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'
  1337. }" title="Click to toggle link status">
  1338. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  1339. <span>${parent.state}</span>
  1340. </button>
  1341. </td>
  1342. <td class="py-3 px-4 text-right space-x-2 font-sans">
  1343. ${(() => {
  1344. const c = (state.dhcpClients || []).find(dc => dc.interface === parent.name);
  1345. if (c) {
  1346. 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>`;
  1347. }
  1348. if (!supportsDHCPClient(parent)) {
  1349. return '';
  1350. }
  1351. 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>`;
  1352. })()}
  1353. ${canHaveVlan ? `
  1354. <button onclick="openVlanModal('${parent.name}')"
  1355. 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">
  1356. + Add VLAN
  1357. </button>
  1358. ` : ''}
  1359. <button onclick="openIfaceModal('${parent.name}')"
  1360. 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">
  1361. Edit
  1362. </button>
  1363. </td>
  1364. `;
  1365. tbody.appendChild(parentRow);
  1366. if (isExpanded) {
  1367. const drawerRow = document.createElement('tr');
  1368. drawerRow.className = 'bg-slate-950/80 border-b border-slate-800/90';
  1369. const drawerCell = document.createElement('td');
  1370. drawerCell.colSpan = 8;
  1371. drawerCell.className = 'p-0';
  1372. drawerCell.innerHTML = `
  1373. <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">
  1374. <div class="flex items-center justify-between mb-3">
  1375. <div class="flex items-center space-x-3">
  1376. <span class="font-bold text-xs text-white uppercase tracking-wider flex items-center gap-1.5 font-sans">
  1377. <span>VLAN Sub-interfaces on <code class="text-cyan-300 lowercase">${parent.name}</code></span>
  1378. </span>
  1379. <span class="text-[11px] bg-cyan-950 text-cyan-400 px-2 py-0.5 rounded-full border border-cyan-800/60 font-mono">
  1380. ${childVlans.length} Attached
  1381. </span>
  1382. </div>
  1383. <button onclick="openVlanModal('${parent.name}')"
  1384. 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">
  1385. <span>+ Create VLAN on ${parent.name}</span>
  1386. </button>
  1387. </div>
  1388. ${childVlans.length === 0 ? `
  1389. <div class="p-6 text-center border border-dashed border-slate-800 rounded-xl bg-slate-900/40 font-sans">
  1390. <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>
  1391. <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">
  1392. <span>+ Create Your First VLAN on ${parent.name}</span>
  1393. </button>
  1394. </div>
  1395. ` : `
  1396. <div class="overflow-x-auto rounded-lg border border-slate-800 bg-slate-900/90 shadow-inner">
  1397. <table class="w-full text-left text-xs font-mono">
  1398. <thead class="text-slate-400 bg-slate-950/70 border-b border-slate-800 uppercase tracking-wider text-[10px] font-sans">
  1399. <tr>
  1400. <th class="py-2.5 px-4">VLAN ID</th>
  1401. <th class="py-2.5 px-4">Interface Device</th>
  1402. <th class="py-2.5 px-4">Subnet Gateway</th>
  1403. <th class="py-2.5 px-4">Role / Alias</th>
  1404. <th class="py-2.5 px-4">MTU</th>
  1405. <th class="py-2.5 px-4">Throughput</th>
  1406. <th class="py-2.5 px-4">Status</th>
  1407. <th class="py-2.5 px-4 text-right">Actions</th>
  1408. </tr>
  1409. </thead>
  1410. <tbody class="divide-y divide-slate-800/70">
  1411. ${childVlans.map(v => {
  1412. const isVlanUp = v.state === 'UP';
  1413. return `
  1414. <tr class="hover:bg-slate-800/40 transition">
  1415. <td class="py-2.5 px-4">
  1416. <span class="px-2 py-0.5 rounded text-xs font-bold bg-cyan-950 text-cyan-300 border border-cyan-800 shadow-sm">
  1417. VLAN ${v.vlan_id}
  1418. </span>
  1419. </td>
  1420. <td class="py-2.5 px-4 font-bold text-white flex items-center gap-1.5">
  1421. <span class="text-cyan-500">└─</span>
  1422. <span class="cursor-pointer hover:text-cyan-400 flex items-center gap-1" onclick="openIfaceModal('${v.name}')" title="Configure / Rename ${v.name}">
  1423. <span>${v.name}</span>
  1424. <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>
  1425. </span>
  1426. </td>
  1427. <td class="py-2.5 px-4 text-emerald-400 font-medium">
  1428. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  1429. ${(() => {
  1430. const c = (state.dhcpClients || []).find(dc => dc.interface === v.name);
  1431. if (!c) return '';
  1432. 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';
  1433. 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>`;
  1434. })()}
  1435. </td>
  1436. <td class="py-2.5 px-4 font-sans text-slate-300">
  1437. <div class="flex items-center gap-1.5">
  1438. ${getRoleBadge(v.role || 'LAN')}
  1439. <span class="text-slate-400 text-xs">${v.description || '-'}</span>
  1440. </div>
  1441. </td>
  1442. <td class="py-2.5 px-4 text-slate-400">${v.mtu}</td>
  1443. <td class="py-2.5 px-4 text-[11px]">
  1444. <span id="vlan-rate-rx-${v.name}" class="text-emerald-400">↓ ${v.rate?.rx_human || '0 B/s'}</span>
  1445. <span id="vlan-rate-tx-${v.name}" class="text-cyan-400 ml-1.5">↑ ${v.rate?.tx_human || '0 B/s'}</span>
  1446. </td>
  1447. <td class="py-2.5 px-4 font-sans">
  1448. <button onclick="toggleInterfaceState('${v.name}', '${isVlanUp ? 'down' : 'up'}')"
  1449. class="flex items-center gap-1 text-[11px] font-semibold px-2 py-0.5 rounded-full ${
  1450. 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'
  1451. }">
  1452. <span class="w-1.5 h-1.5 rounded-full ${isVlanUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  1453. <span>${v.state}</span>
  1454. </button>
  1455. </td>
  1456. <td class="py-2.5 px-4 text-right space-x-1.5 font-sans">
  1457. ${(() => {
  1458. const c = (state.dhcpClients || []).find(dc => dc.interface === v.name);
  1459. if (c) {
  1460. 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>`;
  1461. }
  1462. if (!supportsDHCPClient(v)) {
  1463. return '';
  1464. }
  1465. 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>`;
  1466. })()}
  1467. <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>
  1468. <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>
  1469. </td>
  1470. </tr>
  1471. `;
  1472. }).join('')}
  1473. </tbody>
  1474. </table>
  1475. </div>
  1476. `}
  1477. </div>
  1478. `;
  1479. drawerRow.appendChild(drawerCell);
  1480. tbody.appendChild(drawerRow);
  1481. }
  1482. });
  1483. }
  1484. // Render VLANs Dedicated View
  1485. function renderVlansList() {
  1486. const tbody = document.getElementById('vlans-table-body');
  1487. if (!tbody) return;
  1488. const emptyState = document.getElementById('vlans-empty-state');
  1489. const countBadge = document.getElementById('vlans-table-count');
  1490. const query = (document.getElementById('vlan-search')?.value || '').toLowerCase();
  1491. const allVlans = state.vlans || [];
  1492. if (countBadge) countBadge.innerText = allVlans.length;
  1493. const filtered = allVlans.filter(v => {
  1494. if (!query) return true;
  1495. return v.name.toLowerCase().includes(query) ||
  1496. String(v.vlan_id).includes(query) ||
  1497. (v.description || '').toLowerCase().includes(query) ||
  1498. (v.ipv4 && v.ipv4.some(ip => ip.includes(query)));
  1499. });
  1500. if (allVlans.length === 0) {
  1501. emptyState.classList.remove('hidden');
  1502. tbody.innerHTML = '';
  1503. return;
  1504. }
  1505. emptyState.classList.add('hidden');
  1506. const sig = `${query}|` + filtered.map(v => `${v.name}:${v.state}:${(v.ipv4||[]).join(',')}:${v.vlan_id}:${v.mtu}`).join(';');
  1507. if (tbody.dataset.sig === sig) return;
  1508. tbody.dataset.sig = sig;
  1509. tbody.innerHTML = '';
  1510. filtered.forEach(v => {
  1511. const isUp = v.state === 'UP';
  1512. const tr = document.createElement('tr');
  1513. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  1514. tr.innerHTML = `
  1515. <td class="py-3 px-4">
  1516. <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">
  1517. VLAN ${v.vlan_id}
  1518. </span>
  1519. </td>
  1520. <td class="py-3 px-4 font-bold text-white">
  1521. <span class="cursor-pointer hover:text-cyan-400 flex items-center gap-1.5" onclick="openIfaceModal('${v.name}')" title="Configure / Rename ${v.name}">
  1522. <span>${v.name}</span>
  1523. <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>
  1524. </span>
  1525. </td>
  1526. <td class="py-3 px-4 text-slate-300">
  1527. <span class="bg-slate-800 text-slate-200 px-2 py-0.5 rounded text-[11px]">${v.parent_name || 'eth0'}</span>
  1528. </td>
  1529. <td class="py-3 px-4 text-emerald-400 font-medium">
  1530. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  1531. </td>
  1532. <td class="py-3 px-4 text-slate-300 font-sans">
  1533. <span class="text-slate-400 text-xs">${v.description || v.role || '-'}</span>
  1534. </td>
  1535. <td class="py-3 px-4 text-slate-400">${v.mtu}</td>
  1536. <td class="py-3 px-4 font-sans">
  1537. <button onclick="toggleInterfaceState('${v.name}', '${isUp ? 'down' : 'up'}')"
  1538. class="flex items-center gap-1.5 text-xs font-semibold px-2 py-0.5 rounded-full ${
  1539. 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'
  1540. }">
  1541. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  1542. <span>${v.state}</span>
  1543. </button>
  1544. </td>
  1545. <td class="py-3 px-4 text-right space-x-2 font-sans">
  1546. <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>
  1547. <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>
  1548. </td>
  1549. `;
  1550. tbody.appendChild(tr);
  1551. });
  1552. }
  1553. // Toggle interface UP / DOWN
  1554. async function toggleInterfaceState(name, newState) {
  1555. try {
  1556. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(name)}/state`, {
  1557. method: 'POST',
  1558. headers: { 'Content-Type': 'application/json' },
  1559. body: JSON.stringify({ state: newState })
  1560. });
  1561. const data = await res.json();
  1562. if (res.ok) {
  1563. showToast('Interface Updated', `Interface ${name} is now ${newState.toUpperCase()}`, 'success');
  1564. fetchData(false);
  1565. } else {
  1566. showToast('Error', data.message || 'Failed to toggle interface state', 'error');
  1567. }
  1568. } catch (err) {
  1569. showToast('Error', err.message, 'error');
  1570. }
  1571. }
  1572. // ---------------- MikroTik Flag & Utilities ----------------
  1573. function renderMikroTikFlag(running, disabled) {
  1574. if (running) {
  1575. 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>`;
  1576. }
  1577. if (disabled) {
  1578. 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>`;
  1579. }
  1580. 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>`;
  1581. }
  1582. function copyToClipboard(text, label = 'Text') {
  1583. navigator.clipboard.writeText(text).then(() => {
  1584. showToast('Copied', `${label} copied to clipboard`, 'success');
  1585. }).catch(() => {
  1586. prompt('Copy value:', text);
  1587. });
  1588. }
  1589. // ======================== PPP Profiles Shared Helper ========================
  1590. async function fetchPPPProfilesList() {
  1591. try {
  1592. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`);
  1593. if (res.ok) {
  1594. state.pppProfiles = await res.json();
  1595. }
  1596. } catch (err) {
  1597. console.error('Failed to load PPP profiles:', err);
  1598. }
  1599. }
  1600. function populateProfileSelect(selectId, selectedVal, defaultVal = 'default') {
  1601. const sel = document.getElementById(selectId);
  1602. if (!sel) return;
  1603. const profiles = (state.pppProfiles && state.pppProfiles.length > 0) ? state.pppProfiles : [
  1604. { name: 'default', use_encryption: 'no' },
  1605. { name: 'default-encryption', use_encryption: 'required' }
  1606. ];
  1607. sel.innerHTML = '';
  1608. profiles.forEach(p => {
  1609. const opt = document.createElement('option');
  1610. opt.value = p.name;
  1611. const encBadge = p.use_encryption === 'required' ? ' (MPPE-128)' : (p.use_encryption === 'yes' ? ' (MPPE)' : '');
  1612. opt.innerText = `${p.name}${encBadge}`;
  1613. sel.appendChild(opt);
  1614. });
  1615. if (selectedVal) {
  1616. sel.value = selectedVal;
  1617. } else {
  1618. sel.value = defaultVal;
  1619. }
  1620. if (!sel.value && sel.options.length > 0) {
  1621. sel.selectedIndex = 0;
  1622. }
  1623. }
  1624. // ======================== PPPoE Multi-Instance ========================
  1625. async function loadPPPoE(populateInputs = true) {
  1626. try {
  1627. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  1628. await fetchPPPProfilesList();
  1629. }
  1630. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`);
  1631. const list = await res.json();
  1632. state.pppoeList = Array.isArray(list) ? list : [];
  1633. const badge = document.getElementById('pppoe-count-badge');
  1634. if (badge) badge.innerText = `${state.pppoeList.length} Interface${state.pppoeList.length !== 1 ? 's' : ''}`;
  1635. const tbody = document.getElementById('pppoe-table-body');
  1636. const empty = document.getElementById('pppoe-empty');
  1637. if (!tbody) return;
  1638. tbody.innerHTML = '';
  1639. if (state.pppoeList.length === 0) {
  1640. if (empty) empty.classList.remove('hidden');
  1641. } else {
  1642. if (empty) empty.classList.add('hidden');
  1643. state.pppoeList.forEach(inst => {
  1644. const tr = document.createElement('tr');
  1645. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1646. tr.innerHTML = `
  1647. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  1648. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  1649. <td class="py-2.5 px-3 text-cyan-400 font-mono">${escapeHtml(inst.interface)}</td>
  1650. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  1651. <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>
  1652. <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>
  1653. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  1654. <td class="py-2.5 px-3 text-center">
  1655. <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'}">
  1656. ${inst.default_route ? 'Yes' : 'No'}
  1657. </span>
  1658. </td>
  1659. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  1660. ${inst.running ? `
  1661. <button onclick="disconnectPPPoEInstance('${inst.name}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  1662. ` : `
  1663. <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>
  1664. `}
  1665. <button onclick="togglePPPoEState('${inst.name}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  1666. ${inst.disabled ? 'Enable' : 'Disable'}
  1667. </button>
  1668. <button onclick="openEditPPPoEModal('${inst.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  1669. <button onclick="deletePPPoEInstance('${inst.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  1670. </td>
  1671. `;
  1672. tbody.appendChild(tr);
  1673. });
  1674. }
  1675. } catch (err) {
  1676. console.error('Failed to load PPPoE:', err);
  1677. }
  1678. }
  1679. function openAddPPPoEModal() {
  1680. document.getElementById('pppoe-modal-title').innerText = 'Add PPPoE Client Interface';
  1681. document.getElementById('pppoe-modal-edit-orig').value = '';
  1682. document.getElementById('pppoe-modal-name').value = `pppoe-out${(state.pppoeList || []).length + 1}`;
  1683. document.getElementById('pppoe-modal-name').readOnly = false;
  1684. document.getElementById('pppoe-modal-user').value = '';
  1685. document.getElementById('pppoe-modal-pass').value = '';
  1686. document.getElementById('pppoe-modal-service').value = '';
  1687. document.getElementById('pppoe-modal-mtu').value = '1492';
  1688. document.getElementById('pppoe-modal-defroute').checked = true;
  1689. document.getElementById('pppoe-modal-reconnect').checked = true;
  1690. document.getElementById('pppoe-modal-disabled').checked = false;
  1691. // Populate profiles
  1692. populateProfileSelect('pppoe-modal-profile', 'default', 'default');
  1693. // Populate interfaces
  1694. const sel = document.getElementById('pppoe-modal-iface');
  1695. sel.innerHTML = '';
  1696. (state.interfaces || []).forEach(i => {
  1697. if (i.name === 'lo') return;
  1698. const opt = document.createElement('option');
  1699. opt.value = i.name;
  1700. opt.innerText = `${i.name} (${i.role || i.type})`;
  1701. sel.appendChild(opt);
  1702. });
  1703. document.getElementById('pppoe-modal').classList.remove('hidden');
  1704. }
  1705. function openEditPPPoEModal(name) {
  1706. const inst = (state.pppoeList || []).find(i => i.name === name);
  1707. if (!inst) return;
  1708. document.getElementById('pppoe-modal-title').innerText = `Edit PPPoE Client: ${name}`;
  1709. document.getElementById('pppoe-modal-edit-orig').value = name;
  1710. document.getElementById('pppoe-modal-name').value = inst.name;
  1711. document.getElementById('pppoe-modal-name').readOnly = true;
  1712. document.getElementById('pppoe-modal-user').value = inst.username || '';
  1713. document.getElementById('pppoe-modal-pass').value = inst.password || '';
  1714. document.getElementById('pppoe-modal-service').value = inst.service_name || '';
  1715. document.getElementById('pppoe-modal-mtu').value = inst.mtu || 1492;
  1716. document.getElementById('pppoe-modal-defroute').checked = inst.default_route ?? true;
  1717. document.getElementById('pppoe-modal-reconnect').checked = inst.auto_reconnect ?? true;
  1718. document.getElementById('pppoe-modal-disabled').checked = !!inst.disabled;
  1719. // Populate profiles
  1720. populateProfileSelect('pppoe-modal-profile', inst.profile || 'default', 'default');
  1721. const sel = document.getElementById('pppoe-modal-iface');
  1722. sel.innerHTML = '';
  1723. (state.interfaces || []).forEach(i => {
  1724. if (i.name === 'lo') return;
  1725. const opt = document.createElement('option');
  1726. opt.value = i.name;
  1727. opt.innerText = `${i.name} (${i.role || i.type})`;
  1728. if (i.name === inst.interface) opt.selected = true;
  1729. sel.appendChild(opt);
  1730. });
  1731. document.getElementById('pppoe-modal').classList.remove('hidden');
  1732. }
  1733. function closePPPoEModal() {
  1734. document.getElementById('pppoe-modal').classList.add('hidden');
  1735. }
  1736. async function submitSavePPPoE(e) {
  1737. e.preventDefault();
  1738. const name = document.getElementById('pppoe-modal-name').value.trim();
  1739. const iface = document.getElementById('pppoe-modal-iface').value;
  1740. const user = document.getElementById('pppoe-modal-user').value.trim();
  1741. const pass = document.getElementById('pppoe-modal-pass').value;
  1742. const profile = document.getElementById('pppoe-modal-profile')?.value || 'default';
  1743. const service = document.getElementById('pppoe-modal-service').value.trim();
  1744. const mtu = parseInt(document.getElementById('pppoe-modal-mtu').value, 10) || 1492;
  1745. const defRoute = document.getElementById('pppoe-modal-defroute').checked;
  1746. const reconnect = document.getElementById('pppoe-modal-reconnect').checked;
  1747. const disabled = document.getElementById('pppoe-modal-disabled').checked;
  1748. try {
  1749. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`, {
  1750. method: 'POST',
  1751. headers: { 'Content-Type': 'application/json' },
  1752. body: JSON.stringify({
  1753. name,
  1754. interface: iface,
  1755. username: user,
  1756. password: pass,
  1757. profile: profile,
  1758. service_name: service,
  1759. mtu,
  1760. default_route: defRoute,
  1761. auto_reconnect: reconnect,
  1762. disabled
  1763. })
  1764. });
  1765. if (res.ok) {
  1766. showToast('PPPoE Saved', `Configuration for ${name} saved`, 'success');
  1767. closePPPoEModal();
  1768. loadPPPoE(false);
  1769. fetchData(false);
  1770. } else {
  1771. const err = await res.json();
  1772. showToast('Error', err.message || 'Failed to save PPPoE', 'error');
  1773. }
  1774. } catch (err) {
  1775. showToast('Error', err.message, 'error');
  1776. }
  1777. }
  1778. async function connectPPPoEInstance(name) {
  1779. try {
  1780. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  1781. if (res.ok) {
  1782. showToast('Connecting', `Dialing ${name}...`, 'info');
  1783. setTimeout(() => loadPPPoE(false), 2000);
  1784. }
  1785. } catch (err) {
  1786. showToast('Error', err.message, 'error');
  1787. }
  1788. }
  1789. async function disconnectPPPoEInstance(name) {
  1790. try {
  1791. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  1792. if (res.ok) {
  1793. showToast('Disconnected', `${name} session terminated`, 'info');
  1794. setTimeout(() => loadPPPoE(false), 1000);
  1795. }
  1796. } catch (err) {
  1797. showToast('Error', err.message, 'error');
  1798. }
  1799. }
  1800. async function togglePPPoEState(name, enable) {
  1801. try {
  1802. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/state`, {
  1803. method: 'POST',
  1804. headers: { 'Content-Type': 'application/json' },
  1805. body: JSON.stringify({ enabled: enable })
  1806. });
  1807. if (res.ok) {
  1808. showToast(enable ? 'Enabled' : 'Disabled', `${name} is now ${enable ? 'enabled' : 'disabled'}`, 'info');
  1809. loadPPPoE(false);
  1810. }
  1811. } catch (err) {
  1812. showToast('Error', err.message, 'error');
  1813. }
  1814. }
  1815. async function deletePPPoEInstance(name) {
  1816. if (!confirm(`Are you sure you want to delete PPPoE client ${name}?`)) return;
  1817. try {
  1818. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1819. if (res.ok) {
  1820. showToast('Deleted', `PPPoE client ${name} removed`, 'success');
  1821. loadPPPoE(false);
  1822. fetchData(false);
  1823. }
  1824. } catch (err) {
  1825. showToast('Error', err.message, 'error');
  1826. }
  1827. }
  1828. // ======================== WireGuard Multi-Interface & Multi-Peer ========================
  1829. state.wgSubTab = 'ifaces';
  1830. function switchWGSubTab(tab) {
  1831. state.wgSubTab = tab;
  1832. const ifacesPanel = document.getElementById('wg-subtab-ifaces');
  1833. const peersPanel = document.getElementById('wg-subtab-peers');
  1834. const ifacesBtn = document.getElementById('wg-subtab-btn-ifaces');
  1835. const peersBtn = document.getElementById('wg-subtab-btn-peers');
  1836. if (tab === 'ifaces') {
  1837. ifacesPanel?.classList.remove('hidden');
  1838. peersPanel?.classList.add('hidden');
  1839. 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';
  1840. 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';
  1841. } else {
  1842. ifacesPanel?.classList.add('hidden');
  1843. peersPanel?.classList.remove('hidden');
  1844. 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';
  1845. 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';
  1846. renderWGPeers();
  1847. }
  1848. }
  1849. async function loadWireGuard(populateInputs = true) {
  1850. try {
  1851. const [ifacesRes, peersRes] = await Promise.all([
  1852. fetch(`${API_BASE}/vpn/wireguard/interfaces`),
  1853. fetch(`${API_BASE}/vpn/wireguard/peers`)
  1854. ]);
  1855. const ifaces = ifacesRes.ok ? await ifacesRes.json() : [];
  1856. const peers = peersRes.ok ? await peersRes.json() : [];
  1857. state.wgInterfaces = Array.isArray(ifaces) ? ifaces : [];
  1858. state.wgPeers = Array.isArray(peers) ? peers : [];
  1859. // Badges
  1860. const ifacesCountBadge = document.getElementById('wg-ifaces-count');
  1861. if (ifacesCountBadge) ifacesCountBadge.innerText = `${state.wgInterfaces.length} Interfaces`;
  1862. const peersCountBadge = document.getElementById('wg-peers-count');
  1863. if (peersCountBadge) peersCountBadge.innerText = `${state.wgPeers.length} Peers`;
  1864. const subTabIfaces = document.getElementById('wg-subtab-badge-ifaces');
  1865. if (subTabIfaces) subTabIfaces.innerText = state.wgInterfaces.length;
  1866. const subTabPeers = document.getElementById('wg-subtab-badge-peers');
  1867. if (subTabPeers) subTabPeers.innerText = state.wgPeers.length;
  1868. // Render Interfaces
  1869. const ifacesTbody = document.getElementById('wg-ifaces-table-body');
  1870. const ifacesEmpty = document.getElementById('wg-ifaces-empty');
  1871. if (ifacesTbody) {
  1872. ifacesTbody.innerHTML = '';
  1873. if (state.wgInterfaces.length === 0) {
  1874. if (ifacesEmpty) ifacesEmpty.classList.remove('hidden');
  1875. } else {
  1876. if (ifacesEmpty) ifacesEmpty.classList.add('hidden');
  1877. state.wgInterfaces.forEach(iface => {
  1878. const peersOnIface = state.wgPeers.filter(p => p.interface === iface.name).length;
  1879. const tr = document.createElement('tr');
  1880. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1881. tr.innerHTML = `
  1882. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(iface.running, iface.disabled)}</td>
  1883. <td class="py-2.5 px-3">
  1884. <div class="flex items-center gap-1.5">
  1885. <span class="font-bold text-white">${escapeHtml(iface.name)}</span>
  1886. ${iface.comment ? `<span class="text-[10px] text-slate-400 font-sans italic">(${escapeHtml(iface.comment)})</span>` : ''}
  1887. </div>
  1888. </td>
  1889. <td class="py-2.5 px-3 text-amber-400 font-mono">${iface.listen_port}</td>
  1890. <td class="py-2.5 px-3 text-emerald-400 font-mono">${iface.address || '<span class="text-slate-600 font-sans">--</span>'}</td>
  1891. <td class="py-2.5 px-3 text-slate-300 font-mono">
  1892. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${iface.public_key}', 'Public Key')" title="Click to copy: ${iface.public_key}">
  1893. ${(iface.public_key || '').substring(0, 10)}... 📋
  1894. </span>
  1895. </td>
  1896. <td class="py-2.5 px-3 text-slate-400 font-mono">${iface.mtu || 1420}</td>
  1897. <td class="py-2.5 px-3 text-center">
  1898. <span class="px-2 py-0.5 rounded text-[10px] font-sans bg-slate-800 text-slate-300">${peersOnIface} peer${peersOnIface !== 1 ? 's' : ''}</span>
  1899. </td>
  1900. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  1901. ${iface.running ? `
  1902. <button onclick="stopWGInterface('${iface.name}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Stop</button>
  1903. ` : `
  1904. <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>
  1905. `}
  1906. <button onclick="toggleWGInterfaceState('${iface.name}', ${iface.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white font-medium">
  1907. ${iface.disabled ? 'Enable' : 'Disable'}
  1908. </button>
  1909. <button onclick="openEditWGInterfaceModal('${iface.name}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Edit</button>
  1910. <button onclick="deleteWGInterface('${iface.name}')" class="text-xs text-slate-500 hover:text-rose-400 font-medium">Delete</button>
  1911. </td>
  1912. `;
  1913. ifacesTbody.appendChild(tr);
  1914. });
  1915. }
  1916. }
  1917. // Populate filter dropdown in peers tab
  1918. const filterSel = document.getElementById('wg-peers-filter-iface');
  1919. if (filterSel) {
  1920. const currentVal = filterSel.value;
  1921. filterSel.innerHTML = '<option value="">All Interfaces</option>';
  1922. state.wgInterfaces.forEach(i => {
  1923. const opt = document.createElement('option');
  1924. opt.value = i.name;
  1925. opt.innerText = i.name;
  1926. if (i.name === currentVal) opt.selected = true;
  1927. filterSel.appendChild(opt);
  1928. });
  1929. }
  1930. renderWGPeers();
  1931. } catch (err) {
  1932. console.error('Failed to load WireGuard:', err);
  1933. }
  1934. }
  1935. function formatWGPeerEndpoint(address, port) {
  1936. if (!address || address === '(none)') return '--';
  1937. let addr = address.trim();
  1938. let p = port || 0;
  1939. while (addr.includes(':') && !addr.startsWith('[')) {
  1940. const lastColon = addr.lastIndexOf(':');
  1941. const maybePort = addr.substring(lastColon + 1);
  1942. if (!isNaN(parseInt(maybePort, 10)) && parseInt(maybePort, 10) > 0) {
  1943. if (!p) p = parseInt(maybePort, 10);
  1944. addr = addr.substring(0, lastColon);
  1945. } else {
  1946. break;
  1947. }
  1948. }
  1949. return p ? `${addr}:${p}` : addr;
  1950. }
  1951. function renderWGPeers() {
  1952. const filterSel = document.getElementById('wg-peers-filter-iface');
  1953. const selectedIface = filterSel ? filterSel.value : '';
  1954. const tbody = document.getElementById('wg-peers-table-body');
  1955. const empty = document.getElementById('wg-peers-empty');
  1956. if (!tbody) return;
  1957. tbody.innerHTML = '';
  1958. const filtered = selectedIface ? state.wgPeers.filter(p => p.interface === selectedIface) : state.wgPeers;
  1959. if (filtered.length === 0) {
  1960. if (empty) empty.classList.remove('hidden');
  1961. } else {
  1962. if (empty) empty.classList.add('hidden');
  1963. filtered.forEach(p => {
  1964. const isOnline = p.latest_handshake && !p.latest_handshake.includes('Never');
  1965. const tr = document.createElement('tr');
  1966. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1967. tr.innerHTML = `
  1968. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(isOnline, p.disabled)}</td>
  1969. <td class="py-2.5 px-3 font-mono font-bold text-rose-400">${escapeHtml(p.interface)}</td>
  1970. <td class="py-2.5 px-3 font-bold text-white font-sans">${escapeHtml(p.name || 'Unnamed')}</td>
  1971. <td class="py-2.5 px-3 text-slate-300 font-mono">
  1972. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${p.public_key}', 'Peer Public Key')" title="${p.public_key}">
  1973. ${(p.public_key || '').substring(0, 10)}... 📋
  1974. </span>
  1975. </td>
  1976. <td class="py-2.5 px-3 text-emerald-400 font-mono font-semibold">${(p.allowed_ips || []).join(', ')}</td>
  1977. <td class="py-2.5 px-3 text-slate-400 font-mono">${formatWGPeerEndpoint(p.endpoint_address, p.endpoint_port)}</td>
  1978. <td class="py-2.5 px-3 text-slate-300 font-sans">${p.latest_handshake || 'Never'}</td>
  1979. <td class="py-2.5 px-3 font-mono text-[11px]">
  1980. <span class="text-emerald-400">↓ ${p.transfer_rx_human || '0 B'}</span>
  1981. <span class="text-cyan-400 ml-1">↑ ${p.transfer_tx_human || '0 B'}</span>
  1982. </td>
  1983. <td class="py-2.5 px-3 text-right font-sans space-x-2 whitespace-nowrap">
  1984. <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">
  1985. ${p.disabled ? 'Enable' : 'Disable'}
  1986. </button>
  1987. <button onclick="openEditWGPeerModal('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Edit</button>
  1988. <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>
  1989. <button onclick="deleteWGPeer('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Delete</button>
  1990. </td>
  1991. `;
  1992. tbody.appendChild(tr);
  1993. });
  1994. }
  1995. }
  1996. function openAddWGInterfaceModal() {
  1997. document.getElementById('wg-iface-modal-title').innerText = 'Add WireGuard Interface';
  1998. document.getElementById('wg-iface-modal-edit-orig').value = '';
  1999. const nameEl = document.getElementById('wg-iface-modal-name');
  2000. nameEl.value = `wg${(state.wgInterfaces || []).length}`;
  2001. nameEl.readOnly = false;
  2002. document.getElementById('wg-iface-modal-port').value = 51820 + (state.wgInterfaces || []).length;
  2003. document.getElementById('wg-iface-modal-addr').value = `10.${10 + (state.wgInterfaces || []).length}.0.1/24`;
  2004. document.getElementById('wg-iface-modal-mtu').value = '1420';
  2005. document.getElementById('wg-iface-modal-comment').value = '';
  2006. document.getElementById('wg-iface-modal-pubkey').value = '';
  2007. document.getElementById('wg-iface-modal-privkey').value = '';
  2008. document.getElementById('wg-iface-modal-disabled').checked = false;
  2009. generateWGInterfaceKeys();
  2010. document.getElementById('wg-iface-modal').classList.remove('hidden');
  2011. }
  2012. function openEditWGInterfaceModal(name) {
  2013. const iface = (state.wgInterfaces || []).find(i => i.name === name);
  2014. if (!iface) return;
  2015. document.getElementById('wg-iface-modal-title').innerText = `Edit WireGuard Interface: ${name}`;
  2016. document.getElementById('wg-iface-modal-edit-orig').value = name;
  2017. const nameEl = document.getElementById('wg-iface-modal-name');
  2018. nameEl.value = iface.name;
  2019. nameEl.readOnly = false; // ALLOW RENAMING
  2020. document.getElementById('wg-iface-modal-port').value = iface.listen_port || 51820;
  2021. document.getElementById('wg-iface-modal-addr').value = iface.address || '';
  2022. document.getElementById('wg-iface-modal-mtu').value = iface.mtu || 1420;
  2023. document.getElementById('wg-iface-modal-comment').value = iface.comment || '';
  2024. document.getElementById('wg-iface-modal-pubkey').value = iface.public_key || '';
  2025. document.getElementById('wg-iface-modal-privkey').value = iface.private_key || '';
  2026. document.getElementById('wg-iface-modal-disabled').checked = !!iface.disabled;
  2027. document.getElementById('wg-iface-modal').classList.remove('hidden');
  2028. }
  2029. function closeAddWGInterfaceModal() {
  2030. document.getElementById('wg-iface-modal').classList.add('hidden');
  2031. }
  2032. async function generateWGInterfaceKeys() {
  2033. try {
  2034. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  2035. const keys = await res.json();
  2036. if (res.ok) {
  2037. document.getElementById('wg-iface-modal-privkey').value = keys.private_key;
  2038. document.getElementById('wg-iface-modal-pubkey').value = keys.public_key;
  2039. }
  2040. } catch (err) {
  2041. showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
  2042. }
  2043. }
  2044. async function onWGInterfacePrivKeyInput() {
  2045. const privKey = document.getElementById('wg-iface-modal-privkey').value.trim();
  2046. if (!privKey) return;
  2047. try {
  2048. const res = await fetch(`${API_BASE}/vpn/wireguard/calc-pubkey`, {
  2049. method: 'POST',
  2050. headers: { 'Content-Type': 'application/json' },
  2051. body: JSON.stringify({ private_key: privKey })
  2052. });
  2053. if (res.ok) {
  2054. const data = await res.json();
  2055. if (data.public_key) {
  2056. document.getElementById('wg-iface-modal-pubkey').value = data.public_key;
  2057. }
  2058. }
  2059. } catch (err) {
  2060. // Ignore while typing
  2061. }
  2062. }
  2063. function toggleWGPrivKeyVisibility() {
  2064. const el = document.getElementById('wg-iface-modal-privkey');
  2065. const btn = document.getElementById('btn-toggle-wg-privkey');
  2066. if (el.type === 'password') {
  2067. el.type = 'text';
  2068. btn.innerText = '🙈 Hide';
  2069. } else {
  2070. el.type = 'password';
  2071. btn.innerText = '👁️ Show';
  2072. }
  2073. }
  2074. function copyWGInterfacePubKey() {
  2075. const pub = document.getElementById('wg-iface-modal-pubkey').value;
  2076. if (pub) copyToClipboard(pub, 'Interface Public Key');
  2077. }
  2078. async function submitSaveWGInterface(e) {
  2079. e.preventDefault();
  2080. const origName = document.getElementById('wg-iface-modal-edit-orig').value.trim();
  2081. const name = document.getElementById('wg-iface-modal-name').value.trim();
  2082. const port = parseInt(document.getElementById('wg-iface-modal-port').value, 10) || 51820;
  2083. const addr = document.getElementById('wg-iface-modal-addr').value.trim();
  2084. const mtu = parseInt(document.getElementById('wg-iface-modal-mtu').value, 10) || 1420;
  2085. const comment = document.getElementById('wg-iface-modal-comment').value.trim();
  2086. const pub = document.getElementById('wg-iface-modal-pubkey').value.trim();
  2087. const priv = document.getElementById('wg-iface-modal-privkey').value.trim();
  2088. const disabled = document.getElementById('wg-iface-modal-disabled').checked;
  2089. try {
  2090. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces`, {
  2091. method: 'POST',
  2092. headers: { 'Content-Type': 'application/json' },
  2093. body: JSON.stringify({
  2094. orig_name: origName,
  2095. name,
  2096. listen_port: port,
  2097. address: addr,
  2098. mtu,
  2099. comment,
  2100. public_key: pub,
  2101. private_key: priv,
  2102. disabled
  2103. })
  2104. });
  2105. const data = await res.json();
  2106. if (res.ok) {
  2107. showToast('WireGuard Saved', `Interface ${name} configured successfully`, 'success');
  2108. closeAddWGInterfaceModal();
  2109. loadWireGuard(false);
  2110. fetchData(false);
  2111. } else {
  2112. showToast('Error', data.error || 'Failed to save interface', 'error');
  2113. }
  2114. } catch (err) {
  2115. showToast('Error', err.message, 'error');
  2116. }
  2117. }
  2118. async function startWGInterface(name) {
  2119. try {
  2120. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/start`, { method: 'POST' });
  2121. if (res.ok) {
  2122. showToast('Interface UP', `Started WireGuard interface ${name}`, 'success');
  2123. loadWireGuard(false);
  2124. fetchData(false);
  2125. }
  2126. } catch (err) {
  2127. showToast('Error', err.message, 'error');
  2128. }
  2129. }
  2130. async function stopWGInterface(name) {
  2131. try {
  2132. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  2133. if (res.ok) {
  2134. showToast('Interface DOWN', `Stopped WireGuard interface ${name}`, 'info');
  2135. loadWireGuard(false);
  2136. fetchData(false);
  2137. }
  2138. } catch (err) {
  2139. showToast('Error', err.message, 'error');
  2140. }
  2141. }
  2142. async function toggleWGInterfaceState(name, enable) {
  2143. try {
  2144. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/state`, {
  2145. method: 'POST',
  2146. headers: { 'Content-Type': 'application/json' },
  2147. body: JSON.stringify({ enabled: enable })
  2148. });
  2149. if (res.ok) {
  2150. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  2151. loadWireGuard(false);
  2152. fetchData(false);
  2153. }
  2154. } catch (err) {
  2155. showToast('Error', err.message, 'error');
  2156. }
  2157. }
  2158. async function deleteWGInterface(name) {
  2159. if (!confirm(`Are you sure you want to delete WireGuard interface ${name}? All associated peers will also be removed.`)) return;
  2160. try {
  2161. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2162. if (res.ok) {
  2163. showToast('Deleted', `Interface ${name} removed`, 'success');
  2164. loadWireGuard(false);
  2165. fetchData(false);
  2166. }
  2167. } catch (err) {
  2168. showToast('Error', err.message, 'error');
  2169. }
  2170. }
  2171. function populateWGPeerIfaceSelect(selectedIface = '') {
  2172. const sel = document.getElementById('wg-peer-modal-iface');
  2173. if (!sel) return;
  2174. sel.innerHTML = '';
  2175. (state.wgInterfaces || []).forEach(i => {
  2176. const opt = document.createElement('option');
  2177. opt.value = i.name;
  2178. opt.innerText = `${i.name} (${i.address || 'No IP'})`;
  2179. if (i.name === selectedIface) opt.selected = true;
  2180. sel.appendChild(opt);
  2181. });
  2182. }
  2183. function openAddWGPeerModal() {
  2184. if ((state.wgInterfaces || []).length === 0) {
  2185. showToast('No Interfaces', 'Please add a WireGuard interface first before adding peers', 'warning');
  2186. openAddWGInterfaceModal();
  2187. return;
  2188. }
  2189. document.getElementById('wg-peer-modal-title').innerText = 'Add WireGuard Peer';
  2190. document.getElementById('wg-peer-modal-edit-orig-iface').value = '';
  2191. document.getElementById('wg-peer-modal-edit-orig-pubkey').value = '';
  2192. populateWGPeerIfaceSelect();
  2193. document.getElementById('wg-peer-modal-name').value = '';
  2194. document.getElementById('wg-peer-modal-pubkey').value = '';
  2195. document.getElementById('wg-peer-modal-allowedips').value = '10.10.0.2/32';
  2196. document.getElementById('wg-peer-modal-endpoint').value = '';
  2197. document.getElementById('wg-peer-modal-port').value = '';
  2198. document.getElementById('wg-peer-modal-keepalive').value = '25';
  2199. document.getElementById('wg-peer-modal-preshared').value = '';
  2200. document.getElementById('wg-peer-modal-disabled').checked = false;
  2201. document.getElementById('wg-peer-key-warning').classList.add('hidden');
  2202. document.getElementById('wg-peer-gen-key-box').classList.add('hidden');
  2203. document.getElementById('wg-peer-modal').classList.remove('hidden');
  2204. }
  2205. function openEditWGPeerModal(ifaceName, pubKey) {
  2206. const peer = (state.wgPeers || []).find(p => p.interface === ifaceName && p.public_key === pubKey);
  2207. if (!peer) {
  2208. showToast('Not Found', 'Peer not found', 'warning');
  2209. return;
  2210. }
  2211. document.getElementById('wg-peer-modal-title').innerText = `Edit WireGuard Peer (${peer.name || ifaceName})`;
  2212. document.getElementById('wg-peer-modal-edit-orig-iface').value = peer.interface;
  2213. document.getElementById('wg-peer-modal-edit-orig-pubkey').value = peer.public_key;
  2214. populateWGPeerIfaceSelect(peer.interface);
  2215. document.getElementById('wg-peer-modal-name').value = peer.name || '';
  2216. document.getElementById('wg-peer-modal-pubkey').value = peer.public_key || '';
  2217. document.getElementById('wg-peer-modal-allowedips').value = (peer.allowed_ips || []).join(', ');
  2218. let epHost = (peer.endpoint_address || '').trim();
  2219. let epPort = peer.endpoint_port || '';
  2220. while (epHost.includes(':') && !epHost.startsWith('[')) {
  2221. const lastColon = epHost.lastIndexOf(':');
  2222. const maybePort = epHost.substring(lastColon + 1);
  2223. if (!isNaN(parseInt(maybePort, 10)) && parseInt(maybePort, 10) > 0) {
  2224. if (!epPort) epPort = parseInt(maybePort, 10);
  2225. epHost = epHost.substring(0, lastColon);
  2226. } else {
  2227. break;
  2228. }
  2229. }
  2230. document.getElementById('wg-peer-modal-endpoint').value = epHost;
  2231. document.getElementById('wg-peer-modal-port').value = epPort;
  2232. document.getElementById('wg-peer-modal-keepalive').value = peer.persistent_keepalive ?? 25;
  2233. document.getElementById('wg-peer-modal-preshared').value = peer.preshared_key || '';
  2234. document.getElementById('wg-peer-modal-disabled').checked = !!peer.disabled;
  2235. document.getElementById('wg-peer-key-warning').classList.add('hidden');
  2236. document.getElementById('wg-peer-gen-key-box').classList.add('hidden');
  2237. document.getElementById('wg-peer-modal').classList.remove('hidden');
  2238. }
  2239. function closeAddWGPeerModal() {
  2240. document.getElementById('wg-peer-modal').classList.add('hidden');
  2241. }
  2242. async function generatePeerKeypairHelper() {
  2243. try {
  2244. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  2245. const keys = await res.json();
  2246. if (res.ok) {
  2247. document.getElementById('wg-peer-modal-pubkey').value = keys.public_key;
  2248. document.getElementById('wg-peer-gen-privkey').value = keys.private_key;
  2249. document.getElementById('wg-peer-gen-key-box').classList.remove('hidden');
  2250. checkWGPeerKeyValidity();
  2251. showToast('Keypair Generated', 'Public key inserted and client private key ready to copy', 'info');
  2252. }
  2253. } catch (err) {
  2254. showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
  2255. }
  2256. }
  2257. function copyGeneratedPeerPrivKey() {
  2258. const priv = document.getElementById('wg-peer-gen-privkey').value;
  2259. if (priv) copyToClipboard(priv, 'Client Private Key');
  2260. }
  2261. async function generatePeerPSK() {
  2262. try {
  2263. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  2264. const keys = await res.json();
  2265. if (res.ok && keys.private_key) {
  2266. document.getElementById('wg-peer-modal-preshared').value = keys.private_key;
  2267. showToast('PSK Generated', 'Generated 256-bit preshared key', 'info');
  2268. }
  2269. } catch (err) {
  2270. showToast('Error', err.message, 'error');
  2271. }
  2272. }
  2273. function checkWGPeerKeyValidity() {
  2274. const ifaceName = document.getElementById('wg-peer-modal-iface').value;
  2275. const peerPubKey = document.getElementById('wg-peer-modal-pubkey').value.trim();
  2276. const warningEl = document.getElementById('wg-peer-key-warning');
  2277. if (!warningEl) return;
  2278. const targetIface = (state.wgInterfaces || []).find(i => i.name === ifaceName);
  2279. if (targetIface && targetIface.public_key && peerPubKey && targetIface.public_key === peerPubKey) {
  2280. warningEl.classList.remove('hidden');
  2281. } else {
  2282. warningEl.classList.add('hidden');
  2283. }
  2284. }
  2285. async function submitSaveWGPeer(e) {
  2286. e.preventDefault();
  2287. const origIface = document.getElementById('wg-peer-modal-edit-orig-iface').value.trim();
  2288. const origPubKey = document.getElementById('wg-peer-modal-edit-orig-pubkey').value.trim();
  2289. const iface = document.getElementById('wg-peer-modal-iface').value;
  2290. const name = document.getElementById('wg-peer-modal-name').value.trim();
  2291. const pub = document.getElementById('wg-peer-modal-pubkey').value.trim();
  2292. const allowed = document.getElementById('wg-peer-modal-allowedips').value
  2293. .split(',')
  2294. .map(s => s.trim())
  2295. .filter(s => s.length > 0);
  2296. let epHost = document.getElementById('wg-peer-modal-endpoint').value.trim();
  2297. let epPort = parseInt(document.getElementById('wg-peer-modal-port').value, 10) || 0;
  2298. while (epHost.includes(':') && !epHost.startsWith('[')) {
  2299. const lastColon = epHost.lastIndexOf(':');
  2300. const maybePort = epHost.substring(lastColon + 1);
  2301. if (!isNaN(parseInt(maybePort, 10)) && parseInt(maybePort, 10) > 0) {
  2302. if (!epPort) epPort = parseInt(maybePort, 10);
  2303. epHost = epHost.substring(0, lastColon);
  2304. } else {
  2305. break;
  2306. }
  2307. }
  2308. const keepalive = parseInt(document.getElementById('wg-peer-modal-keepalive').value, 10) || 0;
  2309. const psk = document.getElementById('wg-peer-modal-preshared').value.trim();
  2310. const disabled = document.getElementById('wg-peer-modal-disabled').checked;
  2311. // Validation
  2312. const targetIface = (state.wgInterfaces || []).find(i => i.name === iface);
  2313. if (targetIface && targetIface.public_key === pub) {
  2314. showToast('Invalid Peer Key', 'Peer public key cannot be the same as the interface public key!', 'error');
  2315. return;
  2316. }
  2317. try {
  2318. const res = await fetch(`${API_BASE}/vpn/wireguard/peers`, {
  2319. method: 'POST',
  2320. headers: { 'Content-Type': 'application/json' },
  2321. body: JSON.stringify({
  2322. orig_interface: origIface,
  2323. orig_public_key: origPubKey,
  2324. interface: iface,
  2325. name,
  2326. public_key: pub,
  2327. allowed_ips: allowed,
  2328. endpoint_address: epHost,
  2329. endpoint_port: epPort,
  2330. persistent_keepalive: keepalive,
  2331. preshared_key: psk,
  2332. disabled
  2333. })
  2334. });
  2335. const data = await res.json();
  2336. if (res.ok) {
  2337. showToast('Peer Saved', `Peer ${name} saved on ${iface}`, 'success');
  2338. closeAddWGPeerModal();
  2339. loadWireGuard(false);
  2340. } else {
  2341. showToast('Error', data.error || 'Failed to save peer', 'error');
  2342. }
  2343. } catch (err) {
  2344. showToast('Error', err.message, 'error');
  2345. }
  2346. }
  2347. async function toggleWGPeerState(iface, pubkey, enable) {
  2348. try {
  2349. const res = await fetch(`${API_BASE}/vpn/wireguard/peers/state`, {
  2350. method: 'POST',
  2351. headers: { 'Content-Type': 'application/json' },
  2352. body: JSON.stringify({ interface: iface, public_key: pubkey, enabled: enable })
  2353. });
  2354. const data = await res.json();
  2355. if (res.ok) {
  2356. showToast(enable ? 'Peer Enabled' : 'Peer Disabled', `Peer state updated on ${iface}`, 'info');
  2357. loadWireGuard(false);
  2358. } else {
  2359. showToast('Error', data.error || 'Failed to update peer state', 'error');
  2360. }
  2361. } catch (err) {
  2362. showToast('Error', err.message, 'error');
  2363. }
  2364. }
  2365. async function deleteWGPeer(iface, pubkey) {
  2366. if (!confirm(`Are you sure you want to remove peer from ${iface}?`)) return;
  2367. try {
  2368. const res = await fetch(`${API_BASE}/vpn/wireguard/peers/delete`, {
  2369. method: 'POST',
  2370. headers: { 'Content-Type': 'application/json' },
  2371. body: JSON.stringify({ interface: iface, public_key: pubkey })
  2372. });
  2373. const data = await res.json();
  2374. if (res.ok) {
  2375. showToast('Peer Deleted', 'WireGuard peer removed', 'success');
  2376. loadWireGuard(false);
  2377. } else {
  2378. showToast('Error', data.error || 'Failed to remove peer', 'error');
  2379. }
  2380. } catch (err) {
  2381. showToast('Error', err.message, 'error');
  2382. }
  2383. }
  2384. // ======================== IPSec FortiGate Phase 1 & 2 Multi-Tunnel Engine ========================
  2385. function switchIpsecModalTab(tab) {
  2386. const p1Tab = document.getElementById('tab-btn-ipsec-p1');
  2387. const p2Tab = document.getElementById('tab-btn-ipsec-p2');
  2388. const p1Content = document.getElementById('ipsec-tab-content-p1');
  2389. const p2Content = document.getElementById('ipsec-tab-content-p2');
  2390. const stepBtn = document.getElementById('btn-ipsec-switch-step');
  2391. if (tab === 'p1') {
  2392. if (p1Tab) {
  2393. 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';
  2394. }
  2395. if (p2Tab) {
  2396. 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';
  2397. }
  2398. if (p1Content) p1Content.classList.remove('hidden');
  2399. if (p2Content) p2Content.classList.add('hidden');
  2400. if (stepBtn) stepBtn.innerHTML = 'Next: Phase 2 Selectors &rarr;';
  2401. } else {
  2402. if (p1Tab) {
  2403. 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';
  2404. }
  2405. if (p2Tab) {
  2406. 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';
  2407. }
  2408. if (p1Content) p1Content.classList.add('hidden');
  2409. if (p2Content) p2Content.classList.remove('hidden');
  2410. if (stepBtn) stepBtn.innerHTML = '&larr; Back: Phase 1 (IKE)';
  2411. }
  2412. }
  2413. function toggleIpsecPhaseStep() {
  2414. const p1Content = document.getElementById('ipsec-tab-content-p1');
  2415. if (p1Content && !p1Content.classList.contains('hidden')) {
  2416. switchIpsecModalTab('p2');
  2417. } else {
  2418. switchIpsecModalTab('p1');
  2419. }
  2420. }
  2421. function toggleIpsecPskVisibility() {
  2422. const pskInput = document.getElementById('ipsec-modal-psk');
  2423. if (!pskInput) return;
  2424. pskInput.type = pskInput.type === 'password' ? 'text' : 'password';
  2425. }
  2426. function addIpsecLocalSubnet(val = '') {
  2427. const container = document.getElementById('ipsec-modal-local-subnets-container');
  2428. if (!container) return;
  2429. const row = document.createElement('div');
  2430. row.className = 'flex items-center gap-2 ipsec-subnet-row';
  2431. row.innerHTML = `
  2432. <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">
  2433. <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>
  2434. `;
  2435. container.appendChild(row);
  2436. }
  2437. function addIpsecRemoteSubnet(val = '') {
  2438. const container = document.getElementById('ipsec-modal-remote-subnets-container');
  2439. if (!container) return;
  2440. const row = document.createElement('div');
  2441. row.className = 'flex items-center gap-2 ipsec-subnet-row';
  2442. row.innerHTML = `
  2443. <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">
  2444. <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>
  2445. `;
  2446. container.appendChild(row);
  2447. }
  2448. function updateIpsecEspProposalFromPFS(val) {
  2449. const prop = document.getElementById('ipsec-modal-espprop');
  2450. if (!prop) return;
  2451. if (val === 'none') {
  2452. prop.value = 'aes256-sha256,aes128-sha256,default';
  2453. } else {
  2454. prop.value = `aes256-sha256-${val},aes128-sha256-${val},default`;
  2455. }
  2456. }
  2457. function updateIpsecIkeProposalFromDH(dh) {
  2458. const el = document.getElementById('ipsec-modal-ikeprop');
  2459. if (el) {
  2460. el.value = `aes256-sha256-${dh},aes128-sha256-${dh},default`;
  2461. }
  2462. }
  2463. function safeSetVal(id, val) {
  2464. const el = document.getElementById(id);
  2465. if (el) el.value = val;
  2466. }
  2467. function safeSetChecked(id, val) {
  2468. const el = document.getElementById(id);
  2469. if (el) el.checked = !!val;
  2470. }
  2471. function safeGetVal(id, def = '') {
  2472. const el = document.getElementById(id);
  2473. return el ? el.value : def;
  2474. }
  2475. async function loadIPSec(populateInputs = true) {
  2476. try {
  2477. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`);
  2478. const list = await res.json();
  2479. state.ipsecTunnels = Array.isArray(list) ? list : [];
  2480. const activeCount = state.ipsecTunnels.filter(t => t.running || t.status === 'ESTABLISHED').length;
  2481. const badge = document.getElementById('ipsec-sas-badge');
  2482. if (badge) badge.innerText = `${activeCount} Active SAs`;
  2483. const tbody = document.getElementById('ipsec-table-body');
  2484. const empty = document.getElementById('ipsec-empty');
  2485. if (!tbody) return;
  2486. tbody.innerHTML = '';
  2487. if (state.ipsecTunnels.length === 0) {
  2488. if (empty) empty.classList.remove('hidden');
  2489. } else {
  2490. if (empty) empty.classList.add('hidden');
  2491. state.ipsecTunnels.forEach(c => {
  2492. const isEstablished = c.running || c.status === 'ESTABLISHED';
  2493. const tr = document.createElement('tr');
  2494. tr.className = 'hover:bg-slate-800/40 transition text-xs select-none';
  2495. // Local subnets tags
  2496. const localList = (c.local_subnets && c.local_subnets.length > 0) ? c.local_subnets : (c.local_subnet ? [c.local_subnet] : ['0.0.0.0/0']);
  2497. 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('');
  2498. // Remote subnets tags
  2499. const remoteList = (c.remote_subnets && c.remote_subnets.length > 0) ? c.remote_subnets : (c.remote_subnet ? [c.remote_subnet] : ['0.0.0.0/0']);
  2500. 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('');
  2501. const ikeVersionBadge = (c.ike_version || 'ikev2').toUpperCase();
  2502. const p2Name = c.phase2_name || `${c.name}_p2`;
  2503. tr.innerHTML = `
  2504. <td class="py-2.5 px-3 text-center">
  2505. ${isEstablished ? `
  2506. <span class="inline-flex items-center gap-1.5 text-emerald-400 font-mono font-bold text-[11px]" title="Active SA Established">
  2507. <span class="w-2.5 h-2.5 rounded-full bg-emerald-400 animate-pulse"></span>
  2508. <span>UP</span>
  2509. </span>
  2510. ` : (c.disabled ? `
  2511. <span class="inline-flex items-center gap-1.5 text-slate-500 font-mono text-[11px]" title="Tunnel Disabled">
  2512. <span class="w-2 h-2 rounded-full bg-rose-500"></span>
  2513. <span>DOWN</span>
  2514. </span>
  2515. ` : `
  2516. <span class="inline-flex items-center gap-1.5 text-amber-400 font-mono text-[11px]" title="Disconnected / Idle">
  2517. <span class="w-2 h-2 rounded-full bg-amber-400"></span>
  2518. <span>IDLE</span>
  2519. </span>
  2520. `)}
  2521. </td>
  2522. <td class="py-2.5 px-4 font-bold text-white">
  2523. <div class="flex items-center gap-2">
  2524. <span class="text-amber-400">🛡</span>
  2525. <div>
  2526. <div>${escapeHtml(c.name)}</div>
  2527. <div class="text-[10px] text-slate-500 font-normal">P2: ${escapeHtml(p2Name)}</div>
  2528. </div>
  2529. </div>
  2530. </td>
  2531. <td class="py-2.5 px-4 text-slate-300 font-mono font-medium">${escapeHtml(c.remote_addrs || '%any')}</td>
  2532. <td class="py-2.5 px-4 font-sans">
  2533. <div class="flex items-center gap-1.5">
  2534. <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>
  2535. <span class="text-[10px] text-slate-400">${c.auth_method || 'PSK'}</span>
  2536. </div>
  2537. </td>
  2538. <td class="py-2.5 px-4">
  2539. <div class="space-y-1">
  2540. <div class="flex items-center flex-wrap gap-1">
  2541. <span class="text-[9px] text-cyan-400 uppercase font-bold mr-1">Local:</span>
  2542. ${localBadges}
  2543. </div>
  2544. <div class="flex items-center flex-wrap gap-1">
  2545. <span class="text-[9px] text-purple-400 uppercase font-bold mr-1">Remote:</span>
  2546. ${remoteBadges}
  2547. </div>
  2548. </div>
  2549. </td>
  2550. <td class="py-2.5 px-4 font-mono text-[11px] text-slate-400">
  2551. <div class="truncate max-w-[140px]" title="${escapeHtml(c.esp_proposals || '')}">
  2552. ${escapeHtml(c.esp_proposals || 'aes256-sha256')}
  2553. </div>
  2554. <div class="text-[10px] text-slate-500">PFS: ${escapeHtml(c.pfs_group || 'modp2048')}</div>
  2555. </td>
  2556. <td class="py-2.5 px-4 text-right space-x-2 font-sans">
  2557. ${isEstablished ? `
  2558. <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>
  2559. ` : `
  2560. <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>
  2561. `}
  2562. <button onclick="toggleIPSecState('${c.name}', ${c.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  2563. ${c.disabled ? 'Enable' : 'Disable'}
  2564. </button>
  2565. <button onclick="openEditIPSecModal('${c.name}')" class="text-xs text-amber-400 hover:text-amber-300">Edit</button>
  2566. <button onclick="deleteIPSecConn('${c.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2567. </td>
  2568. `;
  2569. tbody.appendChild(tr);
  2570. });
  2571. }
  2572. } catch (err) {
  2573. console.error('Failed to load IPSec:', err);
  2574. }
  2575. }
  2576. function openAddIPSecModal() {
  2577. const modal = document.getElementById('ipsec-modal');
  2578. if (!modal) return;
  2579. const title = document.getElementById('ipsec-modal-title');
  2580. if (title) title.innerText = 'Configure IPSec Site-to-Site Tunnel';
  2581. // Phase 1 Fields
  2582. safeSetVal('ipsec-modal-name', `tunnel-${(state.ipsecTunnels || []).length + 1}`);
  2583. const nameEl = document.getElementById('ipsec-modal-name');
  2584. if (nameEl) nameEl.readOnly = false;
  2585. safeSetVal('ipsec-modal-ikeversion', 'ikev2');
  2586. safeSetVal('ipsec-modal-ikever', 'ikev2');
  2587. safeSetVal('ipsec-modal-remotegw', '');
  2588. safeSetVal('ipsec-modal-localaddrs', '');
  2589. safeSetVal('ipsec-modal-comments', '');
  2590. safeSetVal('ipsec-modal-psk', '');
  2591. safeSetVal('ipsec-modal-ikeprop', 'aes256-sha256-modp2048,aes128-sha256-modp2048,default');
  2592. safeSetVal('ipsec-modal-dhgroup', 'modp2048');
  2593. safeSetVal('ipsec-modal-ikekeylife', '86400');
  2594. safeSetVal('ipsec-modal-localid', '');
  2595. safeSetVal('ipsec-modal-remoteid', '');
  2596. safeSetVal('ipsec-modal-dpd', 'on-demand');
  2597. // Phase 2 Fields
  2598. safeSetVal('ipsec-modal-p2name', `tunnel-${(state.ipsecTunnels || []).length + 1}_p2`);
  2599. safeSetVal('ipsec-modal-espkeylife', '28800');
  2600. safeSetVal('ipsec-modal-espprop', 'aes256-sha256-modp2048,aes128-sha256-modp2048,default');
  2601. safeSetVal('ipsec-modal-pfsgroup', 'modp2048');
  2602. safeSetChecked('ipsec-modal-autostart', true);
  2603. safeSetChecked('ipsec-modal-disabled', false);
  2604. // Clear & Populate default dynamic subnets
  2605. const localContainer = document.getElementById('ipsec-modal-local-subnets-container');
  2606. const remoteContainer = document.getElementById('ipsec-modal-remote-subnets-container');
  2607. if (localContainer) {
  2608. localContainer.innerHTML = '';
  2609. addIpsecLocalSubnet('192.168.10.0/24');
  2610. }
  2611. if (remoteContainer) {
  2612. remoteContainer.innerHTML = '';
  2613. addIpsecRemoteSubnet('192.168.20.0/24');
  2614. }
  2615. switchIpsecModalTab('p1');
  2616. modal.classList.remove('hidden');
  2617. }
  2618. function openEditIPSecModal(name) {
  2619. const modal = document.getElementById('ipsec-modal');
  2620. if (!modal) return;
  2621. const conn = (state.ipsecTunnels || []).find(c => c.name === name);
  2622. if (!conn) return;
  2623. const title = document.getElementById('ipsec-modal-title');
  2624. if (title) title.innerText = `Edit IPSec Tunnel: ${name}`;
  2625. // Phase 1 Fields
  2626. safeSetVal('ipsec-modal-name', conn.name);
  2627. const nameEl = document.getElementById('ipsec-modal-name');
  2628. if (nameEl) nameEl.readOnly = true;
  2629. safeSetVal('ipsec-modal-ikeversion', conn.ike_version || 'ikev2');
  2630. safeSetVal('ipsec-modal-ikever', conn.ike_version || 'ikev2');
  2631. safeSetVal('ipsec-modal-remotegw', conn.remote_addrs || '');
  2632. safeSetVal('ipsec-modal-localaddrs', conn.local_addrs || '');
  2633. safeSetVal('ipsec-modal-comments', conn.comment || '');
  2634. safeSetVal('ipsec-modal-psk', conn.preshared_key || '');
  2635. safeSetVal('ipsec-modal-ikeprop', conn.ike_proposals || 'aes256-sha256-modp2048,default');
  2636. safeSetVal('ipsec-modal-ikekeylife', conn.ike_keylife || 86400);
  2637. safeSetVal('ipsec-modal-localid', conn.local_id || '');
  2638. safeSetVal('ipsec-modal-remoteid', conn.remote_id || '');
  2639. safeSetVal('ipsec-modal-dpd', conn.dpd || 'on-demand');
  2640. // Phase 2 Fields
  2641. safeSetVal('ipsec-modal-p2name', conn.phase2_name || `${conn.name}_p2`);
  2642. safeSetVal('ipsec-modal-espkeylife', conn.esp_keylife || 28800);
  2643. safeSetVal('ipsec-modal-espprop', conn.esp_proposals || 'aes256-sha256-modp2048,default');
  2644. safeSetVal('ipsec-modal-pfsgroup', conn.pfs_group || 'modp2048');
  2645. safeSetChecked('ipsec-modal-autostart', conn.auto_start ?? true);
  2646. safeSetChecked('ipsec-modal-disabled', !!conn.disabled);
  2647. // Populate dynamic subnets
  2648. const localContainer = document.getElementById('ipsec-modal-local-subnets-container');
  2649. const remoteContainer = document.getElementById('ipsec-modal-remote-subnets-container');
  2650. if (localContainer) {
  2651. localContainer.innerHTML = '';
  2652. const locals = (conn.local_subnets && conn.local_subnets.length > 0) ? conn.local_subnets : (conn.local_subnet ? [conn.local_subnet] : ['192.168.10.0/24']);
  2653. locals.forEach(s => addIpsecLocalSubnet(s));
  2654. }
  2655. if (remoteContainer) {
  2656. remoteContainer.innerHTML = '';
  2657. const remotes = (conn.remote_subnets && conn.remote_subnets.length > 0) ? conn.remote_subnets : (conn.remote_subnet ? [conn.remote_subnet] : ['192.168.20.0/24']);
  2658. remotes.forEach(s => addIpsecRemoteSubnet(s));
  2659. }
  2660. switchIpsecModalTab('p1');
  2661. modal.classList.remove('hidden');
  2662. }
  2663. function closeAddIPSecModal() {
  2664. const modal = document.getElementById('ipsec-modal');
  2665. if (modal) modal.classList.add('hidden');
  2666. }
  2667. async function submitSaveIPSec(e) {
  2668. if (e) e.preventDefault();
  2669. const name = safeGetVal('ipsec-modal-name').trim();
  2670. if (!name) {
  2671. showToast('Error', 'Tunnel name is required', 'error');
  2672. return;
  2673. }
  2674. const ikeVersion = safeGetVal('ipsec-modal-ikeversion') || safeGetVal('ipsec-modal-ikever', 'ikev2');
  2675. const remotegw = safeGetVal('ipsec-modal-remotegw').trim();
  2676. const localAddrs = safeGetVal('ipsec-modal-localaddrs').trim() || '%any';
  2677. const comments = safeGetVal('ipsec-modal-comments').trim();
  2678. const psk = safeGetVal('ipsec-modal-psk');
  2679. const ikeProposals = safeGetVal('ipsec-modal-ikeprop', 'aes256-sha256-modp2048,default').trim();
  2680. const ikeKeylife = parseInt(safeGetVal('ipsec-modal-ikekeylife', '86400'), 10) || 86400;
  2681. const localId = safeGetVal('ipsec-modal-localid').trim();
  2682. const remoteId = safeGetVal('ipsec-modal-remoteid').trim();
  2683. const dpd = safeGetVal('ipsec-modal-dpd', 'on-demand');
  2684. const phase2Name = safeGetVal('ipsec-modal-p2name').trim() || `${name}_p2`;
  2685. const espProposals = safeGetVal('ipsec-modal-espprop', 'aes256-sha256-modp2048,default').trim();
  2686. const espKeylife = parseInt(safeGetVal('ipsec-modal-espkeylife', '28800'), 10) || 28800;
  2687. const pfsGroup = safeGetVal('ipsec-modal-pfsgroup', 'modp2048');
  2688. const autostart = document.getElementById('ipsec-modal-autostart')?.checked ?? true;
  2689. const disabled = document.getElementById('ipsec-modal-disabled')?.checked ?? false;
  2690. // Scrape dynamic local and remote subnets
  2691. const localInputs = document.querySelectorAll('#ipsec-modal-local-subnets-container input');
  2692. const localSubnets = [];
  2693. localInputs.forEach(inp => {
  2694. const v = inp.value.trim();
  2695. if (v) localSubnets.push(v);
  2696. });
  2697. const remoteInputs = document.querySelectorAll('#ipsec-modal-remote-subnets-container input');
  2698. const remoteSubnets = [];
  2699. remoteInputs.forEach(inp => {
  2700. const v = inp.value.trim();
  2701. if (v) remoteSubnets.push(v);
  2702. });
  2703. try {
  2704. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`, {
  2705. method: 'POST',
  2706. headers: { 'Content-Type': 'application/json' },
  2707. body: JSON.stringify({
  2708. name,
  2709. comment: comments,
  2710. ike_version: ikeVersion,
  2711. local_addrs: localAddrs,
  2712. remote_addrs: remotegw,
  2713. preshared_key: psk,
  2714. ike_proposals: ikeProposals,
  2715. ike_keylife: ikeKeylife,
  2716. local_id: localId,
  2717. remote_id: remoteId,
  2718. dpd: dpd,
  2719. phase2_name: phase2Name,
  2720. esp_proposals: espProposals,
  2721. esp_keylife: espKeylife,
  2722. pfs_group: pfsGroup,
  2723. pfs: pfsGroup !== 'none',
  2724. local_subnets: localSubnets,
  2725. remote_subnets: remoteSubnets,
  2726. local_subnet: localSubnets[0] || '0.0.0.0/0',
  2727. remote_subnet: remoteSubnets[0] || '0.0.0.0/0',
  2728. auto_start: autostart,
  2729. disabled
  2730. })
  2731. });
  2732. if (res.ok) {
  2733. showToast('IPSec Saved', `FortiGate Tunnel ${name} configured`, 'success');
  2734. closeAddIPSecModal();
  2735. loadIPSec(false);
  2736. } else {
  2737. const err = await res.json();
  2738. showToast('Error', err.error || 'Failed to save IPSec tunnel', 'error');
  2739. }
  2740. } catch (err) {
  2741. showToast('Error', err.message, 'error');
  2742. }
  2743. }
  2744. async function startIPSecTunnel(name) {
  2745. try {
  2746. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/start`, { method: 'POST' });
  2747. if (res.ok) {
  2748. showToast('Initiating Tunnel', `Attempting SA handshake for ${name}...`, 'info');
  2749. setTimeout(() => loadIPSec(false), 2000);
  2750. }
  2751. } catch (err) {
  2752. showToast('Error', err.message, 'error');
  2753. }
  2754. }
  2755. async function stopIPSecTunnel(name) {
  2756. try {
  2757. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  2758. if (res.ok) {
  2759. showToast('Terminated', `IPSec SA for ${name} closed`, 'info');
  2760. loadIPSec(false);
  2761. }
  2762. } catch (err) {
  2763. showToast('Error', err.message, 'error');
  2764. }
  2765. }
  2766. async function toggleIPSecState(name, enable) {
  2767. try {
  2768. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/state`, {
  2769. method: 'POST',
  2770. headers: { 'Content-Type': 'application/json' },
  2771. body: JSON.stringify({ enabled: enable })
  2772. });
  2773. if (res.ok) {
  2774. showToast(enable ? 'Enabled' : 'Disabled', `IPSec tunnel ${name} updated`, 'info');
  2775. loadIPSec(false);
  2776. }
  2777. } catch (err) {
  2778. showToast('Error', err.message, 'error');
  2779. }
  2780. }
  2781. async function deleteIPSecConn(name) {
  2782. if (!confirm(`Are you sure you want to delete IPSec tunnel ${name}?`)) return;
  2783. try {
  2784. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2785. if (res.ok) {
  2786. showToast('Deleted', `IPSec connection ${name} removed`, 'success');
  2787. loadIPSec(false);
  2788. fetchData(false);
  2789. }
  2790. } catch (err) {
  2791. showToast('Error', err.message, 'error');
  2792. }
  2793. }
  2794. // ======================== L2TP Multi-Instance ========================
  2795. async function loadL2TP(populateInputs = true) {
  2796. try {
  2797. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2798. await fetchPPPProfilesList();
  2799. }
  2800. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`);
  2801. const list = await res.json();
  2802. state.l2tpList = Array.isArray(list) ? list : [];
  2803. const badge = document.getElementById('l2tp-count-badge');
  2804. if (badge) badge.innerText = `${state.l2tpList.length} Client${state.l2tpList.length !== 1 ? 's' : ''}`;
  2805. const tbody = document.getElementById('l2tp-table-body');
  2806. const empty = document.getElementById('l2tp-empty');
  2807. if (!tbody) return;
  2808. tbody.innerHTML = '';
  2809. if (state.l2tpList.length === 0) {
  2810. if (empty) empty.classList.remove('hidden');
  2811. } else {
  2812. if (empty) empty.classList.add('hidden');
  2813. state.l2tpList.forEach(inst => {
  2814. const tr = document.createElement('tr');
  2815. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  2816. tr.innerHTML = `
  2817. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  2818. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  2819. <td class="py-2.5 px-3 text-cyan-400 font-mono">${escapeHtml(inst.connect_to)}</td>
  2820. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  2821. <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>
  2822. <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>
  2823. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  2824. <td class="py-2.5 px-3 text-center">
  2825. <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'}">
  2826. ${inst.default_route ? 'Yes' : 'No'}
  2827. </span>
  2828. </td>
  2829. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  2830. ${inst.running ? `
  2831. <button onclick="disconnectL2TPInstance('${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  2832. ` : `
  2833. <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>
  2834. `}
  2835. <button onclick="toggleL2TPState('${escapeHtml(inst.name)}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  2836. ${inst.disabled ? 'Enable' : 'Disable'}
  2837. </button>
  2838. <button onclick="openEditL2TPModal('${escapeHtml(inst.name)}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2839. <button onclick="deleteL2TPInstance('${escapeHtml(inst.name)}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2840. </td>
  2841. `;
  2842. tbody.appendChild(tr);
  2843. });
  2844. }
  2845. } catch (err) {
  2846. console.error('Failed to load L2TP:', err);
  2847. }
  2848. }
  2849. async function openAddL2TPModal() {
  2850. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2851. await fetchPPPProfilesList();
  2852. }
  2853. document.getElementById('l2tp-modal-title').innerText = 'Add L2TP Client Interface';
  2854. document.getElementById('l2tp-modal-name').value = `l2tp-out${(state.l2tpList || []).length + 1}`;
  2855. document.getElementById('l2tp-modal-name').readOnly = false;
  2856. document.getElementById('l2tp-modal-server').value = '';
  2857. document.getElementById('l2tp-modal-user').value = '';
  2858. document.getElementById('l2tp-modal-pass').value = '';
  2859. document.getElementById('l2tp-modal-ipsec').value = '';
  2860. document.getElementById('l2tp-modal-defroute').checked = true;
  2861. document.getElementById('l2tp-modal-disabled').checked = false;
  2862. populateProfileSelect('l2tp-modal-profile', 'default-encryption', 'default-encryption');
  2863. document.getElementById('l2tp-modal').classList.remove('hidden');
  2864. }
  2865. async function openEditL2TPModal(name) {
  2866. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2867. await fetchPPPProfilesList();
  2868. }
  2869. const inst = (state.l2tpList || []).find(i => i.name === name);
  2870. if (!inst) return;
  2871. document.getElementById('l2tp-modal-title').innerText = `Edit L2TP Client: ${name}`;
  2872. document.getElementById('l2tp-modal-name').value = inst.name;
  2873. document.getElementById('l2tp-modal-name').readOnly = true;
  2874. document.getElementById('l2tp-modal-server').value = inst.connect_to || '';
  2875. document.getElementById('l2tp-modal-user').value = inst.username || '';
  2876. document.getElementById('l2tp-modal-pass').value = inst.password || '';
  2877. document.getElementById('l2tp-modal-ipsec').value = inst.ipsec_secret || '';
  2878. document.getElementById('l2tp-modal-defroute').checked = inst.default_route ?? true;
  2879. document.getElementById('l2tp-modal-disabled').checked = !!inst.disabled;
  2880. populateProfileSelect('l2tp-modal-profile', inst.profile || 'default-encryption', 'default-encryption');
  2881. document.getElementById('l2tp-modal').classList.remove('hidden');
  2882. }
  2883. function closeL2TPModal() {
  2884. document.getElementById('l2tp-modal').classList.add('hidden');
  2885. }
  2886. async function submitSaveL2TP(e) {
  2887. e.preventDefault();
  2888. const name = document.getElementById('l2tp-modal-name').value.trim();
  2889. const server = document.getElementById('l2tp-modal-server').value.trim();
  2890. const user = document.getElementById('l2tp-modal-user').value.trim();
  2891. const pass = document.getElementById('l2tp-modal-pass').value;
  2892. const profile = document.getElementById('l2tp-modal-profile')?.value || 'default-encryption';
  2893. const ipsec = document.getElementById('l2tp-modal-ipsec').value;
  2894. const defRoute = document.getElementById('l2tp-modal-defroute').checked;
  2895. const disabled = document.getElementById('l2tp-modal-disabled').checked;
  2896. try {
  2897. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`, {
  2898. method: 'POST',
  2899. headers: { 'Content-Type': 'application/json' },
  2900. body: JSON.stringify({
  2901. name,
  2902. connect_to: server,
  2903. username: user,
  2904. password: pass,
  2905. profile: profile,
  2906. ipsec_secret: ipsec,
  2907. default_route: defRoute,
  2908. disabled
  2909. })
  2910. });
  2911. if (res.ok) {
  2912. showToast('L2TP Saved', `Client ${name} configuration saved`, 'success');
  2913. closeL2TPModal();
  2914. loadL2TP(false);
  2915. fetchData(false);
  2916. }
  2917. } catch (err) {
  2918. showToast('Error', err.message, 'error');
  2919. }
  2920. }
  2921. async function connectL2TPInstance(name) {
  2922. try {
  2923. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  2924. if (res.ok) {
  2925. showToast('Connecting', `Dialing L2TP ${name}...`, 'info');
  2926. setTimeout(() => loadL2TP(false), 2000);
  2927. }
  2928. } catch (err) {
  2929. showToast('Error', err.message, 'error');
  2930. }
  2931. }
  2932. async function disconnectL2TPInstance(name) {
  2933. try {
  2934. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  2935. if (res.ok) {
  2936. showToast('Disconnected', `L2TP tunnel ${name} terminated`, 'info');
  2937. loadL2TP(false);
  2938. }
  2939. } catch (err) {
  2940. showToast('Error', err.message, 'error');
  2941. }
  2942. }
  2943. async function toggleL2TPState(name, enable) {
  2944. try {
  2945. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/state`, {
  2946. method: 'POST',
  2947. headers: { 'Content-Type': 'application/json' },
  2948. body: JSON.stringify({ enabled: enable })
  2949. });
  2950. if (res.ok) {
  2951. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  2952. loadL2TP(false);
  2953. }
  2954. } catch (err) {
  2955. showToast('Error', err.message, 'error');
  2956. }
  2957. }
  2958. async function deleteL2TPInstance(name) {
  2959. if (!confirm(`Are you sure you want to delete L2TP client ${name}?`)) return;
  2960. try {
  2961. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2962. if (res.ok) {
  2963. showToast('Deleted', `L2TP client ${name} removed`, 'success');
  2964. loadL2TP(false);
  2965. fetchData(false);
  2966. }
  2967. } catch (err) {
  2968. showToast('Error', err.message, 'error');
  2969. }
  2970. }
  2971. // ======================== PPTP Multi-Instance ========================
  2972. async function loadPPTP(populateInputs = true) {
  2973. try {
  2974. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2975. await fetchPPPProfilesList();
  2976. }
  2977. const res = await fetch(`${API_BASE}/vpn/pptp/clients`);
  2978. const list = await res.json();
  2979. state.pptpList = Array.isArray(list) ? list : [];
  2980. const badge = document.getElementById('pptp-count-badge');
  2981. if (badge) badge.innerText = `${state.pptpList.length} Client${state.pptpList.length !== 1 ? 's' : ''}`;
  2982. const tbody = document.getElementById('pptp-table-body');
  2983. const empty = document.getElementById('pptp-empty');
  2984. if (!tbody) return;
  2985. tbody.innerHTML = '';
  2986. if (state.pptpList.length === 0) {
  2987. if (empty) empty.classList.remove('hidden');
  2988. } else {
  2989. if (empty) empty.classList.add('hidden');
  2990. state.pptpList.forEach(inst => {
  2991. const tr = document.createElement('tr');
  2992. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  2993. tr.innerHTML = `
  2994. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  2995. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  2996. <td class="py-2.5 px-3 text-purple-400 font-mono">${escapeHtml(inst.connect_to)}</td>
  2997. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  2998. <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>
  2999. <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>
  3000. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  3001. <td class="py-2.5 px-3 text-center">
  3002. <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'}">
  3003. ${inst.require_mppe ? 'MPPE-128' : 'None'}
  3004. </span>
  3005. </td>
  3006. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  3007. ${inst.running ? `
  3008. <button onclick="disconnectPPTPInstance('${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  3009. ` : `
  3010. <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>
  3011. `}
  3012. <button onclick="togglePPTPState('${escapeHtml(inst.name)}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  3013. ${inst.disabled ? 'Enable' : 'Disable'}
  3014. </button>
  3015. <button onclick="openEditPPTPModal('${escapeHtml(inst.name)}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  3016. <button onclick="deletePPTPInstance('${escapeHtml(inst.name)}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  3017. </td>
  3018. `;
  3019. tbody.appendChild(tr);
  3020. });
  3021. }
  3022. } catch (err) {
  3023. console.error('Failed to load PPTP:', err);
  3024. }
  3025. }
  3026. async function openAddPPTPModal() {
  3027. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  3028. await fetchPPPProfilesList();
  3029. }
  3030. document.getElementById('pptp-modal-title').innerText = 'Add PPTP Client Interface';
  3031. document.getElementById('pptp-modal-name').value = `pptp-out${(state.pptpList || []).length + 1}`;
  3032. document.getElementById('pptp-modal-name').readOnly = false;
  3033. document.getElementById('pptp-modal-server').value = '';
  3034. document.getElementById('pptp-modal-user').value = '';
  3035. document.getElementById('pptp-modal-pass').value = '';
  3036. document.getElementById('pptp-modal-mppe').checked = true;
  3037. document.getElementById('pptp-modal-defroute').checked = true;
  3038. document.getElementById('pptp-modal-disabled').checked = false;
  3039. populateProfileSelect('pptp-modal-profile', 'default-encryption', 'default-encryption');
  3040. document.getElementById('pptp-modal').classList.remove('hidden');
  3041. }
  3042. async function openEditPPTPModal(name) {
  3043. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  3044. await fetchPPPProfilesList();
  3045. }
  3046. const inst = (state.pptpList || []).find(i => i.name === name);
  3047. if (!inst) return;
  3048. document.getElementById('pptp-modal-title').innerText = `Edit PPTP Client: ${name}`;
  3049. document.getElementById('pptp-modal-name').value = inst.name;
  3050. document.getElementById('pptp-modal-name').readOnly = true;
  3051. document.getElementById('pptp-modal-server').value = inst.connect_to || '';
  3052. document.getElementById('pptp-modal-user').value = inst.username || '';
  3053. document.getElementById('pptp-modal-pass').value = inst.password || '';
  3054. document.getElementById('pptp-modal-mppe').checked = inst.require_mppe ?? true;
  3055. document.getElementById('pptp-modal-defroute').checked = inst.default_route ?? true;
  3056. document.getElementById('pptp-modal-disabled').checked = !!inst.disabled;
  3057. populateProfileSelect('pptp-modal-profile', inst.profile || 'default-encryption', 'default-encryption');
  3058. document.getElementById('pptp-modal').classList.remove('hidden');
  3059. }
  3060. function closePPTPModal() {
  3061. document.getElementById('pptp-modal').classList.add('hidden');
  3062. }
  3063. async function submitSavePPTP(e) {
  3064. e.preventDefault();
  3065. const name = document.getElementById('pptp-modal-name').value.trim();
  3066. const server = document.getElementById('pptp-modal-server').value.trim();
  3067. const user = document.getElementById('pptp-modal-user').value.trim();
  3068. const pass = document.getElementById('pptp-modal-pass').value;
  3069. const profile = document.getElementById('pptp-modal-profile')?.value || 'default-encryption';
  3070. const mppe = document.getElementById('pptp-modal-mppe').checked;
  3071. const defRoute = document.getElementById('pptp-modal-defroute').checked;
  3072. const disabled = document.getElementById('pptp-modal-disabled').checked;
  3073. try {
  3074. const res = await fetch(`${API_BASE}/vpn/pptp/clients`, {
  3075. method: 'POST',
  3076. headers: { 'Content-Type': 'application/json' },
  3077. body: JSON.stringify({
  3078. name,
  3079. connect_to: server,
  3080. username: user,
  3081. password: pass,
  3082. profile: profile,
  3083. require_mppe: mppe,
  3084. default_route: defRoute,
  3085. auto_reconnect: true,
  3086. disabled
  3087. })
  3088. });
  3089. if (res.ok) {
  3090. showToast('PPTP Saved', `Client ${name} configuration saved`, 'success');
  3091. closePPTPModal();
  3092. loadPPTP(false);
  3093. fetchData(false);
  3094. }
  3095. } catch (err) {
  3096. showToast('Error', err.message, 'error');
  3097. }
  3098. }
  3099. async function connectPPTPInstance(name) {
  3100. try {
  3101. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  3102. if (res.ok) {
  3103. showToast('Connecting', `Dialing PPTP ${name}...`, 'info');
  3104. setTimeout(() => loadPPTP(false), 2000);
  3105. }
  3106. } catch (err) {
  3107. showToast('Error', err.message, 'error');
  3108. }
  3109. }
  3110. async function disconnectPPTPInstance(name) {
  3111. try {
  3112. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  3113. if (res.ok) {
  3114. showToast('Disconnected', `PPTP tunnel ${name} terminated`, 'info');
  3115. loadPPTP(false);
  3116. }
  3117. } catch (err) {
  3118. showToast('Error', err.message, 'error');
  3119. }
  3120. }
  3121. async function togglePPTPState(name, enable) {
  3122. try {
  3123. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/state`, {
  3124. method: 'POST',
  3125. headers: { 'Content-Type': 'application/json' },
  3126. body: JSON.stringify({ enabled: enable })
  3127. });
  3128. if (res.ok) {
  3129. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  3130. loadPPTP(false);
  3131. }
  3132. } catch (err) {
  3133. showToast('Error', err.message, 'error');
  3134. }
  3135. }
  3136. async function deletePPTPInstance(name) {
  3137. if (!confirm(`Are you sure you want to delete PPTP client ${name}?`)) return;
  3138. try {
  3139. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  3140. if (res.ok) {
  3141. showToast('Deleted', `PPTP client ${name} removed`, 'success');
  3142. loadPPTP(false);
  3143. fetchData(false);
  3144. }
  3145. } catch (err) {
  3146. showToast('Error', err.message, 'error');
  3147. }
  3148. }
  3149. // ---------------- Modal & Helper Functions ----------------
  3150. function openVlanModal(defaultParent = '') {
  3151. const select = document.getElementById('vlan-parent');
  3152. select.innerHTML = '';
  3153. const allIfaces = state.interfaces || [];
  3154. const eligible = allIfaces.filter(i => supportsVLAN(i));
  3155. if (eligible.length === 0) {
  3156. const opt = document.createElement('option');
  3157. opt.value = '';
  3158. opt.innerText = 'No VLAN-capable interfaces available';
  3159. select.appendChild(opt);
  3160. } else {
  3161. eligible.forEach(i => {
  3162. const opt = document.createElement('option');
  3163. opt.value = i.name;
  3164. opt.innerText = `${i.name} (${i.role || i.type || 'Ethernet'} - ${i.state})`;
  3165. if (i.name === defaultParent) opt.selected = true;
  3166. select.appendChild(opt);
  3167. });
  3168. }
  3169. document.getElementById('vlan-id').value = '';
  3170. document.getElementById('vlan-name').value = '';
  3171. document.getElementById('vlan-ip').value = '';
  3172. document.getElementById('vlan-desc').value = '';
  3173. populateRoleSelects('LAN');
  3174. autoSuggestVlanName();
  3175. document.getElementById('vlan-modal').classList.remove('hidden');
  3176. }
  3177. function closeVlanModal() {
  3178. document.getElementById('vlan-modal').classList.add('hidden');
  3179. }
  3180. function autoSuggestVlanName() {
  3181. const parent = document.getElementById('vlan-parent').value;
  3182. if (!parent) return;
  3183. const id = document.getElementById('vlan-id').value;
  3184. const nameInput = document.getElementById('vlan-name');
  3185. if (parent && id) nameInput.placeholder = `${parent}.${id}`;
  3186. }
  3187. function setSubnetPreset(cidr) {
  3188. const ipInput = document.getElementById('vlan-ip');
  3189. const id = document.getElementById('vlan-id').value || '10';
  3190. ipInput.value = `192.168.${id}.1${cidr}`;
  3191. }
  3192. async function submitCreateVlan(e) {
  3193. e.preventDefault();
  3194. const btn = document.getElementById('vlan-submit-btn');
  3195. btn.disabled = true;
  3196. btn.innerText = 'Creating...';
  3197. const parent = document.getElementById('vlan-parent').value;
  3198. if (!parent) {
  3199. showToast('Error', 'Please select a valid VLAN-capable parent interface', 'error');
  3200. btn.disabled = false;
  3201. btn.innerText = 'Create VLAN';
  3202. return;
  3203. }
  3204. const id = parseInt(document.getElementById('vlan-id').value, 10);
  3205. const name = document.getElementById('vlan-name').value.trim();
  3206. const ip = document.getElementById('vlan-ip').value.trim();
  3207. const role = document.getElementById('vlan-role').value;
  3208. const desc = document.getElementById('vlan-desc').value.trim();
  3209. try {
  3210. const res = await fetch(`${API_BASE}/vlans`, {
  3211. method: 'POST',
  3212. headers: { 'Content-Type': 'application/json' },
  3213. body: JSON.stringify({
  3214. parent_name: parent,
  3215. vlan_id: id,
  3216. name: name,
  3217. ip_address: ip,
  3218. role: role,
  3219. description: desc,
  3220. mtu: 1500,
  3221. auto_up: true
  3222. })
  3223. });
  3224. const data = await res.json();
  3225. if (res.ok) {
  3226. showToast('VLAN Created', `Created ${data.name} (VLAN ${data.vlan_id})`, 'success');
  3227. state.expandedParents.add(parent);
  3228. closeVlanModal();
  3229. await fetchData(true);
  3230. if (state.activeTab !== 'interfaces') navigate('interfaces');
  3231. } else {
  3232. showToast('Creation Failed', data.message || 'Failed to create VLAN', 'error');
  3233. }
  3234. } catch (err) {
  3235. showToast('Error', err.message, 'error');
  3236. } finally {
  3237. btn.disabled = false;
  3238. btn.innerText = 'Create VLAN';
  3239. }
  3240. }
  3241. async function confirmDeleteVlan(name) {
  3242. if (!confirm(`Delete VLAN interface ${name}?`)) return;
  3243. try {
  3244. const res = await fetch(`${API_BASE}/vlans/${encodeURIComponent(name)}`, { method: 'DELETE' });
  3245. if (res.ok) {
  3246. showToast('VLAN Deleted', `Interface ${name} removed`, 'success');
  3247. closeIfaceModal();
  3248. fetchData(true);
  3249. }
  3250. } catch (err) {
  3251. showToast('Error', err.message, 'error');
  3252. }
  3253. }
  3254. function openIfaceModal(name) {
  3255. const iface = (state.interfaces || []).find(i => i.name === name);
  3256. if (!iface) return;
  3257. state.currentModalIface = iface.name;
  3258. document.getElementById('modal-iface-name').innerText = iface.name;
  3259. document.getElementById('modal-iface-badge').innerText = iface.is_vlan ? `VLAN ${iface.vlan_id}` : iface.type;
  3260. document.getElementById('modal-iface-mtu').value = iface.mtu;
  3261. populateRoleSelects(iface.role || 'LAN');
  3262. document.getElementById('modal-iface-desc').value = iface.description || '';
  3263. const nameInput = document.getElementById('modal-iface-new-name');
  3264. const renameBtn = document.getElementById('modal-btn-rename');
  3265. const renameHelp = document.getElementById('modal-iface-rename-help');
  3266. if (nameInput) {
  3267. nameInput.value = iface.name;
  3268. if (iface.name === 'lo' || iface.type === 'loopback') {
  3269. nameInput.disabled = true;
  3270. if (renameBtn) renameBtn.disabled = true;
  3271. if (renameHelp) renameHelp.innerText = 'Loopback interface cannot be renamed.';
  3272. } else {
  3273. nameInput.disabled = false;
  3274. if (renameBtn) renameBtn.disabled = false;
  3275. if (renameHelp) renameHelp.innerText = 'Device name in Linux (max 15 characters). Automatically preserves operational link state and metadata.';
  3276. }
  3277. }
  3278. const delBtn = document.getElementById('modal-delete-vlan-btn');
  3279. if (iface.is_vlan) {
  3280. delBtn.classList.remove('hidden');
  3281. } else {
  3282. delBtn.classList.add('hidden');
  3283. }
  3284. renderModalIPs(iface);
  3285. document.getElementById('iface-modal').classList.remove('hidden');
  3286. }
  3287. function renderModalIPs(iface) {
  3288. const container = document.getElementById('modal-ip-list');
  3289. container.innerHTML = '';
  3290. const addrs = [...(iface.ipv4 || []), ...(iface.ipv6 || [])];
  3291. if (addrs.length === 0) {
  3292. container.innerHTML = `<span class="text-slate-500 text-xs font-sans">No IP addresses currently bound</span>`;
  3293. return;
  3294. }
  3295. addrs.forEach(addr => {
  3296. const row = document.createElement('div');
  3297. row.className = 'flex items-center justify-between p-2 rounded bg-slate-900 border border-slate-800';
  3298. row.innerHTML = `
  3299. <span class="text-white">${addr}</span>
  3300. <button onclick="removeInterfaceIP('${addr}')" class="text-[11px] text-rose-400 hover:text-rose-300 font-sans">Remove</button>
  3301. `;
  3302. container.appendChild(row);
  3303. });
  3304. }
  3305. function closeIfaceModal() {
  3306. document.getElementById('iface-modal').classList.add('hidden');
  3307. state.currentModalIface = null;
  3308. }
  3309. async function setIfaceState(name, newState) {
  3310. const target = name || state.currentModalIface;
  3311. if (!target) return;
  3312. await toggleInterfaceState(target, newState);
  3313. const updated = (state.interfaces || []).find(i => i.name === target);
  3314. if (updated) openIfaceModal(target);
  3315. }
  3316. async function applyMTU() {
  3317. const mtu = parseInt(document.getElementById('modal-iface-mtu').value, 10);
  3318. try {
  3319. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/mtu`, {
  3320. method: 'POST',
  3321. headers: { 'Content-Type': 'application/json' },
  3322. body: JSON.stringify({ mtu })
  3323. });
  3324. if (res.ok) {
  3325. showToast('MTU Applied', `Set MTU to ${mtu} on ${state.currentModalIface}`, 'success');
  3326. fetchData(false);
  3327. }
  3328. } catch (err) {
  3329. showToast('Error', err.message, 'error');
  3330. }
  3331. }
  3332. async function addInterfaceIP() {
  3333. const ip = document.getElementById('modal-new-ip').value.trim();
  3334. if (!ip) return;
  3335. try {
  3336. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  3337. method: 'POST',
  3338. headers: { 'Content-Type': 'application/json' },
  3339. body: JSON.stringify({ ip })
  3340. });
  3341. if (res.ok) {
  3342. showToast('IP Added', `Bound ${ip} to ${state.currentModalIface}`, 'success');
  3343. document.getElementById('modal-new-ip').value = '';
  3344. await fetchData(false);
  3345. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  3346. if (iface) renderModalIPs(iface);
  3347. } else {
  3348. const err = await res.json();
  3349. showToast('Error', err.error || err.message || 'Failed to add IP address', 'error');
  3350. }
  3351. } catch (err) {
  3352. showToast('Error', err.message, 'error');
  3353. }
  3354. }
  3355. async function removeInterfaceIP(ip) {
  3356. if (!confirm(`Remove IP ${ip}?`)) return;
  3357. try {
  3358. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  3359. method: 'DELETE',
  3360. headers: { 'Content-Type': 'application/json' },
  3361. body: JSON.stringify({ ip })
  3362. });
  3363. if (res.ok) {
  3364. showToast('IP Removed', `Removed ${ip}`, 'success');
  3365. await fetchData(false);
  3366. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  3367. if (iface) renderModalIPs(iface);
  3368. }
  3369. } catch (err) {
  3370. showToast('Error', err.message, 'error');
  3371. }
  3372. }
  3373. async function renameInterface() {
  3374. const oldName = state.currentModalIface;
  3375. const newNameInput = document.getElementById('modal-iface-new-name');
  3376. const newName = (newNameInput?.value || '').trim();
  3377. if (!oldName) return;
  3378. if (!newName) {
  3379. showToast('Warning', 'Interface name cannot be empty', 'warning');
  3380. return;
  3381. }
  3382. if (newName === oldName) {
  3383. showToast('Info', `Interface name is already "${oldName}"`, 'info');
  3384. return;
  3385. }
  3386. if (newName.length > 15) {
  3387. showToast('Validation Error', 'Interface name cannot exceed 15 characters (Linux IFNAMSIZ)', 'error');
  3388. return;
  3389. }
  3390. if (!/^[a-zA-Z0-9_][a-zA-Z0-9_.-]*$/.test(newName)) {
  3391. showToast('Validation Error', 'Name must contain only alphanumeric characters, underscores, hyphens or dots', 'error');
  3392. return;
  3393. }
  3394. const renameBtn = document.getElementById('modal-btn-rename');
  3395. if (renameBtn) {
  3396. renameBtn.disabled = true;
  3397. renameBtn.innerHTML = `<span class="animate-spin inline-block mr-1">⟳</span> Renaming...`;
  3398. }
  3399. try {
  3400. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(oldName)}/rename`, {
  3401. method: 'POST',
  3402. headers: { 'Content-Type': 'application/json' },
  3403. body: JSON.stringify({ new_name: newName })
  3404. });
  3405. const data = await res.json();
  3406. if (!res.ok) {
  3407. showToast('Rename Failed', data.error || data.message || 'Failed to rename interface', 'error');
  3408. return;
  3409. }
  3410. showToast('Interface Renamed', `Successfully renamed ${oldName} → ${newName}`, 'success');
  3411. state.currentModalIface = newName;
  3412. document.getElementById('modal-iface-name').innerText = newName;
  3413. // Refresh application state
  3414. await fetchData(false);
  3415. const updated = (state.interfaces || []).find(i => i.name === newName);
  3416. if (updated) {
  3417. openIfaceModal(newName);
  3418. } else {
  3419. closeIfaceModal();
  3420. }
  3421. } catch (err) {
  3422. showToast('Error', err.message, 'error');
  3423. } finally {
  3424. if (renameBtn) {
  3425. renameBtn.disabled = false;
  3426. renameBtn.innerHTML = `
  3427. <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>
  3428. <span>Rename</span>
  3429. `;
  3430. }
  3431. }
  3432. }
  3433. async function saveInterfaceMetadata() {
  3434. const oldName = state.currentModalIface;
  3435. const newName = (document.getElementById('modal-iface-new-name')?.value || '').trim();
  3436. const role = document.getElementById('modal-iface-role').value;
  3437. const desc = document.getElementById('modal-iface-desc').value.trim();
  3438. let targetName = oldName;
  3439. // If user changed the name before clicking Save Changes, execute rename first
  3440. if (newName && newName !== oldName && oldName !== 'lo') {
  3441. try {
  3442. const renameRes = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(oldName)}/rename`, {
  3443. method: 'POST',
  3444. headers: { 'Content-Type': 'application/json' },
  3445. body: JSON.stringify({ new_name: newName })
  3446. });
  3447. const data = await renameRes.json();
  3448. if (!renameRes.ok) {
  3449. showToast('Rename Failed', data.error || data.message || 'Could not rename interface', 'error');
  3450. return;
  3451. }
  3452. targetName = newName;
  3453. state.currentModalIface = newName;
  3454. showToast('Renamed', `Interface renamed from ${oldName} to ${newName}`, 'success');
  3455. } catch (err) {
  3456. showToast('Error', err.message, 'error');
  3457. return;
  3458. }
  3459. }
  3460. try {
  3461. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(targetName)}/metadata`, {
  3462. method: 'POST',
  3463. headers: { 'Content-Type': 'application/json' },
  3464. body: JSON.stringify({ role, description: desc })
  3465. });
  3466. if (res.ok) {
  3467. showToast('Saved', 'Interface configuration updated', 'success');
  3468. closeIfaceModal();
  3469. fetchData(false);
  3470. } else {
  3471. const err = await res.json();
  3472. showToast('Error', err.error || err.message || 'Failed to save metadata', 'error');
  3473. }
  3474. } catch (err) {
  3475. showToast('Error', err.message, 'error');
  3476. }
  3477. }
  3478. // ======================== IPTABLES FIREWALL ========================
  3479. state.fwSubTab = 'filter';
  3480. state.routesSubTab = 'routes';
  3481. function nativeNATChain(chain) {
  3482. const value = (chain || '').toLowerCase();
  3483. if (value === 'dstnat') return 'prerouting';
  3484. if (value === 'srcnat') return 'postrouting';
  3485. return ['prerouting', 'input', 'output', 'postrouting'].includes(value) ? value : (chain || '');
  3486. }
  3487. function nativeFirewallTarget(action) {
  3488. const name = (action || '').toLowerCase();
  3489. return ({'src-nat':'SNAT', 'dst-nat':'DNAT', 'add-src-to-address-list':'SET (add source)', 'add-dst-to-address-list':'SET (add destination)', 'mark-connection':'CONNMARK', 'mark-packet':'MARK', 'mark-routing':'MARK (routing)', 'change-dscp':'DSCP', 'change-mss':'TCPMSS', 'change-ttl':'TTL / HL', 'set-priority':'CLASSIFY', 'passthrough':'COUNT / continue', 'jump':'JUMP'})[name] || name.toUpperCase();
  3490. }
  3491. function renderRuleFlag(disabled, hasComment) {
  3492. let flags = '';
  3493. if (disabled) flags += '<span class="text-rose-400 font-bold" title="Disabled">X</span>';
  3494. if (hasComment) flags += '<span class="text-amber-400 font-bold ml-1" title="Has Comment">C</span>';
  3495. return flags || '<span class="text-slate-600">-</span>';
  3496. }
  3497. function renderActionBadge(action) {
  3498. const act = (action || '').toLowerCase();
  3499. let color = 'bg-slate-800 text-slate-300';
  3500. if (act === 'accept') color = 'bg-emerald-500/20 text-emerald-300 border border-emerald-500/30';
  3501. else if (act === 'drop' || act === 'reject') color = 'bg-rose-500/20 text-rose-300 border border-rose-500/30';
  3502. else if (act === 'masquerade' || act === 'src-nat' || act === 'dst-nat') color = 'bg-amber-500/20 text-amber-300 border border-amber-500/30';
  3503. else if (act.startsWith('mark-')) color = 'bg-purple-500/20 text-purple-300 border border-purple-500/30';
  3504. else if (act === 'log') color = 'bg-cyan-500/20 text-cyan-300 border border-cyan-500/30';
  3505. return `<span class="px-2 py-0.5 rounded text-[10px] font-mono font-semibold ${color}">${escapeHtml(nativeFirewallTarget(action))}</span>`;
  3506. }
  3507. function switchFWSubTab(tab) {
  3508. state.fwSubTab = tab;
  3509. const tabs = ['filter', 'nat', 'mangle', 'addrlist', 'geo', 'connections'];
  3510. tabs.forEach(t => {
  3511. const panel = document.getElementById(`fw-subtab-${t}`);
  3512. const btn = document.getElementById(`fw-subtab-btn-${t}`);
  3513. if (panel) {
  3514. if (t === tab) panel.classList.remove('hidden');
  3515. else panel.classList.add('hidden');
  3516. }
  3517. if (btn) {
  3518. if (t === tab) {
  3519. 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';
  3520. } else {
  3521. 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';
  3522. }
  3523. }
  3524. });
  3525. const addBtn = document.getElementById('fw-primary-add-btn');
  3526. if (addBtn) {
  3527. if (tab === 'filter') addBtn.innerHTML = '<span>+ Add Filter Rule</span>';
  3528. else if (tab === 'nat') addBtn.innerHTML = '<span>+ Add NAT Rule</span>';
  3529. else if (tab === 'mangle') addBtn.innerHTML = '<span>+ Add Mangle Rule</span>';
  3530. else if (tab === 'addrlist') addBtn.innerHTML = '<span>+ Add Address List</span>';
  3531. else if (tab === 'geo') addBtn.innerHTML = '<span>⚙️ Schedule Settings</span>';
  3532. else if (tab === 'connections') addBtn.innerHTML = '<span>Refresh Flows</span>';
  3533. }
  3534. if (tab === 'filter') renderFilterRules();
  3535. else if (tab === 'nat') renderNATRules();
  3536. else if (tab === 'mangle') renderMangleRules();
  3537. else if (tab === 'addrlist') renderAddressLists();
  3538. else if (tab === 'geo') loadGeoIP();
  3539. else if (tab === 'connections') loadConnections();
  3540. setTimeout(initTableSorting, 50);
  3541. }
  3542. function openCurrentFWModal() {
  3543. if (state.fwSubTab === 'filter') openAddFilterModal();
  3544. else if (state.fwSubTab === 'nat') openAddNATModal();
  3545. else if (state.fwSubTab === 'mangle') openAddMangleModal();
  3546. else if (state.fwSubTab === 'addrlist') openAddAddrListModal();
  3547. else if (state.fwSubTab === 'geo') openGeoIntervalModal();
  3548. else if (state.fwSubTab === 'connections') loadConnections();
  3549. }
  3550. async function loadFirewall(populateDropdowns = true) {
  3551. try {
  3552. const [summaryRes, filterRes, natRes, mangleRes, addrlistRes, geoStatusRes, geoCountriesRes] = await Promise.all([
  3553. fetch(`${API_BASE}/firewall/summary`),
  3554. fetch(`${API_BASE}/firewall/filter`),
  3555. fetch(`${API_BASE}/firewall/nat`),
  3556. fetch(`${API_BASE}/firewall/mangle`),
  3557. fetch(`${API_BASE}/firewall/address-lists`),
  3558. fetch(`${API_BASE}/firewall/geoip/status`),
  3559. fetch(`${API_BASE}/firewall/geoip/countries`)
  3560. ]);
  3561. if (summaryRes.ok) state.fwSummary = await summaryRes.json();
  3562. const applyError = document.getElementById('fw-apply-error');
  3563. if (applyError) {
  3564. applyError.textContent = state.fwSummary?.last_error ? 'Firewall configuration was not applied: ' + state.fwSummary.last_error : '';
  3565. applyError.classList.toggle('hidden', !state.fwSummary?.last_error);
  3566. }
  3567. if (filterRes.ok) state.filterRules = await filterRes.json();
  3568. if (natRes.ok) state.natRules = await natRes.json();
  3569. if (mangleRes.ok) state.mangleRules = await mangleRes.json();
  3570. if (addrlistRes.ok) state.addressLists = await addrlistRes.json();
  3571. if (geoStatusRes.ok) state.geoStatus = await geoStatusRes.json();
  3572. if (geoCountriesRes.ok) state.geoCountries = await geoCountriesRes.json();
  3573. if (applyError) { const messages=[state.fwSummary?.last_error, state.fwSummary?.connections_error, state.geoStatus?.last_error && 'GeoIP: '+state.geoStatus.last_error].filter(Boolean); applyError.textContent=messages.join(' · '); applyError.classList.toggle('hidden', !messages.length); }
  3574. // Badges
  3575. const bFilter = document.getElementById('fw-badge-filter');
  3576. if (bFilter) bFilter.innerText = (state.filterRules || []).length;
  3577. const bNat = document.getElementById('fw-badge-nat');
  3578. if (bNat) bNat.innerText = (state.natRules || []).length;
  3579. const bMangle = document.getElementById('fw-badge-mangle');
  3580. if (bMangle) bMangle.innerText = (state.mangleRules || []).length;
  3581. const bAddr = document.getElementById('fw-badge-addrlist');
  3582. if (bAddr) bAddr.innerText = (state.addressLists || []).length;
  3583. const bGeo = document.getElementById('fw-badge-geo');
  3584. if (bGeo) bGeo.innerText = state.geoStatus?.enabled_count || 0;
  3585. const sigFilter = (state.filterRules || []).map(r => JSON.stringify({...r, packets: 0, bytes: 0})).join(';');
  3586. const sigNat = (state.natRules || []).map(r => JSON.stringify({...r, packets: 0, bytes: 0})).join(';');
  3587. const sigMangle = (state.mangleRules || []).map(r => JSON.stringify({...r, packets: 0, bytes: 0})).join(';');
  3588. const sigAddr = (state.addressLists || []).map(a => JSON.stringify(a)).join(';');
  3589. const tbodyFilter = document.getElementById('filter-table-body');
  3590. if (tbodyFilter) {
  3591. if (populateDropdowns || tbodyFilter.dataset.sig !== sigFilter) {
  3592. tbodyFilter.dataset.sig = sigFilter;
  3593. renderFilterRules();
  3594. } else {
  3595. // In-place live stats update (ZERO flicker)
  3596. (state.filterRules || []).forEach(r => {
  3597. const p = document.getElementById(`filter-pkts-${r.id}`);
  3598. if (p) p.innerText = `${(r.packets || 0).toLocaleString()}p`;
  3599. const b = document.getElementById(`filter-bytes-${r.id}`);
  3600. if (b) b.innerText = formatTraffic(r.bytes || 0).replace('/s', '');
  3601. });
  3602. }
  3603. }
  3604. const tbodyNat = document.getElementById('nat-table-body');
  3605. if (tbodyNat) {
  3606. if (populateDropdowns || tbodyNat.dataset.sig !== sigNat) {
  3607. tbodyNat.dataset.sig = sigNat;
  3608. renderNATRules();
  3609. } else {
  3610. (state.natRules || []).forEach(r => {
  3611. const p = document.getElementById(`nat-pkts-${r.id}`);
  3612. if (p) p.innerText = `${(r.packets || 0).toLocaleString()}p`;
  3613. const b = document.getElementById(`nat-bytes-${r.id}`);
  3614. if (b) b.innerText = formatTraffic(r.bytes || 0).replace('/s', '');
  3615. });
  3616. }
  3617. }
  3618. const tbodyMangle = document.getElementById('mangle-table-body');
  3619. if (tbodyMangle) {
  3620. if (populateDropdowns || tbodyMangle.dataset.sig !== sigMangle) {
  3621. tbodyMangle.dataset.sig = sigMangle;
  3622. renderMangleRules();
  3623. } else {
  3624. (state.mangleRules || []).forEach(r => {
  3625. const p = document.getElementById(`mangle-pkts-${r.id}`);
  3626. if (p) p.innerText = `${(r.packets || 0).toLocaleString()}p`;
  3627. const b = document.getElementById(`mangle-bytes-${r.id}`);
  3628. if (b) b.innerText = formatTraffic(r.bytes || 0).replace('/s', '');
  3629. });
  3630. }
  3631. }
  3632. const tbodyAddr = document.getElementById('addrlist-table-body');
  3633. if (tbodyAddr && (populateDropdowns || tbodyAddr.dataset.sig !== sigAddr)) {
  3634. tbodyAddr.dataset.sig = sigAddr;
  3635. renderAddressLists();
  3636. }
  3637. renderGeoCountries();
  3638. if (state.fwSubTab === 'connections') {
  3639. loadConnections();
  3640. }
  3641. } catch (err) {
  3642. console.error('Failed to load firewall:', err);
  3643. }
  3644. }
  3645. // ----------------- Filter Rules -----------------
  3646. function renderFilterRules() {
  3647. const chainFilter = document.getElementById('filter-filter-chain')?.value || '';
  3648. const tbody = document.getElementById('filter-table-body');
  3649. const empty = document.getElementById('filter-empty');
  3650. if (!tbody) return;
  3651. tbody.innerHTML = '';
  3652. const rules = (state.filterRules || []).filter(r => !chainFilter || (r.chain || '').toLowerCase() === chainFilter);
  3653. document.getElementById('filter-count-badge').innerText = `${rules.length} Rules`;
  3654. if (rules.length === 0) {
  3655. empty?.classList.remove('hidden');
  3656. return;
  3657. }
  3658. empty?.classList.add('hidden');
  3659. rules.forEach((raw, idx) => {
  3660. const r = safeFirewallRow(raw);
  3661. const tr = document.createElement('tr');
  3662. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  3663. const ports = [r.src_port ? 's:' + r.src_port : '', r.dst_port ? 'd:' + r.dst_port : ''].filter(Boolean).join(' ');
  3664. const ifaces = [r.in_interface ? 'in:' + r.in_interface : '', r.out_interface ? 'out:' + r.out_interface : ''].filter(Boolean).join(' ');
  3665. let actionExtra = '';
  3666. if (r.action === 'reject') {
  3667. actionExtra = `<span class="block text-[10px] text-rose-300 font-mono mt-0.5">(${r.reject_with || 'icmp-net-unreach'})</span>`;
  3668. } else if (r.action === 'jump') {
  3669. actionExtra = `<span class="block text-[10px] text-yellow-300 font-mono mt-0.5">&rarr; ${r.jump_target || '-'}</span>`;
  3670. } else if (r.action.includes('address-list') || r.action.includes('address list')) {
  3671. actionExtra = `<span class="block text-[10px] text-emerald-300 font-mono mt-0.5">&rarr; ${r.address_list || '-'}</span>`;
  3672. } else if (r.action === 'log' && r.log_prefix) {
  3673. actionExtra = `<span class="block text-[10px] text-slate-400 font-mono mt-0.5">${r.log_prefix}</span>`;
  3674. }
  3675. tr.innerHTML = `
  3676. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  3677. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  3678. <td class="py-2.5 px-3 font-bold text-white">${(r.chain || '').toUpperCase()}</td>
  3679. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  3680. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  3681. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'} <span class="text-[9px] text-slate-500">IPv${r.ip_version || 4}</span></td>
  3682. <td class="py-2.5 px-3 text-amber-400">${ports || '-'}</td>
  3683. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  3684. <td class="py-2.5 px-3">${renderActionBadge(r.action)}${actionExtra}</td>
  3685. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  3686. <span class="text-slate-300" id="filter-pkts-${r.id}">${(r.packets || 0).toLocaleString()}p</span> /
  3687. <span class="text-slate-500" id="filter-bytes-${r.id}">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  3688. </td>
  3689. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  3690. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  3691. <button onclick="moveFilterRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  3692. <button onclick="moveFilterRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  3693. <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>
  3694. <button onclick="openEditFilterModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  3695. <button onclick="deleteFilterRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  3696. </td>
  3697. `;
  3698. tbody.appendChild(tr);
  3699. });
  3700. }
  3701. function formatTarget(addr, list, geo) {
  3702. const parts = [];
  3703. if (addr) parts.push(`<span>${addr}</span>`);
  3704. if (list) {
  3705. const inv = list.startsWith('!') ? '!' : '';
  3706. const clean = list.replace(/^!/, '');
  3707. 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>`);
  3708. }
  3709. if (geo) {
  3710. const inv = geo.startsWith('!') ? '!' : '';
  3711. const clean = geo.replace(/^!/, '').replace(/^geo:/, '');
  3712. 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>`);
  3713. }
  3714. if (parts.length === 0) return '<span class="text-slate-600">0.0.0.0/0</span>';
  3715. return parts.join(' ');
  3716. }
  3717. function populateInterfaceSelect(selectId, currentVal = '') {
  3718. const sel = document.getElementById(selectId);
  3719. if (!sel) return;
  3720. sel.innerHTML = '<option value="">(Any Interface)</option>';
  3721. const sdwanNames = new Set((state.sdwanGroups || []).map(g => g.name));
  3722. (state.interfaces || []).filter(i => !sdwanNames.has(i.name)).forEach(i => {
  3723. const opt = document.createElement('option');
  3724. opt.value = i.name;
  3725. opt.innerText = `${i.name} (${i.role || i.type})`;
  3726. if (i.name === currentVal) opt.selected = true;
  3727. sel.appendChild(opt);
  3728. });
  3729. if (state.sdwanGroups && state.sdwanGroups.length > 0) {
  3730. const optgroup = document.createElement('optgroup');
  3731. optgroup.label = 'SD-WAN Groups';
  3732. state.sdwanGroups.forEach(g => {
  3733. const opt = document.createElement('option');
  3734. opt.value = g.name;
  3735. opt.innerText = `${g.name} [SD-WAN: ${g.mode}]`;
  3736. if (g.name === currentVal) opt.selected = true;
  3737. optgroup.appendChild(opt);
  3738. });
  3739. sel.appendChild(optgroup);
  3740. }
  3741. }
  3742. function populateAddressListSelect(selectId, currentVal = '') {
  3743. const sel = document.getElementById(selectId);
  3744. if (!sel) return;
  3745. sel.innerHTML = '<option value="">(None)</option>';
  3746. const cleanVal = (currentVal || '').replace(/^!/, '');
  3747. const ruleLists = [...(state.filterRules||[]), ...(state.natRules||[]), ...(state.mangleRules||[])].flatMap(r => [r.src_address_list,r.dst_address_list,r.address_list]).filter(Boolean).map(n => n.replace(/^!/, '')).filter(n => !n.startsWith('geo:') && !n.startsWith('geo_'));
  3748. const customNames = Array.from(new Set([...(state.addressLists || []).map(a => a.name), ...ruleLists])).sort();
  3749. customNames.forEach(name => {
  3750. const count = (state.addressLists || []).filter(a => a.name === name).length;
  3751. const opt = document.createElement('option');
  3752. opt.value = name;
  3753. opt.innerText = `${name} (${count} entries)`;
  3754. if (name === cleanVal) opt.selected = true;
  3755. sel.appendChild(opt);
  3756. });
  3757. if (cleanVal && !Array.from(sel.options).some(option => option.value === cleanVal)) {
  3758. const opt = document.createElement('option');
  3759. opt.value = cleanVal;
  3760. opt.innerText = cleanVal;
  3761. opt.selected = true;
  3762. sel.appendChild(opt);
  3763. }
  3764. populateCommonAddrListDatalist();
  3765. }
  3766. function populateCommonAddrListDatalist() {
  3767. const dl = document.getElementById('fw-addrlist-datalist');
  3768. if (!dl) return;
  3769. dl.innerHTML = '';
  3770. const names = Array.from(new Set((state.addressLists || []).map(a => a.name).filter(Boolean))).sort();
  3771. names.forEach(name => {
  3772. const opt = document.createElement('option');
  3773. opt.value = name;
  3774. dl.appendChild(opt);
  3775. });
  3776. }
  3777. function populateGeoIPSelect(selectId, currentVal = '') {
  3778. const sel = document.getElementById(selectId);
  3779. if (!sel) return;
  3780. sel.innerHTML = '<option value="">(None)</option>';
  3781. const cleanVal = (currentVal || '').replace(/^!/, '').replace(/^geo:/, '').toUpperCase();
  3782. // Presets optgroup
  3783. const grpPresets = document.createElement('optgroup');
  3784. grpPresets.label = '⚡ Regional Presets';
  3785. const presets = [
  3786. { code: 'EU', label: '🇪🇺 European Union (EU - 27 countries)' },
  3787. { code: 'BALKANS', label: '🏛️ Balkans (GR, CY, BG, RO, AL, etc.)' },
  3788. { code: 'BLOCKLIST', label: '🛡️ High-Risk Blocklist (CN, RU, IR, KP, BY)' }
  3789. ];
  3790. presets.forEach(p => {
  3791. const opt = document.createElement('option');
  3792. opt.value = p.code;
  3793. opt.innerText = p.label;
  3794. if (p.code === cleanVal) opt.selected = true;
  3795. grpPresets.appendChild(opt);
  3796. });
  3797. sel.appendChild(grpPresets);
  3798. // All Countries optgroup
  3799. const grpCountries = document.createElement('optgroup');
  3800. grpCountries.label = '🌍 All Countries';
  3801. const countries = (state.geoCountries || []).slice().sort((a, b) => a.name.localeCompare(b.name));
  3802. countries.forEach(c => {
  3803. const opt = document.createElement('option');
  3804. opt.value = c.code;
  3805. const subnetsInfo = c.subnet_count ? ` [${c.subnet_count.toLocaleString()} subnets]` : '';
  3806. opt.innerText = `${c.name} (${c.code})${subnetsInfo}`;
  3807. if (c.code === cleanVal) opt.selected = true;
  3808. grpCountries.appendChild(opt);
  3809. });
  3810. sel.appendChild(grpCountries);
  3811. }
  3812. // ==================== FIREWALL FILTER MODAL (DEBTIK WEBFIG / WINBOX V4) ====================
  3813. function switchFwRuleTab(tab) {
  3814. state.activeFwRuleTab = tab;
  3815. document.querySelectorAll('.fw-rule-tab-btn').forEach(btn => {
  3816. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  3817. btn.classList.add('text-slate-400', 'border-transparent');
  3818. });
  3819. const activeBtn = document.getElementById(`fw-tab-btn-${tab}`);
  3820. if (activeBtn) {
  3821. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  3822. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  3823. }
  3824. document.querySelectorAll('.fw-rule-pane').forEach(p => p.classList.add('hidden'));
  3825. const activePane = document.getElementById(`fw-pane-${tab}`);
  3826. if (activePane) activePane.classList.remove('hidden');
  3827. if (tab === 'statistics') {
  3828. startFwStatPolling();
  3829. } else {
  3830. stopFwStatPolling();
  3831. }
  3832. }
  3833. function toggleFwField(fieldKey, expand) {
  3834. const plusBtn = document.getElementById(`fw-plus-${fieldKey}`);
  3835. const fieldBox = document.getElementById(`fw-field-${fieldKey}`);
  3836. if (!plusBtn || !fieldBox) return;
  3837. if (expand) {
  3838. plusBtn.classList.add('hidden');
  3839. fieldBox.classList.remove('hidden');
  3840. const valInput = document.getElementById(`fw-val-${fieldKey}`);
  3841. if (valInput) valInput.focus();
  3842. } else {
  3843. fieldBox.classList.add('hidden');
  3844. plusBtn.classList.remove('hidden');
  3845. const valInput = document.getElementById(`fw-val-${fieldKey}`);
  3846. if (valInput) {
  3847. if (valInput.tagName === 'SELECT') {
  3848. valInput.selectedIndex = 0;
  3849. } else {
  3850. valInput.value = '';
  3851. }
  3852. }
  3853. const invInput = document.getElementById(`fw-inv-${fieldKey}`);
  3854. if (invInput) invInput.checked = false;
  3855. if (fieldKey === 'cs') {
  3856. ['filter-modal-cs-established', 'filter-modal-cs-related', 'filter-modal-cs-new', 'filter-modal-cs-invalid', 'filter-modal-cs-untracked'].forEach(id => {
  3857. const el = document.getElementById(id);
  3858. if (el) el.checked = false;
  3859. });
  3860. }
  3861. if (fieldKey === 'natstate') {
  3862. ['filter-modal-nat-srcnat', 'filter-modal-nat-dstnat'].forEach(id => {
  3863. const el = document.getElementById(id);
  3864. if (el) el.checked = false;
  3865. });
  3866. }
  3867. if (fieldKey === 'days') {
  3868. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3869. const el = document.getElementById(`fw-day-${d}`);
  3870. if (el) el.checked = true;
  3871. });
  3872. }
  3873. }
  3874. }
  3875. function setFwFieldVal(fieldKey, value, hasInvert = false) {
  3876. if (fieldKey === 'ipsec' && typeof value === 'string') value = value.replace(':', ',');
  3877. if (value !== undefined && value !== null && value !== '' && !(fieldKey === 'proto' && value === 'all')) {
  3878. toggleFwField(fieldKey, true);
  3879. let strVal = String(value);
  3880. if (hasInvert) {
  3881. const inv = strVal.startsWith('!');
  3882. if (inv) strVal = strVal.slice(1);
  3883. const invEl = document.getElementById(`fw-inv-${fieldKey}`);
  3884. if (invEl) invEl.checked = inv;
  3885. else if (inv) strVal = '!'+strVal;
  3886. }
  3887. const valEl = document.getElementById(`fw-val-${fieldKey}`);
  3888. if (valEl) { if (valEl.tagName === 'SELECT' && !Array.from(valEl.options).some(o => o.value === strVal)) { const option=document.createElement('option'); option.value=strVal; option.textContent=strVal+' (saved)'; valEl.appendChild(option); } valEl.value = strVal; }
  3889. } else {
  3890. toggleFwField(fieldKey, false);
  3891. }
  3892. }
  3893. function getFwFieldVal(fieldKey, hasInvert = false) {
  3894. const fieldBox = document.getElementById(`fw-field-${fieldKey}`);
  3895. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  3896. const valEl = document.getElementById(`fw-val-${fieldKey}`);
  3897. let v = valEl ? valEl.value.trim() : '';
  3898. if (!v) return '';
  3899. if (hasInvert) {
  3900. const invEl = document.getElementById(`fw-inv-${fieldKey}`);
  3901. if (invEl && invEl.checked) {
  3902. v = '!' + v.replace(/^!/, '');
  3903. }
  3904. }
  3905. return v;
  3906. }
  3907. function toggleMaximizeFilterModal() {
  3908. const win = document.getElementById('filter-modal-window');
  3909. if (!win) return;
  3910. if (win.classList.contains('max-w-[720px]')) {
  3911. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  3912. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  3913. } else {
  3914. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  3915. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  3916. }
  3917. }
  3918. const FW_NATIVE_CHAINS = {
  3919. filter: [
  3920. { id: 'forward', label: 'FORWARD (routed through router)' },
  3921. { id: 'input', label: 'INPUT (destined to this router)' },
  3922. { id: 'output', label: 'OUTPUT (generated by this router)' }
  3923. ],
  3924. nat: [
  3925. { id: 'postrouting', label: 'POSTROUTING (outgoing after routing — SNAT / MASQUERADE)' },
  3926. { id: 'prerouting', label: 'PREROUTING (incoming before routing — DNAT / REDIRECT)' },
  3927. { id: 'output', label: 'OUTPUT (locally generated — DNAT / REDIRECT)' },
  3928. { id: 'input', label: 'INPUT (destined to this machine — SNAT)' }
  3929. ],
  3930. mangle: [
  3931. { id: 'prerouting', label: 'PREROUTING (incoming before routing)' },
  3932. { id: 'input', label: 'INPUT (destined to this machine)' },
  3933. { id: 'forward', label: 'FORWARD (routed through router)' },
  3934. { id: 'output', label: 'OUTPUT (generated by this machine)' },
  3935. { id: 'postrouting', label: 'POSTROUTING (outgoing after routing)' }
  3936. ]
  3937. };
  3938. function populateChainDropdown(table, currentChain) {
  3939. const sel = document.getElementById(`${table}-modal-chain-select`);
  3940. if (!sel) return;
  3941. const cur = (currentChain || '').trim();
  3942. const lower = cur.toLowerCase();
  3943. const rulesKey = table === 'filter' ? 'filterRules' : table === 'nat' ? 'natRules' : 'mangleRules';
  3944. const rules = state[rulesKey] || [];
  3945. const nativeIds = FW_NATIVE_CHAINS[table].map(c => c.id);
  3946. const customChains = new Set();
  3947. rules.forEach(r => {
  3948. if (r.chain) {
  3949. const c = r.chain.trim();
  3950. const l = c.toLowerCase();
  3951. if (!nativeIds.includes(l) && l !== 'srcnat' && l !== 'dstnat' && !['forward', 'input', 'output', 'prerouting', 'postrouting'].includes(l)) {
  3952. customChains.add(c);
  3953. }
  3954. }
  3955. });
  3956. const isCurrentCustom = cur && !nativeIds.includes(lower) && lower !== 'srcnat' && lower !== 'dstnat' && !['forward', 'input', 'output', 'prerouting', 'postrouting'].includes(lower);
  3957. if (isCurrentCustom) {
  3958. customChains.add(cur);
  3959. }
  3960. let html = '';
  3961. FW_NATIVE_CHAINS[table].forEach(c => {
  3962. html += `<option value="${c.id}">${escapeHtml(c.label)}</option>`;
  3963. });
  3964. if (customChains.size > 0) {
  3965. html += `<optgroup label="Custom Chains">`;
  3966. customChains.forEach(c => {
  3967. html += `<option value="${escapeHtml(c)}">Chain: ${escapeHtml(c)} (custom)</option>`;
  3968. });
  3969. html += `</optgroup>`;
  3970. }
  3971. html += `<option value="__custom__">+ Custom Chain...</option>`;
  3972. sel.innerHTML = html;
  3973. if (isCurrentCustom) {
  3974. sel.value = cur;
  3975. } else if (nativeIds.includes(lower)) {
  3976. sel.value = lower;
  3977. } else if (table === 'nat' && (lower === 'srcnat' || lower === 'dstnat')) {
  3978. sel.value = lower === 'dstnat' ? 'prerouting' : 'postrouting';
  3979. } else {
  3980. sel.value = nativeIds[0];
  3981. }
  3982. const customWrap = document.getElementById(`${table}-modal-custom-wrap`);
  3983. const customInput = document.getElementById(`${table}-modal-custom-input`);
  3984. if (isCurrentCustom || sel.value === '__custom__') {
  3985. if (customWrap) customWrap.classList.remove('hidden');
  3986. if (customInput) customInput.value = cur;
  3987. } else {
  3988. if (customWrap) customWrap.classList.add('hidden');
  3989. if (customInput) customInput.value = '';
  3990. }
  3991. const chainInput = document.getElementById(`${table}-modal-chain`);
  3992. if (chainInput) chainInput.value = cur || sel.value;
  3993. }
  3994. function syncFilterChainFromSelect() {
  3995. const sel = document.getElementById('filter-modal-chain-select');
  3996. const customWrap = document.getElementById('filter-modal-custom-wrap');
  3997. const customInput = document.getElementById('filter-modal-custom-input');
  3998. const chainInput = document.getElementById('filter-modal-chain');
  3999. if (!sel || !chainInput) return;
  4000. if (sel.value === '__custom__') {
  4001. if (customWrap) customWrap.classList.remove('hidden');
  4002. if (customInput) {
  4003. customInput.value = '';
  4004. customInput.focus();
  4005. }
  4006. chainInput.value = '';
  4007. } else {
  4008. if (customWrap) customWrap.classList.add('hidden');
  4009. chainInput.value = sel.value;
  4010. }
  4011. handleFilterChainChange();
  4012. }
  4013. function syncFilterCustomChainInput() {
  4014. const customInput = document.getElementById('filter-modal-custom-input');
  4015. const chainInput = document.getElementById('filter-modal-chain');
  4016. if (customInput && chainInput) {
  4017. chainInput.value = customInput.value.trim();
  4018. }
  4019. handleFilterChainChange();
  4020. }
  4021. function handleFilterChainChange() {
  4022. const chainInput = document.getElementById('filter-modal-chain');
  4023. const chain = (chainInput?.value || 'forward').trim().toLowerCase();
  4024. const sel = document.getElementById('filter-modal-chain-select');
  4025. if (sel && sel.value !== chain && sel.value !== '__custom__') {
  4026. if (['forward', 'input', 'output'].includes(chain)) {
  4027. sel.value = chain;
  4028. }
  4029. }
  4030. const hintEl = document.getElementById('filter-chain-hint');
  4031. if (hintEl) {
  4032. if (chain === 'forward') {
  4033. hintEl.textContent = 'FORWARD: packets routed through this router (accepts both In and Out interfaces).';
  4034. } else if (chain === 'input') {
  4035. hintEl.textContent = 'INPUT: packets destined to this router (In-Interface only; Out-Interface is invalid in iptables).';
  4036. } else if (chain === 'output') {
  4037. hintEl.textContent = 'OUTPUT: packets generated by this router (Out-Interface only; In-Interface is invalid in iptables).';
  4038. } else {
  4039. hintEl.textContent = `Custom chain "${chain}": reached via an explicit JUMP from a built-in chain.`;
  4040. }
  4041. }
  4042. const rowIn = document.getElementById('fw-row-iniface');
  4043. const rowInList = document.getElementById('fw-row-inifacelist');
  4044. const rowOut = document.getElementById('fw-row-outiface');
  4045. const rowOutList = document.getElementById('fw-row-outifacelist');
  4046. const rowInBridge = document.getElementById('fw-row-inbridgeport');
  4047. const rowOutBridge = document.getElementById('fw-row-outbridgeport');
  4048. const rowSrcMac = document.getElementById('fw-row-srcmac');
  4049. if (chain === 'input') {
  4050. if (rowIn) rowIn.classList.remove('hidden');
  4051. if (rowInList) rowInList.classList.remove('hidden');
  4052. if (rowOut) rowOut.classList.add('hidden');
  4053. if (rowOutList) rowOutList.classList.add('hidden');
  4054. if (rowInBridge) rowInBridge.classList.remove('hidden');
  4055. if (rowOutBridge) rowOutBridge.classList.add('hidden');
  4056. if (rowSrcMac) rowSrcMac.classList.remove('hidden');
  4057. } else if (chain === 'output') {
  4058. if (rowIn) rowIn.classList.add('hidden');
  4059. if (rowInList) rowInList.classList.add('hidden');
  4060. if (rowOut) rowOut.classList.remove('hidden');
  4061. if (rowOutList) rowOutList.classList.remove('hidden');
  4062. if (rowInBridge) rowInBridge.classList.add('hidden');
  4063. if (rowOutBridge) rowOutBridge.classList.remove('hidden');
  4064. if (rowSrcMac) rowSrcMac.classList.add('hidden');
  4065. } else {
  4066. if (rowIn) rowIn.classList.remove('hidden');
  4067. if (rowInList) rowInList.classList.remove('hidden');
  4068. if (rowOut) rowOut.classList.remove('hidden');
  4069. if (rowOutList) rowOutList.classList.remove('hidden');
  4070. if (rowInBridge) rowInBridge.classList.remove('hidden');
  4071. if (rowOutBridge) rowOutBridge.classList.remove('hidden');
  4072. if (rowSrcMac) rowSrcMac.classList.remove('hidden');
  4073. }
  4074. checkFilterActionChainCompatibility();
  4075. }
  4076. function checkFilterActionChainCompatibility() {
  4077. const chain = (document.getElementById('filter-modal-chain')?.value || 'forward').trim().toLowerCase();
  4078. const warnBox = document.getElementById('filter-action-incompatible-warn');
  4079. const warnMsg = document.getElementById('filter-action-incompatible-msg');
  4080. if (!warnBox || !warnMsg) return;
  4081. if (chain === 'prerouting' || chain === 'postrouting') {
  4082. warnMsg.textContent = `Chain "${chain.toUpperCase()}" is not available in the Filter table. Filter only supports INPUT, FORWARD, OUTPUT or custom chains.`;
  4083. warnBox.classList.remove('hidden');
  4084. } else {
  4085. warnBox.classList.add('hidden');
  4086. }
  4087. }
  4088. function openAddFilterModal() {
  4089. const tos = document.getElementById('fw-val-tos'); if (tos) tos.value = '';
  4090. switchFwRuleTab('general');
  4091. setFirewallDays('fw', '');
  4092. const badge = document.getElementById('fw-modal-badge');
  4093. if (badge) badge.innerText = 'New...';
  4094. document.getElementById('filter-modal-id').value = '';
  4095. document.getElementById('filter-modal-family').value = '4';
  4096. document.getElementById('filter-modal-enabled').checked = true;
  4097. document.getElementById('filter-modal-comment').value = '';
  4098. document.getElementById('filter-modal-chain').value = 'forward';
  4099. populateChainDropdown('filter', 'forward');
  4100. handleFilterChainChange();
  4101. document.getElementById('filter-modal-action').value = 'accept';
  4102. document.getElementById('filter-modal-log').checked = false;
  4103. populateInterfaceSelect('fw-val-iniface');
  4104. populateInterfaceSelect('fw-val-outiface');
  4105. populateAddressListSelect('fw-val-srclist');
  4106. populateAddressListSelect('fw-val-dstlist');
  4107. populateGeoIPSelect('fw-val-srcgeo');
  4108. populateGeoIPSelect('fw-val-dstgeo');
  4109. const allFieldKeys = [
  4110. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  4111. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  4112. 'routingmark', 'conntype', 'cs', 'natstate',
  4113. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  4114. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  4115. 'ipsec', 'tlshost', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  4116. 'pktsize', 'random', 'tcpflags', 'icmpoptions', 'ipv4options', 'ttl',
  4117. 'time', 'days', 'limit', 'dstlimit', 'psd', 'logprefix'
  4118. ];
  4119. allFieldKeys.forEach(k => toggleFwField(k, false));
  4120. resetRuleCounterDisplay();
  4121. toggleFilterActionFields();
  4122. refreshFirewallRejectTypes();
  4123. document.getElementById('filter-modal').classList.remove('hidden');
  4124. }
  4125. function openEditFilterModal(id) {
  4126. id = decodeURIComponent(id);
  4127. const r = (state.filterRules || []).find(rule => rule.id === id);
  4128. if (!r) return;
  4129. switchFwRuleTab('general');
  4130. const badge = document.getElementById('fw-modal-badge');
  4131. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  4132. document.getElementById('filter-modal-id').value = r.id;
  4133. document.getElementById('filter-modal-family').value = String(r.ip_version || 4);
  4134. document.getElementById('filter-modal-enabled').checked = !r.disabled;
  4135. document.getElementById('filter-modal-comment').value = r.comment || '';
  4136. const filterChain = r.chain || 'forward';
  4137. document.getElementById('filter-modal-chain').value = filterChain;
  4138. populateChainDropdown('filter', filterChain);
  4139. handleFilterChainChange();
  4140. setFirewallActionSelection('filter', r.action || 'accept');
  4141. document.getElementById('filter-modal-log').checked = !!r.log;
  4142. populateInterfaceSelect('fw-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  4143. populateInterfaceSelect('fw-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  4144. populateAddressListSelect('fw-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  4145. populateAddressListSelect('fw-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  4146. populateGeoIPSelect('fw-val-srcgeo', r.src_geoip || '');
  4147. populateGeoIPSelect('fw-val-dstgeo', r.dst_geoip || '');
  4148. setFwFieldVal('src', r.src_address, true);
  4149. setFwFieldVal('dst', r.dst_address, true);
  4150. setFwFieldVal('srclist', r.src_address_list, true);
  4151. setFwFieldVal('dstlist', r.dst_address_list, true);
  4152. setFwFieldVal('srcgeo', r.src_geoip, true);
  4153. setFwFieldVal('dstgeo', r.dst_geoip, true);
  4154. if (r.protocol && r.protocol !== 'all') {
  4155. setFwFieldVal('proto', r.protocol, true);
  4156. } else {
  4157. toggleFwField('proto', false);
  4158. }
  4159. setFwFieldVal('sport', r.src_port, true);
  4160. setFwFieldVal('dport', r.dst_port, true);
  4161. setFwFieldVal('anyport', r.any_port, true);
  4162. setFwFieldVal('iniface', r.in_interface, true);
  4163. setFwFieldVal('outiface', r.out_interface, true);
  4164. setFwFieldVal('inifacelist', r.in_interface_list, true);
  4165. setFwFieldVal('outifacelist', r.out_interface_list, true);
  4166. setFwFieldVal('pktmark', r.packet_mark, true);
  4167. setFwFieldVal('connmark', r.connection_mark, true);
  4168. setFwFieldVal('routingmark', r.routing_mark, true);
  4169. setFwFieldVal('conntype', r.connection_type, false);
  4170. const states = r.connection_state || [];
  4171. if (states.length > 0) {
  4172. toggleFwField('cs', true);
  4173. document.getElementById('filter-modal-cs-established').checked = states.includes('established');
  4174. document.getElementById('filter-modal-cs-related').checked = states.includes('related');
  4175. document.getElementById('filter-modal-cs-new').checked = states.includes('new');
  4176. document.getElementById('filter-modal-cs-invalid').checked = states.includes('invalid');
  4177. document.getElementById('filter-modal-cs-untracked').checked = states.includes('untracked');
  4178. } else {
  4179. toggleFwField('cs', false);
  4180. }
  4181. const natStates = r.connection_nat_state || [];
  4182. if (natStates.length > 0) {
  4183. toggleFwField('natstate', true);
  4184. document.getElementById('filter-modal-nat-srcnat').checked = natStates.includes('srcnat');
  4185. document.getElementById('filter-modal-nat-dstnat').checked = natStates.includes('dstnat');
  4186. } else {
  4187. toggleFwField('natstate', false);
  4188. }
  4189. // Advanced tab fields
  4190. setFwFieldVal('layer7', r.layer7_protocol, false);
  4191. setFwFieldVal('content', r.content, false);
  4192. setFwFieldVal('connbytes', r.connection_bytes, false);
  4193. setFwFieldVal('connrate', r.connection_rate, false);
  4194. setFwFieldVal('pcc', r.pcc, false);
  4195. setFwFieldVal('srcmac', r.src_mac_address, true);
  4196. setFwFieldVal('outbridgeport', r.out_bridge_port, false);
  4197. setFwFieldVal('inbridgeport', r.in_bridge_port, false);
  4198. setFwFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  4199. setFwFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  4200. setFwFieldVal('ipsec', r.ipsec_policy, false);
  4201. setFwFieldVal('tlshost', r.tls_host, false);
  4202. setFwFieldVal('ingresspriority', r.ingress_priority, false);
  4203. setFwFieldVal('priority', r.priority, false);
  4204. setFwFieldVal('dscp', r.dscp, false);
  4205. setFwFieldVal('tcpmss', r.tcp_mss, false);
  4206. { const tosEl = document.getElementById('fw-val-tos'); if (tosEl) tosEl.value = r.tos || ''; }
  4207. setFwFieldVal('pktsize', r.packet_size, false);
  4208. setFwFieldVal('random', r.random, false);
  4209. setFwFieldVal('tcpflags', r.tcp_flags, false);
  4210. setFwFieldVal('icmpoptions', r.icmp_options, false);
  4211. setFwFieldVal('ipv4options', r.ipv4_options, false);
  4212. setFwFieldVal('ttl', r.ttl, false);
  4213. // Extra tab fields
  4214. setFwFieldVal('time', r.time, false);
  4215. if (r.days) {
  4216. toggleFwField('days', true);
  4217. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  4218. const chk = document.getElementById(`fw-day-${d}`);
  4219. if (chk) chk.checked = r.days.toLowerCase().includes(d);
  4220. });
  4221. } else {
  4222. toggleFwField('days', false);
  4223. }
  4224. setFwFieldVal('limit', r.limit, false);
  4225. setFwFieldVal('dstlimit', r.dst_limit, false);
  4226. setFwFieldVal('psd', r.psd, false);
  4227. // Action fields
  4228. if (r.reject_with) {
  4229. const rwEl = document.getElementById('filter-modal-rejectwith');
  4230. if (rwEl) rwEl.value = r.reject_with;
  4231. }
  4232. if (r.jump_target) {
  4233. const jtEl = document.getElementById('filter-modal-jumptarget');
  4234. if (jtEl) jtEl.value = r.jump_target;
  4235. }
  4236. if (r.address_list) {
  4237. const alEl = document.getElementById('filter-modal-action-addrlist');
  4238. if (alEl) alEl.value = r.address_list;
  4239. }
  4240. if (r.address_list_timeout) {
  4241. const toEl = document.getElementById('filter-modal-action-timeout');
  4242. if (toEl) toEl.value = r.address_list_timeout;
  4243. }
  4244. setFwFieldVal('logprefix', r.log_prefix, false);
  4245. // Statistics
  4246. const bEl = document.getElementById('fw-stat-bytes');
  4247. const pEl = document.getElementById('fw-stat-packets');
  4248. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  4249. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  4250. state.fwLastBytes = r.bytes || 0;
  4251. state.fwLastPackets = r.packets || 0;
  4252. state.fwLastTimestamp = Date.now();
  4253. state.fwStatRateHistory = new Array(30).fill(0);
  4254. state.fwStatPktHistory = new Array(30).fill(0);
  4255. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  4256. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  4257. toggleFilterActionFields();
  4258. refreshFirewallRejectTypes();
  4259. document.getElementById('filter-modal').classList.remove('hidden');
  4260. }
  4261. function closeFilterModal() {
  4262. stopFwStatPolling();
  4263. document.getElementById('filter-modal').classList.add('hidden');
  4264. }
  4265. function toggleFilterActionFields() {
  4266. const act = document.getElementById('filter-modal-action')?.value || 'accept';
  4267. const rejectBox = document.getElementById('filter-action-reject-box');
  4268. const jumpBox = document.getElementById('filter-action-jump-box');
  4269. const addrBox = document.getElementById('filter-action-addrlist-box');
  4270. if (rejectBox) {
  4271. if (act === 'reject') rejectBox.classList.remove('hidden');
  4272. else rejectBox.classList.add('hidden');
  4273. }
  4274. if (jumpBox) {
  4275. if (act === 'jump') jumpBox.classList.remove('hidden');
  4276. else jumpBox.classList.add('hidden');
  4277. }
  4278. if (addrBox) {
  4279. if (act === 'add-dst-to-address-list' || act === 'add-src-to-address-list' || act.includes('address-list') || act.includes('address list')) {
  4280. addrBox.classList.remove('hidden');
  4281. } else {
  4282. addrBox.classList.add('hidden');
  4283. }
  4284. }
  4285. if (act === 'log') {
  4286. const logEl = document.getElementById('filter-modal-log');
  4287. if (logEl) logEl.checked = true;
  4288. toggleFwField('logprefix', true);
  4289. }
  4290. }
  4291. function toggleFwLogPrefix() {
  4292. const isLog = document.getElementById('filter-modal-log')?.checked;
  4293. toggleFwField('logprefix', !!isLog);
  4294. }
  4295. function copyFilterRule() {
  4296. document.getElementById('filter-modal-id').value = '';
  4297. const badge = document.getElementById('fw-modal-badge');
  4298. if (badge) badge.innerText = 'New...';
  4299. showToast('Rule Cloned', 'Ready to save as a new rule copy', 'info');
  4300. }
  4301. function resetRuleCounterDisplay() {
  4302. state.fwStatRateHistory = new Array(30).fill(0);
  4303. state.fwStatPktHistory = new Array(30).fill(0);
  4304. state.fwLastBytes = 0;
  4305. state.fwLastPackets = 0;
  4306. state.fwLastTimestamp = Date.now();
  4307. const bEl = document.getElementById('fw-stat-bytes');
  4308. const pEl = document.getElementById('fw-stat-packets');
  4309. const rEl = document.getElementById('fw-stat-rate');
  4310. const prEl = document.getElementById('fw-stat-pktrate');
  4311. if (bEl) bEl.value = '0 B';
  4312. if (pEl) pEl.value = '0';
  4313. if (rEl) rEl.value = '0 bps';
  4314. if (prEl) prEl.value = '0 p/s';
  4315. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  4316. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  4317. showToast('Counters Reset', 'Rule counter display reset to 0', 'info');
  4318. }
  4319. async function resetAllFwCounters() {
  4320. try {
  4321. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  4322. if (res.ok) {
  4323. resetRuleCounterDisplay();
  4324. showToast('All Counters Reset', 'All firewall counters zeroed', 'success');
  4325. loadFirewall(false);
  4326. }
  4327. } catch (err) {
  4328. showToast('Error', err.message, 'error');
  4329. }
  4330. }
  4331. async function applyFilterRule(closeAfter = false) {
  4332. const id = document.getElementById('filter-modal-id').value;
  4333. if (!reviewLegacyFirewallSettings('filter', id)) return;
  4334. let selectedDays; try { selectedDays = getFirewallDays('fw'); } catch(error) { showToast('Error', error.message, 'error'); return; }
  4335. const chain = (document.getElementById('filter-modal-chain').value || '').trim();
  4336. const chainLower = chain.toLowerCase();
  4337. if (!chain) { switchFwRuleTab('general'); showToast('Filter Rule', 'A valid chain is required.', 'error'); document.getElementById('filter-modal-chain').focus(); return; }
  4338. if (chainLower === 'prerouting' || chainLower === 'postrouting') {
  4339. switchFwRuleTab('general');
  4340. showToast('Invalid Chain', `Chain "${chain.toUpperCase()}" is not available in the Filter table in iptables.`, 'error');
  4341. return;
  4342. }
  4343. const action = document.getElementById('filter-modal-action').value;
  4344. const comment = document.getElementById('filter-modal-comment').value.trim();
  4345. const enabled = document.getElementById('filter-modal-enabled').checked;
  4346. const src = getFwFieldVal('src', true);
  4347. const dst = getFwFieldVal('dst', true);
  4348. const srclist = getFwFieldVal('srclist', true);
  4349. const dstlist = getFwFieldVal('dstlist', true);
  4350. const srcgeo = getFwFieldVal('srcgeo', true);
  4351. const dstgeo = getFwFieldVal('dstgeo', true);
  4352. const proto = getFwFieldVal('proto', true);
  4353. const sport = getFwFieldVal('sport', true);
  4354. const dport = getFwFieldVal('dport', true);
  4355. const anyport = getFwFieldVal('anyport', true);
  4356. if ((sport || dport || anyport) && !['tcp', 'udp'].includes(proto)) {
  4357. switchFwRuleTab('general'); toggleFwField('proto', true);
  4358. showToast('Select protocol', 'Port matches require TCP or UDP without protocol inversion.', 'error'); document.getElementById('fw-val-proto').focus(); return;
  4359. }
  4360. let iniface = getFwFieldVal('iniface', true);
  4361. let outiface = getFwFieldVal('outiface', true);
  4362. let inifacelist = getFwFieldVal('inifacelist', true);
  4363. let outifacelist = getFwFieldVal('outifacelist', true);
  4364. if (chainLower === 'input') {
  4365. outiface = '';
  4366. outifacelist = '';
  4367. } else if (chainLower === 'output') {
  4368. iniface = '';
  4369. inifacelist = '';
  4370. }
  4371. const pktmark = getFwFieldVal('pktmark', true);
  4372. const connmark = getFwFieldVal('connmark', true);
  4373. const routingmark = getFwFieldVal('routingmark', true);
  4374. const conntype = getFwFieldVal('conntype', false);
  4375. const states = [];
  4376. const csBox = document.getElementById('fw-field-cs');
  4377. if (csBox && !csBox.classList.contains('hidden')) {
  4378. if (document.getElementById('filter-modal-cs-established')?.checked) states.push('established');
  4379. if (document.getElementById('filter-modal-cs-related')?.checked) states.push('related');
  4380. if (document.getElementById('filter-modal-cs-new')?.checked) states.push('new');
  4381. if (document.getElementById('filter-modal-cs-invalid')?.checked) states.push('invalid');
  4382. if (document.getElementById('filter-modal-cs-untracked')?.checked) states.push('untracked');
  4383. }
  4384. const natStates = [];
  4385. const natBox = document.getElementById('fw-field-natstate');
  4386. if (natBox && !natBox.classList.contains('hidden')) {
  4387. if (document.getElementById('filter-modal-nat-srcnat')?.checked) natStates.push('srcnat');
  4388. if (document.getElementById('filter-modal-nat-dstnat')?.checked) natStates.push('dstnat');
  4389. }
  4390. const payload = {
  4391. ip_version: Number(document.getElementById('filter-modal-family').value),
  4392. id,
  4393. chain,
  4394. action,
  4395. protocol: proto || 'all',
  4396. src_address: src,
  4397. dst_address: dst,
  4398. src_port: sport,
  4399. dst_port: dport,
  4400. any_port: anyport,
  4401. in_interface: iniface,
  4402. out_interface: outiface,
  4403. in_interface_list: inifacelist,
  4404. out_interface_list: outifacelist,
  4405. packet_mark: pktmark,
  4406. connection_mark: connmark,
  4407. routing_mark: routingmark,
  4408. connection_type: conntype,
  4409. connection_state: states,
  4410. connection_nat_state: natStates,
  4411. src_address_list: srclist,
  4412. dst_address_list: dstlist,
  4413. src_geoip: srcgeo,
  4414. dst_geoip: dstgeo,
  4415. comment,
  4416. disabled: !enabled,
  4417. // Advanced tab
  4418. content: getFwFieldVal('content', false),
  4419. src_mac_address: chainLower === 'output' ? '' : getFwFieldVal('srcmac', true),
  4420. out_bridge_port: chainLower === 'input' ? '' : getFwFieldVal('outbridgeport', false),
  4421. in_bridge_port: chainLower === 'output' ? '' : getFwFieldVal('inbridgeport', false),
  4422. ipsec_policy: getFwFieldVal('ipsec', false),
  4423. dscp: getFwFieldVal('dscp', false),
  4424. tcp_mss: getFwFieldVal('tcpmss', false),
  4425. tos: document.getElementById('fw-val-tos')?.value || '',
  4426. packet_size: getFwFieldVal('pktsize', false),
  4427. random: getFwFieldVal('random', false),
  4428. tcp_flags: getFwFieldVal('tcpflags', false),
  4429. icmp_options: getFwFieldVal('icmpoptions', false),
  4430. ttl: getFwFieldVal('ttl', false),
  4431. days: selectedDays,
  4432. // Extra tab
  4433. time: getFwFieldVal('time', false),
  4434. limit: getFwFieldVal('limit', false),
  4435. // Action tab
  4436. reject_with: action === 'reject' ? (document.getElementById('filter-modal-rejectwith')?.value || '') : '',
  4437. jump_target: action === 'jump' ? (document.getElementById('filter-modal-jumptarget')?.value || '') : '',
  4438. address_list: action.startsWith('add-') ? (document.getElementById('filter-modal-action-addrlist')?.value || '') : '',
  4439. address_list_timeout: action.startsWith('add-') ? (document.getElementById('filter-modal-action-timeout')?.value || '') : '',
  4440. log: document.getElementById('filter-modal-log')?.checked || false,
  4441. log_prefix: getFwFieldVal('logprefix', false)
  4442. };
  4443. try {
  4444. const res = await fetch(`${API_BASE}/firewall/filter`, {
  4445. method: 'POST',
  4446. headers: { 'Content-Type': 'application/json' },
  4447. body: JSON.stringify(payload)
  4448. });
  4449. if (res.ok) {
  4450. const data = await res.json();
  4451. showToast('Filter Rule Saved', 'Rule applied successfully to firewall', 'success');
  4452. loadFirewall(false);
  4453. if (closeAfter) {
  4454. closeFilterModal();
  4455. } else {
  4456. if (data.id) {
  4457. document.getElementById('filter-modal-id').value = data.id;
  4458. const badge = document.getElementById('fw-modal-badge');
  4459. if (badge) badge.innerText = `#${data.id}`;
  4460. }
  4461. }
  4462. } else {
  4463. const err = await res.json();
  4464. showToast('Error', err.message || 'Failed to save rule', 'error');
  4465. }
  4466. } catch (err) {
  4467. showToast('Error', err.message, 'error');
  4468. }
  4469. }
  4470. function submitSaveFilterRule(e) {
  4471. if (e && e.preventDefault) e.preventDefault();
  4472. return applyFilterRule(true);
  4473. }
  4474. function startFwStatPolling() {
  4475. stopFwStatPolling();
  4476. pollRuleStats();
  4477. state.fwStatInterval = setInterval(pollRuleStats, 1000);
  4478. }
  4479. function stopFwStatPolling() {
  4480. if (state.fwStatInterval) {
  4481. clearInterval(state.fwStatInterval);
  4482. state.fwStatInterval = null;
  4483. }
  4484. }
  4485. async function pollRuleStats() {
  4486. const id = document.getElementById('filter-modal-id')?.value;
  4487. if (!id) {
  4488. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory || new Array(30).fill(0), 'bps', 'fw-stat-legend-rate');
  4489. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory || new Array(30).fill(0), 'p/s', 'fw-stat-legend-pktrate');
  4490. return;
  4491. }
  4492. try {
  4493. const res = await fetch(`${API_BASE}/firewall/filter`);
  4494. if (!res.ok) return;
  4495. const rules = await res.json();
  4496. const r = rules.find(x => x.id === id);
  4497. if (!r) return;
  4498. const now = Date.now();
  4499. const dt = Math.max(0.2, (now - (state.fwLastTimestamp || now)) / 1000);
  4500. state.fwLastTimestamp = now;
  4501. const curBytes = r.bytes || 0;
  4502. const curPackets = r.packets || 0;
  4503. const deltaBytes = Math.max(0, curBytes - (state.fwLastBytes ?? curBytes));
  4504. const deltaPkts = Math.max(0, curPackets - (state.fwLastPackets ?? curPackets));
  4505. state.fwLastBytes = curBytes;
  4506. state.fwLastPackets = curPackets;
  4507. const rateBps = Math.round((deltaBytes * 8) / dt);
  4508. const ratePkt = Math.round(deltaPkts / dt);
  4509. if (!state.fwStatRateHistory) state.fwStatRateHistory = new Array(30).fill(0);
  4510. if (!state.fwStatPktHistory) state.fwStatPktHistory = new Array(30).fill(0);
  4511. state.fwStatRateHistory.push(rateBps);
  4512. if (state.fwStatRateHistory.length > 30) state.fwStatRateHistory.shift();
  4513. state.fwStatPktHistory.push(ratePkt);
  4514. if (state.fwStatPktHistory.length > 30) state.fwStatPktHistory.shift();
  4515. const bEl = document.getElementById('fw-stat-bytes');
  4516. const pEl = document.getElementById('fw-stat-packets');
  4517. const rEl = document.getElementById('fw-stat-rate');
  4518. const prEl = document.getElementById('fw-stat-pktrate');
  4519. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  4520. if (pEl) pEl.value = curPackets.toLocaleString();
  4521. if (rEl) rEl.value = formatBps(rateBps);
  4522. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  4523. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  4524. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  4525. } catch (e) {
  4526. console.error('Error polling rule stats', e);
  4527. }
  4528. }
  4529. function formatBps(bps) {
  4530. if (bps >= 1000000000) return (bps / 1000000000).toFixed(1) + ' Gbps';
  4531. if (bps >= 1000000) return (bps / 1000000).toFixed(1) + ' Mbps';
  4532. if (bps >= 1000) return (bps / 1000).toFixed(1) + ' kbps';
  4533. return bps + ' bps';
  4534. }
  4535. function renderFwSparkline(svgId, dataArray, unit, legendId) {
  4536. const svg = document.getElementById(svgId);
  4537. if (!svg) return;
  4538. const w = 500;
  4539. const h = 100;
  4540. const paddingRight = 45;
  4541. const graphWidth = w - paddingRight;
  4542. const maxVal = Math.max(5, ...dataArray);
  4543. const currentVal = dataArray[dataArray.length - 1] || 0;
  4544. const leg = document.getElementById(legendId);
  4545. if (leg) {
  4546. leg.innerText = unit === 'bps' ? formatBps(currentVal) : `${currentVal.toLocaleString()} p/s`;
  4547. }
  4548. let gridLines = '';
  4549. for (let i = 0; i <= 5; i++) {
  4550. const y = 8 + (i * (h - 18) / 5);
  4551. const valAtLevel = Math.round(maxVal * (5 - i) / 5);
  4552. const label = unit === 'bps' ? formatBps(valAtLevel) : `${valAtLevel} p/s`;
  4553. gridLines += `
  4554. <line x1="0" y1="${y.toFixed(1)}" x2="${graphWidth}" y2="${y.toFixed(1)}" stroke="#1e2c3e" stroke-width="1" />
  4555. <text x="${w - 2}" y="${(y + 3).toFixed(1)}" fill="#64748b" font-size="9" font-family="monospace" text-anchor="end">${label}</text>
  4556. `;
  4557. }
  4558. const step = graphWidth / (dataArray.length - 1);
  4559. const points = dataArray.map((val, idx) => {
  4560. const x = idx * step;
  4561. const y = (h - 10) - (val / maxVal) * (h - 20);
  4562. return `${x.toFixed(1)},${y.toFixed(1)}`;
  4563. });
  4564. const polylineStr = points.join(' ');
  4565. const areaPath = `M 0,${h - 10} L ${polylineStr} L ${graphWidth},${h - 10} Z`;
  4566. svg.innerHTML = `
  4567. ${gridLines}
  4568. <path d="${areaPath}" fill="rgba(14, 165, 233, 0.12)" />
  4569. <polyline fill="none" stroke="#38bdf8" stroke-width="1.8" stroke-linejoin="round" points="${polylineStr}" />
  4570. <circle cx="${graphWidth}" cy="${points[points.length - 1].split(',')[1]}" r="3" fill="#38bdf8" />
  4571. `;
  4572. }
  4573. async function moveFilterRule(id, dir) {
  4574. id = decodeURIComponent(id);
  4575. try {
  4576. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/move`, {
  4577. method: 'POST',
  4578. headers: { 'Content-Type': 'application/json' },
  4579. body: JSON.stringify({ direction: dir })
  4580. });
  4581. if (!res.ok) throw new Error(await responseError(res));
  4582. await loadFirewall(false);
  4583. } catch (err) {
  4584. showToast('Error', err.message, 'error');
  4585. }
  4586. }
  4587. async function toggleFilterRuleState(id, disabled) {
  4588. id = decodeURIComponent(id);
  4589. try {
  4590. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/state`, {
  4591. method: 'POST',
  4592. headers: { 'Content-Type': 'application/json' },
  4593. body: JSON.stringify({ disabled })
  4594. });
  4595. if (!res.ok) throw new Error(await responseError(res));
  4596. await loadFirewall(false);
  4597. } catch (err) {
  4598. showToast('Error', err.message, 'error');
  4599. }
  4600. }
  4601. async function deleteFilterRule(id) {
  4602. id = decodeURIComponent(id);
  4603. if (!confirm('Are you sure you want to delete this filter rule?')) return;
  4604. try {
  4605. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4606. if (!res.ok) throw new Error(await responseError(res));
  4607. {
  4608. showToast('Deleted', 'Filter rule removed', 'success');
  4609. loadFirewall(false);
  4610. }
  4611. } catch (err) {
  4612. showToast('Error', err.message, 'error');
  4613. }
  4614. }
  4615. // ----------------- NAT Rules -----------------
  4616. function renderNATRules() {
  4617. const chainFilter = document.getElementById('nat-filter-chain')?.value || '';
  4618. const tbody = document.getElementById('nat-table-body');
  4619. const empty = document.getElementById('nat-empty');
  4620. if (!tbody) return;
  4621. tbody.innerHTML = '';
  4622. const rules = (state.natRules || []).filter(r => !chainFilter || nativeNATChain(r.chain) === chainFilter);
  4623. document.getElementById('nat-count-badge').innerText = `${rules.length} Rules`;
  4624. if (rules.length === 0) {
  4625. empty?.classList.remove('hidden');
  4626. return;
  4627. }
  4628. empty?.classList.add('hidden');
  4629. rules.forEach((raw, idx) => {
  4630. const r = safeFirewallRow(raw);
  4631. const tr = document.createElement('tr');
  4632. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  4633. let toTarget = '-';
  4634. if (r.action === 'jump') {
  4635. toTarget = `<span class="text-yellow-300 font-mono font-bold">&rarr; ${r.jump_target || '-'}</span>`;
  4636. } else if (r.action.includes('address-list') || r.action.includes('address list')) {
  4637. toTarget = `<span class="text-emerald-300 font-mono font-bold">&rarr; ${r.address_list || '-'}</span>`;
  4638. } else if (r.action === 'redirect') {
  4639. toTarget = `<span class="text-amber-300 font-mono font-bold">ports:${r.to_ports || 'all'}</span>`;
  4640. } else if (r.action === 'masquerade') {
  4641. 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>`;
  4642. } else if (r.action === 'log') {
  4643. toTarget = `<span class="text-slate-400 font-mono font-bold">${r.log_prefix || 'log'}</span>`;
  4644. } else {
  4645. const parts = [r.to_addresses, r.to_ports].filter(Boolean);
  4646. toTarget = parts.length ? `<span class="text-amber-300 font-mono font-bold">${parts.join(':')}</span>` : '-';
  4647. }
  4648. const ifaces = [r.out_interface ? 'out:' + r.out_interface : r.out_interface_list ? 'out-list:' + r.out_interface_list : '', r.in_interface ? 'in:' + r.in_interface : r.in_interface_list ? 'in-list:' + r.in_interface_list : ''].filter(Boolean).join(' ');
  4649. tr.innerHTML = `
  4650. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  4651. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  4652. <td class="py-2.5 px-3 font-bold text-amber-400">${escapeHtml(nativeNATChain(raw.chain).toUpperCase())}</td>
  4653. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  4654. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  4655. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}${r.dst_port ? ':' + r.dst_port : ''} <span class="text-[9px] text-slate-500">IPv${r.ip_version || 4}</span></td>
  4656. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  4657. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  4658. <td class="py-2.5 px-3 font-mono text-xs">${toTarget}</td>
  4659. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  4660. <span class="text-slate-300" id="nat-pkts-${r.id}">${(r.packets || 0).toLocaleString()}p</span> /
  4661. <span class="text-slate-500" id="nat-bytes-${r.id}">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  4662. </td>
  4663. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  4664. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  4665. <button onclick="moveNATRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  4666. <button onclick="moveNATRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  4667. <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>
  4668. <button onclick="openEditNATModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  4669. <button onclick="deleteNATRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  4670. </td>
  4671. `;
  4672. tbody.appendChild(tr);
  4673. });
  4674. }
  4675. // ==================== FIREWALL NAT MODAL (DEBTIK WEBFIG / WINBOX V4) ====================
  4676. function switchNATRuleTab(tab) {
  4677. if (!document.getElementById(`nat-pane-${tab}`)) tab = 'general';
  4678. state.activeNATRuleTab = tab;
  4679. document.querySelectorAll('.nat-rule-tab-btn').forEach(btn => {
  4680. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  4681. btn.classList.add('text-slate-400', 'border-transparent');
  4682. });
  4683. const activeBtn = document.getElementById(`nat-tab-btn-${tab}`);
  4684. if (activeBtn) {
  4685. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  4686. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  4687. }
  4688. document.querySelectorAll('.nat-rule-pane').forEach(p => p.classList.add('hidden'));
  4689. const activePane = document.getElementById(`nat-pane-${tab}`);
  4690. if (activePane) activePane.classList.remove('hidden');
  4691. if (tab === 'statistics') {
  4692. startNATStatPolling();
  4693. } else {
  4694. stopNATStatPolling();
  4695. }
  4696. }
  4697. function toggleNATField(fieldKey, expand) {
  4698. const plusBtn = document.getElementById(`nat-plus-${fieldKey}`);
  4699. const fieldBox = document.getElementById(`nat-field-${fieldKey}`);
  4700. if (!plusBtn || !fieldBox) return;
  4701. if (expand) {
  4702. plusBtn.classList.add('hidden');
  4703. fieldBox.classList.remove('hidden');
  4704. const valInput = document.getElementById(`nat-val-${fieldKey}`);
  4705. if (valInput) valInput.focus();
  4706. } else {
  4707. fieldBox.classList.add('hidden');
  4708. plusBtn.classList.remove('hidden');
  4709. const valInput = document.getElementById(`nat-val-${fieldKey}`);
  4710. if (valInput) {
  4711. if (valInput.tagName === 'SELECT') {
  4712. valInput.selectedIndex = 0;
  4713. } else {
  4714. valInput.value = '';
  4715. }
  4716. }
  4717. const invInput = document.getElementById(`nat-inv-${fieldKey}`);
  4718. if (invInput) invInput.checked = false;
  4719. if (fieldKey === 'days') {
  4720. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  4721. const el = document.getElementById(`nat-day-${d}`);
  4722. if (el) el.checked = true;
  4723. });
  4724. }
  4725. }
  4726. }
  4727. function setNATFieldVal(fieldKey, value, hasInvert = false) {
  4728. if (fieldKey === 'ipsec' && typeof value === 'string') value = value.replace(':', ',');
  4729. if (value !== undefined && value !== null && value !== '' && !(fieldKey === 'proto' && value === 'all')) {
  4730. toggleNATField(fieldKey, true);
  4731. let strVal = String(value);
  4732. if (hasInvert) {
  4733. const inv = strVal.startsWith('!');
  4734. if (inv) strVal = strVal.slice(1);
  4735. const invEl = document.getElementById(`nat-inv-${fieldKey}`);
  4736. if (invEl) invEl.checked = inv;
  4737. else if (inv) strVal = '!'+strVal;
  4738. }
  4739. const valEl = document.getElementById(`nat-val-${fieldKey}`);
  4740. if (valEl) { if (valEl.tagName === 'SELECT' && !Array.from(valEl.options).some(o => o.value === strVal)) { const option=document.createElement('option'); option.value=strVal; option.textContent=strVal+' (saved)'; valEl.appendChild(option); } valEl.value = strVal; }
  4741. } else {
  4742. toggleNATField(fieldKey, false);
  4743. }
  4744. }
  4745. function getNATFieldVal(fieldKey, hasInvert = false) {
  4746. const fieldBox = document.getElementById(`nat-field-${fieldKey}`);
  4747. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  4748. const valEl = document.getElementById(`nat-val-${fieldKey}`);
  4749. let v = valEl ? valEl.value.trim() : '';
  4750. if (!v) return '';
  4751. if (hasInvert) {
  4752. const invEl = document.getElementById(`nat-inv-${fieldKey}`);
  4753. if (invEl && invEl.checked) {
  4754. v = '!' + v.replace(/^!/, '');
  4755. }
  4756. }
  4757. return v;
  4758. }
  4759. function toggleMaximizeNATModal() {
  4760. const win = document.getElementById('nat-modal-window');
  4761. if (!win) return;
  4762. if (win.classList.contains('max-w-[720px]')) {
  4763. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  4764. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  4765. } else {
  4766. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  4767. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  4768. }
  4769. }
  4770. function syncNATChainFromSelect() {
  4771. const sel = document.getElementById('nat-modal-chain-select');
  4772. const customWrap = document.getElementById('nat-modal-custom-wrap');
  4773. const customInput = document.getElementById('nat-modal-custom-input');
  4774. const chainInput = document.getElementById('nat-modal-chain');
  4775. if (!sel || !chainInput) return;
  4776. if (sel.value === '__custom__') {
  4777. if (customWrap) customWrap.classList.remove('hidden');
  4778. if (customInput) {
  4779. customInput.value = '';
  4780. customInput.focus();
  4781. }
  4782. chainInput.value = '';
  4783. } else {
  4784. if (customWrap) customWrap.classList.add('hidden');
  4785. chainInput.value = sel.value;
  4786. const actEl = document.getElementById('nat-modal-action');
  4787. if (actEl) {
  4788. const curAct = actEl.value;
  4789. if (sel.value === 'prerouting' && ['masquerade', 'src-nat'].includes(curAct)) {
  4790. actEl.value = 'dst-nat';
  4791. } else if (sel.value === 'postrouting' && ['dst-nat', 'redirect'].includes(curAct)) {
  4792. actEl.value = 'masquerade';
  4793. }
  4794. }
  4795. }
  4796. handleNATChainChange();
  4797. }
  4798. function syncNATCustomChainInput() {
  4799. const customInput = document.getElementById('nat-modal-custom-input');
  4800. const chainInput = document.getElementById('nat-modal-chain');
  4801. if (customInput && chainInput) {
  4802. chainInput.value = customInput.value.trim();
  4803. }
  4804. handleNATChainChange();
  4805. }
  4806. function handleNATChainChange() {
  4807. const chainInput = document.getElementById('nat-modal-chain');
  4808. const rawChain = (chainInput?.value || 'postrouting').trim();
  4809. const chain = nativeNATChain(rawChain).toLowerCase();
  4810. const sel = document.getElementById('nat-modal-chain-select');
  4811. if (sel && sel.value !== chain && sel.value !== '__custom__') {
  4812. if (['postrouting', 'prerouting', 'output', 'input'].includes(chain)) {
  4813. sel.value = chain;
  4814. }
  4815. }
  4816. const hintEl = document.getElementById('nat-chain-hint');
  4817. if (hintEl) {
  4818. if (chain === 'prerouting') {
  4819. hintEl.textContent = 'PREROUTING: destination NAT (DNAT / REDIRECT) before routing decision (In-Interface only).';
  4820. } else if (chain === 'postrouting') {
  4821. hintEl.textContent = 'POSTROUTING: source NAT (SNAT / MASQUERADE) after routing decision (Out-Interface only).';
  4822. } else if (chain === 'output') {
  4823. hintEl.textContent = 'OUTPUT: destination NAT for locally generated packets (Out-Interface only).';
  4824. } else if (chain === 'input') {
  4825. hintEl.textContent = 'INPUT: source NAT for packets destined to local sockets (In-Interface only).';
  4826. } else {
  4827. hintEl.textContent = `Custom chain "${rawChain}": user-defined NAT chain reached via JUMP.`;
  4828. }
  4829. }
  4830. const rowIn = document.getElementById('nat-row-iniface');
  4831. const rowInList = document.getElementById('nat-row-inifacelist');
  4832. const rowOut = document.getElementById('nat-row-outiface');
  4833. const rowOutList = document.getElementById('nat-row-outifacelist');
  4834. const rowInBridge = document.getElementById('nat-row-inbridgeport');
  4835. const rowOutBridge = document.getElementById('nat-row-outbridgeport');
  4836. const rowSrcMac = document.getElementById('nat-row-srcmac');
  4837. if (chain === 'prerouting' || chain === 'input') {
  4838. if (rowIn) rowIn.classList.remove('hidden');
  4839. if (rowInList) rowInList.classList.remove('hidden');
  4840. if (rowOut) rowOut.classList.add('hidden');
  4841. if (rowOutList) rowOutList.classList.add('hidden');
  4842. if (rowInBridge) rowInBridge.classList.remove('hidden');
  4843. if (rowOutBridge) rowOutBridge.classList.add('hidden');
  4844. if (rowSrcMac) rowSrcMac.classList.remove('hidden');
  4845. } else if (chain === 'postrouting' || chain === 'output') {
  4846. if (rowIn) rowIn.classList.add('hidden');
  4847. if (rowInList) rowInList.classList.add('hidden');
  4848. if (rowOut) rowOut.classList.remove('hidden');
  4849. if (rowOutList) rowOutList.classList.remove('hidden');
  4850. if (rowInBridge) rowInBridge.classList.add('hidden');
  4851. if (rowOutBridge) rowOutBridge.classList.remove('hidden');
  4852. if (rowSrcMac) rowSrcMac.classList.add('hidden');
  4853. } else {
  4854. if (rowIn) rowIn.classList.remove('hidden');
  4855. if (rowInList) rowInList.classList.remove('hidden');
  4856. if (rowOut) rowOut.classList.remove('hidden');
  4857. if (rowOutList) rowOutList.classList.remove('hidden');
  4858. if (rowInBridge) rowInBridge.classList.remove('hidden');
  4859. if (rowOutBridge) rowOutBridge.classList.remove('hidden');
  4860. if (rowSrcMac) rowSrcMac.classList.remove('hidden');
  4861. }
  4862. checkNATActionChainCompatibility();
  4863. toggleNATActionFields();
  4864. }
  4865. function checkNATActionChainCompatibility() {
  4866. const rawChain = (document.getElementById('nat-modal-chain')?.value || 'postrouting').trim();
  4867. const chain = nativeNATChain(rawChain).toLowerCase();
  4868. const action = (document.getElementById('nat-modal-action')?.value || '').toLowerCase();
  4869. const warnBox = document.getElementById('nat-action-incompatible-warn');
  4870. const warnMsg = document.getElementById('nat-action-incompatible-msg');
  4871. if (!warnBox || !warnMsg) return;
  4872. let msg = '';
  4873. if (['dst-nat', 'redirect'].includes(action)) {
  4874. if (chain !== 'prerouting' && chain !== 'output') {
  4875. msg = `${action === 'dst-nat' ? 'DNAT' : 'REDIRECT'} is only valid in PREROUTING or OUTPUT chains in iptables (current chain: ${chain.toUpperCase()}).`;
  4876. }
  4877. } else if (action === 'masquerade') {
  4878. if (chain !== 'postrouting') {
  4879. msg = `MASQUERADE is only valid in the POSTROUTING chain in iptables (current chain: ${chain.toUpperCase()}).`;
  4880. }
  4881. } else if (action === 'src-nat') {
  4882. if (chain !== 'postrouting' && chain !== 'input') {
  4883. msg = `SNAT is only valid in POSTROUTING or INPUT chains in iptables (current chain: ${chain.toUpperCase()}).`;
  4884. }
  4885. }
  4886. if (msg) {
  4887. warnMsg.textContent = msg;
  4888. warnBox.classList.remove('hidden');
  4889. } else {
  4890. warnBox.classList.add('hidden');
  4891. }
  4892. }
  4893. function toggleNATActionFields() {
  4894. const act = document.getElementById('nat-modal-action')?.value || 'masquerade';
  4895. const rowAddr = document.getElementById('nat-row-toaddr');
  4896. const rowPort = document.getElementById('nat-row-toport');
  4897. const jumpBox = document.getElementById('nat-action-jump-box');
  4898. const addrBox = document.getElementById('nat-action-addrlist-box');
  4899. // Hide all dynamic rows first
  4900. if (rowAddr) rowAddr.classList.add('hidden');
  4901. if (rowPort) rowPort.classList.add('hidden');
  4902. if (jumpBox) jumpBox.classList.add('hidden');
  4903. if (addrBox) addrBox.classList.add('hidden');
  4904. if (['src-nat', 'dst-nat', 'netmap'].includes(act)) {
  4905. if (rowAddr) rowAddr.classList.remove('hidden');
  4906. if (rowPort && act !== 'netmap') rowPort.classList.remove('hidden');
  4907. } else if (act === 'redirect' || act === 'masquerade') {
  4908. if (rowPort) rowPort.classList.remove('hidden');
  4909. } else if (act === 'jump') {
  4910. if (jumpBox) jumpBox.classList.remove('hidden');
  4911. } else if (act.includes('address-list') || act.includes('address list')) {
  4912. if (addrBox) addrBox.classList.remove('hidden');
  4913. }
  4914. if (act === 'log') {
  4915. const logEl = document.getElementById('nat-modal-log');
  4916. if (logEl) logEl.checked = true;
  4917. toggleNATField('logprefix', true);
  4918. }
  4919. }
  4920. function handleNATActionChange() {
  4921. toggleNATActionFields();
  4922. checkNATActionChainCompatibility();
  4923. }
  4924. function toggleNATLogPrefix() {
  4925. const isLog = document.getElementById('nat-modal-log')?.checked;
  4926. toggleNATField('logprefix', !!isLog);
  4927. }
  4928. function openAddNATModal() {
  4929. const tos = document.getElementById('nat-val-tos'); if (tos) tos.value = '';
  4930. switchNATRuleTab('general');
  4931. setFirewallDays('nat', '');
  4932. const badge = document.getElementById('nat-modal-badge');
  4933. if (badge) badge.innerText = 'New...';
  4934. document.getElementById('nat-modal-id').value = '';
  4935. document.getElementById('nat-modal-family').value = '4';
  4936. document.getElementById('nat-modal-enabled').checked = true;
  4937. document.getElementById('nat-modal-comment').value = '';
  4938. document.getElementById('nat-modal-chain').value = 'postrouting';
  4939. populateChainDropdown('nat', 'postrouting');
  4940. handleNATChainChange();
  4941. document.getElementById('nat-modal-action').value = 'masquerade';
  4942. document.getElementById('nat-modal-toaddr').value = '';
  4943. document.getElementById('nat-modal-toport').value = '';
  4944. document.getElementById('nat-modal-log').checked = false;
  4945. populateInterfaceSelect('nat-val-iniface');
  4946. populateInterfaceSelect('nat-val-outiface');
  4947. populateAddressListSelect('nat-val-srclist');
  4948. populateAddressListSelect('nat-val-dstlist');
  4949. populateGeoIPSelect('nat-val-srcgeo');
  4950. populateGeoIPSelect('nat-val-dstgeo');
  4951. const allFieldKeys = [
  4952. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  4953. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  4954. 'routingmark', 'conntype',
  4955. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  4956. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  4957. 'ipsec', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  4958. 'pktsize', 'random', 'icmpoptions', 'ipv4options', 'ttl',
  4959. 'time', 'days', 'limit', 'dstlimit', 'psd', 'logprefix'
  4960. ];
  4961. allFieldKeys.forEach(k => toggleNATField(k, false));
  4962. resetNATCounterDisplay();
  4963. toggleNATActionFields();
  4964. document.getElementById('nat-modal').classList.remove('hidden');
  4965. }
  4966. function openEditNATModal(id) {
  4967. id = decodeURIComponent(id);
  4968. const r = (state.natRules || []).find(rule => rule.id === id);
  4969. if (!r) return;
  4970. setFirewallDays('nat', r.days || '');
  4971. switchNATRuleTab('general');
  4972. const badge = document.getElementById('nat-modal-badge');
  4973. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  4974. document.getElementById('nat-modal-id').value = r.id;
  4975. document.getElementById('nat-modal-family').value = String(r.ip_version || 4);
  4976. document.getElementById('nat-modal-enabled').checked = !r.disabled;
  4977. document.getElementById('nat-modal-comment').value = r.comment || '';
  4978. const natChain = nativeNATChain(r.chain || 'postrouting');
  4979. document.getElementById('nat-modal-chain').value = natChain;
  4980. populateChainDropdown('nat', natChain);
  4981. handleNATChainChange();
  4982. setFirewallActionSelection('nat', r.action || 'accept');
  4983. document.getElementById('nat-modal-toaddr').value = r.to_addresses || '';
  4984. document.getElementById('nat-modal-toport').value = r.to_ports || '';
  4985. document.getElementById('nat-modal-log').checked = !!r.log;
  4986. populateInterfaceSelect('nat-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  4987. populateInterfaceSelect('nat-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  4988. populateAddressListSelect('nat-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  4989. populateAddressListSelect('nat-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  4990. populateGeoIPSelect('nat-val-srcgeo', r.src_geoip || '');
  4991. populateGeoIPSelect('nat-val-dstgeo', r.dst_geoip || '');
  4992. setNATFieldVal('src', r.src_address, true);
  4993. setNATFieldVal('dst', r.dst_address, true);
  4994. setNATFieldVal('srclist', r.src_address_list, true);
  4995. setNATFieldVal('dstlist', r.dst_address_list, true);
  4996. setNATFieldVal('srcgeo', r.src_geoip, true);
  4997. setNATFieldVal('dstgeo', r.dst_geoip, true);
  4998. if (r.protocol && r.protocol !== 'all') {
  4999. setNATFieldVal('proto', r.protocol, true);
  5000. } else {
  5001. toggleNATField('proto', false);
  5002. }
  5003. setNATFieldVal('sport', r.src_port, true);
  5004. setNATFieldVal('dport', r.dst_port, true);
  5005. setNATFieldVal('anyport', r.any_port, true);
  5006. setNATFieldVal('iniface', r.in_interface, true);
  5007. setNATFieldVal('outiface', r.out_interface, true);
  5008. setNATFieldVal('inifacelist', r.in_interface_list, true);
  5009. setNATFieldVal('outifacelist', r.out_interface_list, true);
  5010. setNATFieldVal('pktmark', r.packet_mark, true);
  5011. setNATFieldVal('connmark', r.connection_mark, true);
  5012. setNATFieldVal('routingmark', r.routing_mark, true);
  5013. setNATFieldVal('conntype', r.connection_type, false);
  5014. // Advanced tab fields
  5015. setNATFieldVal('layer7', r.layer7_protocol, false);
  5016. setNATFieldVal('content', r.content, false);
  5017. setNATFieldVal('connbytes', r.connection_bytes, false);
  5018. setNATFieldVal('connrate', r.connection_rate, false);
  5019. setNATFieldVal('pcc', r.pcc, false);
  5020. setNATFieldVal('srcmac', r.src_mac_address, true);
  5021. setNATFieldVal('outbridgeport', r.out_bridge_port, false);
  5022. setNATFieldVal('inbridgeport', r.in_bridge_port, false);
  5023. setNATFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  5024. setNATFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  5025. setNATFieldVal('ipsec', r.ipsec_policy, false);
  5026. setNATFieldVal('ingresspriority', r.ingress_priority, false);
  5027. setNATFieldVal('priority', r.priority, false);
  5028. setNATFieldVal('dscp', r.dscp, false);
  5029. setNATFieldVal('tcpmss', r.tcp_mss, false);
  5030. { const tosEl = document.getElementById('nat-val-tos'); if (tosEl) tosEl.value = r.tos || ''; }
  5031. setNATFieldVal('pktsize', r.packet_size, false);
  5032. setNATFieldVal('random', r.random, false);
  5033. setNATFieldVal('icmpoptions', r.icmp_options, false);
  5034. setNATFieldVal('ipv4options', r.ipv4_options, false);
  5035. setNATFieldVal('ttl', r.ttl, false);
  5036. // Extra tab fields
  5037. setNATFieldVal('time', r.time, false);
  5038. if (r.days) {
  5039. toggleNATField('days', true);
  5040. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  5041. const chk = document.getElementById(`nat-day-${d}`);
  5042. if (chk) chk.checked = r.days.toLowerCase().includes(d);
  5043. });
  5044. } else {
  5045. toggleNATField('days', false);
  5046. }
  5047. setNATFieldVal('limit', r.limit, false);
  5048. setNATFieldVal('dstlimit', r.dst_limit, false);
  5049. setNATFieldVal('psd', r.psd, false);
  5050. // Action fields
  5051. if (r.jump_target) {
  5052. const jtEl = document.getElementById('nat-modal-jumptarget');
  5053. if (jtEl) jtEl.value = r.jump_target;
  5054. }
  5055. if (r.address_list) {
  5056. const alEl = document.getElementById('nat-modal-action-addrlist');
  5057. if (alEl) alEl.value = r.address_list;
  5058. }
  5059. if (r.address_list_timeout) {
  5060. const toEl = document.getElementById('nat-modal-action-timeout');
  5061. if (toEl) toEl.value = r.address_list_timeout;
  5062. }
  5063. setNATFieldVal('logprefix', r.log_prefix, false);
  5064. // Statistics
  5065. const bEl = document.getElementById('nat-stat-bytes');
  5066. const pEl = document.getElementById('nat-stat-packets');
  5067. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  5068. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  5069. state.natLastBytes = r.bytes || 0;
  5070. state.natLastPackets = r.packets || 0;
  5071. state.natLastTimestamp = Date.now();
  5072. state.natStatRateHistory = new Array(30).fill(0);
  5073. state.natStatPktHistory = new Array(30).fill(0);
  5074. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  5075. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  5076. toggleNATActionFields();
  5077. document.getElementById('nat-modal').classList.remove('hidden');
  5078. }
  5079. function closeNATModal() {
  5080. stopNATStatPolling();
  5081. document.getElementById('nat-modal').classList.add('hidden');
  5082. }
  5083. function copyNATRule() {
  5084. document.getElementById('nat-modal-id').value = '';
  5085. const badge = document.getElementById('nat-modal-badge');
  5086. if (badge) badge.innerText = 'New...';
  5087. showToast('Rule Cloned', 'Ready to save as a new NAT rule copy', 'info');
  5088. }
  5089. function resetNATCounterDisplay() {
  5090. state.natStatRateHistory = new Array(30).fill(0);
  5091. state.natStatPktHistory = new Array(30).fill(0);
  5092. state.natLastBytes = 0;
  5093. state.natLastPackets = 0;
  5094. state.natLastTimestamp = Date.now();
  5095. const bEl = document.getElementById('nat-stat-bytes');
  5096. const pEl = document.getElementById('nat-stat-packets');
  5097. const rEl = document.getElementById('nat-stat-rate');
  5098. const prEl = document.getElementById('nat-stat-pktrate');
  5099. if (bEl) bEl.value = '0 B';
  5100. if (pEl) pEl.value = '0';
  5101. if (rEl) rEl.value = '0 bps';
  5102. if (prEl) prEl.value = '0 p/s';
  5103. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  5104. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  5105. showToast('Counters Reset', 'NAT rule counter display reset to 0', 'info');
  5106. }
  5107. async function applyNATRule(closeAfter = false) {
  5108. const id = document.getElementById('nat-modal-id').value;
  5109. if (!reviewLegacyFirewallSettings('nat', id)) return;
  5110. let selectedDays; try { selectedDays = getFirewallDays('nat'); } catch(error) { showToast('Error', error.message, 'error'); return; }
  5111. const chain = (document.getElementById('nat-modal-chain').value || '').trim();
  5112. const chainLower = nativeNATChain(chain).toLowerCase();
  5113. const action = document.getElementById('nat-modal-action').value;
  5114. const comment = document.getElementById('nat-modal-comment').value.trim();
  5115. const enabled = document.getElementById('nat-modal-enabled').checked;
  5116. const src = getNATFieldVal('src', true);
  5117. const dst = getNATFieldVal('dst', true);
  5118. const srclist = getNATFieldVal('srclist', true);
  5119. const dstlist = getNATFieldVal('dstlist', true);
  5120. const srcgeo = getNATFieldVal('srcgeo', true);
  5121. const dstgeo = getNATFieldVal('dstgeo', true);
  5122. const proto = getNATFieldVal('proto', true);
  5123. const sport = getNATFieldVal('sport', true);
  5124. const dport = getNATFieldVal('dport', true);
  5125. const anyport = getNATFieldVal('anyport', true);
  5126. let iniface = getNATFieldVal('iniface', true);
  5127. let outiface = getNATFieldVal('outiface', true);
  5128. let inifacelist = getNATFieldVal('inifacelist', true);
  5129. let outifacelist = getNATFieldVal('outifacelist', true);
  5130. if (chainLower === 'prerouting' || chainLower === 'input') {
  5131. outiface = '';
  5132. outifacelist = '';
  5133. } else if (chainLower === 'postrouting' || chainLower === 'output') {
  5134. iniface = '';
  5135. inifacelist = '';
  5136. }
  5137. const pktmark = getNATFieldVal('pktmark', true);
  5138. const connmark = getNATFieldVal('connmark', true);
  5139. const routingmark = getNATFieldVal('routingmark', true);
  5140. const conntype = getNATFieldVal('conntype', false);
  5141. const usesAddr = ['src-nat', 'dst-nat', 'netmap'].includes(action);
  5142. const usesPort = ['src-nat', 'dst-nat', 'redirect', 'masquerade'].includes(action);
  5143. if (!chain) { switchNATRuleTab('general'); showToast('NAT rule', 'Enter a chain.', 'error'); document.getElementById('nat-modal-chain').focus(); return; }
  5144. if (chainLower === 'forward') { switchNATRuleTab('general'); showToast('Invalid Chain', 'Chain FORWARD is not valid in the NAT table in iptables.', 'error'); return; }
  5145. if (['dst-nat', 'redirect'].includes(action) && chainLower !== 'prerouting' && chainLower !== 'output') {
  5146. switchNATRuleTab('general');
  5147. showToast('Invalid Target for Chain', `${action === 'dst-nat' ? 'DNAT' : 'REDIRECT'} requires PREROUTING or OUTPUT chain in iptables.`, 'error');
  5148. return;
  5149. }
  5150. if (action === 'masquerade' && chainLower !== 'postrouting') {
  5151. switchNATRuleTab('general');
  5152. showToast('Invalid Target for Chain', 'MASQUERADE requires POSTROUTING chain in iptables.', 'error');
  5153. return;
  5154. }
  5155. if (action === 'src-nat' && chainLower !== 'postrouting' && chainLower !== 'input') {
  5156. switchNATRuleTab('general');
  5157. showToast('Invalid Target for Chain', 'SNAT requires POSTROUTING or INPUT chain in iptables.', 'error');
  5158. return;
  5159. }
  5160. if (usesAddr && !document.getElementById('nat-modal-toaddr').value.trim()) { switchNATRuleTab('general'); showToast('NAT rule', 'Enter the destination IP / address for this action.', 'error'); document.getElementById('nat-modal-toaddr').focus(); return; }
  5161. if ((sport || dport || anyport || (usesPort && document.getElementById('nat-modal-toport').value.trim())) && !['tcp', 'udp'].includes(proto)) {
  5162. switchNATRuleTab('general'); toggleNATField('proto', true); document.getElementById('nat-val-proto').value = proto || 'all';
  5163. showToast('Select protocol', 'Port rules require TCP or UDP. For DNS, create one UDP and one TCP rule.', 'error'); document.getElementById('nat-val-proto').focus(); return;
  5164. }
  5165. const payload = {
  5166. ip_version: Number(document.getElementById('nat-modal-family').value),
  5167. id,
  5168. chain,
  5169. action,
  5170. to_addresses: usesAddr ? (document.getElementById('nat-modal-toaddr')?.value.trim() || '') : '',
  5171. to_ports: usesPort ? (document.getElementById('nat-modal-toport')?.value.trim() || '') : '',
  5172. protocol: proto || 'all',
  5173. src_address: src,
  5174. dst_address: dst,
  5175. src_port: sport,
  5176. dst_port: dport,
  5177. any_port: anyport,
  5178. in_interface: iniface,
  5179. out_interface: outiface,
  5180. in_interface_list: inifacelist,
  5181. out_interface_list: outifacelist,
  5182. packet_mark: pktmark,
  5183. connection_mark: connmark,
  5184. routing_mark: routingmark,
  5185. connection_type: conntype,
  5186. src_address_list: srclist,
  5187. dst_address_list: dstlist,
  5188. src_geoip: srcgeo,
  5189. dst_geoip: dstgeo,
  5190. comment,
  5191. disabled: !enabled,
  5192. // Advanced tab
  5193. content: getNATFieldVal('content', false),
  5194. src_mac_address: (chainLower === 'output' || chainLower === 'postrouting') ? '' : getNATFieldVal('srcmac', true),
  5195. out_bridge_port: (chainLower === 'input' || chainLower === 'prerouting') ? '' : getNATFieldVal('outbridgeport', false),
  5196. in_bridge_port: (chainLower === 'output' || chainLower === 'postrouting') ? '' : getNATFieldVal('inbridgeport', false),
  5197. ipsec_policy: getNATFieldVal('ipsec', false),
  5198. dscp: getNATFieldVal('dscp', false),
  5199. tcp_mss: getNATFieldVal('tcpmss', false),
  5200. tos: document.getElementById('nat-val-tos')?.value || '',
  5201. packet_size: getNATFieldVal('pktsize', false),
  5202. random: getNATFieldVal('random', false),
  5203. icmp_options: getNATFieldVal('icmpoptions', false),
  5204. ttl: getNATFieldVal('ttl', false),
  5205. days: selectedDays,
  5206. // Extra tab
  5207. time: getNATFieldVal('time', false),
  5208. limit: getNATFieldVal('limit', false),
  5209. // Action tab
  5210. jump_target: action === 'jump' ? (document.getElementById('nat-modal-jumptarget')?.value || '') : '',
  5211. address_list: action.includes('address') ? (document.getElementById('nat-modal-action-addrlist')?.value || '') : '',
  5212. address_list_timeout: action.includes('address') ? (document.getElementById('nat-modal-action-timeout')?.value || '') : '',
  5213. log: document.getElementById('nat-modal-log')?.checked || false,
  5214. log_prefix: getNATFieldVal('logprefix', false)
  5215. };
  5216. try {
  5217. const res = await fetch(`${API_BASE}/firewall/nat`, {
  5218. method: 'POST',
  5219. headers: { 'Content-Type': 'application/json' },
  5220. body: JSON.stringify(payload)
  5221. });
  5222. if (res.ok) {
  5223. const data = await res.json();
  5224. showToast('NAT Rule Saved', 'NAT mapping updated', 'success');
  5225. loadFirewall(false);
  5226. if (closeAfter) {
  5227. closeNATModal();
  5228. } else {
  5229. if (data.id) {
  5230. document.getElementById('nat-modal-id').value = data.id;
  5231. const badge = document.getElementById('nat-modal-badge');
  5232. if (badge) badge.innerText = `#${data.id}`;
  5233. }
  5234. }
  5235. } else {
  5236. const err = await res.json();
  5237. showToast('Error', err.message || 'Failed to save rule', 'error');
  5238. }
  5239. } catch (err) {
  5240. showToast('Error', err.message, 'error');
  5241. }
  5242. }
  5243. function submitSaveNATRule(e) {
  5244. if (e && e.preventDefault) e.preventDefault();
  5245. return applyNATRule(true);
  5246. }
  5247. function startNATStatPolling() {
  5248. stopNATStatPolling();
  5249. pollNATRuleStats();
  5250. state.natStatInterval = setInterval(pollNATRuleStats, 1000);
  5251. }
  5252. function stopNATStatPolling() {
  5253. if (state.natStatInterval) {
  5254. clearInterval(state.natStatInterval);
  5255. state.natStatInterval = null;
  5256. }
  5257. }
  5258. async function pollNATRuleStats() {
  5259. const id = document.getElementById('nat-modal-id')?.value;
  5260. if (!id) {
  5261. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory || new Array(30).fill(0), 'bps', 'nat-stat-legend-rate');
  5262. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory || new Array(30).fill(0), 'p/s', 'nat-stat-legend-pktrate');
  5263. return;
  5264. }
  5265. try {
  5266. const res = await fetch(`${API_BASE}/firewall/nat`);
  5267. if (!res.ok) return;
  5268. const rules = await res.json();
  5269. const r = rules.find(x => x.id === id);
  5270. if (!r) return;
  5271. const now = Date.now();
  5272. const dt = Math.max(0.2, (now - (state.natLastTimestamp || now)) / 1000);
  5273. state.natLastTimestamp = now;
  5274. const curBytes = r.bytes || 0;
  5275. const curPackets = r.packets || 0;
  5276. const deltaBytes = Math.max(0, curBytes - (state.natLastBytes ?? curBytes));
  5277. const deltaPkts = Math.max(0, curPackets - (state.natLastPackets ?? curPackets));
  5278. state.natLastBytes = curBytes;
  5279. state.natLastPackets = curPackets;
  5280. const rateBps = Math.round((deltaBytes * 8) / dt);
  5281. const ratePkt = Math.round(deltaPkts / dt);
  5282. if (!state.natStatRateHistory) state.natStatRateHistory = new Array(30).fill(0);
  5283. if (!state.natStatPktHistory) state.natStatPktHistory = new Array(30).fill(0);
  5284. state.natStatRateHistory.push(rateBps);
  5285. if (state.natStatRateHistory.length > 30) state.natStatRateHistory.shift();
  5286. state.natStatPktHistory.push(ratePkt);
  5287. if (state.natStatPktHistory.length > 30) state.natStatPktHistory.shift();
  5288. const bEl = document.getElementById('nat-stat-bytes');
  5289. const pEl = document.getElementById('nat-stat-packets');
  5290. const rEl = document.getElementById('nat-stat-rate');
  5291. const prEl = document.getElementById('nat-stat-pktrate');
  5292. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  5293. if (pEl) pEl.value = curPackets.toLocaleString();
  5294. if (rEl) rEl.value = formatBps(rateBps);
  5295. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  5296. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  5297. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  5298. } catch (e) {
  5299. console.error('Error polling NAT rule stats', e);
  5300. }
  5301. }
  5302. async function moveNATRule(id, dir) {
  5303. id = decodeURIComponent(id);
  5304. try {
  5305. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/move`, {
  5306. method: 'POST',
  5307. headers: { 'Content-Type': 'application/json' },
  5308. body: JSON.stringify({ direction: dir })
  5309. });
  5310. if (!res.ok) throw new Error(await responseError(res));
  5311. await loadFirewall(false);
  5312. } catch (err) {
  5313. showToast('Error', err.message, 'error');
  5314. }
  5315. }
  5316. async function toggleNATRuleState(id, disabled) {
  5317. id = decodeURIComponent(id);
  5318. try {
  5319. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/state`, {
  5320. method: 'POST',
  5321. headers: { 'Content-Type': 'application/json' },
  5322. body: JSON.stringify({ disabled })
  5323. });
  5324. if (!res.ok) throw new Error(await responseError(res));
  5325. await loadFirewall(false);
  5326. } catch (err) {
  5327. showToast('Error', err.message, 'error');
  5328. }
  5329. }
  5330. async function deleteNATRule(id) {
  5331. id = decodeURIComponent(id);
  5332. if (!confirm('Are you sure you want to delete this NAT rule?')) return;
  5333. try {
  5334. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5335. if (!res.ok) throw new Error(await responseError(res));
  5336. {
  5337. showToast('Deleted', 'NAT rule removed', 'success');
  5338. loadFirewall(false);
  5339. }
  5340. } catch (err) {
  5341. showToast('Error', err.message, 'error');
  5342. }
  5343. }
  5344. // ----------------- Mangle Rules -----------------
  5345. function renderMangleRules() {
  5346. const chainFilter = document.getElementById('mangle-filter-chain')?.value || '';
  5347. const tbody = document.getElementById('mangle-table-body');
  5348. const empty = document.getElementById('mangle-empty');
  5349. if (!tbody) return;
  5350. tbody.innerHTML = '';
  5351. const rules = (state.mangleRules || []).filter(r => !chainFilter || (r.chain || '').toLowerCase() === chainFilter);
  5352. document.getElementById('mangle-count-badge').innerText = `${rules.length} Rules`;
  5353. if (rules.length === 0) {
  5354. empty?.classList.remove('hidden');
  5355. return;
  5356. }
  5357. empty?.classList.add('hidden');
  5358. rules.forEach((raw, idx) => {
  5359. const r = safeFirewallRow(raw);
  5360. const tr = document.createElement('tr');
  5361. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  5362. let markVal = '<span class="text-slate-500">-</span>';
  5363. if (r.new_connection_mark) markVal = `<span class="text-cyan-300 font-mono font-bold">${r.new_connection_mark}</span>`;
  5364. else if (r.new_routing_mark) markVal = `<span class="text-amber-300 font-mono font-bold">${r.new_routing_mark}</span>`;
  5365. else if (r.new_packet_mark) markVal = `<span class="text-emerald-300 font-mono font-bold">${r.new_packet_mark}</span>`;
  5366. else if (r.new_mss) markVal = `<span class="text-sky-300 font-mono font-bold">mss:${r.new_mss}</span>`;
  5367. else if (r.action === 'change-dscp') markVal = `<span class="text-purple-300 font-mono font-bold">dscp:${r.new_dscp}</span>`;
  5368. else if (r.new_ttl) markVal = `<span class="text-blue-300 font-mono font-bold">ttl:${r.new_ttl}</span>`;
  5369. else if (r.new_priority) markVal = `<span class="text-indigo-300 font-mono font-bold">prio:${r.new_priority}</span>`;
  5370. else if (r.route) markVal = `<span class="text-orange-300 font-mono font-bold">route:${r.route}</span>`;
  5371. else if (r.sniff_target) markVal = `<span class="text-pink-300 font-mono font-bold">sniff:${r.sniff_target}</span>`;
  5372. else if (r.action === 'jump') markVal = `<span class="text-yellow-300 font-mono font-bold">&rarr; ${r.jump_target || '-'}</span>`;
  5373. 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>`;
  5374. else if (r.action === 'log') markVal = `<span class="text-slate-400 font-mono font-bold">${r.log_prefix || 'log'}</span>`;
  5375. tr.innerHTML = `
  5376. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  5377. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  5378. <td class="py-2.5 px-3 font-bold text-purple-400">${(r.chain || '').toUpperCase()}</td>
  5379. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  5380. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  5381. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  5382. <td class="py-2.5 px-3 font-mono text-xs">${markVal}</td>
  5383. <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>
  5384. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  5385. <span class="text-slate-300" id="mangle-pkts-${r.id}">${(r.packets || 0).toLocaleString()}p</span> /
  5386. <span class="text-slate-500" id="mangle-bytes-${r.id}">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  5387. </td>
  5388. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  5389. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  5390. <button onclick="moveMangleRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  5391. <button onclick="moveMangleRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  5392. <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>
  5393. <button onclick="openEditMangleModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  5394. <button onclick="deleteMangleRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  5395. </td>
  5396. `;
  5397. tbody.appendChild(tr);
  5398. });
  5399. }
  5400. // ==================== FIREWALL MANGLE MODAL (DEBTIK WEBFIG / WINBOX V4) ====================
  5401. function switchMangleRuleTab(tab) {
  5402. state.activeMangleRuleTab = tab;
  5403. document.querySelectorAll('.mangle-rule-tab-btn').forEach(btn => {
  5404. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  5405. btn.classList.add('text-slate-400', 'border-transparent');
  5406. });
  5407. const activeBtn = document.getElementById(`mangle-tab-btn-${tab}`);
  5408. if (activeBtn) {
  5409. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  5410. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  5411. }
  5412. document.querySelectorAll('.mangle-rule-pane').forEach(p => p.classList.add('hidden'));
  5413. const activePane = document.getElementById(`mangle-pane-${tab}`);
  5414. if (activePane) activePane.classList.remove('hidden');
  5415. if (tab === 'statistics') {
  5416. startMangleStatPolling();
  5417. } else {
  5418. stopMangleStatPolling();
  5419. }
  5420. }
  5421. function toggleMangleField(fieldKey, expand) {
  5422. const plusBtn = document.getElementById(`mangle-plus-${fieldKey}`);
  5423. const fieldBox = document.getElementById(`mangle-field-${fieldKey}`);
  5424. if (!plusBtn || !fieldBox) return;
  5425. if (expand) {
  5426. plusBtn.classList.add('hidden');
  5427. fieldBox.classList.remove('hidden');
  5428. const valInput = document.getElementById(`mangle-val-${fieldKey}`);
  5429. if (valInput) valInput.focus();
  5430. } else {
  5431. fieldBox.classList.add('hidden');
  5432. plusBtn.classList.remove('hidden');
  5433. const valInput = document.getElementById(`mangle-val-${fieldKey}`);
  5434. if (valInput) {
  5435. if (valInput.tagName === 'SELECT') {
  5436. valInput.selectedIndex = 0;
  5437. } else {
  5438. valInput.value = '';
  5439. }
  5440. }
  5441. const invInput = document.getElementById(`mangle-inv-${fieldKey}`);
  5442. if (invInput) invInput.checked = false;
  5443. if (fieldKey === 'cs') {
  5444. ['mangle-modal-cs-established', 'mangle-modal-cs-related', 'mangle-modal-cs-new', 'mangle-modal-cs-invalid', 'mangle-modal-cs-untracked'].forEach(id => {
  5445. const el = document.getElementById(id);
  5446. if (el) el.checked = false;
  5447. });
  5448. }
  5449. if (fieldKey === 'natstate') {
  5450. ['mangle-modal-nat-srcnat', 'mangle-modal-nat-dstnat'].forEach(id => {
  5451. const el = document.getElementById(id);
  5452. if (el) el.checked = false;
  5453. });
  5454. }
  5455. }
  5456. }
  5457. function setMangleFieldVal(fieldKey, value, hasInvert = false) {
  5458. if (fieldKey === 'ipsec' && typeof value === 'string') value = value.replace(':', ',');
  5459. if (value !== undefined && value !== null && value !== '' && !(fieldKey === 'proto' && value === 'all')) {
  5460. toggleMangleField(fieldKey, true);
  5461. let strVal = String(value);
  5462. if (hasInvert) {
  5463. const inv = strVal.startsWith('!');
  5464. if (inv) strVal = strVal.slice(1);
  5465. const invEl = document.getElementById(`mangle-inv-${fieldKey}`);
  5466. if (invEl) invEl.checked = inv;
  5467. else if (inv) strVal = '!'+strVal;
  5468. }
  5469. const valEl = document.getElementById(`mangle-val-${fieldKey}`);
  5470. if (valEl) { if (valEl.tagName === 'SELECT' && !Array.from(valEl.options).some(o => o.value === strVal)) { const option=document.createElement('option'); option.value=strVal; option.textContent=strVal+' (saved)'; valEl.appendChild(option); } valEl.value = strVal; }
  5471. } else {
  5472. toggleMangleField(fieldKey, false);
  5473. }
  5474. }
  5475. function getMangleFieldVal(fieldKey, hasInvert = false) {
  5476. const fieldBox = document.getElementById(`mangle-field-${fieldKey}`);
  5477. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  5478. const valEl = document.getElementById(`mangle-val-${fieldKey}`);
  5479. let v = valEl ? valEl.value.trim() : '';
  5480. if (!v) return '';
  5481. if (hasInvert) {
  5482. const invEl = document.getElementById(`mangle-inv-${fieldKey}`);
  5483. if (invEl && invEl.checked) {
  5484. v = '!' + v.replace(/^!/, '');
  5485. }
  5486. }
  5487. return v;
  5488. }
  5489. function toggleMaximizeMangleModal() {
  5490. const win = document.getElementById('mangle-modal-window');
  5491. if (!win) return;
  5492. if (win.classList.contains('max-w-[720px]')) {
  5493. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  5494. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  5495. } else {
  5496. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  5497. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  5498. }
  5499. }
  5500. function syncMangleChainFromSelect() {
  5501. const sel = document.getElementById('mangle-modal-chain-select');
  5502. const customWrap = document.getElementById('mangle-modal-custom-wrap');
  5503. const customInput = document.getElementById('mangle-modal-custom-input');
  5504. const chainInput = document.getElementById('mangle-modal-chain');
  5505. if (!sel || !chainInput) return;
  5506. if (sel.value === '__custom__') {
  5507. if (customWrap) customWrap.classList.remove('hidden');
  5508. if (customInput) {
  5509. customInput.value = '';
  5510. customInput.focus();
  5511. }
  5512. chainInput.value = '';
  5513. } else {
  5514. if (customWrap) customWrap.classList.add('hidden');
  5515. chainInput.value = sel.value;
  5516. }
  5517. handleMangleChainChange();
  5518. }
  5519. function syncMangleCustomChainInput() {
  5520. const customInput = document.getElementById('mangle-modal-custom-input');
  5521. const chainInput = document.getElementById('mangle-modal-chain');
  5522. if (customInput && chainInput) {
  5523. chainInput.value = customInput.value.trim();
  5524. }
  5525. handleMangleChainChange();
  5526. }
  5527. function handleMangleChainChange() {
  5528. const chainInput = document.getElementById('mangle-modal-chain');
  5529. const rawChain = (chainInput?.value || 'prerouting').trim();
  5530. const chain = rawChain.toLowerCase();
  5531. const sel = document.getElementById('mangle-modal-chain-select');
  5532. if (sel && sel.value !== chain && sel.value !== '__custom__') {
  5533. if (['prerouting', 'input', 'forward', 'output', 'postrouting'].includes(chain)) {
  5534. sel.value = chain;
  5535. }
  5536. }
  5537. const hintEl = document.getElementById('mangle-chain-hint');
  5538. if (hintEl) {
  5539. if (chain === 'prerouting') {
  5540. hintEl.textContent = 'PREROUTING: packets altered before routing decision (In-Interface only).';
  5541. } else if (chain === 'input') {
  5542. hintEl.textContent = 'INPUT: packets altered before local socket delivery (In-Interface only).';
  5543. } else if (chain === 'forward') {
  5544. hintEl.textContent = 'FORWARD: transit packets routed through this router (accepts both In and Out interfaces).';
  5545. } else if (chain === 'output') {
  5546. hintEl.textContent = 'OUTPUT: locally generated packets before routing decision (Out-Interface only).';
  5547. } else if (chain === 'postrouting') {
  5548. hintEl.textContent = 'POSTROUTING: packets altered after routing decision before transmission (Out-Interface only; CLASSIFY supported).';
  5549. } else {
  5550. hintEl.textContent = `Custom chain "${rawChain}": user-defined Mangle chain reached via JUMP.`;
  5551. }
  5552. }
  5553. const rowIn = document.getElementById('mangle-row-iniface');
  5554. const rowInList = document.getElementById('mangle-row-inifacelist');
  5555. const rowOut = document.getElementById('mangle-row-outiface');
  5556. const rowOutList = document.getElementById('mangle-row-outifacelist');
  5557. const rowInBridge = document.getElementById('mangle-row-inbridgeport');
  5558. const rowOutBridge = document.getElementById('mangle-row-outbridgeport');
  5559. const rowSrcMac = document.getElementById('mangle-row-srcmac');
  5560. if (chain === 'prerouting' || chain === 'input') {
  5561. if (rowIn) rowIn.classList.remove('hidden');
  5562. if (rowInList) rowInList.classList.remove('hidden');
  5563. if (rowOut) rowOut.classList.add('hidden');
  5564. if (rowOutList) rowOutList.classList.add('hidden');
  5565. if (rowInBridge) rowInBridge.classList.remove('hidden');
  5566. if (rowOutBridge) rowOutBridge.classList.add('hidden');
  5567. if (rowSrcMac) rowSrcMac.classList.remove('hidden');
  5568. } else if (chain === 'output' || chain === 'postrouting') {
  5569. if (rowIn) rowIn.classList.add('hidden');
  5570. if (rowInList) rowInList.classList.add('hidden');
  5571. if (rowOut) rowOut.classList.remove('hidden');
  5572. if (rowOutList) rowOutList.classList.remove('hidden');
  5573. if (rowInBridge) rowInBridge.classList.add('hidden');
  5574. if (rowOutBridge) rowOutBridge.classList.remove('hidden');
  5575. if (rowSrcMac) rowSrcMac.classList.add('hidden');
  5576. } else {
  5577. if (rowIn) rowIn.classList.remove('hidden');
  5578. if (rowInList) rowInList.classList.remove('hidden');
  5579. if (rowOut) rowOut.classList.remove('hidden');
  5580. if (rowOutList) rowOutList.classList.remove('hidden');
  5581. if (rowInBridge) rowInBridge.classList.remove('hidden');
  5582. if (rowOutBridge) rowOutBridge.classList.remove('hidden');
  5583. if (rowSrcMac) rowSrcMac.classList.remove('hidden');
  5584. }
  5585. checkMangleActionChainCompatibility();
  5586. toggleMangleActionFields();
  5587. }
  5588. function checkMangleActionChainCompatibility() {
  5589. const rawChain = (document.getElementById('mangle-modal-chain')?.value || 'prerouting').trim();
  5590. const chain = rawChain.toLowerCase();
  5591. const action = (document.getElementById('mangle-modal-action')?.value || '').toLowerCase();
  5592. const warnBox = document.getElementById('mangle-action-incompatible-warn');
  5593. const warnMsg = document.getElementById('mangle-action-incompatible-msg');
  5594. if (!warnBox || !warnMsg) return;
  5595. let msg = '';
  5596. if (action === 'set-priority' && chain !== 'postrouting') {
  5597. msg = 'CLASSIFY (set-priority) requires the POSTROUTING chain in iptables.';
  5598. }
  5599. if (msg) {
  5600. warnMsg.textContent = msg;
  5601. warnBox.classList.remove('hidden');
  5602. } else {
  5603. warnBox.classList.add('hidden');
  5604. }
  5605. }
  5606. function toggleMangleActionFields() {
  5607. const act = document.getElementById('mangle-modal-action')?.value || 'mark-connection';
  5608. // Hide all dynamic rows first
  5609. ['newconnmark', 'newroutingmark', 'newpktmark', 'newmss', 'newdscp', 'newttl', 'newpriority', 'route', 'sniff', 'passthrough'].forEach(id => {
  5610. const el = document.getElementById(`mangle-row-${id}`);
  5611. if (el) el.classList.add('hidden');
  5612. });
  5613. const jumpBox = document.getElementById('mangle-action-jump-box');
  5614. const addrBox = document.getElementById('mangle-action-addrlist-box');
  5615. if (jumpBox) jumpBox.classList.add('hidden');
  5616. if (addrBox) addrBox.classList.add('hidden');
  5617. // Activate matching rows
  5618. if (act === 'mark-connection') {
  5619. document.getElementById('mangle-row-newconnmark')?.classList.remove('hidden');
  5620. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5621. } else if (act === 'mark-routing') {
  5622. document.getElementById('mangle-row-newroutingmark')?.classList.remove('hidden');
  5623. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5624. } else if (act === 'mark-packet') {
  5625. document.getElementById('mangle-row-newpktmark')?.classList.remove('hidden');
  5626. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5627. } else if (act === 'change-mss') {
  5628. document.getElementById('mangle-row-newmss')?.classList.remove('hidden');
  5629. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5630. } else if (act === 'change-dscp') {
  5631. document.getElementById('mangle-row-newdscp')?.classList.remove('hidden');
  5632. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5633. } else if (act === 'change-ttl') {
  5634. document.getElementById('mangle-row-newttl')?.classList.remove('hidden');
  5635. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5636. } else if (act === 'set-priority') {
  5637. document.getElementById('mangle-row-newpriority')?.classList.remove('hidden');
  5638. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5639. } else if (act === 'route') {
  5640. document.getElementById('mangle-row-route')?.classList.remove('hidden');
  5641. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5642. } else if (act === 'sniff-pc' || act === 'sniff-tzsp') {
  5643. document.getElementById('mangle-row-sniff')?.classList.remove('hidden');
  5644. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5645. } else if (act === 'clear-df' || act === 'strip-ipv4-options') {
  5646. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5647. } else if (act === 'jump') {
  5648. if (jumpBox) jumpBox.classList.remove('hidden');
  5649. } else if (act.includes('address-list') || act.includes('address list')) {
  5650. if (addrBox) addrBox.classList.remove('hidden');
  5651. }
  5652. if (act === 'log') {
  5653. const logEl = document.getElementById('mangle-modal-log');
  5654. if (logEl) logEl.checked = true;
  5655. toggleMangleField('logprefix', true);
  5656. }
  5657. checkMangleActionChainCompatibility();
  5658. }
  5659. function toggleMangleLogPrefix() {
  5660. const isLog = document.getElementById('mangle-modal-log')?.checked;
  5661. toggleMangleField('logprefix', !!isLog);
  5662. }
  5663. const allMangleFieldKeys = [
  5664. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  5665. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  5666. 'routingmark', 'conntype', 'cs', 'natstate',
  5667. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  5668. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  5669. 'ipsec', 'tlshost', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  5670. 'pktsize', 'random', 'tcpflags', 'icmpoptions', 'ipv4options', 'ttl',
  5671. 'nth', 'connlimit', 'srcaddrtype', 'dstaddrtype', 'hotspot', 'ipfragment',
  5672. 'limit', 'dstlimit', 'time', 'psd', 'logprefix'
  5673. ];
  5674. function openAddMangleModal() {
  5675. const tos = document.getElementById('mangle-val-tos'); if (tos) tos.value = '';
  5676. switchMangleRuleTab('general');
  5677. const badge = document.getElementById('mangle-modal-badge');
  5678. if (badge) badge.innerText = 'New...';
  5679. document.getElementById('mangle-modal-id').value = '';
  5680. document.getElementById('mangle-modal-family').value = '4';
  5681. document.getElementById('mangle-modal-enabled').checked = true;
  5682. document.getElementById('mangle-modal-comment').value = '';
  5683. document.getElementById('mangle-modal-chain').value = 'prerouting';
  5684. populateChainDropdown('mangle', 'prerouting');
  5685. handleMangleChainChange();
  5686. document.getElementById('mangle-modal-action').value = 'mark-connection';
  5687. if (document.getElementById('mangle-modal-newconnmark')) document.getElementById('mangle-modal-newconnmark').value = '';
  5688. if (document.getElementById('mangle-modal-newroutingmark')) document.getElementById('mangle-modal-newroutingmark').value = '';
  5689. if (document.getElementById('mangle-modal-newpktmark')) document.getElementById('mangle-modal-newpktmark').value = '';
  5690. if (document.getElementById('mangle-modal-newmss')) document.getElementById('mangle-modal-newmss').value = '';
  5691. if (document.getElementById('mangle-modal-newdscp')) document.getElementById('mangle-modal-newdscp').value = '';
  5692. if (document.getElementById('mangle-modal-newttl')) document.getElementById('mangle-modal-newttl').value = '';
  5693. if (document.getElementById('mangle-modal-newpriority')) document.getElementById('mangle-modal-newpriority').value = '';
  5694. if (document.getElementById('mangle-modal-route')) document.getElementById('mangle-modal-route').value = '';
  5695. if (document.getElementById('mangle-modal-sniff')) document.getElementById('mangle-modal-sniff').value = '';
  5696. if (document.getElementById('mangle-modal-jumptarget')) document.getElementById('mangle-modal-jumptarget').value = '';
  5697. if (document.getElementById('mangle-modal-action-addrlist')) document.getElementById('mangle-modal-action-addrlist').value = '';
  5698. if (document.getElementById('mangle-modal-action-timeout')) document.getElementById('mangle-modal-action-timeout').value = '';
  5699. if (document.getElementById('mangle-modal-passthrough')) document.getElementById('mangle-modal-passthrough').checked = true;
  5700. if (document.getElementById('mangle-modal-log')) document.getElementById('mangle-modal-log').checked = false;
  5701. populateInterfaceSelect('mangle-val-iniface');
  5702. populateInterfaceSelect('mangle-val-outiface');
  5703. populateAddressListSelect('mangle-val-srclist');
  5704. populateAddressListSelect('mangle-val-dstlist');
  5705. populateGeoIPSelect('mangle-val-srcgeo');
  5706. populateGeoIPSelect('mangle-val-dstgeo');
  5707. allMangleFieldKeys.forEach(k => toggleMangleField(k, false));
  5708. resetMangleCounterDisplay();
  5709. toggleMangleActionFields();
  5710. document.getElementById('mangle-modal').classList.remove('hidden');
  5711. }
  5712. function openEditMangleModal(id) {
  5713. id = decodeURIComponent(id);
  5714. const r = (state.mangleRules || []).find(rule => rule.id === id);
  5715. if (!r) return;
  5716. switchMangleRuleTab('general');
  5717. const badge = document.getElementById('mangle-modal-badge');
  5718. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  5719. document.getElementById('mangle-modal-id').value = r.id;
  5720. document.getElementById('mangle-modal-family').value = String(r.ip_version || 4);
  5721. document.getElementById('mangle-modal-enabled').checked = !r.disabled;
  5722. document.getElementById('mangle-modal-comment').value = r.comment || '';
  5723. const mangleChain = r.chain || 'prerouting';
  5724. document.getElementById('mangle-modal-chain').value = mangleChain;
  5725. populateChainDropdown('mangle', mangleChain);
  5726. handleMangleChainChange();
  5727. setFirewallActionSelection('mangle', r.action || 'accept');
  5728. if (document.getElementById('mangle-modal-newconnmark')) document.getElementById('mangle-modal-newconnmark').value = r.new_connection_mark || '';
  5729. if (document.getElementById('mangle-modal-newroutingmark')) document.getElementById('mangle-modal-newroutingmark').value = r.new_routing_mark || '';
  5730. if (document.getElementById('mangle-modal-newpktmark')) document.getElementById('mangle-modal-newpktmark').value = r.new_packet_mark || '';
  5731. if (document.getElementById('mangle-modal-newmss')) document.getElementById('mangle-modal-newmss').value = r.new_mss || '';
  5732. if (document.getElementById('mangle-modal-newdscp')) document.getElementById('mangle-modal-newdscp').value = r.new_dscp != null ? r.new_dscp : '';
  5733. if (document.getElementById('mangle-modal-newttl')) document.getElementById('mangle-modal-newttl').value = r.new_ttl || '';
  5734. if (document.getElementById('mangle-modal-newpriority')) document.getElementById('mangle-modal-newpriority').value = r.new_priority || '';
  5735. if (document.getElementById('mangle-modal-route')) document.getElementById('mangle-modal-route').value = r.route || '';
  5736. if (document.getElementById('mangle-modal-sniff')) document.getElementById('mangle-modal-sniff').value = r.sniff_target || '';
  5737. if (document.getElementById('mangle-modal-jumptarget')) document.getElementById('mangle-modal-jumptarget').value = r.jump_target || '';
  5738. if (document.getElementById('mangle-modal-action-addrlist')) document.getElementById('mangle-modal-action-addrlist').value = r.address_list || '';
  5739. if (document.getElementById('mangle-modal-action-timeout')) document.getElementById('mangle-modal-action-timeout').value = r.address_list_timeout || '';
  5740. if (document.getElementById('mangle-modal-passthrough')) document.getElementById('mangle-modal-passthrough').checked = r.passthrough ?? true;
  5741. if (document.getElementById('mangle-modal-log')) document.getElementById('mangle-modal-log').checked = !!r.log;
  5742. populateInterfaceSelect('mangle-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  5743. populateInterfaceSelect('mangle-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  5744. populateAddressListSelect('mangle-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  5745. populateAddressListSelect('mangle-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  5746. populateGeoIPSelect('mangle-val-srcgeo', r.src_geoip || '');
  5747. populateGeoIPSelect('mangle-val-dstgeo', r.dst_geoip || '');
  5748. setMangleFieldVal('src', r.src_address, true);
  5749. setMangleFieldVal('dst', r.dst_address, true);
  5750. setMangleFieldVal('srclist', r.src_address_list, true);
  5751. setMangleFieldVal('dstlist', r.dst_address_list, true);
  5752. setMangleFieldVal('srcgeo', r.src_geoip, true);
  5753. setMangleFieldVal('dstgeo', r.dst_geoip, true);
  5754. if (r.protocol && r.protocol !== 'all') {
  5755. setMangleFieldVal('proto', r.protocol, true);
  5756. } else {
  5757. toggleMangleField('proto', false);
  5758. }
  5759. setMangleFieldVal('sport', r.src_port, true);
  5760. setMangleFieldVal('dport', r.dst_port, true);
  5761. setMangleFieldVal('anyport', r.any_port, true);
  5762. setMangleFieldVal('iniface', r.in_interface, true);
  5763. setMangleFieldVal('outiface', r.out_interface, true);
  5764. setMangleFieldVal('inifacelist', r.in_interface_list, true);
  5765. setMangleFieldVal('outifacelist', r.out_interface_list, true);
  5766. setMangleFieldVal('pktmark', r.packet_mark, true);
  5767. setMangleFieldVal('connmark', r.connection_mark, true);
  5768. setMangleFieldVal('routingmark', r.routing_mark, true);
  5769. setMangleFieldVal('conntype', r.connection_type, false);
  5770. // Connection State
  5771. const states = r.connection_state || [];
  5772. if (states.length > 0) {
  5773. toggleMangleField('cs', true);
  5774. ['established', 'related', 'new', 'invalid', 'untracked'].forEach(s => {
  5775. const el = document.getElementById(`mangle-modal-cs-${s}`);
  5776. if (el) el.checked = states.includes(s);
  5777. });
  5778. } else {
  5779. toggleMangleField('cs', false);
  5780. }
  5781. // Connection NAT State
  5782. const natStates = r.connection_nat_state || [];
  5783. if (natStates.length > 0) {
  5784. toggleMangleField('natstate', true);
  5785. ['srcnat', 'dstnat'].forEach(s => {
  5786. const el = document.getElementById(`mangle-modal-nat-${s}`);
  5787. if (el) el.checked = natStates.includes(s);
  5788. });
  5789. } else {
  5790. toggleMangleField('natstate', false);
  5791. }
  5792. // Advanced tab fields
  5793. setMangleFieldVal('layer7', r.layer7_protocol, false);
  5794. setMangleFieldVal('content', r.content, false);
  5795. setMangleFieldVal('connbytes', r.connection_bytes, false);
  5796. setMangleFieldVal('connrate', r.connection_rate, false);
  5797. setMangleFieldVal('pcc', r.pcc, false);
  5798. setMangleFieldVal('srcmac', r.src_mac_address, true);
  5799. setMangleFieldVal('outbridgeport', r.out_bridge_port, false);
  5800. setMangleFieldVal('inbridgeport', r.in_bridge_port, false);
  5801. setMangleFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  5802. setMangleFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  5803. setMangleFieldVal('ipsec', r.ipsec_policy, false);
  5804. setMangleFieldVal('tlshost', r.tls_host, false);
  5805. setMangleFieldVal('ingresspriority', r.ingress_priority, false);
  5806. setMangleFieldVal('priority', r.priority, false);
  5807. setMangleFieldVal('dscp', r.dscp, false);
  5808. setMangleFieldVal('tcpmss', r.tcp_mss, false);
  5809. { const tosEl = document.getElementById('mangle-val-tos'); if (tosEl) tosEl.value = r.tos || ''; }
  5810. setMangleFieldVal('pktsize', r.packet_size, false);
  5811. setMangleFieldVal('random', r.random, false);
  5812. setMangleFieldVal('tcpflags', r.tcp_flags, false);
  5813. setMangleFieldVal('icmpoptions', r.icmp_options, false);
  5814. setMangleFieldVal('ipv4options', r.ipv4_options, false);
  5815. setMangleFieldVal('ttl', r.ttl, false);
  5816. // Extra tab fields
  5817. setMangleFieldVal('nth', r.nth, false);
  5818. setMangleFieldVal('connlimit', r.connection_limit, false);
  5819. setMangleFieldVal('srcaddrtype', r.src_address_type, false);
  5820. setMangleFieldVal('dstaddrtype', r.dst_address_type, false);
  5821. setMangleFieldVal('hotspot', r.hotspot, false);
  5822. setMangleFieldVal('ipfragment', r.ip_fragment, false);
  5823. setMangleFieldVal('limit', r.limit, false);
  5824. setMangleFieldVal('dstlimit', r.dst_limit, false);
  5825. setMangleFieldVal('time', r.time, false);
  5826. setMangleFieldVal('psd', r.psd, false);
  5827. // Action fields
  5828. if (r.jump_target) {
  5829. const jtEl = document.getElementById('mangle-modal-jumptarget');
  5830. if (jtEl) jtEl.value = r.jump_target;
  5831. }
  5832. if (r.address_list) {
  5833. const alEl = document.getElementById('mangle-modal-action-addrlist');
  5834. if (alEl) alEl.value = r.address_list;
  5835. }
  5836. if (r.address_list_timeout) {
  5837. const toEl = document.getElementById('mangle-modal-action-timeout');
  5838. if (toEl) toEl.value = r.address_list_timeout;
  5839. }
  5840. setMangleFieldVal('logprefix', r.log_prefix, false);
  5841. // Statistics
  5842. const bEl = document.getElementById('mangle-stat-bytes');
  5843. const pEl = document.getElementById('mangle-stat-packets');
  5844. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  5845. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  5846. state.mangleLastBytes = r.bytes || 0;
  5847. state.mangleLastPackets = r.packets || 0;
  5848. state.mangleLastTimestamp = Date.now();
  5849. state.mangleStatRateHistory = new Array(30).fill(0);
  5850. state.mangleStatPktHistory = new Array(30).fill(0);
  5851. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  5852. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  5853. toggleMangleActionFields();
  5854. document.getElementById('mangle-modal').classList.remove('hidden');
  5855. }
  5856. function closeMangleModal() {
  5857. stopMangleStatPolling();
  5858. document.getElementById('mangle-modal').classList.add('hidden');
  5859. }
  5860. function copyMangleRule() {
  5861. document.getElementById('mangle-modal-id').value = '';
  5862. const badge = document.getElementById('mangle-modal-badge');
  5863. if (badge) badge.innerText = 'New...';
  5864. showToast('Rule Cloned', 'Ready to save as a new Mangle rule copy', 'info');
  5865. }
  5866. function resetMangleCounterDisplay() {
  5867. state.mangleStatRateHistory = new Array(30).fill(0);
  5868. state.mangleStatPktHistory = new Array(30).fill(0);
  5869. state.mangleLastBytes = 0;
  5870. state.mangleLastPackets = 0;
  5871. state.mangleLastTimestamp = Date.now();
  5872. const bEl = document.getElementById('mangle-stat-bytes');
  5873. const pEl = document.getElementById('mangle-stat-packets');
  5874. const rEl = document.getElementById('mangle-stat-rate');
  5875. const prEl = document.getElementById('mangle-stat-pktrate');
  5876. if (bEl) bEl.value = '0 B';
  5877. if (pEl) pEl.value = '0';
  5878. if (rEl) rEl.value = '0 bps';
  5879. if (prEl) prEl.value = '0 p/s';
  5880. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  5881. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  5882. showToast('Counters Reset', 'Mangle rule counter display reset to 0', 'info');
  5883. }
  5884. async function applyMangleRule(closeAfter = false) {
  5885. const id = document.getElementById('mangle-modal-id').value;
  5886. if (!reviewLegacyFirewallSettings('mangle', id)) return;
  5887. const chain = (document.getElementById('mangle-modal-chain').value || '').trim();
  5888. const chainLower = chain.toLowerCase();
  5889. const action = document.getElementById('mangle-modal-action').value;
  5890. const comment = document.getElementById('mangle-modal-comment').value.trim();
  5891. const enabled = document.getElementById('mangle-modal-enabled').checked;
  5892. const src = getMangleFieldVal('src', true);
  5893. const dst = getMangleFieldVal('dst', true);
  5894. const srclist = getMangleFieldVal('srclist', true);
  5895. const dstlist = getMangleFieldVal('dstlist', true);
  5896. const srcgeo = getMangleFieldVal('srcgeo', true);
  5897. const dstgeo = getMangleFieldVal('dstgeo', true);
  5898. const proto = getMangleFieldVal('proto', true);
  5899. const sport = getMangleFieldVal('sport', true);
  5900. const dport = getMangleFieldVal('dport', true);
  5901. const anyport = getMangleFieldVal('anyport', true);
  5902. if ((sport || dport || anyport) && !['tcp', 'udp'].includes(proto)) {
  5903. switchMangleRuleTab('general'); toggleMangleField('proto', true);
  5904. showToast('Select protocol', 'Port matches require TCP or UDP without protocol inversion.', 'error'); document.getElementById('mangle-val-proto').focus(); return;
  5905. }
  5906. let iniface = getMangleFieldVal('iniface', true);
  5907. let outiface = getMangleFieldVal('outiface', true);
  5908. let inifacelist = getMangleFieldVal('inifacelist', true);
  5909. let outifacelist = getMangleFieldVal('outifacelist', true);
  5910. if (chainLower === 'prerouting' || chainLower === 'input') {
  5911. outiface = '';
  5912. outifacelist = '';
  5913. } else if (chainLower === 'output' || chainLower === 'postrouting') {
  5914. iniface = '';
  5915. inifacelist = '';
  5916. }
  5917. if (!chain) { switchMangleRuleTab('general'); showToast('Mangle rule', 'Enter a chain.', 'error'); document.getElementById('mangle-modal-chain').focus(); return; }
  5918. if (action === 'set-priority' && chainLower !== 'postrouting') {
  5919. switchMangleRuleTab('general');
  5920. showToast('Invalid Target for Chain', 'CLASSIFY (set-priority) requires POSTROUTING chain in iptables.', 'error');
  5921. return;
  5922. }
  5923. const pktmark = getMangleFieldVal('pktmark', true);
  5924. const connmark = getMangleFieldVal('connmark', true);
  5925. const routingmark = getMangleFieldVal('routingmark', true);
  5926. const conntype = getMangleFieldVal('conntype', false);
  5927. const states = [];
  5928. const csBox = document.getElementById('mangle-field-cs');
  5929. if (csBox && !csBox.classList.contains('hidden')) {
  5930. ['established', 'related', 'new', 'invalid', 'untracked'].forEach(s => {
  5931. if (document.getElementById(`mangle-modal-cs-${s}`)?.checked) states.push(s);
  5932. });
  5933. }
  5934. const natStates = [];
  5935. const natBox = document.getElementById('mangle-field-natstate');
  5936. if (natBox && !natBox.classList.contains('hidden')) {
  5937. ['srcnat', 'dstnat'].forEach(s => {
  5938. if (document.getElementById(`mangle-modal-nat-${s}`)?.checked) natStates.push(s);
  5939. });
  5940. }
  5941. const payload = {
  5942. ip_version: Number(document.getElementById('mangle-modal-family').value),
  5943. id,
  5944. chain,
  5945. action,
  5946. protocol: proto || 'all',
  5947. src_address: src,
  5948. dst_address: dst,
  5949. src_port: sport,
  5950. dst_port: dport,
  5951. any_port: anyport,
  5952. in_interface: iniface,
  5953. out_interface: outiface,
  5954. in_interface_list: inifacelist,
  5955. out_interface_list: outifacelist,
  5956. packet_mark: pktmark,
  5957. connection_mark: connmark,
  5958. routing_mark: routingmark,
  5959. connection_type: conntype,
  5960. connection_state: states,
  5961. connection_nat_state: natStates,
  5962. src_address_list: srclist,
  5963. dst_address_list: dstlist,
  5964. src_geoip: srcgeo,
  5965. dst_geoip: dstgeo,
  5966. comment,
  5967. disabled: !enabled,
  5968. // Advanced tab
  5969. content: getMangleFieldVal('content', false),
  5970. src_mac_address: (chainLower === 'output' || chainLower === 'postrouting') ? '' : getMangleFieldVal('srcmac', true),
  5971. out_bridge_port: (chainLower === 'input' || chainLower === 'prerouting') ? '' : getMangleFieldVal('outbridgeport', false),
  5972. in_bridge_port: (chainLower === 'output' || chainLower === 'postrouting') ? '' : getMangleFieldVal('inbridgeport', false),
  5973. ipsec_policy: getMangleFieldVal('ipsec', false),
  5974. dscp: getMangleFieldVal('dscp', false),
  5975. tcp_mss: getMangleFieldVal('tcpmss', false),
  5976. tos: document.getElementById('mangle-val-tos')?.value || '',
  5977. packet_size: getMangleFieldVal('pktsize', false),
  5978. random: getMangleFieldVal('random', false),
  5979. tcp_flags: getMangleFieldVal('tcpflags', false),
  5980. icmp_options: getMangleFieldVal('icmpoptions', false),
  5981. ttl: getMangleFieldVal('ttl', false),
  5982. // Extra tab
  5983. nth: getMangleFieldVal('nth', false),
  5984. connection_limit: getMangleFieldVal('connlimit', false),
  5985. src_address_type: getMangleFieldVal('srcaddrtype', false),
  5986. dst_address_type: getMangleFieldVal('dstaddrtype', false),
  5987. ip_fragment: getMangleFieldVal('ipfragment', false),
  5988. limit: getMangleFieldVal('limit', false),
  5989. time: getMangleFieldVal('time', false),
  5990. // Action tab
  5991. new_connection_mark: action === 'mark-connection' ? (document.getElementById('mangle-modal-newconnmark')?.value.trim() || '') : '',
  5992. new_routing_mark: action === 'mark-routing' ? (document.getElementById('mangle-modal-newroutingmark')?.value.trim() || '') : '',
  5993. new_packet_mark: action === 'mark-packet' ? (document.getElementById('mangle-modal-newpktmark')?.value.trim() || '') : '',
  5994. new_mss: action === 'change-mss' ? (document.getElementById('mangle-modal-newmss')?.value.trim() || '') : '',
  5995. new_dscp: action === 'change-dscp' ? parseInt(document.getElementById('mangle-modal-newdscp')?.value || '0', 10) : 0,
  5996. new_ttl: action === 'change-ttl' ? (document.getElementById('mangle-modal-newttl')?.value.trim() || '') : '',
  5997. new_priority: action === 'set-priority' ? (document.getElementById('mangle-modal-newpriority')?.value.trim() || '') : '',
  5998. passthrough: document.getElementById('mangle-modal-passthrough')?.checked ?? true,
  5999. jump_target: action === 'jump' ? (document.getElementById('mangle-modal-jumptarget')?.value || '') : '',
  6000. address_list: action.includes('address') ? (document.getElementById('mangle-modal-action-addrlist')?.value || '') : '',
  6001. address_list_timeout: action.includes('address') ? (document.getElementById('mangle-modal-action-timeout')?.value || '') : '',
  6002. log: document.getElementById('mangle-modal-log')?.checked || false,
  6003. log_prefix: getMangleFieldVal('logprefix', false)
  6004. };
  6005. try {
  6006. const res = await fetch(`${API_BASE}/firewall/mangle`, {
  6007. method: 'POST',
  6008. headers: { 'Content-Type': 'application/json' },
  6009. body: JSON.stringify(payload)
  6010. });
  6011. if (res.ok) {
  6012. const data = await res.json();
  6013. showToast('Mangle Rule Saved', 'Marking rule updated', 'success');
  6014. loadFirewall(false);
  6015. if (closeAfter) {
  6016. closeMangleModal();
  6017. } else {
  6018. if (data.id) {
  6019. document.getElementById('mangle-modal-id').value = data.id;
  6020. const badge = document.getElementById('mangle-modal-badge');
  6021. if (badge) badge.innerText = `#${data.id}`;
  6022. }
  6023. }
  6024. } else {
  6025. const err = await res.json();
  6026. showToast('Error', err.message || 'Failed to save mangle rule', 'error');
  6027. }
  6028. } catch (err) {
  6029. showToast('Error', err.message, 'error');
  6030. }
  6031. }
  6032. function submitSaveMangleRule(e) {
  6033. if (e && e.preventDefault) e.preventDefault();
  6034. return applyMangleRule(true);
  6035. }
  6036. function startMangleStatPolling() {
  6037. stopMangleStatPolling();
  6038. pollMangleRuleStats();
  6039. state.mangleStatInterval = setInterval(pollMangleRuleStats, 1000);
  6040. }
  6041. function stopMangleStatPolling() {
  6042. if (state.mangleStatInterval) {
  6043. clearInterval(state.mangleStatInterval);
  6044. state.mangleStatInterval = null;
  6045. }
  6046. }
  6047. async function pollMangleRuleStats() {
  6048. const id = document.getElementById('mangle-modal-id')?.value;
  6049. if (!id) {
  6050. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory || new Array(30).fill(0), 'bps', 'mangle-stat-legend-rate');
  6051. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory || new Array(30).fill(0), 'p/s', 'mangle-stat-legend-pktrate');
  6052. return;
  6053. }
  6054. try {
  6055. const res = await fetch(`${API_BASE}/firewall/mangle`);
  6056. if (!res.ok) return;
  6057. const rules = await res.json();
  6058. const r = rules.find(x => x.id === id);
  6059. if (!r) return;
  6060. const now = Date.now();
  6061. const dt = Math.max(0.2, (now - (state.mangleLastTimestamp || now)) / 1000);
  6062. state.mangleLastTimestamp = now;
  6063. const curBytes = r.bytes || 0;
  6064. const curPackets = r.packets || 0;
  6065. const deltaBytes = Math.max(0, curBytes - (state.mangleLastBytes ?? curBytes));
  6066. const deltaPkts = Math.max(0, curPackets - (state.mangleLastPackets ?? curPackets));
  6067. state.mangleLastBytes = curBytes;
  6068. state.mangleLastPackets = curPackets;
  6069. const rateBps = Math.round((deltaBytes * 8) / dt);
  6070. const ratePkt = Math.round(deltaPkts / dt);
  6071. if (!state.mangleStatRateHistory) state.mangleStatRateHistory = new Array(30).fill(0);
  6072. if (!state.mangleStatPktHistory) state.mangleStatPktHistory = new Array(30).fill(0);
  6073. state.mangleStatRateHistory.push(rateBps);
  6074. if (state.mangleStatRateHistory.length > 30) state.mangleStatRateHistory.shift();
  6075. state.mangleStatPktHistory.push(ratePkt);
  6076. if (state.mangleStatPktHistory.length > 30) state.mangleStatPktHistory.shift();
  6077. const bEl = document.getElementById('mangle-stat-bytes');
  6078. const pEl = document.getElementById('mangle-stat-packets');
  6079. const rEl = document.getElementById('mangle-stat-rate');
  6080. const prEl = document.getElementById('mangle-stat-pktrate');
  6081. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  6082. if (pEl) pEl.value = curPackets.toLocaleString();
  6083. if (rEl) rEl.value = formatBps(rateBps);
  6084. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  6085. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  6086. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  6087. } catch (e) {
  6088. console.error('Error polling Mangle rule stats', e);
  6089. }
  6090. }
  6091. async function moveMangleRule(id, dir) {
  6092. id = decodeURIComponent(id);
  6093. try {
  6094. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/move`, {
  6095. method: 'POST',
  6096. headers: { 'Content-Type': 'application/json' },
  6097. body: JSON.stringify({ direction: dir })
  6098. });
  6099. if (!res.ok) throw new Error(await responseError(res));
  6100. await loadFirewall(false);
  6101. } catch (err) {
  6102. showToast('Error', err.message, 'error');
  6103. }
  6104. }
  6105. async function toggleMangleRuleState(id, disabled) {
  6106. id = decodeURIComponent(id);
  6107. try {
  6108. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/state`, {
  6109. method: 'POST',
  6110. headers: { 'Content-Type': 'application/json' },
  6111. body: JSON.stringify({ disabled })
  6112. });
  6113. if (!res.ok) throw new Error(await responseError(res));
  6114. await loadFirewall(false);
  6115. } catch (err) {
  6116. showToast('Error', err.message, 'error');
  6117. }
  6118. }
  6119. async function deleteMangleRule(id) {
  6120. id = decodeURIComponent(id);
  6121. if (!confirm('Are you sure you want to delete this mangle rule?')) return;
  6122. try {
  6123. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6124. if (!res.ok) throw new Error(await responseError(res));
  6125. {
  6126. showToast('Deleted', 'Mangle rule removed', 'success');
  6127. loadFirewall(false);
  6128. }
  6129. } catch (err) {
  6130. showToast('Error', err.message, 'error');
  6131. }
  6132. }
  6133. // ----------------- Address Lists -----------------
  6134. function renderAddressLists() {
  6135. const filterList = document.getElementById('addrlist-filter-name')?.value || '';
  6136. const tbody = document.getElementById('addrlist-table-body');
  6137. const empty = document.getElementById('addrlist-empty');
  6138. if (!tbody) return;
  6139. tbody.innerHTML = '';
  6140. const entries = (state.addressLists || []).filter(e => !filterList || e.name === filterList);
  6141. document.getElementById('addrlist-count-badge').innerText = `${entries.length} Entries${entries.filter(e => e.dynamic).length >= 2000 ? ' (dynamic results capped at 2000)' : ''}`;
  6142. // Update filter select
  6143. const sel = document.getElementById('addrlist-filter-name');
  6144. if (sel) {
  6145. const cur = sel.value;
  6146. sel.innerHTML = '<option value="">All Lists</option>';
  6147. const set = new Set((state.addressLists || []).map(a => a.name));
  6148. set.forEach(n => {
  6149. const opt = document.createElement('option');
  6150. opt.value = n;
  6151. opt.innerText = n;
  6152. if (n === cur) opt.selected = true;
  6153. sel.appendChild(opt);
  6154. });
  6155. }
  6156. if (entries.length === 0) {
  6157. empty?.classList.remove('hidden');
  6158. return;
  6159. }
  6160. empty?.classList.add('hidden');
  6161. entries.forEach((raw, idx) => {
  6162. const e = safeFirewallRow(raw);
  6163. const tr = document.createElement('tr');
  6164. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${e.disabled ? 'opacity-50' : ''}`;
  6165. if (!e.dynamic) tr.setAttribute('ondblclick', `openEditAddrListModal('${e.id}')`);
  6166. tr.innerHTML = `
  6167. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  6168. <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>
  6169. <td class="py-2.5 px-3 font-bold text-white font-mono">${e.name}</td>
  6170. <td class="py-2.5 px-3 font-mono font-bold text-emerald-400">${e.address}</td>
  6171. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[150px]">${e.dynamic ? 'Dynamic · '+(e.timeout ? e.timeout+'s remaining' : 'no expiry') : e.comment || '-'}</td>
  6172. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  6173. ${e.dynamic ? '' : ` <button onclick="toggleAddrListState('${e.id}', ${!e.disabled})" class="text-xs ${e.disabled ? 'text-emerald-400' : 'text-slate-400'} hover:underline">${e.disabled ? 'Enable' : 'Disable'}</button>
  6174. <button onclick="openEditAddrListModal('${e.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-medium">Edit</button>
  6175. `}
  6176. <button onclick="deleteAddrList('${e.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  6177. </td>
  6178. `;
  6179. tbody.appendChild(tr);
  6180. });
  6181. populateCommonAddrListDatalist();
  6182. }
  6183. function openAddAddrListModal() {
  6184. document.getElementById('addrlist-modal-title').innerText = 'Add Address List Entry';
  6185. document.getElementById('addrlist-modal-id').value = '';
  6186. document.getElementById('addrlist-modal-name').value = '';
  6187. document.getElementById('addrlist-modal-addr').value = '';
  6188. document.getElementById('addrlist-modal-comment').value = '';
  6189. document.getElementById('addrlist-modal-disabled').checked = false;
  6190. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  6191. if (submitBtn) submitBtn.innerText = 'Add to List';
  6192. document.getElementById('addrlist-modal').classList.remove('hidden');
  6193. }
  6194. function openEditAddrListModal(id) {
  6195. id = decodeURIComponent(id);
  6196. const e = (state.addressLists || []).find(item => item.id === id);
  6197. if (!e) return;
  6198. document.getElementById('addrlist-modal-title').innerText = `Edit Address List Entry: ${e.name}`;
  6199. document.getElementById('addrlist-modal-id').value = e.id;
  6200. document.getElementById('addrlist-modal-name').value = e.name;
  6201. document.getElementById('addrlist-modal-addr').value = e.address;
  6202. document.getElementById('addrlist-modal-comment').value = e.comment || '';
  6203. document.getElementById('addrlist-modal-disabled').checked = !!e.disabled;
  6204. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  6205. if (submitBtn) submitBtn.innerText = 'Save Changes';
  6206. document.getElementById('addrlist-modal').classList.remove('hidden');
  6207. }
  6208. function closeAddrListModal() {
  6209. document.getElementById('addrlist-modal').classList.add('hidden');
  6210. }
  6211. async function submitSaveAddrList(e) {
  6212. e.preventDefault();
  6213. const id = document.getElementById('addrlist-modal-id').value;
  6214. const name = document.getElementById('addrlist-modal-name').value.trim();
  6215. const addr = document.getElementById('addrlist-modal-addr').value.trim();
  6216. const comment = document.getElementById('addrlist-modal-comment').value.trim();
  6217. const disabled = document.getElementById('addrlist-modal-disabled').checked;
  6218. try {
  6219. const res = await fetch(`${API_BASE}/firewall/address-lists`, {
  6220. method: 'POST',
  6221. headers: { 'Content-Type': 'application/json' },
  6222. body: JSON.stringify({ id, name, address: addr, comment, disabled })
  6223. });
  6224. if (res.ok) {
  6225. showToast('Address List Item Saved', `Saved ${addr} in ${name}`, 'success');
  6226. closeAddrListModal();
  6227. loadFirewall(false);
  6228. } else {
  6229. const err = await res.json();
  6230. showToast('Error', err.message || 'Failed to save address list', 'error');
  6231. }
  6232. } catch (err) {
  6233. showToast('Error', err.message, 'error');
  6234. }
  6235. }
  6236. async function toggleAddrListState(id, disabled) {
  6237. id = decodeURIComponent(id);
  6238. try {
  6239. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}/state`, {
  6240. method: 'POST',
  6241. headers: { 'Content-Type': 'application/json' },
  6242. body: JSON.stringify({ disabled })
  6243. });
  6244. if (res.ok) {
  6245. loadFirewall(false);
  6246. }
  6247. } catch (err) {
  6248. showToast('Error', err.message, 'error');
  6249. }
  6250. }
  6251. async function deleteAddrList(id) {
  6252. id = decodeURIComponent(id);
  6253. if (!confirm('Are you sure you want to delete this address list item?')) return;
  6254. try {
  6255. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6256. if (res.ok) {
  6257. showToast('Deleted', 'Address list item removed', 'info');
  6258. loadFirewall(false);
  6259. }
  6260. } catch (err) {
  6261. showToast('Error', err.message, 'error');
  6262. }
  6263. }
  6264. // ----------------- Geo-Location IP Management -----------------
  6265. async function loadGeoIP() {
  6266. try {
  6267. const [statusRes, countriesRes] = await Promise.all([
  6268. fetch(`${API_BASE}/firewall/geoip/status`),
  6269. fetch(`${API_BASE}/firewall/geoip/countries`)
  6270. ]);
  6271. if (statusRes.ok) state.geoStatus = await statusRes.json();
  6272. if (countriesRes.ok) state.geoCountries = await countriesRes.json();
  6273. updateGeoHeader();
  6274. renderGeoCountries();
  6275. } catch (err) {
  6276. console.error('Failed to load GeoIP:', err);
  6277. }
  6278. }
  6279. function getGeoUsageMap() {
  6280. const usage = {};
  6281. const checkRule = (r, type) => {
  6282. ['src_geoip', 'dst_geoip'].forEach(field => {
  6283. let val = (r && r[field]) || '';
  6284. let code = val.replace(/^!/, '').replace(/^geo:/, '').replace(/^geo_/, '').toUpperCase().trim();
  6285. if (code) {
  6286. if (!usage[code]) usage[code] = [];
  6287. const label = `${type} #${r.priority !== undefined ? r.priority : (r.id || '')}`;
  6288. if (!usage[code].includes(label)) usage[code].push(label);
  6289. }
  6290. });
  6291. };
  6292. (state.filterRules || []).forEach(r => checkRule(r, 'Filter'));
  6293. (state.natRules || []).forEach(r => checkRule(r, 'NAT'));
  6294. (state.mangleRules || []).forEach(r => checkRule(r, 'Mangle'));
  6295. return usage;
  6296. }
  6297. function updateGeoHeader() {
  6298. const s = state.geoStatus || {};
  6299. const statusBadge = document.getElementById('geo-status-badge');
  6300. if (statusBadge) {
  6301. statusBadge.innerText = s.auto_update ? 'Auto-Update ON' : 'Auto-Update OFF';
  6302. statusBadge.className = s.auto_update
  6303. ? 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-emerald-500/20 text-emerald-300 border border-emerald-500/30'
  6304. : 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 text-slate-400';
  6305. }
  6306. const intervalLabel = document.getElementById('geo-interval-label');
  6307. if (intervalLabel) {
  6308. intervalLabel.innerText = `Every ${s.interval_hours || 24}h`;
  6309. }
  6310. const usageMap = getGeoUsageMap();
  6311. const inUseCount = Object.keys(usageMap).length;
  6312. const activeCountEl = document.getElementById('geo-stat-active-countries');
  6313. if (activeCountEl) activeCountEl.innerText = inUseCount.toLocaleString();
  6314. const totalSubnetsEl = document.getElementById('geo-stat-total-subnets');
  6315. if (totalSubnetsEl) totalSubnetsEl.innerText = (s.total_subnets || 0).toLocaleString();
  6316. const lastSyncEl = document.getElementById('geo-stat-last-sync');
  6317. if (lastSyncEl) {
  6318. if (s.last_updated && !s.last_updated.startsWith('0001')) {
  6319. const d = new Date(s.last_updated);
  6320. lastSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  6321. } else {
  6322. lastSyncEl.innerText = 'Never (Sync Pending)';
  6323. }
  6324. }
  6325. const nextSyncEl = document.getElementById('geo-stat-next-sync');
  6326. if (nextSyncEl) {
  6327. if (s.next_update && !s.next_update.startsWith('0001')) {
  6328. const d = new Date(s.next_update);
  6329. nextSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  6330. } else {
  6331. nextSyncEl.innerText = '-';
  6332. }
  6333. }
  6334. const badge = document.getElementById('fw-badge-geo');
  6335. if (badge) badge.innerText = inUseCount || (state.geoCountries || []).filter(c => c.subnet_count > 0).length || 0;
  6336. }
  6337. function renderGeoCountries() {
  6338. const tbody = document.getElementById('geo-table-body');
  6339. const empty = document.getElementById('geo-empty');
  6340. if (!tbody) return;
  6341. tbody.innerHTML = '';
  6342. const q = (document.getElementById('geo-search-input')?.value || '').trim().toLowerCase();
  6343. const continent = document.getElementById('geo-continent-filter')?.value || '';
  6344. const inUseOnly = document.getElementById('geo-filter-inuse-only')?.checked;
  6345. const cachedOnly = document.getElementById('geo-filter-cached-only')?.checked;
  6346. const usageMap = getGeoUsageMap();
  6347. const countries = (state.geoCountries || []).filter(c => {
  6348. const isUsed = !!usageMap[c.code];
  6349. if (inUseOnly && !isUsed) return false;
  6350. if (cachedOnly && (!c.subnet_count || c.subnet_count === 0)) return false;
  6351. if (continent && c.continent !== continent) return false;
  6352. if (q) {
  6353. const matchCode = c.code.toLowerCase().includes(q);
  6354. const matchName = c.name.toLowerCase().includes(q);
  6355. if (!matchCode && !matchName) return false;
  6356. }
  6357. return true;
  6358. });
  6359. if (countries.length === 0) {
  6360. empty?.classList.remove('hidden');
  6361. return;
  6362. }
  6363. empty?.classList.add('hidden');
  6364. countries.forEach(c => {
  6365. const tr = document.createElement('tr');
  6366. const isUsed = !!usageMap[c.code];
  6367. const rulesUsing = usageMap[c.code] || [];
  6368. tr.className = `hover:bg-slate-800/40 transition text-xs ${isUsed ? 'bg-emerald-950/20' : ''}`;
  6369. let statusHtml = '';
  6370. if (isUsed) {
  6371. 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>`;
  6372. } else if (c.subnet_count > 0) {
  6373. 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>';
  6374. } else {
  6375. statusHtml = '<span class="px-2 py-0.5 rounded text-[10px] font-mono text-slate-500 bg-slate-800/60">READY</span>';
  6376. }
  6377. tr.innerHTML = `
  6378. <td class="py-2.5 px-3 text-center">
  6379. <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'}">
  6380. ${c.code}
  6381. </span>
  6382. </td>
  6383. <td class="py-2.5 px-3 font-bold text-white">${c.name}</td>
  6384. <td class="py-2.5 px-3 text-slate-400">${c.continent}</td>
  6385. <td class="py-2.5 px-3 font-mono ${c.subnet_count > 0 ? 'text-emerald-400 font-bold' : 'text-slate-500'}">
  6386. ${c.subnet_count > 0 ? c.subnet_count.toLocaleString() + ' CIDRs' : 'Not Cached'}
  6387. </td>
  6388. <td class="py-2.5 px-3 font-mono text-purple-300">${c.ipset_name}</td>
  6389. <td class="py-2.5 px-3">
  6390. ${statusHtml}
  6391. </td>
  6392. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  6393. <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>
  6394. <button onclick="viewGeoSubnets('${c.code}')" class="text-xs text-slate-400 hover:text-white" title="Preview Subnet Ranges">View</button>
  6395. </td>
  6396. `;
  6397. tbody.appendChild(tr);
  6398. });
  6399. }
  6400. function quickFilterGeo(preset) {
  6401. const searchInput = document.getElementById('geo-search-input');
  6402. const continentSel = document.getElementById('geo-continent-filter');
  6403. const inUseCheck = document.getElementById('geo-filter-inuse-only');
  6404. const cachedCheck = document.getElementById('geo-filter-cached-only');
  6405. if (searchInput) searchInput.value = '';
  6406. if (continentSel) continentSel.value = '';
  6407. if (inUseCheck) inUseCheck.checked = false;
  6408. if (cachedCheck) cachedCheck.checked = false;
  6409. if (preset === 'GR') {
  6410. if (searchInput) searchInput.value = 'Greece';
  6411. } else if (preset === 'Europe') {
  6412. if (continentSel) continentSel.value = 'Europe';
  6413. } else if (preset === 'HIGHRISK') {
  6414. if (searchInput) searchInput.value = 'China';
  6415. }
  6416. renderGeoCountries();
  6417. }
  6418. async function toggleGeoCountry(code, enabled) {
  6419. try {
  6420. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/toggle`, {
  6421. method: 'POST',
  6422. headers: { 'Content-Type': 'application/json' },
  6423. body: JSON.stringify({ enabled })
  6424. });
  6425. if (res.ok) {
  6426. showToast(enabled ? 'Country Enabled' : 'Country Disabled', `${code} ${enabled ? 'active in firewall' : 'removed from firewall'}`, 'success');
  6427. loadGeoIP();
  6428. } else {
  6429. const err = await res.json();
  6430. showToast('Error', err.message || 'Failed to toggle country', 'error');
  6431. }
  6432. } catch (err) {
  6433. showToast('Error', err.message, 'error');
  6434. }
  6435. }
  6436. async function updateGeoCountry(code) {
  6437. try {
  6438. showToast('Syncing Country', `Downloading latest IP blocks for ${code}...`, 'info');
  6439. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/update`, { method: 'POST' });
  6440. if (res.ok) {
  6441. const data = await res.json();
  6442. showToast('Synced', `Loaded ${data.subnets} CIDR blocks for ${code}`, 'success');
  6443. loadGeoIP();
  6444. } else {
  6445. const err = await res.json();
  6446. showToast('Sync Error', err.message || 'Failed to sync country', 'error');
  6447. }
  6448. } catch (err) {
  6449. showToast('Error', err.message, 'error');
  6450. }
  6451. }
  6452. async function triggerGeoUpdateNow() {
  6453. const spinner = document.getElementById('geo-update-spinner');
  6454. if (spinner) spinner.classList.remove('hidden');
  6455. try {
  6456. const res = await fetch(`${API_BASE}/firewall/geoip/update-now`, { method: 'POST' });
  6457. if (res.ok) {
  6458. showToast('Update Started', 'Updating all active GeoIP country zones in background...', 'info');
  6459. setTimeout(() => {
  6460. loadGeoIP();
  6461. if (spinner) spinner.classList.add('hidden');
  6462. }, 2500);
  6463. } else {
  6464. const err = await res.json();
  6465. showToast('Notice', err.message || 'Update in progress', 'info');
  6466. if (spinner) spinner.classList.add('hidden');
  6467. }
  6468. } catch (err) {
  6469. showToast('Error', err.message, 'error');
  6470. if (spinner) spinner.classList.add('hidden');
  6471. }
  6472. }
  6473. async function applyGeoPreset(preset) {
  6474. try {
  6475. const res = await fetch(`${API_BASE}/firewall/geoip/batch-toggle`, {
  6476. method: 'POST',
  6477. headers: { 'Content-Type': 'application/json' },
  6478. body: JSON.stringify({ preset, enabled: preset !== 'NONE' })
  6479. });
  6480. if (res.ok) {
  6481. showToast('Preset Applied', `Preset ${preset} updated in firewall`, 'success');
  6482. loadGeoIP();
  6483. }
  6484. } catch (err) {
  6485. showToast('Error', err.message, 'error');
  6486. }
  6487. }
  6488. function openGeoIntervalModal() {
  6489. const s = state.geoStatus || {};
  6490. document.getElementById('geo-cfg-autoupdate').checked = s.auto_update !== false;
  6491. const sel = document.getElementById('geo-cfg-interval');
  6492. const customBox = document.getElementById('geo-cfg-custom-box');
  6493. const customHoursInput = document.getElementById('geo-cfg-custom-hours');
  6494. const curHours = s.interval_hours || 24;
  6495. const matchOption = Array.from(sel.options).find(o => parseInt(o.value, 10) === curHours);
  6496. if (matchOption) {
  6497. sel.value = String(curHours);
  6498. customBox.classList.add('hidden');
  6499. } else {
  6500. sel.value = 'custom';
  6501. customHoursInput.value = curHours;
  6502. customBox.classList.remove('hidden');
  6503. }
  6504. document.getElementById('geo-interval-modal').classList.remove('hidden');
  6505. }
  6506. function closeGeoIntervalModal() {
  6507. document.getElementById('geo-interval-modal').classList.add('hidden');
  6508. }
  6509. function toggleCustomGeoInterval() {
  6510. const val = document.getElementById('geo-cfg-interval').value;
  6511. const customBox = document.getElementById('geo-cfg-custom-box');
  6512. if (val === 'custom') {
  6513. customBox.classList.remove('hidden');
  6514. } else {
  6515. customBox.classList.add('hidden');
  6516. }
  6517. }
  6518. async function submitGeoIntervalSettings(e) {
  6519. e.preventDefault();
  6520. const autoUpdate = document.getElementById('geo-cfg-autoupdate').checked;
  6521. const intervalVal = document.getElementById('geo-cfg-interval').value;
  6522. let hours = 24;
  6523. if (intervalVal === 'custom') {
  6524. hours = parseInt(document.getElementById('geo-cfg-custom-hours').value, 10) || 24;
  6525. } else {
  6526. hours = parseInt(intervalVal, 10) || 24;
  6527. }
  6528. try {
  6529. const res = await fetch(`${API_BASE}/firewall/geoip/config`, {
  6530. method: 'POST',
  6531. headers: { 'Content-Type': 'application/json' },
  6532. body: JSON.stringify({ auto_update: autoUpdate, interval_hours: hours })
  6533. });
  6534. if (res.ok) {
  6535. showToast('Schedule Saved', `Auto-update set to every ${hours} hours`, 'success');
  6536. closeGeoIntervalModal();
  6537. loadGeoIP();
  6538. } else {
  6539. const err = await res.json();
  6540. showToast('Error', err.message || 'Failed to save schedule', 'error');
  6541. }
  6542. } catch (err) {
  6543. showToast('Error', err.message, 'error');
  6544. }
  6545. }
  6546. async function viewGeoSubnets(code, name) {
  6547. if (!name) {
  6548. const found = (state.geoCountries || []).find(x => x.code === code);
  6549. name = found ? found.name : code;
  6550. }
  6551. document.getElementById('geo-subnets-title').innerText = `${name} (${code}) Subnets`;
  6552. document.getElementById('geo-subnets-subtitle').innerText = `Kernel IPSet: mk_geo_${code}`;
  6553. const listEl = document.getElementById('geo-subnets-list');
  6554. listEl.innerHTML = '<span class="text-slate-500">Loading subnets...</span>';
  6555. document.getElementById('geo-subnets-modal').classList.remove('hidden');
  6556. try {
  6557. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/subnets`);
  6558. if (res.ok) {
  6559. const data = await res.json();
  6560. const subnets = data.subnets || [];
  6561. if (subnets.length === 0) {
  6562. listEl.innerHTML = '<span class="text-slate-500">No cached subnets found. Click Sync to download this zone.</span>';
  6563. } else {
  6564. listEl.innerHTML = subnets.map(s => `<div>${s}</div>`).join('');
  6565. }
  6566. } else {
  6567. listEl.innerHTML = '<span class="text-rose-400">Failed to load subnets.</span>';
  6568. }
  6569. } catch (err) {
  6570. listEl.innerHTML = `<span class="text-rose-400">Error: ${err.message}</span>`;
  6571. }
  6572. }
  6573. function closeGeoSubnetsModal() {
  6574. document.getElementById('geo-subnets-modal').classList.add('hidden');
  6575. }
  6576. // ----------------- Active Connections Tracking -----------------
  6577. async function loadConnections() {
  6578. try {
  6579. const res = await fetch(`${API_BASE}/firewall/connections`);
  6580. const data = await res.json();
  6581. if (!res.ok) throw new Error(data.message || 'Connection tracking unavailable');
  6582. state.connections = Array.isArray(data) ? data : [];
  6583. document.getElementById('fw-badge-connections').innerText = state.connections.length;
  6584. document.getElementById('conns-count-badge').innerText = `${state.connections.length} Flows`;
  6585. renderConnections();
  6586. } catch (err) {
  6587. console.error('Failed to load connections:', err);
  6588. const badge=document.getElementById('conns-count-badge'); if(badge) badge.textContent='Unavailable: '+err.message;
  6589. }
  6590. }
  6591. function renderConnections() {
  6592. const search = (document.getElementById('conns-search-input')?.value || '').toLowerCase();
  6593. const protoFilter = document.getElementById('conns-filter-proto')?.value || '';
  6594. const tbody = document.getElementById('conns-table-body');
  6595. const empty = document.getElementById('conns-empty');
  6596. if (!tbody) return;
  6597. tbody.innerHTML = '';
  6598. const conns = (state.connections || []).filter(c => {
  6599. if (protoFilter && c.protocol !== protoFilter) return false;
  6600. if (search) {
  6601. const line = `${c.protocol} ${c.src_address} ${c.dst_address} ${c.src_port} ${c.dst_port} ${c.tcp_state} ${c.connection_mark}`.toLowerCase();
  6602. if (!line.includes(search)) return false;
  6603. }
  6604. return true;
  6605. });
  6606. if (conns.length === 0) {
  6607. empty?.classList.remove('hidden');
  6608. return;
  6609. }
  6610. empty?.classList.add('hidden');
  6611. conns.slice(0, 150).forEach(c => {
  6612. const tr = document.createElement('tr');
  6613. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  6614. let stateColor = 'text-slate-400';
  6615. if (c.tcp_state === 'ESTABLISHED') stateColor = 'text-emerald-400 font-bold';
  6616. else if (c.tcp_state === 'TIME_WAIT' || c.tcp_state === 'SYN_SENT') stateColor = 'text-amber-400';
  6617. tr.innerHTML = `
  6618. <td class="py-2.5 px-3 font-bold text-cyan-400">${c.protocol}</td>
  6619. <td class="py-2.5 px-3 font-mono text-white">${c.src_address}:${c.src_port}</td>
  6620. <td class="py-2.5 px-3 font-mono text-white">${c.dst_address}:${c.dst_port}</td>
  6621. <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>
  6622. <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>
  6623. <td class="py-2.5 px-3 font-mono ${stateColor}">${c.tcp_state}</td>
  6624. <td class="py-2.5 px-3 font-mono text-purple-300">${c.connection_mark || '-'}</td>
  6625. <td class="py-2.5 px-3 text-slate-500">${c.timeout ? c.timeout + 's' : '-'}</td>
  6626. <td class="py-2.5 px-3 text-right font-sans">
  6627. ${['TCP','UDP','SCTP','DCCP','ICMP','ICMPV6'].includes(c.protocol) ? ` <button onclick="killConnection('${c.protocol}', '${c.src_address}', ${c.src_port}, '${c.dst_address}', ${c.dst_port}, ${c.ip_version || 4}, ${c.zone || 0}, ${c.icmp_id ?? 'null'}, ${c.icmp_type ?? 'null'}, ${c.icmp_code ?? 'null'})" class="text-xs text-rose-400 hover:text-rose-300">Kill</button>` : ''}
  6628. </td>
  6629. `;
  6630. tbody.appendChild(tr);
  6631. });
  6632. }
  6633. async function killConnection(protocol, src, sport, dst, dport, ip_version, zone, icmp_id, icmp_type, icmp_code) {
  6634. try {
  6635. const res = await fetch(`${API_BASE}/firewall/connections/kill`, {
  6636. method: 'POST',
  6637. headers: { 'Content-Type': 'application/json' },
  6638. body: JSON.stringify({ protocol, src, sport, dst, dport, ip_version, zone, icmp_id, icmp_type, icmp_code })
  6639. });
  6640. if (res.ok) {
  6641. showToast('Terminated', `Killed flow ${src}:${sport} -> ${dst}:${dport}`, 'info');
  6642. loadConnections();
  6643. } else { const error = await res.json(); showToast('Error', error.message || 'Unable to terminate this flow', 'error'); }
  6644. } catch (err) {
  6645. showToast('Error', err.message, 'error');
  6646. }
  6647. }
  6648. async function resetFirewallCounters() {
  6649. if (!confirm('Reset all firewall packet and byte counters to zero?')) return;
  6650. try {
  6651. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  6652. if (res.ok) {
  6653. showToast('Counters Reset', 'All rules counters reset to 0', 'success');
  6654. loadFirewall(false);
  6655. }
  6656. } catch (err) {
  6657. showToast('Error', err.message, 'error');
  6658. }
  6659. }
  6660. // ======================== MIKROTIK ROUTING & POLICY (/ip route) ========================
  6661. function switchRoutesSubTab(tab) {
  6662. state.routesSubTab = tab;
  6663. const tabs = ['routes', 'rules', 'tables'];
  6664. tabs.forEach(t => {
  6665. const panel = document.getElementById(`routes-subtab-${t}`);
  6666. const btn = document.getElementById(`routes-subtab-btn-${t}`);
  6667. if (panel) {
  6668. if (t === tab) panel.classList.remove('hidden');
  6669. else panel.classList.add('hidden');
  6670. }
  6671. if (btn) {
  6672. if (t === tab) {
  6673. 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';
  6674. } else {
  6675. 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';
  6676. }
  6677. }
  6678. });
  6679. setTimeout(initTableSorting, 50);
  6680. }
  6681. async function loadRoutes() {
  6682. try {
  6683. const [routesRes, rulesRes, tablesRes] = await Promise.all([
  6684. fetch(`${API_BASE}/routes`),
  6685. fetch(`${API_BASE}/routing/rules`),
  6686. fetch(`${API_BASE}/routing/tables`)
  6687. ]);
  6688. if (routesRes.ok) state.routes = await routesRes.json();
  6689. if (rulesRes.ok) state.policyRules = await rulesRes.json();
  6690. if (tablesRes.ok) state.routingTables = await tablesRes.json();
  6691. const bRoutes = document.getElementById('routes-badge-routes');
  6692. if (bRoutes) bRoutes.innerText = (state.routes || []).length;
  6693. const showSystem = document.getElementById('prule-show-system')?.checked;
  6694. const userRules = (state.policyRules || []).filter(pr => showSystem || (!pr.is_default && !pr.is_system));
  6695. const bRules = document.getElementById('routes-badge-rules');
  6696. if (bRules) bRules.innerText = userRules.length;
  6697. const bTables = document.getElementById('routes-badge-tables');
  6698. if (bTables) bTables.innerText = (state.routingTables || []).length;
  6699. const bRoutesCount = document.getElementById('badge-routes-count');
  6700. if (bRoutesCount) bRoutesCount.innerText = (state.routes || []).length;
  6701. renderRoutesList();
  6702. renderPolicyRules();
  6703. renderRoutingTables();
  6704. } catch (err) {
  6705. console.error('Failed to load routing:', err);
  6706. }
  6707. }
  6708. function getRouteProtocolBadge(proto) {
  6709. const p = (proto || 'static').toLowerCase();
  6710. switch (p) {
  6711. case 'bgp':
  6712. 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>`;
  6713. case 'ibgp':
  6714. 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>`;
  6715. case 'ospf':
  6716. 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>`;
  6717. case 'rip':
  6718. 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>`;
  6719. case 'babel':
  6720. return `<span class="px-2 py-0.5 rounded text-[10px] font-bold font-mono uppercase bg-teal-500/20 text-teal-300 border border-teal-500/30">babel</span>`;
  6721. case 'eigrp':
  6722. 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">eigrp</span>`;
  6723. case 'static':
  6724. 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>`;
  6725. case 'connected':
  6726. 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>`;
  6727. case 'dhcp':
  6728. 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>`;
  6729. case 'multicast':
  6730. 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>`;
  6731. default:
  6732. 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>`;
  6733. }
  6734. }
  6735. function renderRoutesList() {
  6736. const tableFilter = document.getElementById('routes-filter-table')?.value || '';
  6737. const typeFilter = document.getElementById('routes-filter-type')?.value || '';
  6738. const tbody = document.getElementById('routes-table-body');
  6739. const empty = document.getElementById('routes-empty');
  6740. if (!tbody) return;
  6741. // Update table filter select
  6742. const sel = document.getElementById('routes-filter-table');
  6743. if (sel) {
  6744. const cur = sel.value;
  6745. sel.innerHTML = '<option value="">All Tables</option>';
  6746. (state.routingTables || []).forEach(t => {
  6747. const opt = document.createElement('option');
  6748. opt.value = t.name;
  6749. opt.innerText = t.name;
  6750. if (t.name === cur) opt.selected = true;
  6751. sel.appendChild(opt);
  6752. });
  6753. }
  6754. const routes = (state.routes || []).filter(r => {
  6755. if (tableFilter && r.routing_table !== tableFilter) return false;
  6756. if (typeFilter === 'ecmp' && !r.ecmp) return false;
  6757. if (typeFilter === 'multicast' && !r.multicast) return false;
  6758. if (typeFilter === 'static' && !r.static) return false;
  6759. if (typeFilter === 'dynamic' && !r.dynamic) return false;
  6760. if (typeFilter === 'connected' && !r.connect) return false;
  6761. if (typeFilter === 'bgp' && (r.protocol || '').toLowerCase() !== 'bgp' && (r.protocol || '').toLowerCase() !== 'ibgp') return false;
  6762. if (typeFilter === 'ospf' && (r.protocol || '').toLowerCase() !== 'ospf') return false;
  6763. if (typeFilter === 'dhcp' && (r.protocol || '').toLowerCase() !== 'dhcp') return false;
  6764. return true;
  6765. });
  6766. const ecmpCount = (state.routes || []).filter(r => r.ecmp).length;
  6767. const mcCount = (state.routes || []).filter(r => r.multicast).length;
  6768. let summaryText = `${routes.length} Routes`;
  6769. if (ecmpCount > 0) summaryText += ` • ${ecmpCount} ECMP`;
  6770. if (mcCount > 0) summaryText += ` • ${mcCount} Multicast/IGMP`;
  6771. const badgeEl = document.getElementById('routes-count-badge');
  6772. if (badgeEl) badgeEl.innerText = summaryText;
  6773. if (routes.length === 0) {
  6774. empty?.classList.remove('hidden');
  6775. tbody.innerHTML = '';
  6776. return;
  6777. }
  6778. empty?.classList.add('hidden');
  6779. const sig = `${tableFilter}|${typeFilter}|` + routes.map(r =>
  6780. `${r.id}:${r.dst_address}:${r.gateway}:${r.interface}:${r.distance}:${r.routing_table}:${r.active}:${r.disabled}:${r.protocol}:${r.comment}:${r.check_gateway}:${r.check_target}:${r.health_status}:${(r.health_rtt_ms || 0).toFixed(0)}`
  6781. ).join(';');
  6782. if (tbody.dataset.sig === sig) {
  6783. return; // Routes table unchanged! Do not wipe DOM or flicker!
  6784. }
  6785. tbody.dataset.sig = sig;
  6786. tbody.innerHTML = '';
  6787. routes.forEach(r => {
  6788. const tr = document.createElement('tr');
  6789. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${r.disabled ? 'opacity-50' : ''}`;
  6790. tr.setAttribute('ondblclick', `openEditRouteModal('${r.id}')`);
  6791. // Routing Flags string: D=Dynamic, A=Active, C=Connect, S=Static, E=ECMP, M=Multicast, X=Disabled
  6792. let flags = '';
  6793. if (r.dynamic) flags += 'D';
  6794. if (r.active) flags += 'A';
  6795. if (r.connect) flags += 'C';
  6796. if (r.static) flags += 'S';
  6797. if (r.ecmp) flags += 'E';
  6798. if (r.multicast) flags += 'M';
  6799. if (r.disabled) flags += 'X';
  6800. const isDefault = r.dst_address === 'default' || r.dst_address === '0.0.0.0/0';
  6801. let healthCell = `<span class="text-slate-600 font-mono text-[11px]">-</span>`;
  6802. if (r.check_gateway === 'internet') {
  6803. if (r.health_status === 'online') {
  6804. const ms = (r.health_rtt_ms || 0).toFixed(0);
  6805. healthCell = `
  6806. <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)">
  6807. <span class="w-1.5 h-1.5 rounded-full bg-emerald-400 animate-pulse"></span>
  6808. <span>Internet OK (${ms}ms)</span>
  6809. </span>
  6810. `;
  6811. } else if (r.health_status === 'offline') {
  6812. healthCell = `
  6813. <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.">
  6814. <span class="w-1.5 h-1.5 rounded-full bg-rose-400"></span>
  6815. <span>Internet Down</span>
  6816. </span>
  6817. `;
  6818. } else {
  6819. healthCell = `
  6820. <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">
  6821. <span class="w-1.5 h-1.5 rounded-full bg-amber-400 animate-ping"></span>
  6822. <span>Checking...</span>
  6823. </span>
  6824. `;
  6825. }
  6826. } else if (r.check_gateway === 'ping') {
  6827. if (r.health_status === 'online') {
  6828. healthCell = `
  6829. <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">
  6830. <span class="w-1.5 h-1.5 rounded-full bg-cyan-400"></span>
  6831. <span>Gateway OK (${(r.health_rtt_ms || 0).toFixed(0)}ms)</span>
  6832. </span>
  6833. `;
  6834. } else if (r.health_status === 'offline') {
  6835. healthCell = `
  6836. <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">
  6837. <span class="w-1.5 h-1.5 rounded-full bg-rose-400"></span>
  6838. <span>Gateway Dead</span>
  6839. </span>
  6840. `;
  6841. }
  6842. }
  6843. const flagDescriptions = [];
  6844. if (r.dynamic) flagDescriptions.push('Dynamic (D)');
  6845. if (r.active) flagDescriptions.push('Active (A)');
  6846. if (r.connect) flagDescriptions.push('Connected (C)');
  6847. if (r.static) flagDescriptions.push('Static (S)');
  6848. if (r.ecmp) flagDescriptions.push('ECMP - Equal-Cost Multi-Path (E)');
  6849. if (r.multicast) flagDescriptions.push('Multicast / IGMP Group (M)');
  6850. if (r.disabled) flagDescriptions.push('Disabled (X)');
  6851. tr.innerHTML = `
  6852. <td class="py-2.5 px-3 text-center">
  6853. <span class="px-1.5 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 ${
  6854. 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')
  6855. }" title="Flags: ${flagDescriptions.join(', ')}">
  6856. ${flags || '-'}
  6857. </span>
  6858. </td>
  6859. <td class="py-2.5 px-3">
  6860. <div class="flex items-center gap-1.5 flex-wrap">
  6861. <span class="font-bold ${isDefault ? 'text-cyan-300' : 'text-white'}">${escapeHtml(r.dst_address)}</span>
  6862. ${r.ecmp ? `
  6863. <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)">
  6864. <span>⚡ ECMP</span>
  6865. </span>
  6866. ` : ''}
  6867. ${r.multicast ? `
  6868. <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">
  6869. <span>IGMP</span>
  6870. </span>
  6871. ` : ''}
  6872. </div>
  6873. </td>
  6874. <td class="py-2.5 px-3">${getRouteProtocolBadge(r.protocol)}</td>
  6875. <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>
  6876. <td class="py-2.5 px-3 text-slate-400 font-mono">${(r.distance !== undefined && r.distance !== null) ? r.distance : 0}</td>
  6877. <td class="py-2.5 px-3 font-mono font-semibold text-purple-300">${r.routing_table || 'main'}</td>
  6878. <td class="py-2.5 px-3 text-emerald-400 font-mono">${
  6879. (state.sdwanGroups || []).some(g => g.name === r.interface)
  6880. ? `<span class="px-1.5 py-0.5 rounded text-[10px] bg-cyan-950/70 text-cyan-300 border border-cyan-700/50 font-bold inline-flex items-center gap-1"><span>⚡</span><span>${escapeHtml(r.interface)}</span></span>`
  6881. : (r.interface || '-')
  6882. }</td>
  6883. <td class="py-2.5 px-3">${healthCell}</td>
  6884. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]">${r.comment || '-'}</td>
  6885. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  6886. ${r.static ? `
  6887. <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>
  6888. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold">Edit</button>
  6889. <button onclick="deleteRoute('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  6890. ` : `
  6891. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">View</button>
  6892. `}
  6893. </td>
  6894. `;
  6895. tbody.appendChild(tr);
  6896. });
  6897. }
  6898. function openAddRouteModal() {
  6899. document.getElementById('route-modal-title').innerText = 'Add Static Route';
  6900. document.getElementById('route-modal-id').value = '';
  6901. document.getElementById('route-modal-old-dst').value = '';
  6902. document.getElementById('route-modal-old-gw').value = '';
  6903. document.getElementById('route-modal-old-distance').value = '';
  6904. document.getElementById('route-modal-old-table').value = '';
  6905. document.getElementById('route-modal-old-iface').value = '';
  6906. const dstInput = document.getElementById('route-modal-dst');
  6907. const gwInput = document.getElementById('route-modal-gw');
  6908. const distInput = document.getElementById('route-modal-distance');
  6909. const ifaceSelect = document.getElementById('route-modal-iface');
  6910. const tableSelect = document.getElementById('route-modal-table');
  6911. const commentInput = document.getElementById('route-modal-comment');
  6912. const disCheck = document.getElementById('route-modal-disabled');
  6913. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  6914. dstInput.disabled = false;
  6915. dstInput.value = '0.0.0.0/0';
  6916. gwInput.disabled = false;
  6917. gwInput.value = '';
  6918. distInput.disabled = false;
  6919. distInput.value = '1';
  6920. ifaceSelect.disabled = false;
  6921. tableSelect.disabled = false;
  6922. commentInput.disabled = false;
  6923. commentInput.value = '';
  6924. disCheck.disabled = false;
  6925. disCheck.checked = false;
  6926. if (saveBtn) saveBtn.classList.remove('hidden');
  6927. const checkGw = document.getElementById('route-modal-check-gw');
  6928. if (checkGw) checkGw.value = 'internet';
  6929. const checkTarget = document.getElementById('route-modal-check-target');
  6930. if (checkTarget) checkTarget.value = '1.1.1.1';
  6931. const checkInterval = document.getElementById('route-modal-check-interval');
  6932. if (checkInterval) checkInterval.value = '5';
  6933. const checkThresh = document.getElementById('route-modal-check-threshold');
  6934. if (checkThresh) checkThresh.value = '3';
  6935. toggleRouteCheckModeUI();
  6936. populateInterfaceSelect('route-modal-iface');
  6937. // Populate tables
  6938. tableSelect.innerHTML = '';
  6939. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  6940. const opt = document.createElement('option');
  6941. opt.value = t.name;
  6942. opt.innerText = t.name;
  6943. if (t.name === 'main') opt.selected = true;
  6944. tableSelect.appendChild(opt);
  6945. });
  6946. document.getElementById('route-modal').classList.remove('hidden');
  6947. }
  6948. function openEditRouteModal(id) {
  6949. const r = (state.routes || []).find(route => route.id === id);
  6950. if (!r) return;
  6951. const isStatic = !!r.static;
  6952. document.getElementById('route-modal-title').innerText = isStatic
  6953. ? `Edit Route: ${r.dst_address}`
  6954. : `Route Properties (Read Only): ${r.dst_address}`;
  6955. document.getElementById('route-modal-id').value = r.id;
  6956. document.getElementById('route-modal-old-dst').value = r.dst_address || '';
  6957. document.getElementById('route-modal-old-gw').value = r.gateway || '';
  6958. document.getElementById('route-modal-old-distance').value = (r.distance !== undefined && r.distance !== null) ? r.distance : '';
  6959. document.getElementById('route-modal-old-table').value = r.routing_table || 'main';
  6960. document.getElementById('route-modal-old-iface').value = r.interface || '';
  6961. const dstInput = document.getElementById('route-modal-dst');
  6962. const gwInput = document.getElementById('route-modal-gw');
  6963. const distInput = document.getElementById('route-modal-distance');
  6964. const ifaceSelect = document.getElementById('route-modal-iface');
  6965. const tableSelect = document.getElementById('route-modal-table');
  6966. const commentInput = document.getElementById('route-modal-comment');
  6967. const disCheck = document.getElementById('route-modal-disabled');
  6968. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  6969. dstInput.value = r.dst_address;
  6970. gwInput.value = r.gateway || '';
  6971. distInput.value = (r.distance !== undefined && r.distance !== null) ? r.distance : 1;
  6972. commentInput.value = r.comment || '';
  6973. disCheck.checked = !!r.disabled;
  6974. const checkGw = document.getElementById('route-modal-check-gw');
  6975. if (checkGw) checkGw.value = r.check_gateway || 'none';
  6976. const checkTarget = document.getElementById('route-modal-check-target');
  6977. if (checkTarget) checkTarget.value = r.check_target || '1.1.1.1';
  6978. const checkInterval = document.getElementById('route-modal-check-interval');
  6979. if (checkInterval) checkInterval.value = r.check_interval || 5;
  6980. const checkThresh = document.getElementById('route-modal-check-threshold');
  6981. if (checkThresh) checkThresh.value = r.check_threshold || 3;
  6982. toggleRouteCheckModeUI();
  6983. dstInput.disabled = !isStatic;
  6984. gwInput.disabled = !isStatic;
  6985. distInput.disabled = !isStatic;
  6986. ifaceSelect.disabled = !isStatic;
  6987. tableSelect.disabled = !isStatic;
  6988. commentInput.disabled = !isStatic;
  6989. disCheck.disabled = !isStatic;
  6990. if (checkGw) checkGw.disabled = !isStatic;
  6991. if (checkTarget) checkTarget.disabled = !isStatic;
  6992. if (checkInterval) checkInterval.disabled = !isStatic;
  6993. if (checkThresh) checkThresh.disabled = !isStatic;
  6994. if (saveBtn) {
  6995. if (isStatic) {
  6996. saveBtn.classList.remove('hidden');
  6997. } else {
  6998. saveBtn.classList.add('hidden');
  6999. }
  7000. }
  7001. populateInterfaceSelect('route-modal-iface', r.interface);
  7002. tableSelect.innerHTML = '';
  7003. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  7004. const opt = document.createElement('option');
  7005. opt.value = t.name;
  7006. opt.innerText = t.name;
  7007. if (t.name === (r.routing_table || 'main')) opt.selected = true;
  7008. tableSelect.appendChild(opt);
  7009. });
  7010. document.getElementById('route-modal').classList.remove('hidden');
  7011. }
  7012. function closeRouteModal() {
  7013. document.getElementById('route-modal').classList.add('hidden');
  7014. }
  7015. function setRouteCheckTarget(ip) {
  7016. const inp = document.getElementById('route-modal-check-target');
  7017. if (inp) inp.value = ip;
  7018. }
  7019. function toggleRouteCheckModeUI() {
  7020. const mode = document.getElementById('route-modal-check-gw')?.value || 'none';
  7021. const targetRow = document.getElementById('route-row-check-target');
  7022. const paramsRow = document.getElementById('route-row-check-params');
  7023. if (mode === 'none') {
  7024. if (targetRow) targetRow.classList.add('opacity-40', 'pointer-events-none');
  7025. if (paramsRow) paramsRow.classList.add('opacity-40', 'pointer-events-none');
  7026. } else if (mode === 'ping') {
  7027. if (targetRow) targetRow.classList.add('opacity-40', 'pointer-events-none');
  7028. if (paramsRow) paramsRow.classList.remove('opacity-40', 'pointer-events-none');
  7029. } else { // internet
  7030. if (targetRow) targetRow.classList.remove('opacity-40', 'pointer-events-none');
  7031. if (paramsRow) paramsRow.classList.remove('opacity-40', 'pointer-events-none');
  7032. }
  7033. }
  7034. async function submitSaveRoute(e) {
  7035. e.preventDefault();
  7036. const id = document.getElementById('route-modal-id').value;
  7037. const oldDst = document.getElementById('route-modal-old-dst')?.value || '';
  7038. const oldGw = document.getElementById('route-modal-old-gw')?.value || '';
  7039. const oldDistStr = document.getElementById('route-modal-old-distance')?.value;
  7040. const oldTable = document.getElementById('route-modal-old-table')?.value || '';
  7041. const oldIface = document.getElementById('route-modal-old-iface')?.value || '';
  7042. const dst = document.getElementById('route-modal-dst').value.trim();
  7043. const gw = document.getElementById('route-modal-gw').value.trim();
  7044. const table = document.getElementById('route-modal-table').value;
  7045. const distance = parseInt(document.getElementById('route-modal-distance').value, 10) || 0;
  7046. const iface = document.getElementById('route-modal-iface').value;
  7047. const comment = document.getElementById('route-modal-comment').value.trim();
  7048. const disabled = document.getElementById('route-modal-disabled').checked;
  7049. const check_gateway = document.getElementById('route-modal-check-gw')?.value || 'none';
  7050. const check_target = document.getElementById('route-modal-check-target')?.value.trim() || '1.1.1.1';
  7051. const check_interval = parseInt(document.getElementById('route-modal-check-interval')?.value, 10) || 5;
  7052. const check_threshold = parseInt(document.getElementById('route-modal-check-threshold')?.value, 10) || 3;
  7053. if (!dst) {
  7054. showToast('Error', 'Destination address is required', 'error');
  7055. return;
  7056. }
  7057. if (!gw && !iface) {
  7058. showToast('Error', 'Either Gateway IP or Interface must be specified', 'error');
  7059. return;
  7060. }
  7061. const payload = {
  7062. id,
  7063. old_dst_address: oldDst,
  7064. old_gateway: oldGw,
  7065. old_routing_table: oldTable,
  7066. old_interface: oldIface,
  7067. dst_address: dst,
  7068. gateway: gw || iface,
  7069. routing_table: table,
  7070. distance,
  7071. interface: iface,
  7072. comment,
  7073. disabled,
  7074. check_gateway,
  7075. check_target,
  7076. check_interval,
  7077. check_threshold
  7078. };
  7079. if (oldDistStr !== undefined && oldDistStr !== '') {
  7080. payload.old_distance = parseInt(oldDistStr, 10);
  7081. }
  7082. try {
  7083. const res = await fetch(`${API_BASE}/routes`, {
  7084. method: 'POST',
  7085. headers: { 'Content-Type': 'application/json' },
  7086. body: JSON.stringify(payload)
  7087. });
  7088. if (res.ok) {
  7089. showToast('Route Saved', `Route to ${dst} installed`, 'success');
  7090. closeRouteModal();
  7091. const tbody = document.getElementById('routes-table-body');
  7092. if (tbody) tbody.dataset.sig = '';
  7093. loadRoutes();
  7094. } else {
  7095. const err = await res.json().catch(() => ({}));
  7096. showToast('Error', err.message || err.error || 'Failed to save route', 'error');
  7097. }
  7098. } catch (err) {
  7099. showToast('Error', err.message, 'error');
  7100. }
  7101. }
  7102. async function toggleRouteState(id, disabled) {
  7103. try {
  7104. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}/state`, {
  7105. method: 'POST',
  7106. headers: { 'Content-Type': 'application/json' },
  7107. body: JSON.stringify({ disabled })
  7108. });
  7109. if (res.ok) {
  7110. const tbody = document.getElementById('routes-table-body');
  7111. if (tbody) tbody.dataset.sig = '';
  7112. loadRoutes();
  7113. } else {
  7114. const err = await res.json().catch(() => ({}));
  7115. showToast('Error', err.message || err.error || 'Failed to update route state', 'error');
  7116. }
  7117. } catch (err) {
  7118. showToast('Error', err.message, 'error');
  7119. }
  7120. }
  7121. async function deleteRoute(id) {
  7122. if (!confirm('Are you sure you want to delete this route?')) return;
  7123. try {
  7124. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7125. if (res.ok) {
  7126. showToast('Deleted', 'Route removed', 'success');
  7127. const tbody = document.getElementById('routes-table-body');
  7128. if (tbody) tbody.dataset.sig = '';
  7129. loadRoutes();
  7130. } else {
  7131. const err = await res.json().catch(() => ({}));
  7132. showToast('Error', err.message || err.error || 'Failed to delete route', 'error');
  7133. }
  7134. } catch (err) {
  7135. showToast('Error', err.message, 'error');
  7136. }
  7137. }
  7138. // ----------------- Policy Rules (/ip route rule) -----------------
  7139. function renderPolicyRules() {
  7140. const tbody = document.getElementById('rules-table-body');
  7141. const empty = document.getElementById('rules-empty');
  7142. if (!tbody) return;
  7143. const showSystem = document.getElementById('prule-show-system')?.checked;
  7144. const filtered = (state.policyRules || []).filter(pr => showSystem || (!pr.is_default && !pr.is_system));
  7145. const countBadge = document.getElementById('rules-count-badge');
  7146. if (countBadge) countBadge.innerText = `${filtered.length} Rules`;
  7147. const bRules = document.getElementById('routes-badge-rules');
  7148. if (bRules) bRules.innerText = filtered.length;
  7149. if (filtered.length === 0) {
  7150. empty?.classList.remove('hidden');
  7151. tbody.innerHTML = '';
  7152. return;
  7153. }
  7154. empty?.classList.add('hidden');
  7155. const sig = `${showSystem}|` + filtered.map(pr => `${pr.id}:${pr.priority}:${pr.src_address}:${pr.dst_address}:${pr.table}:${pr.routing_mark}`).join(';');
  7156. if (tbody.dataset.sig === sig) return;
  7157. tbody.dataset.sig = sig;
  7158. tbody.innerHTML = '';
  7159. filtered.forEach(pr => {
  7160. const isSys = pr.is_default || pr.is_system;
  7161. const tr = document.createElement('tr');
  7162. tr.className = `hover:bg-slate-800/40 transition text-xs ${isSys ? 'opacity-70 bg-slate-950/20' : ''}`;
  7163. tr.innerHTML = `
  7164. <td class="py-2.5 px-3 font-mono text-cyan-400 font-bold">${pr.priority}</td>
  7165. <td class="py-2.5 px-3 font-mono text-white">${pr.src_address || '<span class="text-slate-600">all</span>'}</td>
  7166. <td class="py-2.5 px-3 font-mono text-white">${pr.dst_address || '<span class="text-slate-600">all</span>'}</td>
  7167. <td class="py-2.5 px-3 font-mono font-bold text-purple-300">${pr.routing_mark || '<span class="text-slate-600">-</span>'}</td>
  7168. <td class="py-2.5 px-3 font-mono font-bold text-amber-300">${pr.table}</td>
  7169. <td class="py-2.5 px-3 font-mono text-slate-300">${pr.action}</td>
  7170. <td class="py-2.5 px-3 text-right font-sans">
  7171. ${!pr.is_default ? `
  7172. <button onclick="deletePolicyRule('${pr.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  7173. ` : `<span class="text-slate-600 text-[10px]">Default</span>`}
  7174. </td>
  7175. `;
  7176. tbody.appendChild(tr);
  7177. });
  7178. }
  7179. function openAddPolicyRuleModal() {
  7180. const userRules = (state.policyRules || []).filter(pr => !pr.is_default && !pr.is_system);
  7181. document.getElementById('prule-modal-pref').value = userRules.length * 10 + 1000;
  7182. document.getElementById('prule-modal-mark').value = '';
  7183. document.getElementById('prule-modal-src').value = '';
  7184. document.getElementById('prule-modal-dst').value = '';
  7185. const sel = document.getElementById('prule-modal-table');
  7186. sel.innerHTML = '';
  7187. (state.routingTables || []).forEach(t => {
  7188. const opt = document.createElement('option');
  7189. opt.value = t.name;
  7190. opt.innerText = t.name;
  7191. sel.appendChild(opt);
  7192. });
  7193. document.getElementById('prule-modal').classList.remove('hidden');
  7194. }
  7195. function closePolicyRuleModal() {
  7196. document.getElementById('prule-modal').classList.add('hidden');
  7197. }
  7198. async function submitSavePolicyRule(e) {
  7199. e.preventDefault();
  7200. const pref = parseInt(document.getElementById('prule-modal-pref').value, 10) || 1000;
  7201. const mark = document.getElementById('prule-modal-mark').value.trim();
  7202. const src = document.getElementById('prule-modal-src').value.trim();
  7203. const dst = document.getElementById('prule-modal-dst').value.trim();
  7204. const table = document.getElementById('prule-modal-table').value;
  7205. const action = document.getElementById('prule-modal-action').value;
  7206. try {
  7207. const res = await fetch(`${API_BASE}/routing/rules`, {
  7208. method: 'POST',
  7209. headers: { 'Content-Type': 'application/json' },
  7210. body: JSON.stringify({ priority: pref, routing_mark: mark, src_address: src, dst_address: dst, table, action })
  7211. });
  7212. if (res.ok) {
  7213. showToast('Rule Added', `Policy rule installed for table ${table}`, 'success');
  7214. closePolicyRuleModal();
  7215. loadRoutes();
  7216. } else {
  7217. const err = await res.json();
  7218. showToast('Error', err.message, 'error');
  7219. }
  7220. } catch (err) {
  7221. showToast('Error', err.message, 'error');
  7222. }
  7223. }
  7224. async function deletePolicyRule(id) {
  7225. if (!confirm('Are you sure you want to remove this policy rule?')) return;
  7226. try {
  7227. const res = await fetch(`${API_BASE}/routing/rules/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7228. if (res.ok) {
  7229. showToast('Rule Removed', 'Policy rule deleted', 'success');
  7230. loadRoutes();
  7231. }
  7232. } catch (err) {
  7233. showToast('Error', err.message, 'error');
  7234. }
  7235. }
  7236. // ----------------- Routing Tables -----------------
  7237. function renderRoutingTables() {
  7238. const tbody = document.getElementById('tables-table-body');
  7239. if (!tbody) return;
  7240. const tables = state.routingTables || [];
  7241. const sig = tables.map(t => `${t.table_id}:${t.name}:${t.comment}`).join(';');
  7242. if (tbody.dataset.sig === sig) return;
  7243. tbody.dataset.sig = sig;
  7244. tbody.innerHTML = '';
  7245. (state.routingTables || []).forEach(t => {
  7246. const tr = document.createElement('tr');
  7247. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  7248. tr.innerHTML = `
  7249. <td class="py-2.5 px-3 text-cyan-400 font-bold">${t.table_id}</td>
  7250. <td class="py-2.5 px-3 font-bold text-white">${t.name}</td>
  7251. <td class="py-2.5 px-3 text-slate-400 italic">${t.comment || '-'}</td>
  7252. `;
  7253. tbody.appendChild(tr);
  7254. });
  7255. }
  7256. function openAddTableModal() {
  7257. document.getElementById('table-modal-name').value = '';
  7258. document.getElementById('table-modal-id').value = '';
  7259. document.getElementById('table-modal-comment').value = '';
  7260. document.getElementById('table-modal').classList.remove('hidden');
  7261. }
  7262. function closeTableModal() {
  7263. document.getElementById('table-modal').classList.add('hidden');
  7264. }
  7265. async function submitSaveTable(e) {
  7266. e.preventDefault();
  7267. const name = document.getElementById('table-modal-name').value.trim();
  7268. const id = parseInt(document.getElementById('table-modal-id').value, 10) || 0;
  7269. const comment = document.getElementById('table-modal-comment').value.trim();
  7270. try {
  7271. const res = await fetch(`${API_BASE}/routing/tables`, {
  7272. method: 'POST',
  7273. headers: { 'Content-Type': 'application/json' },
  7274. body: JSON.stringify({ name, table_id: id, comment })
  7275. });
  7276. if (res.ok) {
  7277. showToast('Table Created', `Routing table ${name} registered`, 'success');
  7278. closeTableModal();
  7279. loadRoutes();
  7280. } else {
  7281. const err = await res.json();
  7282. showToast('Error', err.message, 'error');
  7283. }
  7284. } catch (err) {
  7285. showToast('Error', err.message, 'error');
  7286. }
  7287. }
  7288. async function loadDebianConfig() {
  7289. const view = document.getElementById('debian-config-view');
  7290. view.innerText = 'Generating live configuration...';
  7291. try {
  7292. const res = await fetch(`${API_BASE}/debian/config`);
  7293. const data = await res.json();
  7294. view.innerText = data.content || '# Empty config';
  7295. } catch (err) {
  7296. view.innerText = 'Failed to generate Debian network config.';
  7297. }
  7298. }
  7299. async function saveDebianConfig() {
  7300. try {
  7301. const res = await fetch(`${API_BASE}/debian/apply`, { method: 'POST' });
  7302. const data = await res.json();
  7303. if (res.ok) {
  7304. showToast('Configuration Saved', data.message || 'Saved to /etc/network/interfaces.d/vlans.cfg', 'success');
  7305. loadDebianConfig();
  7306. }
  7307. } catch (err) {
  7308. showToast('Error', err.message, 'error');
  7309. }
  7310. }
  7311. function showToast(title, message, type = 'info') {
  7312. const container = document.getElementById('toast-container');
  7313. const toast = document.createElement('div');
  7314. const borderColors = {
  7315. success: 'border-emerald-500/40 bg-slate-900/95 text-emerald-400',
  7316. error: 'border-rose-500/40 bg-slate-900/95 text-rose-400',
  7317. info: 'border-cyan-500/40 bg-slate-900/95 text-cyan-400'
  7318. };
  7319. 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}`;
  7320. toast.innerHTML = `
  7321. <div class="flex-1">
  7322. <div class="font-bold text-xs text-white">${escapeHtml(title)}</div>
  7323. <div class="text-[11px] text-slate-300 mt-0.5 leading-relaxed font-sans">${escapeHtml(message)}</div>
  7324. </div>
  7325. `;
  7326. container.appendChild(toast);
  7327. requestAnimationFrame(() => toast.classList.remove('translate-y-2', 'opacity-0'));
  7328. setTimeout(() => {
  7329. toast.classList.add('opacity-0', 'translate-y-2');
  7330. setTimeout(() => toast.remove(), 300);
  7331. }, 4000);
  7332. }
  7333. function formatTraffic(bytesPerSec) {
  7334. if (bytesPerSec < 1024) return `${Math.round(bytesPerSec)} B/s`;
  7335. const kb = bytesPerSec / 1024;
  7336. if (kb < 1024) return `${kb.toFixed(1)} KB/s`;
  7337. const mb = kb / 1024;
  7338. return `${mb.toFixed(2)} MB/s`;
  7339. }
  7340. function toggleSidebar() {
  7341. const sb = document.getElementById('sidebar');
  7342. sb.classList.toggle('-translate-x-full');
  7343. }
  7344. // ======================== EoIP (Ethernet over IP) ========================
  7345. async function loadEoIP(populate = true) {
  7346. try {
  7347. const res = await fetch(`${API_BASE}/vpn/eoip`);
  7348. const data = await res.json();
  7349. state.eoipTunnels = Array.isArray(data) ? data : [];
  7350. const badge = document.getElementById('eoip-count-badge');
  7351. if (badge) badge.innerText = `${state.eoipTunnels.length} Tunnels`;
  7352. const sideBadge = document.getElementById('badge-eoip-count');
  7353. if (sideBadge) sideBadge.innerText = state.eoipTunnels.length;
  7354. renderEoIPTunnels();
  7355. } catch (err) {
  7356. console.error('Failed to load EoIP:', err);
  7357. }
  7358. }
  7359. function renderEoIPTunnels() {
  7360. const tbody = document.getElementById('eoip-table-body');
  7361. const empty = document.getElementById('eoip-empty');
  7362. if (!tbody) return;
  7363. tbody.innerHTML = '';
  7364. const tunnels = state.eoipTunnels || [];
  7365. if (tunnels.length === 0) {
  7366. empty?.classList.remove('hidden');
  7367. return;
  7368. }
  7369. empty?.classList.add('hidden');
  7370. tunnels.forEach(t => {
  7371. const tr = document.createElement('tr');
  7372. tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
  7373. tr.innerHTML = `
  7374. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.running, t.disabled)}</td>
  7375. <td class="py-2.5 px-3 font-bold text-white font-mono">${t.name}</td>
  7376. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${t.tunnel_id}</td>
  7377. <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>
  7378. <td class="py-2.5 px-3 text-cyan-300 font-mono">${t.remote_address}</td>
  7379. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.local_address || '(any)'}</td>
  7380. <td class="py-2.5 px-3 text-slate-300 font-mono text-[11px]">${t.mac_address || '-'}</td>
  7381. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.mtu || 1500}</td>
  7382. <td class="py-2.5 px-3 font-mono text-[11px]">
  7383. <span class="text-emerald-400">↓ ${t.rx_human || '0 B'}</span>
  7384. <span class="text-cyan-400 ml-1">↑ ${t.tx_human || '0 B'}</span>
  7385. </td>
  7386. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${t.comment || ''}">${t.comment || '-'}</td>
  7387. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  7388. <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>
  7389. <button onclick="openEditEoIPModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  7390. <button onclick="deleteEoIP('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  7391. </td>
  7392. `;
  7393. tbody.appendChild(tr);
  7394. });
  7395. }
  7396. function openAddEoIPModal() {
  7397. document.getElementById('eoip-modal-title').innerText = 'Add EoIP Tunnel';
  7398. document.getElementById('eoip-modal-id').value = '';
  7399. document.getElementById('eoip-modal-name').value = `eoip-tunnel${(state.eoipTunnels || []).length + 1}`;
  7400. document.getElementById('eoip-modal-tunnelid').value = (state.eoipTunnels || []).length + 10;
  7401. document.getElementById('eoip-modal-remote').value = '';
  7402. document.getElementById('eoip-modal-ip').value = '';
  7403. document.getElementById('eoip-modal-local').value = '';
  7404. document.getElementById('eoip-modal-mac').value = '';
  7405. document.getElementById('eoip-modal-mtu').value = '1500';
  7406. document.getElementById('eoip-modal-comment').value = '';
  7407. document.getElementById('eoip-modal-clampmss').checked = true;
  7408. document.getElementById('eoip-modal-disabled').checked = false;
  7409. document.getElementById('eoip-modal').classList.remove('hidden');
  7410. }
  7411. function openEditEoIPModal(id) {
  7412. const t = (state.eoipTunnels || []).find(tun => tun.id === id);
  7413. if (!t) return;
  7414. document.getElementById('eoip-modal-title').innerText = `Edit EoIP Tunnel (${t.name})`;
  7415. document.getElementById('eoip-modal-id').value = t.id;
  7416. document.getElementById('eoip-modal-name').value = t.name;
  7417. document.getElementById('eoip-modal-tunnelid').value = t.tunnel_id;
  7418. document.getElementById('eoip-modal-remote').value = t.remote_address;
  7419. document.getElementById('eoip-modal-ip').value = t.ip_address || '';
  7420. document.getElementById('eoip-modal-local').value = t.local_address || '';
  7421. document.getElementById('eoip-modal-mac').value = t.mac_address || '';
  7422. document.getElementById('eoip-modal-mtu').value = t.mtu || 1500;
  7423. document.getElementById('eoip-modal-comment').value = t.comment || '';
  7424. document.getElementById('eoip-modal-clampmss').checked = !!t.clamp_mss;
  7425. document.getElementById('eoip-modal-disabled').checked = !!t.disabled;
  7426. document.getElementById('eoip-modal').classList.remove('hidden');
  7427. }
  7428. function closeEoIPModal() {
  7429. document.getElementById('eoip-modal').classList.add('hidden');
  7430. }
  7431. async function submitSaveEoIP(e) {
  7432. e.preventDefault();
  7433. const id = document.getElementById('eoip-modal-id').value;
  7434. const name = document.getElementById('eoip-modal-name').value.trim();
  7435. const tunnelId = parseInt(document.getElementById('eoip-modal-tunnelid').value);
  7436. const remote = document.getElementById('eoip-modal-remote').value.trim();
  7437. const ipAddress = document.getElementById('eoip-modal-ip').value.trim();
  7438. const local = document.getElementById('eoip-modal-local').value.trim();
  7439. const mac = document.getElementById('eoip-modal-mac').value.trim();
  7440. const mtu = parseInt(document.getElementById('eoip-modal-mtu').value) || 1500;
  7441. const comment = document.getElementById('eoip-modal-comment').value.trim();
  7442. const clampMss = document.getElementById('eoip-modal-clampmss').checked;
  7443. const disabled = document.getElementById('eoip-modal-disabled').checked;
  7444. try {
  7445. const res = await fetch(`${API_BASE}/vpn/eoip`, {
  7446. method: 'POST',
  7447. headers: { 'Content-Type': 'application/json' },
  7448. body: JSON.stringify({
  7449. id,
  7450. name,
  7451. tunnel_id: tunnelId,
  7452. remote_address: remote,
  7453. ip_address: ipAddress,
  7454. local_address: local,
  7455. mac_address: mac,
  7456. mtu,
  7457. clamp_mss: clampMss,
  7458. comment,
  7459. disabled
  7460. })
  7461. });
  7462. if (res.ok) {
  7463. showToast('EoIP Saved', `Tunnel ${name} configured successfully`, 'success');
  7464. closeEoIPModal();
  7465. loadEoIP(false);
  7466. fetchData(false);
  7467. } else {
  7468. const err = await res.json();
  7469. showToast('Error', err.message, 'error');
  7470. }
  7471. } catch (err) {
  7472. showToast('Error', err.message, 'error');
  7473. }
  7474. }
  7475. async function toggleEoIPState(id, disabled) {
  7476. try {
  7477. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}/state`, {
  7478. method: 'POST',
  7479. headers: { 'Content-Type': 'application/json' },
  7480. body: JSON.stringify({ disabled })
  7481. });
  7482. if (res.ok) {
  7483. showToast(disabled ? 'Disabled' : 'Enabled', 'EoIP tunnel state updated', 'info');
  7484. loadEoIP(false);
  7485. fetchData(false);
  7486. }
  7487. } catch (err) {
  7488. showToast('Error', err.message, 'error');
  7489. }
  7490. }
  7491. async function deleteEoIP(id) {
  7492. if (!confirm('Are you sure you want to delete this EoIP tunnel?')) return;
  7493. try {
  7494. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7495. if (res.ok) {
  7496. showToast('Deleted', 'EoIP tunnel removed', 'success');
  7497. loadEoIP(false);
  7498. fetchData(false);
  7499. }
  7500. } catch (err) {
  7501. showToast('Error', err.message, 'error');
  7502. }
  7503. }
  7504. // ======================== VXLAN (Virtual Extensible LAN) ========================
  7505. async function loadVXLAN(populate = true) {
  7506. try {
  7507. const [tunnelsRes, vtepsRes] = await Promise.all([
  7508. fetch(`${API_BASE}/vpn/vxlan`),
  7509. fetch(`${API_BASE}/vpn/vxlan/vteps`)
  7510. ]);
  7511. if (tunnelsRes.ok) {
  7512. state.vxlanTunnels = await tunnelsRes.json() || [];
  7513. }
  7514. if (vtepsRes.ok) {
  7515. state.vxlanVteps = await vtepsRes.json() || [];
  7516. }
  7517. renderVXLANTable();
  7518. renderVXLANVtepsTable();
  7519. const countBadge = document.getElementById('vxlan-count-badge');
  7520. if (countBadge) countBadge.innerText = `${(state.vxlanTunnels || []).length} Tunnels`;
  7521. const vtepsCountBadge = document.getElementById('vxlan-vteps-count-badge');
  7522. if (vtepsCountBadge) vtepsCountBadge.innerText = `${(state.vxlanVteps || []).length} VTEPs`;
  7523. const navBadge = document.getElementById('badge-vxlan-count');
  7524. if (navBadge) navBadge.innerText = (state.vxlanTunnels || []).length;
  7525. } catch (err) {
  7526. console.error('Error loading VXLAN:', err);
  7527. }
  7528. }
  7529. function renderVXLANTable() {
  7530. const tbody = document.getElementById('vxlan-table-body');
  7531. const empty = document.getElementById('vxlan-empty');
  7532. if (!tbody || !empty) return;
  7533. tbody.innerHTML = '';
  7534. const tunnels = state.vxlanTunnels || [];
  7535. if (tunnels.length === 0) {
  7536. empty.classList.remove('hidden');
  7537. return;
  7538. }
  7539. empty.classList.add('hidden');
  7540. tunnels.forEach(t => {
  7541. const tr = document.createElement('tr');
  7542. tr.className = 'hover:bg-slate-800/40 transition border-b border-slate-800/60';
  7543. let flag = '';
  7544. if (t.disabled) {
  7545. flag = '<span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 text-slate-400 font-bold border border-slate-700" title="Disabled">X</span>';
  7546. } else if (t.running) {
  7547. flag = '<span class="px-1.5 py-0.5 rounded text-[10px] bg-amber-950 text-amber-300 font-bold border border-amber-800/50" title="Running">R</span>';
  7548. } else {
  7549. flag = '<span class="px-1.5 py-0.5 rounded text-[10px] bg-rose-950 text-rose-300 font-bold border border-rose-800/50" title="Down">!</span>';
  7550. }
  7551. const vtepCount = (t.vteps || []).length;
  7552. const underlayDesc = t.parent_interface || t.local_address ? `${t.parent_interface || '-'}${t.local_address ? ' / ' + t.local_address : ''}` : '(any)';
  7553. tr.innerHTML = `
  7554. <td class="py-2.5 px-3 text-center">${flag}</td>
  7555. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(t.name)}</td>
  7556. <td class="py-2.5 px-3 font-bold text-amber-400 font-mono">${t.vni}</td>
  7557. <td class="py-2.5 px-3 text-slate-300 font-mono">${t.port || 4789}</td>
  7558. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${escapeHtml(t.ip_address || '') || '<span class="text-slate-500 font-normal">Unassigned</span>'}</td>
  7559. <td class="py-2.5 px-3 text-slate-300 font-mono text-[11px]">${escapeHtml(underlayDesc)}</td>
  7560. <td class="py-2.5 px-3 text-slate-400 font-mono text-[11px]">${escapeHtml(t.mac_address || '-')}</td>
  7561. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.mtu || 1500}</td>
  7562. <td class="py-2.5 px-3 font-mono">
  7563. <span class="px-2 py-0.5 rounded-full text-[10px] bg-slate-800 text-amber-300 border border-slate-700 cursor-pointer" onclick="openAddVXLANVtepModal('${escapeHtml(t.name)}')" title="Click to add VTEP peer">${vtepCount} VTEP${vtepCount === 1 ? '' : 's'}</span>
  7564. </td>
  7565. <td class="py-2.5 px-3 font-mono text-[11px]">
  7566. <span class="text-emerald-400">↓ ${t.rx_human || '0 B'}</span>
  7567. <span class="text-amber-400 ml-1">↑ ${t.tx_human || '0 B'}</span>
  7568. </td>
  7569. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(t.comment || '')}">${escapeHtml(t.comment || '-')}</td>
  7570. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  7571. <button onclick="toggleVXLANState('${t.id}', ${!t.disabled})" class="text-xs ${t.disabled ? 'text-amber-400' : 'text-slate-400'} hover:underline">${t.disabled ? 'Enable' : 'Disable'}</button>
  7572. <button onclick="openEditVXLANModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  7573. <button onclick="deleteVXLAN('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  7574. </td>
  7575. `;
  7576. tbody.appendChild(tr);
  7577. });
  7578. }
  7579. function renderVXLANVtepsTable() {
  7580. const tbody = document.getElementById('vxlan-vteps-table-body');
  7581. const empty = document.getElementById('vxlan-vteps-empty');
  7582. if (!tbody || !empty) return;
  7583. tbody.innerHTML = '';
  7584. const vteps = state.vxlanVteps || [];
  7585. if (vteps.length === 0) {
  7586. empty.classList.remove('hidden');
  7587. return;
  7588. }
  7589. empty.classList.add('hidden');
  7590. vteps.forEach(v => {
  7591. const tr = document.createElement('tr');
  7592. tr.className = 'hover:bg-slate-800/40 transition border-b border-slate-800/60';
  7593. tr.innerHTML = `
  7594. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(v.interface)}</td>
  7595. <td class="py-2.5 px-3 text-amber-400 font-mono font-semibold">${escapeHtml(v.remote_ip)}</td>
  7596. <td class="py-2.5 px-3 text-slate-300 font-mono">${v.port > 0 ? v.port : 'default'}</td>
  7597. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[150px]" title="${escapeHtml(v.comment || '')}">${escapeHtml(v.comment || '-')}</td>
  7598. <td class="py-2.5 px-3 text-right font-sans whitespace-nowrap">
  7599. <button onclick="deleteVXLANVtep('${escapeHtml(v.interface)}', '${escapeHtml(v.id || v.remote_ip)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  7600. </td>
  7601. `;
  7602. tbody.appendChild(tr);
  7603. });
  7604. }
  7605. function openAddVXLANModal() {
  7606. document.getElementById('vxlan-modal-title').innerText = 'Add VXLAN Interface';
  7607. document.getElementById('vxlan-modal-id').value = '';
  7608. document.getElementById('vxlan-modal-name').value = `vxlan${(state.vxlanTunnels || []).length + 100}`;
  7609. document.getElementById('vxlan-modal-vni').value = (state.vxlanTunnels || []).length + 100;
  7610. document.getElementById('vxlan-modal-port').value = '4789';
  7611. document.getElementById('vxlan-modal-ip').value = '';
  7612. document.getElementById('vxlan-modal-parent').value = '';
  7613. document.getElementById('vxlan-modal-local').value = '';
  7614. document.getElementById('vxlan-modal-remote').value = '';
  7615. document.getElementById('vxlan-modal-group').value = '';
  7616. document.getElementById('vxlan-modal-mac').value = '';
  7617. document.getElementById('vxlan-modal-mtu').value = '1500';
  7618. document.getElementById('vxlan-modal-comment').value = '';
  7619. document.getElementById('vxlan-modal-learning').checked = true;
  7620. document.getElementById('vxlan-modal-disabled').checked = false;
  7621. document.getElementById('vxlan-modal').classList.remove('hidden');
  7622. }
  7623. function openEditVXLANModal(id) {
  7624. const t = (state.vxlanTunnels || []).find(tun => tun.id === id);
  7625. if (!t) return;
  7626. document.getElementById('vxlan-modal-title').innerText = `Edit VXLAN Interface (${t.name})`;
  7627. document.getElementById('vxlan-modal-id').value = t.id;
  7628. document.getElementById('vxlan-modal-name').value = t.name;
  7629. document.getElementById('vxlan-modal-vni').value = t.vni;
  7630. document.getElementById('vxlan-modal-port').value = t.port || 4789;
  7631. document.getElementById('vxlan-modal-ip').value = t.ip_address || '';
  7632. document.getElementById('vxlan-modal-parent').value = t.parent_interface || '';
  7633. document.getElementById('vxlan-modal-local').value = t.local_address || '';
  7634. document.getElementById('vxlan-modal-remote').value = t.remote_address || '';
  7635. document.getElementById('vxlan-modal-group').value = t.group || '';
  7636. document.getElementById('vxlan-modal-mac').value = t.mac_address || '';
  7637. document.getElementById('vxlan-modal-mtu').value = t.mtu || 1500;
  7638. document.getElementById('vxlan-modal-comment').value = t.comment || '';
  7639. document.getElementById('vxlan-modal-learning').checked = t.learning !== false;
  7640. document.getElementById('vxlan-modal-disabled').checked = !!t.disabled;
  7641. document.getElementById('vxlan-modal').classList.remove('hidden');
  7642. }
  7643. function closeVXLANModal() {
  7644. document.getElementById('vxlan-modal').classList.add('hidden');
  7645. }
  7646. async function submitSaveVXLAN(e) {
  7647. e.preventDefault();
  7648. const id = document.getElementById('vxlan-modal-id').value;
  7649. const name = document.getElementById('vxlan-modal-name').value.trim();
  7650. const vni = parseInt(document.getElementById('vxlan-modal-vni').value);
  7651. const port = parseInt(document.getElementById('vxlan-modal-port').value) || 4789;
  7652. const ipAddress = document.getElementById('vxlan-modal-ip').value.trim();
  7653. const parentInterface = document.getElementById('vxlan-modal-parent').value.trim();
  7654. const local = document.getElementById('vxlan-modal-local').value.trim();
  7655. const remote = document.getElementById('vxlan-modal-remote').value.trim();
  7656. const group = document.getElementById('vxlan-modal-group').value.trim();
  7657. const mac = document.getElementById('vxlan-modal-mac').value.trim();
  7658. const mtu = parseInt(document.getElementById('vxlan-modal-mtu').value) || 1500;
  7659. const comment = document.getElementById('vxlan-modal-comment').value.trim();
  7660. const learning = document.getElementById('vxlan-modal-learning').checked;
  7661. const disabled = document.getElementById('vxlan-modal-disabled').checked;
  7662. try {
  7663. const res = await fetch(`${API_BASE}/vpn/vxlan`, {
  7664. method: 'POST',
  7665. headers: { 'Content-Type': 'application/json' },
  7666. body: JSON.stringify({
  7667. id,
  7668. name,
  7669. vni,
  7670. port,
  7671. ip_address: ipAddress,
  7672. parent_interface: parentInterface,
  7673. local_address: local,
  7674. remote_address: remote,
  7675. group,
  7676. mac_address: mac,
  7677. mtu,
  7678. learning,
  7679. comment,
  7680. disabled
  7681. })
  7682. });
  7683. if (res.ok) {
  7684. showToast('VXLAN Saved', `Interface ${name} configured successfully`, 'success');
  7685. closeVXLANModal();
  7686. loadVXLAN(false);
  7687. fetchData(false);
  7688. } else {
  7689. const err = await res.json();
  7690. showToast('Error', err.message, 'error');
  7691. }
  7692. } catch (err) {
  7693. showToast('Error', err.message, 'error');
  7694. }
  7695. }
  7696. async function toggleVXLANState(id, disabled) {
  7697. try {
  7698. const res = await fetch(`${API_BASE}/vpn/vxlan/${encodeURIComponent(id)}/state`, {
  7699. method: 'POST',
  7700. headers: { 'Content-Type': 'application/json' },
  7701. body: JSON.stringify({ disabled })
  7702. });
  7703. if (res.ok) {
  7704. showToast(disabled ? 'Disabled' : 'Enabled', 'VXLAN interface state updated', 'info');
  7705. loadVXLAN(false);
  7706. fetchData(false);
  7707. }
  7708. } catch (err) {
  7709. showToast('Error', err.message, 'error');
  7710. }
  7711. }
  7712. async function deleteVXLAN(id) {
  7713. if (!confirm('Are you sure you want to delete this VXLAN interface?')) return;
  7714. try {
  7715. const res = await fetch(`${API_BASE}/vpn/vxlan/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7716. if (res.ok) {
  7717. showToast('Deleted', 'VXLAN interface removed', 'success');
  7718. loadVXLAN(false);
  7719. fetchData(false);
  7720. }
  7721. } catch (err) {
  7722. showToast('Error', err.message, 'error');
  7723. }
  7724. }
  7725. function openAddVXLANVtepModal(defaultIface = '') {
  7726. const sel = document.getElementById('vxlan-vtep-modal-interface');
  7727. if (sel) {
  7728. sel.innerHTML = '';
  7729. const tunnels = state.vxlanTunnels || [];
  7730. tunnels.forEach(t => {
  7731. const opt = document.createElement('option');
  7732. opt.value = t.name;
  7733. opt.innerText = `${t.name} (VNI ${t.vni})`;
  7734. if (defaultIface && t.name === defaultIface) {
  7735. opt.selected = true;
  7736. }
  7737. sel.appendChild(opt);
  7738. });
  7739. }
  7740. document.getElementById('vxlan-vtep-modal-remote').value = '';
  7741. document.getElementById('vxlan-vtep-modal-port').value = '';
  7742. document.getElementById('vxlan-vtep-modal-comment').value = '';
  7743. document.getElementById('vxlan-vtep-modal').classList.remove('hidden');
  7744. }
  7745. function closeVXLANVtepModal() {
  7746. document.getElementById('vxlan-vtep-modal').classList.add('hidden');
  7747. }
  7748. async function submitSaveVXLANVtep(e) {
  7749. e.preventDefault();
  7750. const iface = document.getElementById('vxlan-vtep-modal-interface').value;
  7751. const remote = document.getElementById('vxlan-vtep-modal-remote').value.trim();
  7752. const port = parseInt(document.getElementById('vxlan-vtep-modal-port').value) || 0;
  7753. const comment = document.getElementById('vxlan-vtep-modal-comment').value.trim();
  7754. try {
  7755. const res = await fetch(`${API_BASE}/vpn/vxlan/vteps`, {
  7756. method: 'POST',
  7757. headers: { 'Content-Type': 'application/json' },
  7758. body: JSON.stringify({
  7759. interface: iface,
  7760. remote_ip: remote,
  7761. port,
  7762. comment
  7763. })
  7764. });
  7765. if (res.ok) {
  7766. showToast('VTEP Added', `Peer ${remote} added to ${iface}`, 'success');
  7767. closeVXLANVtepModal();
  7768. loadVXLAN(false);
  7769. fetchData(false);
  7770. } else {
  7771. const err = await res.json();
  7772. showToast('Error', err.message, 'error');
  7773. }
  7774. } catch (err) {
  7775. showToast('Error', err.message, 'error');
  7776. }
  7777. }
  7778. async function deleteVXLANVtep(iface, vtepIdOrIp) {
  7779. if (!confirm(`Are you sure you want to remove VTEP ${vtepIdOrIp} from ${iface}?`)) return;
  7780. try {
  7781. const res = await fetch(`${API_BASE}/vpn/vxlan/${encodeURIComponent(iface)}/vteps/${encodeURIComponent(vtepIdOrIp)}`, {
  7782. method: 'DELETE'
  7783. });
  7784. if (res.ok) {
  7785. showToast('Deleted', 'Remote VTEP removed', 'success');
  7786. loadVXLAN(false);
  7787. fetchData(false);
  7788. }
  7789. } catch (err) {
  7790. showToast('Error', err.message, 'error');
  7791. }
  7792. }
  7793. // ======================== AeroTUN (Custom Encrypted VPN with Adaptive LZ4) ========================
  7794. const aeroRateSamples = new Map();
  7795. const aeroLiveRates = new Map();
  7796. async function loadAeroTUN(populate = true) {
  7797. try {
  7798. const [tunnelsRes, statsRes] = await Promise.all([
  7799. fetch(`${API_BASE}/vpn/aerotun/tunnels`),
  7800. fetch(`${API_BASE}/vpn/aerotun/stats`)
  7801. ]);
  7802. if (tunnelsRes.ok) {
  7803. const data = await tunnelsRes.json();
  7804. state.aerotunTunnels = Array.isArray(data) ? data : [];
  7805. const now = Date.now();
  7806. for (const t of state.aerotunTunnels) {
  7807. const old = aeroRateSamples.get(t.id), seconds = old ? (now-old.time)/1000 : 0;
  7808. if (seconds >= 0.5 && seconds <= 60 && t.rx_bytes >= old.rx && t.tx_bytes >= old.tx && t.packets_rx >= old.prx && t.packets_tx >= old.ptx) {
  7809. aeroLiveRates.set(t.id,{rx:(t.rx_bytes-old.rx)*8/seconds/1e6,tx:(t.tx_bytes-old.tx)*8/seconds/1e6,prx:(t.packets_rx-old.prx)/seconds,ptx:(t.packets_tx-old.ptx)/seconds});
  7810. } else if (!old || seconds > 60 || t.rx_bytes < old.rx || t.tx_bytes < old.tx) aeroLiveRates.delete(t.id);
  7811. if (!old || seconds >= 0.5) aeroRateSamples.set(t.id,{time:now,rx:t.rx_bytes||0,tx:t.tx_bytes||0,prx:t.packets_rx||0,ptx:t.packets_tx||0});
  7812. }
  7813. }
  7814. if (statsRes.ok) {
  7815. state.aerotunStats = await statsRes.json();
  7816. }
  7817. const countBadge = document.getElementById('aerotun-count-badge');
  7818. if (countBadge) countBadge.innerText = `${(state.aerotunTunnels || []).length} Tunnels`;
  7819. const sideBadge = document.getElementById('badge-aerotun-count');
  7820. if (sideBadge) sideBadge.innerText = (state.aerotunTunnels || []).length;
  7821. renderAeroTUN();
  7822. if (state.aeroHealthSelected) await refreshAeroTUNHealth();
  7823. } catch (err) {
  7824. console.error('Failed to load AeroTUN:', err);
  7825. }
  7826. }
  7827. function renderAeroTUN() {
  7828. const tbody = document.getElementById('aerotun-table-body');
  7829. const empty = document.getElementById('aerotun-empty');
  7830. // Update summary cards
  7831. const stats = state.aerotunStats || {};
  7832. const tunnels = state.aerotunTunnels || [];
  7833. const statActive = document.getElementById('aerotun-stat-active');
  7834. if (statActive) {
  7835. const activeCount = tunnels.filter(t => t.connected).length;
  7836. statActive.innerText = `${activeCount} / ${tunnels.length}`;
  7837. }
  7838. const statSaved = document.getElementById('aerotun-stat-saved');
  7839. if (statSaved) {
  7840. statSaved.innerText = formatBytes(stats.total_saved_bytes || 0);
  7841. }
  7842. const statRatio = document.getElementById('aerotun-stat-ratio');
  7843. if (statRatio) {
  7844. statRatio.innerText = stats.average_ratio || '1.00x (0% saved)';
  7845. }
  7846. const statTraffic = document.getElementById('aerotun-stat-traffic');
  7847. if (statTraffic) {
  7848. statTraffic.innerText = `↓ ${formatBytes(stats.total_rx_bytes || 0)} / ↑ ${formatBytes(stats.total_tx_bytes || 0)}`;
  7849. }
  7850. if (!tbody) return;
  7851. tbody.innerHTML = '';
  7852. if (tunnels.length === 0) {
  7853. empty?.classList.remove('hidden');
  7854. return;
  7855. }
  7856. empty?.classList.add('hidden');
  7857. tunnels.forEach(t => {
  7858. const tr = document.createElement('tr');
  7859. tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
  7860. const modeBadge = t.mode === 'server'
  7861. ? `<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>`
  7862. : `<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>`;
  7863. const endpointInfo = t.mode === 'server'
  7864. ? `<span class="text-sky-300 font-mono">Port :${t.listen_port || 51830}</span>`
  7865. : `<span class="text-indigo-300 font-mono">${escapeHtml(t.remote_endpoint || '(not set)')}</span>`;
  7866. const compBadge = t.compression
  7867. ? `<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>`
  7868. : `<span class="text-slate-500 text-[10px]">Off</span>`;
  7869. const activePeer = t.connected && t.active_peer_endpoint
  7870. ? `<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>`
  7871. : `<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>`;
  7872. const rawRx = formatBytes(t.rx_bytes || 0);
  7873. const rawTx = formatBytes(t.tx_bytes || 0);
  7874. const wireRx = formatBytes(t.wire_bytes_in || 0);
  7875. const wireTx = formatBytes(t.wire_bytes_out || 0);
  7876. const rate = aeroLiveRates.get(t.id);
  7877. const id = encodeURIComponent(String(t.id || '')).replace(/'/g, '%27');
  7878. tr.innerHTML = `
  7879. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.connected, t.disabled)}</td>
  7880. <td class="py-2.5 px-3 font-bold text-white font-mono flex items-center gap-1.5">
  7881. <span>${escapeHtml(t.name)}</span>
  7882. ${t.default_route ? '<span class="text-[9px] px-1 rounded bg-amber-500/20 text-amber-300 border border-amber-500/30">DEF</span>' : ''}
  7883. <span class="text-slate-400 text-[10px]">v${t.protocol_version || 2}</span>
  7884. </td>
  7885. <td class="py-2.5 px-3">${modeBadge}</td>
  7886. <td class="py-2.5 px-3 text-xs font-mono">${endpointInfo}</td>
  7887. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${escapeHtml(t.local_address || '-')}</td>
  7888. <td class="py-2.5 px-3">${compBadge}</td>
  7889. <td class="py-2.5 px-3">${activePeer}</td>
  7890. <td class="py-2.5 px-3 font-mono text-[11px]">
  7891. <span class="text-emerald-400">↓ ${rawRx}</span>
  7892. <span class="text-cyan-400 ml-1">↑ ${rawTx}</span>
  7893. ${rate ? `<div class="text-slate-400">↓ ${rate.rx.toFixed(2)} / ↑ ${rate.tx.toFixed(2)} Mbit/s</div>` : ''}
  7894. </td>
  7895. <td class="py-2.5 px-3 font-mono text-[11px]">
  7896. <span class="text-slate-400">↓ ${wireRx}</span>
  7897. <span class="text-slate-400 ml-1">↑ ${wireTx}</span>
  7898. </td>
  7899. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(t.comment || '')}">${escapeHtml(t.comment || '-')}</td>
  7900. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  7901. <button onclick="openAeroTUNHealth('${id}')" class="text-xs text-sky-400 hover:text-sky-300 font-medium">Health</button>
  7902. ${t.running
  7903. ? `<button onclick="stopAeroTUNTunnel('${t.id}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Stop</button>`
  7904. : `<button onclick="startAeroTUNTunnel('${t.id}')" class="text-xs text-emerald-400 hover:text-emerald-300 font-medium">Start</button>`
  7905. }
  7906. <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>
  7907. <button onclick="openEditAeroTUNModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  7908. <button onclick="deleteAeroTUN('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  7909. </td>
  7910. `;
  7911. tbody.appendChild(tr);
  7912. });
  7913. }
  7914. async function openAeroTUNHealth(encodedID) {
  7915. state.aeroHealthSelected = decodeURIComponent(encodedID);
  7916. const tunnel=(state.aerotunTunnels||[]).find(x=>x.id===state.aeroHealthSelected);
  7917. let underlay='';try {underlay=new URL(`http://${tunnel?.remote_endpoint||tunnel?.active_peer_endpoint||''}`).hostname.replace(/^\[|\]$/g,'')} catch {}
  7918. document.getElementById('aerotun-compare-host').value=underlay;
  7919. document.getElementById('aerotun-compare-result').textContent='';
  7920. document.getElementById('aerotun-health-result').textContent = '';
  7921. document.getElementById('aerotun-health-panel').classList.remove('hidden');
  7922. await refreshAeroTUNHealth();
  7923. document.getElementById('aerotun-health-panel').scrollIntoView({behavior:'smooth',block:'nearest'});
  7924. }
  7925. function closeAeroTUNHealth() { aeroCompareCancel=true; state.aeroHealthSelected = ''; document.getElementById('aerotun-health-panel').classList.add('hidden'); }
  7926. async function refreshAeroTUNHealth() {
  7927. const id=state.aeroHealthSelected,t=(state.aerotunTunnels||[]).find(x=>x.id===id);if(!id)return;
  7928. if(!t){document.getElementById('aerotun-health-status').textContent='Tunnel no longer exists.';return}
  7929. document.getElementById('aerotun-health-title').textContent=`Health: ${t.name}`;
  7930. try {
  7931. const response=await fetch(`${API_BASE}/vpn/aerotun/health`);if(!response.ok)throw new Error(await responseError(response));const data=await response.json();if(state.aeroHealthSelected!==id)return;
  7932. const current=(data.states||[]).find(x=>x.tunnel_id===id);const status=current?.status||'unknown';const since=current?.since&&!current.since.startsWith('0001')?new Date(current.since).toLocaleString():'—';const rate=aeroLiveRates.get(id);
  7933. const d=t.drop_breakdown;
  7934. document.getElementById('aerotun-health-status').textContent=`Status: ${status} since ${since} · Backend: ${t.backend||'—'} · MTU: ${t.mtu||'—'} / configured ${t.configured_mtu||(!t.running?t.mtu:'—')||'—'} · Last authenticated packet: ${t.last_handshake||'never'} · Drops: ${t.dropped_packets||0}${d?` (outgoing invalid ${d.invalid_outgoing}, session ${d.missing_session}, send ${d.send_failure}, incoming invalid ${d.invalid_incoming}, source policy ${d.source_policy}, interface ${d.interface_write})`:''} · Authentication failures: ${t.auth_failures||0} · Replay drops: ${t.replay_drops||0}${Number.isFinite(data.service_cpu_percent)?` · Service CPU (all features): ${data.service_cpu_percent.toFixed(1)}% of one core`:''}${rate?` · RX/TX: ${rate.rx.toFixed(2)} / ${rate.tx.toFixed(2)} Mbit/s, ${rate.prx.toFixed(0)} / ${rate.ptx.toFixed(0)} packets/s`:''}${t.last_error?` · Last error: ${t.last_error}`:''}`;
  7935. const events=(data.events||[]).filter(e=>e.tunnel_id===id).slice(0,100),node=document.getElementById('aerotun-health-history');node.replaceChildren();
  7936. if(!events.length){node.textContent='No events recorded yet.';return}
  7937. for(const e of events){const line=document.createElement('div');line.textContent=`${new Date(e.time).toLocaleString()} · ${e.type==='check'?'Check':(e.previous?`${e.previous} → ${e.status}${e.previous_duration_seconds?` (after ${Math.round(e.previous_duration_seconds)} s)`:''}`:e.status)}${e.detail?` · ${e.detail}`:''}`;node.appendChild(line)}
  7938. } catch(e){document.getElementById('aerotun-health-history').textContent=`Health history unavailable: ${e.message}`}
  7939. }
  7940. async function runAeroTUNHealthCheck() {
  7941. const id=state.aeroHealthSelected;if(!id)return;const button=document.getElementById('aerotun-health-check-btn'),output=document.getElementById('aerotun-health-result');button.disabled=true;output.textContent='Checking…';
  7942. try {const response=await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/health-check`,{method:'POST'});if(!response.ok)throw new Error(await responseError(response));const r=await response.json();if(state.aeroHealthSelected!==id)return;output.textContent=`Peer echo: ${r.reachability}${r.rtt_ms!=null?` · RTT ${r.rtt_upper_bound?'<':''}${r.rtt_ms} ms`:''} · ${r.mtu}-byte overlay probe: ${r.mtu_probe}. ${r.explanation}`;await refreshAeroTUNHealth()}
  7943. catch(e){if(state.aeroHealthSelected===id)output.textContent=`Health check failed: ${e.message}`}
  7944. finally {button.disabled=false}
  7945. }
  7946. let aeroCompareRunning=false, aeroCompareCancel=false;
  7947. function stopAeroTUNComparison() { aeroCompareCancel=true;document.getElementById('aerotun-compare-result').textContent+='\nStopping after the current test.'; }
  7948. async function runAeroTUNComparison() {
  7949. if(aeroCompareRunning)return;
  7950. const id=state.aeroHealthSelected,t=(state.aerotunTunnels||[]).find(x=>x.id===id),direct=document.getElementById('aerotun-compare-host').value.trim(),port=Number(document.getElementById('aerotun-compare-port').value),peer=(t?.peer_address||'').split('/')[0].trim();
  7951. const output=document.getElementById('aerotun-compare-result'),button=document.getElementById('aerotun-compare-btn'),stop=document.getElementById('aerotun-compare-stop');
  7952. if(!t?.connected||!peer||!direct||!Number.isInteger(port)||port<1||port>65535||peer===direct){output.textContent='A connected tunnel, peer IP, different direct server address and valid port are required.';return}
  7953. if(peer.includes(':')||direct.includes(':')){output.textContent='This comparison currently supports IPv4 addresses or IPv4-resolvable hostnames.';return}
  7954. aeroCompareRunning=true;aeroCompareCancel=false;button.disabled=true;stop.classList.remove('hidden');output.textContent='Starting. The direct address uses the system routing table.';
  7955. const get=async(path,body)=>{const r=await fetch(`${API_BASE}${path}`,body?{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(body)}:{});if(!r.ok)throw new Error(await responseError(r));return r.json()};
  7956. const results=[];
  7957. try {
  7958. for(const [path,target,direction] of [['Tunnel',peer,'tx'],['Tunnel',peer,'rx'],['Direct',direct,'tx'],['Direct',direct,'rx']]) {
  7959. if(aeroCompareCancel)break;
  7960. if((await get('/tools/bwtest/status')).running)throw new Error('Another bandwidth test is running; comparison stopped.');
  7961. output.textContent+=`\n${path} ${direction.toUpperCase()}: testing…`;
  7962. const started=await get('/tools/bwtest/start',{target,port,protocol:'tcp',direction,bandwidth_limit:0,packet_size:1200,streams:2,duration:8}),session=started.session_id;let status,complete=false;
  7963. for(let i=0;i<30;i++){await new Promise(resolve=>setTimeout(resolve,1000));status=await get('/tools/bwtest/status');if(status.session_id!==session)throw new Error('Bandwidth test session changed; comparison stopped.');if(!status.running){complete=true;break}}
  7964. if(!complete)throw new Error('Timed out waiting for the bandwidth test.');if(status.error)throw new Error(`${path} ${direction.toUpperCase()}: ${status.error}`);
  7965. const value=status.summary?.[direction==='tx'?'avg_tx_mbps':'avg_rx_mbps'];if(!Number.isFinite(value)||value<=0)throw new Error(`${path} ${direction.toUpperCase()}: no delivered data.`);
  7966. results.push(`${path} ${direction.toUpperCase()}: ${value.toFixed(2)} Mbit/s`);output.textContent='Results:\n'+results.join('\n');
  7967. }
  7968. if(aeroCompareCancel)output.textContent+='\nComparison stopped.';
  7969. else output.textContent+='\nDirect results are meaningful only if both addresses reach the same server over different routes.';
  7970. } catch(e){output.textContent+=`\nComparison incomplete: ${e.message}`}
  7971. finally {aeroCompareRunning=false;button.disabled=false;stop.classList.add('hidden')}
  7972. }
  7973. let aeroModalGeneration = 0;
  7974. let aeroIdentityDraft = '';
  7975. let aeroSaving = false;
  7976. let aeroPSKRequest = 0;
  7977. function discardAeroIdentityDraft(id) {
  7978. if (id) fetch(`${API_BASE}/vpn/aerotun/identity-drafts/${encodeURIComponent(id)}`, {method:'DELETE'}).catch(() => {});
  7979. }
  7980. async function generateAeroTUNIdentity() {
  7981. const generation = aeroModalGeneration;
  7982. const retry = document.getElementById('aerotun-retry-identity');
  7983. if (aeroIdentityDraft) { discardAeroIdentityDraft(aeroIdentityDraft); aeroIdentityDraft = ''; }
  7984. retry.classList.add('hidden');
  7985. document.getElementById('aerotun-modal-public').value = '';
  7986. try {
  7987. const res = await fetch(`${API_BASE}/vpn/aerotun/identity-drafts`, {method:'POST'});
  7988. if (!res.ok) throw new Error(await responseError(res));
  7989. const draft = await res.json();
  7990. if (generation !== aeroModalGeneration) { discardAeroIdentityDraft(draft.draft_id); return; }
  7991. aeroIdentityDraft = draft.draft_id;
  7992. document.getElementById('aerotun-modal-public').value = draft.public_key;
  7993. updateAeroTUNSetupHint();
  7994. } catch (err) {
  7995. if (generation !== aeroModalGeneration) return;
  7996. retry.classList.remove('hidden');
  7997. updateAeroTUNSetupHint();
  7998. showToast('Identity Generation Failed', err.message, 'error');
  7999. }
  8000. }
  8001. function onAeroTUNModeChange() {
  8002. const mode = document.getElementById('aerotun-modal-mode').value;
  8003. const endpointInput = document.getElementById('aerotun-modal-endpoint');
  8004. const portInput = document.getElementById('aerotun-modal-port');
  8005. if (mode === 'server') {
  8006. if (!portInput.value) portInput.value = '51830';
  8007. endpointInput.placeholder = 'Optional / learned roaming peer';
  8008. } else {
  8009. endpointInput.placeholder = 'vpn.example.com:51830 (required)';
  8010. if (!portInput.value) portInput.value = '';
  8011. }
  8012. }
  8013. function onAeroTUNPeerChange() {
  8014. const peer = document.getElementById('aerotun-modal-peer');
  8015. const allowed = document.getElementById('aerotun-modal-allowed');
  8016. const previous = peer.dataset.allowedDefault || '';
  8017. const host = peer.value.trim().split('/')[0];
  8018. const next = host ? `${host}/${host.includes(':') ? 128 : 32}` : '';
  8019. if (allowed.value.trim() === previous) allowed.value = next;
  8020. peer.dataset.allowedDefault = next;
  8021. }
  8022. async function generateAeroTUNKey(automatic = false) {
  8023. const generation = aeroModalGeneration, request = ++aeroPSKRequest;
  8024. const input = document.getElementById('aerotun-modal-psk'), previous = input.value;
  8025. try {
  8026. const res = await fetch(`${API_BASE}/vpn/aerotun/genkey`);
  8027. if (!res.ok) throw new Error(await responseError(res));
  8028. const data = await res.json();
  8029. if (generation !== aeroModalGeneration || request !== aeroPSKRequest || (automatic && input.value !== previous)) return;
  8030. input.value = data.key;
  8031. if (!automatic) showToast('Key Generated', 'Share this PSK securely with the peer before enabling', 'success');
  8032. } catch (err) {
  8033. if (generation === aeroModalGeneration && request === aeroPSKRequest) showToast('Key Generation Failed', err.message, 'error');
  8034. }
  8035. }
  8036. function updateAeroTUNSetupHint() {
  8037. const version = document.getElementById('aerotun-modal-protocol').value;
  8038. const key = document.getElementById('aerotun-modal-public').value;
  8039. const peer = document.getElementById('aerotun-modal-peerkey').value.trim();
  8040. const hint = document.getElementById('aerotun-setup-hint');
  8041. document.getElementById('aerotun-v3-fields').classList.toggle('hidden', version !== '3');
  8042. if (!hint) return;
  8043. hint.innerText = version !== '3' ? 'Legacy v2 uses a shared PSK. Both endpoints must use the same protocol.' : !key ? (document.getElementById('aerotun-modal-id').value ? 'Save this existing tunnel disabled to create its v3 identity, then exchange public keys.' : 'Generating the local identity. You can fill in the other settings while you wait.') : !peer ? 'Copy the local public key to the peer and paste its public key here. Use the same PSK on both endpoints; save disabled if the peer key is not ready.' : 'Check reciprocal addresses, allowed peer source prefixes and the shared PSK before enabling. Allowed prefixes do not create LAN routes.';
  8044. }
  8045. async function copyAeroTUNPublicKey() {
  8046. const input = document.getElementById('aerotun-modal-public');
  8047. if (!input.value) { showToast('Key Not Ready', 'Wait for the local identity or retry key generation.', 'info'); return; }
  8048. try {
  8049. await navigator.clipboard.writeText(input.value);
  8050. showToast('Public Key Copied', 'Paste it into the other endpoint’s pinned peer key', 'success');
  8051. } catch {
  8052. input.focus(); input.select();
  8053. showToast('Copy Public Key', 'Key selected; press Ctrl+C to copy', 'info');
  8054. }
  8055. }
  8056. async function copyAeroTUNPSK() {
  8057. const input = document.getElementById('aerotun-modal-psk');
  8058. if (!input.value) { showToast('PSK Not Available', 'Generate or enter a PSK to copy it. Existing keys are not displayed.', 'info'); return; }
  8059. try { await navigator.clipboard.writeText(input.value); showToast('PSK Copied', 'Share it securely with the peer.', 'success'); }
  8060. catch { input.type = 'text'; input.focus(); input.select(); showToast('Copy PSK', 'Key selected; press Ctrl+C to copy.', 'info'); }
  8061. }
  8062. function openAddAeroTUNModal() {
  8063. if (aeroSaving) return;
  8064. aeroModalGeneration++; discardAeroIdentityDraft(aeroIdentityDraft); aeroIdentityDraft = '';
  8065. const tunnels = state.aerotunTunnels || [];
  8066. const usedNames = new Set(tunnels.map(t => t.name));
  8067. const usedPorts = new Set(tunnels.map(t => Number(t.listen_port)));
  8068. let index = 0; while (index < 256 && (usedNames.has(`aerotun${index}`) || usedPorts.has(51830 + index) || tunnels.some(t => (t.local_address || '').startsWith(`10.99.${index}.`)))) index++;
  8069. if (index >= 256) index = 0;
  8070. document.getElementById('aerotun-modal-title').innerText = 'Add AeroTUN Interface';
  8071. document.getElementById('aerotun-modal-id').value = '';
  8072. document.getElementById('aerotun-modal-protocol').value='3';
  8073. document.getElementById('aerotun-modal-public').value='';
  8074. document.getElementById('aerotun-modal-peerkey').value='';
  8075. document.getElementById('aerotun-modal-allowed').value=`10.99.${index}.2/32`;
  8076. document.getElementById('aerotun-modal-name').value = `aerotun${index}`;
  8077. document.getElementById('aerotun-modal-mode').value = 'server';
  8078. document.getElementById('aerotun-modal-port').value = 51830 + index;
  8079. document.getElementById('aerotun-modal-endpoint').value = '';
  8080. document.getElementById('aerotun-modal-local').value = `10.99.${index}.1/24`;
  8081. document.getElementById('aerotun-modal-peer').value = `10.99.${index}.2/24`;
  8082. document.getElementById('aerotun-modal-peer').dataset.allowedDefault = `10.99.${index}.2/32`;
  8083. document.getElementById('aerotun-modal-psk').value = '';
  8084. document.getElementById('aerotun-modal-mtu').value = '1420';
  8085. document.getElementById('aerotun-modal-comment').value = '';
  8086. document.getElementById('aerotun-modal-compression').checked = false;
  8087. document.getElementById('aerotun-modal-defroute').checked = false;
  8088. document.getElementById('aerotun-modal-disabled').checked = true;
  8089. document.getElementById('aerotun-modal-psk').type = 'password';
  8090. document.getElementById('aerotun-modal-psk').placeholder = 'Generate or enter the shared key';
  8091. onAeroTUNModeChange();
  8092. updateAeroTUNSetupHint();
  8093. document.getElementById('aerotun-modal').classList.remove('hidden');
  8094. generateAeroTUNKey(true);
  8095. generateAeroTUNIdentity();
  8096. }
  8097. function openEditAeroTUNModal(id) {
  8098. if (aeroSaving) return;
  8099. const t = (state.aerotunTunnels || []).find(tun => tun.id === id);
  8100. if (!t) return;
  8101. aeroModalGeneration++; discardAeroIdentityDraft(aeroIdentityDraft); aeroIdentityDraft = '';
  8102. document.getElementById('aerotun-retry-identity').classList.add('hidden');
  8103. document.getElementById('aerotun-modal-title').innerText = `Edit AeroTUN Interface (${t.name})`;
  8104. document.getElementById('aerotun-modal-id').value = t.id;
  8105. document.getElementById('aerotun-modal-protocol').value=String(t.protocol_version || 2);
  8106. document.getElementById('aerotun-modal-public').value=t.public_key || '';
  8107. document.getElementById('aerotun-modal-peerkey').value=t.peer_public_key || '';
  8108. document.getElementById('aerotun-modal-allowed').value=(t.allowed_ips || []).join(', ');
  8109. document.getElementById('aerotun-modal-name').value = t.name;
  8110. document.getElementById('aerotun-modal-mode').value = t.mode || 'server';
  8111. document.getElementById('aerotun-modal-port').value = t.listen_port || '';
  8112. document.getElementById('aerotun-modal-endpoint').value = t.remote_endpoint || '';
  8113. document.getElementById('aerotun-modal-local').value = t.local_address || '';
  8114. document.getElementById('aerotun-modal-peer').value = t.peer_address || '';
  8115. const peerHost = (t.peer_address || '').split('/')[0];
  8116. document.getElementById('aerotun-modal-peer').dataset.allowedDefault = peerHost ? `${peerHost}/${peerHost.includes(':') ? 128 : 32}` : '';
  8117. document.getElementById('aerotun-modal-psk').value = '';
  8118. document.getElementById('aerotun-modal-psk').type = 'password';
  8119. document.getElementById('aerotun-modal-psk').placeholder = t.has_psk ? 'Leave blank to keep the existing key' : 'New random 256-bit PSK';
  8120. document.getElementById('aerotun-modal-mtu').value = t.configured_mtu || t.mtu || 1420;
  8121. document.getElementById('aerotun-modal-comment').value = t.comment || '';
  8122. document.getElementById('aerotun-modal-compression').checked = !!t.compression;
  8123. document.getElementById('aerotun-modal-defroute').checked = !!t.default_route;
  8124. document.getElementById('aerotun-modal-disabled').checked = !!t.disabled;
  8125. onAeroTUNModeChange();
  8126. updateAeroTUNSetupHint();
  8127. document.getElementById('aerotun-modal').classList.remove('hidden');
  8128. }
  8129. function closeAeroTUNModal() {
  8130. if (aeroSaving) return;
  8131. aeroModalGeneration++; discardAeroIdentityDraft(aeroIdentityDraft); aeroIdentityDraft = '';
  8132. document.getElementById('aerotun-modal-psk').value = '';
  8133. document.getElementById('aerotun-modal').classList.add('hidden');
  8134. }
  8135. async function submitSaveAeroTUN(e) {
  8136. e.preventDefault();
  8137. if (aeroSaving) return;
  8138. const id = document.getElementById('aerotun-modal-id').value;
  8139. const name = document.getElementById('aerotun-modal-name').value.trim();
  8140. const mode = document.getElementById('aerotun-modal-mode').value;
  8141. const port = parseInt(document.getElementById('aerotun-modal-port').value) || 0;
  8142. const endpoint = document.getElementById('aerotun-modal-endpoint').value.trim();
  8143. const local = document.getElementById('aerotun-modal-local').value.trim();
  8144. const peer = document.getElementById('aerotun-modal-peer').value.trim();
  8145. const psk = document.getElementById('aerotun-modal-psk').value.trim();
  8146. const mtuValue = document.getElementById('aerotun-modal-mtu').value;
  8147. const mtu = mtuValue === '' ? 1420 : Number(mtuValue);
  8148. const comment = document.getElementById('aerotun-modal-comment').value.trim();
  8149. const compression = document.getElementById('aerotun-modal-compression').checked;
  8150. const defaultRoute = document.getElementById('aerotun-modal-defroute').checked;
  8151. const disabled = document.getElementById('aerotun-modal-disabled').checked;
  8152. if (mode === 'client' && !endpoint) {
  8153. showToast('Validation Error', 'Remote endpoint (host:port) is required in client mode', 'error');
  8154. return;
  8155. }
  8156. if (defaultRoute && (mode !== 'client' || !endpoint)) {
  8157. showToast('Validation Error', 'Default route requires client mode and a fixed remote endpoint.', 'error');
  8158. return;
  8159. }
  8160. if (!Number.isInteger(mtu) || mtu < 576 || mtu > 9000) {
  8161. showToast('Validation Error', 'MTU must be between 576 and 9000.', 'error');
  8162. return;
  8163. }
  8164. const version = parseInt(document.getElementById('aerotun-modal-protocol').value, 10);
  8165. if (version === 3 && !id && !aeroIdentityDraft) {
  8166. showToast('Local Key Not Ready', 'Wait for the local identity or retry key generation before saving.', 'error');
  8167. return;
  8168. }
  8169. if (version === 3 && !document.getElementById('aerotun-modal-allowed').value.trim()) {
  8170. showToast('Allowed Prefix Required', 'Enter at least one allowed peer source prefix, such as the peer tunnel IP /32.', 'error');
  8171. document.getElementById('aerotun-modal-allowed').focus();
  8172. return;
  8173. }
  8174. if (version === 3 && !disabled && !document.getElementById('aerotun-modal-peerkey').value.trim()) {
  8175. showToast('Peer Key Required', 'Enter the peer public key, or save this tunnel disabled until it is available.', 'error');
  8176. return;
  8177. }
  8178. if (!psk && !id) {
  8179. showToast('Validation Error', 'Pre-shared key (PSK) is required', 'error');
  8180. return;
  8181. }
  8182. aeroSaving = true;
  8183. const submit = document.querySelector('#aerotun-modal button[type="submit"]');
  8184. if (submit) submit.disabled = true;
  8185. try {
  8186. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels`, {
  8187. method: 'POST',
  8188. headers: { 'Content-Type': 'application/json' },
  8189. body: JSON.stringify({
  8190. protocol_version:parseInt(document.getElementById('aerotun-modal-protocol').value,10),
  8191. identity_draft_id: version === 3 && !id ? aeroIdentityDraft : '',
  8192. peer_public_key:document.getElementById('aerotun-modal-peerkey').value.trim(),
  8193. allowed_ips:document.getElementById('aerotun-modal-allowed').value.split(',').map(s=>s.trim()).filter(Boolean),
  8194. id,
  8195. name,
  8196. mode,
  8197. listen_port: port,
  8198. remote_endpoint: endpoint,
  8199. local_address: local,
  8200. peer_address: peer,
  8201. psk,
  8202. mtu,
  8203. compression,
  8204. default_route: defaultRoute,
  8205. comment,
  8206. disabled
  8207. })
  8208. });
  8209. if (res.ok) {
  8210. await res.json();
  8211. if (version !== 3) discardAeroIdentityDraft(aeroIdentityDraft);
  8212. aeroIdentityDraft = '';
  8213. aeroSaving = false;
  8214. closeAeroTUNModal();
  8215. await loadAeroTUN(false);
  8216. showToast('AeroTUN Saved', disabled ? 'Configuration saved; tunnel is disabled' : 'Configuration saved; waiting for authenticated peer traffic', 'success');
  8217. fetchData(false);
  8218. } else {
  8219. const err = await responseError(res);
  8220. if (err.includes('configuration saved but tunnel failed to start')) {
  8221. aeroIdentityDraft = '';
  8222. aeroSaving = false;
  8223. closeAeroTUNModal();
  8224. await loadAeroTUN(false);
  8225. showToast('Saved, but not started', err, 'error');
  8226. } else showToast('Error Saving Tunnel', err, 'error');
  8227. }
  8228. } catch (err) {
  8229. showToast('Network Error', err.message, 'error');
  8230. } finally {
  8231. aeroSaving = false;
  8232. if (submit) submit.disabled = false;
  8233. }
  8234. }
  8235. async function startAeroTUNTunnel(id) {
  8236. try {
  8237. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/start`, { method: 'POST' });
  8238. if (res.ok) {
  8239. showToast('AeroTUN Started', 'Interface started; connection is confirmed by authenticated peer traffic', 'info');
  8240. loadAeroTUN(false);
  8241. fetchData(false);
  8242. } else {
  8243. const err = await res.text();
  8244. showToast('Failed to Start', err, 'error');
  8245. }
  8246. } catch (err) {
  8247. showToast('Error', err.message, 'error');
  8248. }
  8249. }
  8250. async function stopAeroTUNTunnel(id) {
  8251. try {
  8252. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/stop`, { method: 'POST' });
  8253. if (res.ok) {
  8254. showToast('AeroTUN Stopped', 'Tunnel stopped', 'info');
  8255. loadAeroTUN(false);
  8256. fetchData(false);
  8257. } else {
  8258. const err = await res.text();
  8259. showToast('Failed to Stop', err, 'error');
  8260. }
  8261. } catch (err) {
  8262. showToast('Error', err.message, 'error');
  8263. }
  8264. }
  8265. async function toggleAeroTUNState(id, disabled) {
  8266. try {
  8267. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/state`, {
  8268. method: 'POST',
  8269. headers: { 'Content-Type': 'application/json' },
  8270. body: JSON.stringify({ disabled })
  8271. });
  8272. if (res.ok) {
  8273. showToast('State Updated', disabled ? 'Tunnel disabled' : 'Tunnel enabled', 'info');
  8274. loadAeroTUN(false);
  8275. fetchData(false);
  8276. }
  8277. } catch (err) {
  8278. showToast('Error', err.message, 'error');
  8279. }
  8280. }
  8281. async function deleteAeroTUN(id) {
  8282. if (!confirm('Are you sure you want to delete this AeroTUN tunnel?')) return;
  8283. try {
  8284. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8285. if (res.ok) {
  8286. showToast('Deleted', 'AeroTUN tunnel removed', 'success');
  8287. loadAeroTUN(false);
  8288. fetchData(false);
  8289. }
  8290. } catch (err) {
  8291. showToast('Error', err.message, 'error');
  8292. }
  8293. }
  8294. // ======================== PPP Central Hub & Servers ========================
  8295. function switchPPPSubTab(tab) {
  8296. state.pppSubTab = tab;
  8297. const tabs = ['secrets', 'profiles', 'pppoe', 'pptp', 'l2tp', 'active'];
  8298. tabs.forEach(t => {
  8299. const panel = document.getElementById(`ppp-subtab-${t}`);
  8300. const btn = document.getElementById(`ppp-subtab-btn-${t}`);
  8301. if (panel) {
  8302. if (t === tab) panel.classList.remove('hidden');
  8303. else panel.classList.add('hidden');
  8304. }
  8305. if (btn) {
  8306. if (t === tab) {
  8307. 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';
  8308. } else {
  8309. 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';
  8310. }
  8311. }
  8312. });
  8313. const addBtn = document.getElementById('ppp-primary-add-btn');
  8314. if (addBtn) {
  8315. if (tab === 'secrets') addBtn.innerHTML = '<span>+ Add User (Secret)</span>';
  8316. else if (tab === 'profiles') addBtn.innerHTML = '<span>+ Add Profile</span>';
  8317. else if (tab === 'active') addBtn.innerHTML = '<span>Refresh Sessions</span>';
  8318. else addBtn.innerHTML = '<span>Save Config</span>';
  8319. }
  8320. if (tab === 'active') loadPPPSessions();
  8321. }
  8322. function openCurrentPPPModal() {
  8323. if (state.pppSubTab === 'secrets') openAddPPPSecretModal();
  8324. else if (state.pppSubTab === 'profiles') openAddPPPProfileModal();
  8325. else if (state.pppSubTab === 'active') loadPPPSessions();
  8326. else if (state.pppSubTab === 'pppoe') document.querySelector('#ppp-subtab-pppoe form')?.requestSubmit();
  8327. else if (state.pppSubTab === 'pptp') document.querySelector('#ppp-subtab-pptp form')?.requestSubmit();
  8328. else if (state.pppSubTab === 'l2tp') document.querySelector('#ppp-subtab-l2tp form')?.requestSubmit();
  8329. }
  8330. async function loadPPP(populateDropdowns = true) {
  8331. await Promise.all([
  8332. loadPPPSecrets(),
  8333. loadPPPProfiles(),
  8334. loadPPPServers(),
  8335. loadPPPSessions()
  8336. ]);
  8337. }
  8338. async function loadPPPSecrets() {
  8339. try {
  8340. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`);
  8341. const data = await res.json();
  8342. state.pppSecrets = Array.isArray(data) ? data : [];
  8343. const b = document.getElementById('ppp-badge-secrets');
  8344. if (b) b.innerText = state.pppSecrets.length;
  8345. const b2 = document.getElementById('secrets-count-badge');
  8346. if (b2) b2.innerText = `${state.pppSecrets.length} Users`;
  8347. renderPPPSecrets();
  8348. } catch (err) {
  8349. console.error('Failed to load PPP secrets:', err);
  8350. }
  8351. }
  8352. function renderPPPSecrets() {
  8353. const tbody = document.getElementById('secrets-table-body');
  8354. const empty = document.getElementById('secrets-empty');
  8355. if (!tbody) return;
  8356. tbody.innerHTML = '';
  8357. const secrets = state.pppSecrets || [];
  8358. if (secrets.length === 0) {
  8359. empty?.classList.remove('hidden');
  8360. return;
  8361. }
  8362. empty?.classList.add('hidden');
  8363. secrets.forEach(s => {
  8364. const tr = document.createElement('tr');
  8365. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  8366. tr.innerHTML = `
  8367. <td class="py-2.5 px-3 text-center">${renderRuleFlag(s.disabled, !!s.comment)}</td>
  8368. <td class="py-2.5 px-3 font-bold text-white font-mono">${s.name}</td>
  8369. <td class="py-2.5 px-3 text-purple-300 font-mono font-semibold">${s.service}</td>
  8370. <td class="py-2.5 px-3 text-amber-300 font-mono">${s.profile}</td>
  8371. <td class="py-2.5 px-3 text-slate-400 font-mono">${s.local_address || '(profile)'}</td>
  8372. <td class="py-2.5 px-3 text-cyan-400 font-mono font-bold">${s.remote_address || '(profile)'}</td>
  8373. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]">${s.comment || '-'}</td>
  8374. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  8375. <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>
  8376. <button onclick="openEditPPPSecretModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  8377. <button onclick="deletePPPSecret('${s.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  8378. </td>
  8379. `;
  8380. tbody.appendChild(tr);
  8381. });
  8382. }
  8383. async function loadPPPProfiles() {
  8384. try {
  8385. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`);
  8386. const data = await res.json();
  8387. state.pppProfiles = Array.isArray(data) ? data : [];
  8388. const b = document.getElementById('ppp-badge-profiles');
  8389. if (b) b.innerText = state.pppProfiles.length;
  8390. const b2 = document.getElementById('profiles-count-badge');
  8391. if (b2) b2.innerText = `${state.pppProfiles.length} Profiles`;
  8392. // Populate profile selects across modals
  8393. const selects = ['secret-modal-profile', 'pppoe-server-profile', 'pptp-server-profile', 'l2tp-server-profile'];
  8394. selects.forEach(sid => {
  8395. const el = document.getElementById(sid);
  8396. if (!el) return;
  8397. const cur = el.value;
  8398. el.innerHTML = '';
  8399. state.pppProfiles.forEach(p => {
  8400. const opt = document.createElement('option');
  8401. opt.value = p.name;
  8402. opt.innerText = `${p.name} (${p.remote_address})`;
  8403. if (p.name === cur) opt.selected = true;
  8404. el.appendChild(opt);
  8405. });
  8406. });
  8407. renderPPPProfiles();
  8408. } catch (err) {
  8409. console.error('Failed to load PPP profiles:', err);
  8410. }
  8411. }
  8412. function renderPPPProfiles() {
  8413. const tbody = document.getElementById('profiles-table-body');
  8414. if (!tbody) return;
  8415. tbody.innerHTML = '';
  8416. (state.pppProfiles || []).forEach(p => {
  8417. const isDefault = p.name.startsWith('default');
  8418. const tr = document.createElement('tr');
  8419. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  8420. tr.innerHTML = `
  8421. <td class="py-2.5 px-3 font-bold text-white">${p.name}</td>
  8422. <td class="py-2.5 px-3 text-slate-300">${p.local_address}</td>
  8423. <td class="py-2.5 px-3 text-cyan-400 font-bold">${p.remote_address}</td>
  8424. <td class="py-2.5 px-3 text-slate-400">${p.dns_servers || '-'}</td>
  8425. <td class="py-2.5 px-3 text-purple-300 font-semibold">${p.use_encryption}</td>
  8426. <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>
  8427. <td class="py-2.5 px-3 text-slate-400 italic">${p.comment || '-'}</td>
  8428. <td class="py-2.5 px-3 text-right font-sans whitespace-nowrap">
  8429. ${!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>`}
  8430. </td>
  8431. `;
  8432. tbody.appendChild(tr);
  8433. });
  8434. }
  8435. async function loadPPPServers() {
  8436. try {
  8437. const [pppoeRes, pptpRes, l2tpRes, ipsecRes] = await Promise.all([
  8438. fetch(`${API_BASE}/vpn/servers/pppoe`),
  8439. fetch(`${API_BASE}/vpn/servers/pptp`),
  8440. fetch(`${API_BASE}/vpn/servers/l2tp`),
  8441. fetch(`${API_BASE}/vpn/servers/ipsec`)
  8442. ]);
  8443. if (pppoeRes.ok) {
  8444. state.pppoeServer = await pppoeRes.json();
  8445. const s = state.pppoeServer;
  8446. document.getElementById('pppoe-server-enabled').checked = !!s.enabled;
  8447. document.getElementById('pppoe-server-name').value = s.service_name || 'debtik-pppoe';
  8448. populateInterfaceSelect('pppoe-server-iface', s.interface || 'eth0');
  8449. document.getElementById('pppoe-server-profile').value = s.default_profile || 'default';
  8450. document.getElementById('pppoe-server-mtu').value = s.max_mtu || 1480;
  8451. document.getElementById('pppoe-server-onesession').checked = !!s.one_session_per_host;
  8452. const pill = document.getElementById('pppoe-server-status-pill');
  8453. if (pill) {
  8454. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  8455. 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';
  8456. }
  8457. setDotBadge('ppp-badge-pppoe-state', s.running);
  8458. }
  8459. if (pptpRes.ok) {
  8460. state.pptpServer = await pptpRes.json();
  8461. const s = state.pptpServer;
  8462. document.getElementById('pptp-server-enabled').checked = !!s.enabled;
  8463. document.getElementById('pptp-server-port').value = s.port || 1723;
  8464. document.getElementById('pptp-server-profile').value = s.default_profile || 'default-encryption';
  8465. document.getElementById('pptp-server-mppe').checked = s.require_mppe !== false;
  8466. const pill = document.getElementById('pptp-server-status-pill');
  8467. if (pill) {
  8468. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  8469. 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';
  8470. }
  8471. setDotBadge('ppp-badge-pptp-state', s.running);
  8472. }
  8473. if (l2tpRes.ok) {
  8474. state.l2tpServer = await l2tpRes.json();
  8475. const s = state.l2tpServer;
  8476. document.getElementById('l2tp-server-enabled').checked = !!s.enabled;
  8477. document.getElementById('l2tp-server-port').value = s.port || 1701;
  8478. document.getElementById('l2tp-server-profile').value = s.default_profile || 'default';
  8479. document.getElementById('l2tp-server-useipsec').value = s.use_ipsec || 'no';
  8480. document.getElementById('l2tp-server-ipsecsecret').value = s.ipsec_secret || '';
  8481. const pill = document.getElementById('l2tp-server-status-pill');
  8482. if (pill) {
  8483. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  8484. 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';
  8485. }
  8486. setDotBadge('ppp-badge-l2tp-state', s.running);
  8487. }
  8488. if (ipsecRes.ok) {
  8489. state.ipsecServer = await ipsecRes.json();
  8490. const s = state.ipsecServer;
  8491. const modalEn = document.getElementById('modal-ipsec-server-enabled');
  8492. if (modalEn) modalEn.checked = !!s.enabled;
  8493. const modalPsk = document.getElementById('modal-ipsec-server-psk');
  8494. if (modalPsk) modalPsk.value = s.preshared_key || '';
  8495. const modalPool = document.getElementById('modal-ipsec-server-pool');
  8496. if (modalPool) modalPool.value = s.pool_address || '10.10.30.0/24';
  8497. const modalDns = document.getElementById('modal-ipsec-server-dns');
  8498. if (modalDns) modalDns.value = s.dns_servers || '1.1.1.1,8.8.8.8';
  8499. const modalSubnet = document.getElementById('modal-ipsec-server-subnet');
  8500. if (modalSubnet) modalSubnet.value = s.local_subnet || '0.0.0.0/0';
  8501. const pill = document.getElementById('modal-ipsec-server-status');
  8502. if (pill) {
  8503. pill.innerText = s.running ? 'ACTIVE RESPONDER' : 'STOPPED';
  8504. 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';
  8505. }
  8506. }
  8507. } catch (err) {
  8508. console.error('Failed to load VPN servers:', err);
  8509. }
  8510. }
  8511. async function loadPPPSessions() {
  8512. try {
  8513. const res = await fetch(`${API_BASE}/vpn/ppp/active`);
  8514. const data = await res.json();
  8515. state.pppActiveSessions = Array.isArray(data) ? data : [];
  8516. const b = document.getElementById('ppp-badge-active');
  8517. if (b) b.innerText = state.pppActiveSessions.length;
  8518. const sideB = document.getElementById('badge-ppp-sessions');
  8519. if (sideB) sideB.innerText = state.pppActiveSessions.length;
  8520. renderPPPSessions();
  8521. } catch (err) {
  8522. console.error('Failed to load active PPP sessions:', err);
  8523. }
  8524. }
  8525. function renderPPPSessions() {
  8526. const tbody = document.getElementById('active-ppp-table-body');
  8527. const empty = document.getElementById('active-ppp-empty');
  8528. if (!tbody) return;
  8529. tbody.innerHTML = '';
  8530. const list = state.pppActiveSessions || [];
  8531. if (list.length === 0) {
  8532. empty?.classList.remove('hidden');
  8533. return;
  8534. }
  8535. empty?.classList.add('hidden');
  8536. list.forEach(s => {
  8537. const tr = document.createElement('tr');
  8538. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  8539. tr.innerHTML = `
  8540. <td class="py-2.5 px-3 font-bold text-white">${s.interface}</td>
  8541. <td class="py-2.5 px-3 font-semibold text-violet-300">${s.username}</td>
  8542. <td class="py-2.5 px-3 text-cyan-400 uppercase">${s.service}</td>
  8543. <td class="py-2.5 px-3 text-emerald-400 font-bold">${s.address || '-'}</td>
  8544. <td class="py-2.5 px-3 text-slate-400">${s.uptime}</td>
  8545. <td class="py-2.5 px-3 text-[11px]">
  8546. <span class="text-emerald-400">↓ ${s.rx_human || '0 B'}</span>
  8547. <span class="text-cyan-400 ml-1">↑ ${s.tx_human || '0 B'}</span>
  8548. </td>
  8549. <td class="py-2.5 px-3 text-right font-sans">
  8550. <button onclick="disconnectPPPSession('${s.interface}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  8551. </td>
  8552. `;
  8553. tbody.appendChild(tr);
  8554. });
  8555. }
  8556. async function disconnectPPPSession(iface) {
  8557. if (!confirm(`Disconnect session ${iface}?`)) return;
  8558. try {
  8559. const res = await fetch(`${API_BASE}/vpn/ppp/active/${encodeURIComponent(iface)}`, { method: 'DELETE' });
  8560. if (res.ok) {
  8561. showToast('Disconnected', `Session ${iface} terminated`, 'info');
  8562. loadPPPSessions();
  8563. }
  8564. } catch (err) {
  8565. showToast('Error', err.message, 'error');
  8566. }
  8567. }
  8568. // PPP Secret Modal handlers
  8569. function openAddPPPSecretModal() {
  8570. document.getElementById('secret-modal-title').innerText = 'Add PPP Secret';
  8571. document.getElementById('secret-modal-id').value = '';
  8572. document.getElementById('secret-modal-name').value = '';
  8573. document.getElementById('secret-modal-password').value = '';
  8574. document.getElementById('secret-modal-service').value = 'any';
  8575. document.getElementById('secret-modal-profile').value = 'default';
  8576. document.getElementById('secret-modal-local').value = '';
  8577. document.getElementById('secret-modal-remote').value = '';
  8578. document.getElementById('secret-modal-comment').value = '';
  8579. document.getElementById('secret-modal-disabled').checked = false;
  8580. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  8581. }
  8582. function openEditPPPSecretModal(id) {
  8583. const s = (state.pppSecrets || []).find(sec => sec.id === id);
  8584. if (!s) return;
  8585. document.getElementById('secret-modal-title').innerText = `Edit PPP Secret (${s.name})`;
  8586. document.getElementById('secret-modal-id').value = s.id;
  8587. document.getElementById('secret-modal-name').value = s.name;
  8588. document.getElementById('secret-modal-password').value = s.password;
  8589. document.getElementById('secret-modal-service').value = s.service || 'any';
  8590. document.getElementById('secret-modal-profile').value = s.profile || 'default';
  8591. document.getElementById('secret-modal-local').value = s.local_address || '';
  8592. document.getElementById('secret-modal-remote').value = s.remote_address || '';
  8593. document.getElementById('secret-modal-comment').value = s.comment || '';
  8594. document.getElementById('secret-modal-disabled').checked = !!s.disabled;
  8595. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  8596. }
  8597. function closePPPSecretModal() {
  8598. document.getElementById('ppp-secret-modal').classList.add('hidden');
  8599. }
  8600. async function submitSavePPPSecret(e) {
  8601. e.preventDefault();
  8602. const id = document.getElementById('secret-modal-id').value;
  8603. const name = document.getElementById('secret-modal-name').value.trim();
  8604. const password = document.getElementById('secret-modal-password').value.trim();
  8605. const service = document.getElementById('secret-modal-service').value;
  8606. const profile = document.getElementById('secret-modal-profile').value;
  8607. const local = document.getElementById('secret-modal-local').value.trim();
  8608. const remote = document.getElementById('secret-modal-remote').value.trim();
  8609. const comment = document.getElementById('secret-modal-comment').value.trim();
  8610. const disabled = document.getElementById('secret-modal-disabled').checked;
  8611. try {
  8612. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`, {
  8613. method: 'POST',
  8614. headers: { 'Content-Type': 'application/json' },
  8615. body: JSON.stringify({
  8616. id,
  8617. name,
  8618. password,
  8619. service,
  8620. profile,
  8621. local_address: local,
  8622. remote_address: remote,
  8623. comment,
  8624. disabled
  8625. })
  8626. });
  8627. if (res.ok) {
  8628. showToast('Secret Saved', `User ${name} saved to PPP database`, 'success');
  8629. closePPPSecretModal();
  8630. loadPPPSecrets();
  8631. } else {
  8632. const err = await res.json();
  8633. showToast('Error', err.message, 'error');
  8634. }
  8635. } catch (err) {
  8636. showToast('Error', err.message, 'error');
  8637. }
  8638. }
  8639. async function togglePPPSecretState(id, disabled) {
  8640. try {
  8641. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}/state`, {
  8642. method: 'POST',
  8643. headers: { 'Content-Type': 'application/json' },
  8644. body: JSON.stringify({ disabled })
  8645. });
  8646. if (res.ok) {
  8647. showToast(disabled ? 'Disabled' : 'Enabled', 'Secret user state updated', 'info');
  8648. loadPPPSecrets();
  8649. }
  8650. } catch (err) {
  8651. showToast('Error', err.message, 'error');
  8652. }
  8653. }
  8654. async function deletePPPSecret(id) {
  8655. if (!confirm('Are you sure you want to delete this secret account?')) return;
  8656. try {
  8657. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8658. if (res.ok) {
  8659. showToast('Deleted', 'Secret account removed', 'success');
  8660. loadPPPSecrets();
  8661. }
  8662. } catch (err) {
  8663. showToast('Error', err.message, 'error');
  8664. }
  8665. }
  8666. // PPP Profile Modal handlers
  8667. function openAddPPPProfileModal() {
  8668. document.getElementById('profile-modal-name').value = '';
  8669. document.getElementById('profile-modal-local').value = '10.10.10.1';
  8670. document.getElementById('profile-modal-remote').value = '10.10.10.10-10.10.10.50';
  8671. document.getElementById('profile-modal-dns').value = '1.1.1.1,8.8.8.8';
  8672. document.getElementById('profile-modal-encryption').value = 'required';
  8673. document.getElementById('profile-modal-onlyone').checked = true;
  8674. document.getElementById('profile-modal-comment').value = '';
  8675. document.getElementById('ppp-profile-modal').classList.remove('hidden');
  8676. }
  8677. function closePPPProfileModal() {
  8678. document.getElementById('ppp-profile-modal').classList.add('hidden');
  8679. }
  8680. async function submitSavePPPProfile(e) {
  8681. e.preventDefault();
  8682. const name = document.getElementById('profile-modal-name').value.trim();
  8683. const local = document.getElementById('profile-modal-local').value.trim();
  8684. const remote = document.getElementById('profile-modal-remote').value.trim();
  8685. const dns = document.getElementById('profile-modal-dns').value.trim();
  8686. const enc = document.getElementById('profile-modal-encryption').value;
  8687. const onlyone = document.getElementById('profile-modal-onlyone').checked;
  8688. const comment = document.getElementById('profile-modal-comment').value.trim();
  8689. try {
  8690. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`, {
  8691. method: 'POST',
  8692. headers: { 'Content-Type': 'application/json' },
  8693. body: JSON.stringify({
  8694. id: name,
  8695. name,
  8696. local_address: local,
  8697. remote_address: remote,
  8698. dns_servers: dns,
  8699. use_encryption: enc,
  8700. only_one: onlyone,
  8701. comment
  8702. })
  8703. });
  8704. if (res.ok) {
  8705. showToast('Profile Saved', `PPP profile ${name} created`, 'success');
  8706. closePPPProfileModal();
  8707. loadPPPProfiles();
  8708. } else {
  8709. const err = await res.json();
  8710. showToast('Error', err.message, 'error');
  8711. }
  8712. } catch (err) {
  8713. showToast('Error', err.message, 'error');
  8714. }
  8715. }
  8716. async function deletePPPProfile(name) {
  8717. if (!confirm(`Delete PPP profile ${name}?`)) return;
  8718. try {
  8719. const res = await fetch(`${API_BASE}/vpn/ppp/profiles/${encodeURIComponent(name)}`, { method: 'DELETE' });
  8720. if (res.ok) {
  8721. showToast('Deleted', 'Profile removed', 'success');
  8722. loadPPPProfiles();
  8723. } else {
  8724. const err = await res.json();
  8725. showToast('Error', err.message, 'error');
  8726. }
  8727. } catch (err) {
  8728. showToast('Error', err.message, 'error');
  8729. }
  8730. }
  8731. // Server Config submissions
  8732. async function savePPPoEServerConfig(e) {
  8733. e.preventDefault();
  8734. const enabled = document.getElementById('pppoe-server-enabled').checked;
  8735. const name = document.getElementById('pppoe-server-name').value.trim();
  8736. const iface = document.getElementById('pppoe-server-iface').value;
  8737. const profile = document.getElementById('pppoe-server-profile').value;
  8738. const mtu = parseInt(document.getElementById('pppoe-server-mtu').value) || 1480;
  8739. const onesession = document.getElementById('pppoe-server-onesession').checked;
  8740. try {
  8741. const res = await fetch(`${API_BASE}/vpn/servers/pppoe`, {
  8742. method: 'POST',
  8743. headers: { 'Content-Type': 'application/json' },
  8744. body: JSON.stringify({
  8745. enabled,
  8746. service_name: name,
  8747. interface: iface,
  8748. default_profile: profile,
  8749. max_mtu: mtu,
  8750. max_mru: mtu,
  8751. one_session_per_host: onesession
  8752. })
  8753. });
  8754. if (res.ok) {
  8755. showToast('PPPoE Server', enabled ? 'PPPoE Server started' : 'PPPoE Server stopped', 'success');
  8756. loadPPPServers();
  8757. fetchData(false);
  8758. } else {
  8759. const err = await res.json();
  8760. showToast('Error', err.message, 'error');
  8761. }
  8762. } catch (err) {
  8763. showToast('Error', err.message, 'error');
  8764. }
  8765. }
  8766. async function savePPTPServerConfig(e) {
  8767. e.preventDefault();
  8768. const enabled = document.getElementById('pptp-server-enabled').checked;
  8769. const port = parseInt(document.getElementById('pptp-server-port').value) || 1723;
  8770. const profile = document.getElementById('pptp-server-profile').value;
  8771. const mppe = document.getElementById('pptp-server-mppe').checked;
  8772. try {
  8773. const res = await fetch(`${API_BASE}/vpn/servers/pptp`, {
  8774. method: 'POST',
  8775. headers: { 'Content-Type': 'application/json' },
  8776. body: JSON.stringify({
  8777. enabled,
  8778. port,
  8779. default_profile: profile,
  8780. require_mppe: mppe
  8781. })
  8782. });
  8783. if (res.ok) {
  8784. showToast('PPTP Server', enabled ? 'PPTP Server started' : 'PPTP Server stopped', 'success');
  8785. loadPPPServers();
  8786. fetchData(false);
  8787. } else {
  8788. const err = await res.json();
  8789. showToast('Error', err.message, 'error');
  8790. }
  8791. } catch (err) {
  8792. showToast('Error', err.message, 'error');
  8793. }
  8794. }
  8795. async function saveL2TPServerConfig(e) {
  8796. e.preventDefault();
  8797. const enabled = document.getElementById('l2tp-server-enabled').checked;
  8798. const port = parseInt(document.getElementById('l2tp-server-port').value) || 1701;
  8799. const profile = document.getElementById('l2tp-server-profile').value;
  8800. const useipsec = document.getElementById('l2tp-server-useipsec').value;
  8801. const psk = document.getElementById('l2tp-server-ipsecsecret').value.trim();
  8802. try {
  8803. const res = await fetch(`${API_BASE}/vpn/servers/l2tp`, {
  8804. method: 'POST',
  8805. headers: { 'Content-Type': 'application/json' },
  8806. body: JSON.stringify({
  8807. enabled,
  8808. port,
  8809. default_profile: profile,
  8810. use_ipsec: useipsec,
  8811. ipsec_secret: psk
  8812. })
  8813. });
  8814. if (res.ok) {
  8815. showToast('L2TP Server', enabled ? 'L2TP Server started' : 'L2TP Server stopped', 'success');
  8816. loadPPPServers();
  8817. fetchData(false);
  8818. } else {
  8819. const err = await res.json();
  8820. showToast('Error', err.message, 'error');
  8821. }
  8822. } catch (err) {
  8823. showToast('Error', err.message, 'error');
  8824. }
  8825. }
  8826. // IPSec Server Modal
  8827. function openIPSecServerModal() {
  8828. loadPPPServers();
  8829. document.getElementById('ipsec-server-modal').classList.remove('hidden');
  8830. }
  8831. function closeIPSecServerModal() {
  8832. document.getElementById('ipsec-server-modal').classList.add('hidden');
  8833. }
  8834. async function submitSaveIPSecServer(e) {
  8835. e.preventDefault();
  8836. const enabled = document.getElementById('modal-ipsec-server-enabled').checked;
  8837. const psk = document.getElementById('modal-ipsec-server-psk').value.trim();
  8838. const pool = document.getElementById('modal-ipsec-server-pool').value.trim();
  8839. const dns = document.getElementById('modal-ipsec-server-dns').value.trim();
  8840. const subnet = document.getElementById('modal-ipsec-server-subnet').value.trim();
  8841. try {
  8842. const res = await fetch(`${API_BASE}/vpn/servers/ipsec`, {
  8843. method: 'POST',
  8844. headers: { 'Content-Type': 'application/json' },
  8845. body: JSON.stringify({
  8846. enabled,
  8847. preshared_key: psk,
  8848. pool_address: pool,
  8849. dns_servers: dns,
  8850. local_subnet: subnet
  8851. })
  8852. });
  8853. if (res.ok) {
  8854. showToast('IPSec Server', enabled ? 'IKEv2 Roadwarrior responder active' : 'IPSec Server stopped', 'success');
  8855. closeIPSecServerModal();
  8856. loadPPPServers();
  8857. fetchData(false);
  8858. } else {
  8859. const err = await res.json();
  8860. showToast('Error', err.message, 'error');
  8861. }
  8862. } catch (err) {
  8863. showToast('Error', err.message, 'error');
  8864. }
  8865. }
  8866. // WireGuard Client Config Viewer
  8867. let currentWGClientConf = '';
  8868. async function openWGClientConfModal(iface, clientIP) {
  8869. try {
  8870. const res = await fetch(`${API_BASE}/vpn/wireguard/client-config`, {
  8871. method: 'POST',
  8872. headers: { 'Content-Type': 'application/json' },
  8873. body: JSON.stringify({
  8874. interface: iface,
  8875. address: clientIP || '10.10.0.2/32',
  8876. dns: '1.1.1.1, 8.8.8.8'
  8877. })
  8878. });
  8879. if (res.ok) {
  8880. const data = await res.json();
  8881. currentWGClientConf = data.config;
  8882. document.getElementById('wg-client-conf-text').value = currentWGClientConf;
  8883. document.getElementById('wg-client-conf-modal').classList.remove('hidden');
  8884. } else {
  8885. const err = await res.json();
  8886. showToast('Error', err.message, 'error');
  8887. }
  8888. } catch (err) {
  8889. showToast('Error', err.message, 'error');
  8890. }
  8891. }
  8892. function closeWGClientConfModal() {
  8893. document.getElementById('wg-client-conf-modal').classList.add('hidden');
  8894. }
  8895. function copyWGClientConf() {
  8896. if (!currentWGClientConf) return;
  8897. copyToClipboard(currentWGClientConf, 'WireGuard Client Profile');
  8898. }
  8899. function downloadWGClientConf() {
  8900. if (!currentWGClientConf) return;
  8901. const blob = new Blob([currentWGClientConf], { type: 'text/plain;charset=utf-8' });
  8902. const a = document.createElement('a');
  8903. a.href = URL.createObjectURL(blob);
  8904. a.download = 'wireguard-client.conf';
  8905. document.body.appendChild(a);
  8906. a.click();
  8907. document.body.removeChild(a);
  8908. showToast('Downloaded', 'wireguard-client.conf saved', 'success');
  8909. }
  8910. // =========================================================================
  8911. // DYNAMIC ROUTING (FRRouting BGP & OSPFv2)
  8912. // =========================================================================
  8913. state.activeDynSubTab = 'bgp-peers';
  8914. state.activeBgpSubTab = 'bgp-peers';
  8915. state.activeOspfTab = 'instances';
  8916. state.bgpInstance = null;
  8917. state.bgpPeers = [];
  8918. state.bgpNets = [];
  8919. state.bgpRoutes = [];
  8920. state.ospfInstance = null;
  8921. state.ospfInstances = [];
  8922. state.ospfAreas = [];
  8923. state.ospfAreaRanges = [];
  8924. state.ospfTemplates = [];
  8925. state.ospfLiveInterfaces = [];
  8926. state.ospfStaticNbrs = [];
  8927. state.ospfNeighbors = [];
  8928. state.ospfLSA = [];
  8929. state.ospfRoutes = [];
  8930. state.selectedOspfRow = {
  8931. instances: null,
  8932. areas: null,
  8933. 'area-ranges': null,
  8934. templates: null,
  8935. interfaces: null,
  8936. 'static-nbrs': null,
  8937. neighbors: null,
  8938. lsa: null,
  8939. };
  8940. state.ospfSort = {
  8941. instances: { col: 'name', asc: true },
  8942. areas: { col: 'name', asc: true },
  8943. ranges: { col: 'area', asc: true },
  8944. templates: { col: 'interfaces', asc: true },
  8945. live_ifaces: { col: 'interface', asc: true },
  8946. snbrs: { col: 'address', asc: true },
  8947. neighbors: { col: 'address', asc: true },
  8948. lsa: { col: 'instance', asc: true },
  8949. };
  8950. function switchBgpSubTab(subTab) {
  8951. state.activeBgpSubTab = subTab;
  8952. const tabs = ['bgp-peers', 'bgp-nets', 'bgp-routes'];
  8953. tabs.forEach(t => {
  8954. const el = document.getElementById(`dyn-subtab-${t}`);
  8955. const btn = document.getElementById(`bgp-subtab-btn-${t}`);
  8956. if (el) el.classList.toggle('hidden', t !== subTab);
  8957. if (btn) {
  8958. if (t === subTab) {
  8959. 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';
  8960. } else {
  8961. 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';
  8962. }
  8963. }
  8964. });
  8965. }
  8966. function switchOspfTab(tabName) {
  8967. state.activeOspfTab = tabName;
  8968. const tabs = ['instances', 'areas', 'area-ranges', 'templates', 'interfaces', 'static-nbrs', 'neighbors', 'lsa'];
  8969. tabs.forEach(t => {
  8970. const pane = document.getElementById(`ospf-pane-${t}`);
  8971. const btn = document.getElementById(`ospf-tab-btn-${t}`);
  8972. if (pane) pane.classList.toggle('hidden', t !== tabName);
  8973. if (btn) {
  8974. if (t === tabName) {
  8975. 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';
  8976. } else {
  8977. 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';
  8978. }
  8979. }
  8980. });
  8981. }
  8982. function switchOspfSubTab(tab) {
  8983. // Legacy alias
  8984. if (tab === 'ospf-ifaces') switchOspfTab('templates');
  8985. else if (tab === 'ospf-areas') switchOspfTab('areas');
  8986. else if (tab === 'ospf-nbrs') switchOspfTab('neighbors');
  8987. else switchOspfTab('instances');
  8988. }
  8989. function switchDynSubTab(subTab) {
  8990. if (subTab.startsWith('bgp')) {
  8991. if (state.activeTab !== 'bgp') navigate('bgp');
  8992. switchBgpSubTab(subTab);
  8993. } else if (subTab.startsWith('ospf')) {
  8994. if (state.activeTab !== 'ospf') navigate('ospf');
  8995. switchOspfTab('instances');
  8996. }
  8997. }
  8998. async function loadDynamicRouting(showToastMsg = false) {
  8999. try {
  9000. const routingTab = state.activeTab === 'dynamic-routing' ? 'bgp' : state.activeTab;
  9001. const routingViews = new Set(['bgp', 'ospf', 'rip', 'bfd', 'babel', 'radv', 'eigrp', 'routing-filters']);
  9002. const fetchSafeJson = async (url) => {
  9003. const match = url.match(/\/routing\/(bgp|ospf|rip|bfd|babel|radv|eigrp)\//);
  9004. if (routingViews.has(routingTab) && match && match[1] !== routingTab) return null;
  9005. try {
  9006. const r = await fetch(url);
  9007. return r.ok ? await r.json() : null;
  9008. } catch (e) {
  9009. return null;
  9010. }
  9011. };
  9012. const [
  9013. sum, bgpInst, bgpPeers, bgpNets, bgpRoutes,
  9014. ospfInsts, ospfAreas, ospfRanges, ospfTemplates, ospfLiveIfaces, ospfStaticNbrs, ospfNbrs, ospfLsa, filters,
  9015. commLists, asLists,
  9016. ripInsts, ripIfaces, ripNbrsLive, ripRoutes,
  9017. bfdInst, bfdIfaces, bfdPeers, bfdSessions,
  9018. babelInsts, babelIfaces, babelLiveIfaces, babelNbrs, babelRoutes,
  9019. radvInsts, radvIfaces,
  9020. eigrpInsts, eigrpIfaces, eigrpNets, eigrpNbrs, eigrpTopology
  9021. ] = await Promise.all([
  9022. fetchSafeJson(`${API_BASE}/routing/dynamic/summary`),
  9023. fetchSafeJson(`${API_BASE}/routing/bgp/instance`),
  9024. fetchSafeJson(`${API_BASE}/routing/bgp/peers`),
  9025. fetchSafeJson(`${API_BASE}/routing/bgp/networks`),
  9026. fetchSafeJson(`${API_BASE}/routing/bgp/routes`),
  9027. fetchSafeJson(`${API_BASE}/routing/ospf/instances`),
  9028. fetchSafeJson(`${API_BASE}/routing/ospf/areas`),
  9029. fetchSafeJson(`${API_BASE}/routing/ospf/area-ranges`),
  9030. fetchSafeJson(`${API_BASE}/routing/ospf/templates`),
  9031. fetchSafeJson(`${API_BASE}/routing/ospf/interfaces-live`),
  9032. fetchSafeJson(`${API_BASE}/routing/ospf/static-neighbors`),
  9033. fetchSafeJson(`${API_BASE}/routing/ospf/neighbors`),
  9034. fetchSafeJson(`${API_BASE}/routing/ospf/lsa`),
  9035. fetchSafeJson(`${API_BASE}/routing/filters`),
  9036. fetchSafeJson(`${API_BASE}/routing/filters/community-lists`),
  9037. fetchSafeJson(`${API_BASE}/routing/filters/as-lists`),
  9038. fetchSafeJson(`${API_BASE}/routing/rip/instances`),
  9039. fetchSafeJson(`${API_BASE}/routing/rip/interfaces`),
  9040. fetchSafeJson(`${API_BASE}/routing/rip/neighbors-live`),
  9041. fetchSafeJson(`${API_BASE}/routing/rip/routes`),
  9042. fetchSafeJson(`${API_BASE}/routing/bfd/instance`),
  9043. fetchSafeJson(`${API_BASE}/routing/bfd/interfaces`),
  9044. fetchSafeJson(`${API_BASE}/routing/bfd/peers`),
  9045. fetchSafeJson(`${API_BASE}/routing/bfd/sessions`),
  9046. fetchSafeJson(`${API_BASE}/routing/babel/instances`),
  9047. fetchSafeJson(`${API_BASE}/routing/babel/interfaces`),
  9048. fetchSafeJson(`${API_BASE}/routing/babel/interfaces-live`),
  9049. fetchSafeJson(`${API_BASE}/routing/babel/neighbors`),
  9050. fetchSafeJson(`${API_BASE}/routing/babel/routes`),
  9051. fetchSafeJson(`${API_BASE}/routing/radv/instances`),
  9052. fetchSafeJson(`${API_BASE}/routing/radv/interfaces`),
  9053. fetchSafeJson(`${API_BASE}/routing/eigrp/instances`),
  9054. fetchSafeJson(`${API_BASE}/routing/eigrp/interfaces`),
  9055. fetchSafeJson(`${API_BASE}/routing/eigrp/networks`),
  9056. fetchSafeJson(`${API_BASE}/routing/eigrp/neighbors`),
  9057. fetchSafeJson(`${API_BASE}/routing/eigrp/topology`)
  9058. ]);
  9059. if (sum) state.dynSummary = sum;
  9060. if (bgpInst) state.bgpInstance = bgpInst;
  9061. if (bgpPeers) state.bgpPeers = bgpPeers;
  9062. if (bgpNets) state.bgpNets = bgpNets;
  9063. if (bgpRoutes) state.bgpRoutes = bgpRoutes;
  9064. if (ospfInsts) state.ospfInstances = ospfInsts;
  9065. if (ospfAreas) state.ospfAreas = ospfAreas;
  9066. if (ospfRanges) state.ospfAreaRanges = ospfRanges;
  9067. if (ospfTemplates) state.ospfTemplates = ospfTemplates;
  9068. if (ospfLiveIfaces) state.ospfLiveInterfaces = ospfLiveIfaces;
  9069. if (ospfStaticNbrs) state.ospfStaticNbrs = ospfStaticNbrs;
  9070. if (ospfNbrs) state.ospfNeighbors = ospfNbrs;
  9071. if (ospfLsa) state.ospfLSA = ospfLsa;
  9072. if (filters) state.routingFilters = filters;
  9073. if (commLists) state.routingCommunityLists = commLists;
  9074. if (asLists) state.routingASLists = asLists;
  9075. if (ripInsts) state.ripInstances = ripInsts;
  9076. if (ripIfaces) state.ripInterfaces = ripIfaces;
  9077. if (ripNbrsLive) state.ripNeighborsLive = ripNbrsLive;
  9078. if (ripRoutes) state.ripRoutes = ripRoutes;
  9079. if (bfdInst) state.bfdInstance = bfdInst;
  9080. if (bfdIfaces) state.bfdInterfaces = bfdIfaces;
  9081. if (bfdPeers) state.bfdNeighbors = bfdPeers;
  9082. if (bfdSessions) state.bfdSessions = bfdSessions;
  9083. if (babelInsts) state.babelInstances = babelInsts;
  9084. if (babelIfaces) state.babelInterfaces = babelIfaces;
  9085. if (babelLiveIfaces) state.babelInterfacesLive = babelLiveIfaces;
  9086. if (babelNbrs) state.babelNeighbors = babelNbrs;
  9087. if (babelRoutes) state.babelRoutes = babelRoutes;
  9088. if (radvInsts) state.radvInstances = radvInsts;
  9089. if (radvIfaces) state.radvInterfaces = radvIfaces;
  9090. if (eigrpInsts) state.eigrpInstances = eigrpInsts;
  9091. if (eigrpIfaces) state.eigrpInterfaces = eigrpIfaces;
  9092. if (eigrpNets) state.eigrpNetworks = eigrpNets;
  9093. if (eigrpNbrs) state.eigrpNeighbors = eigrpNbrs;
  9094. if (eigrpTopology) state.eigrpTopology = eigrpTopology;
  9095. try { renderBgpStatusPill(); } catch(e) { console.error('renderBgpStatusPill error:', e); }
  9096. try { renderBgpPeers(); } catch(e) { console.error('renderBgpPeers error:', e); }
  9097. try { renderBgpNetworks(); } catch(e) { console.error('renderBgpNetworks error:', e); }
  9098. try { renderBgpRoutes(); } catch(e) { console.error('renderBgpRoutes error:', e); }
  9099. try { renderOspfInstances(); } catch(e) { console.error('renderOspfInstances error:', e); }
  9100. try { renderOspfAreas(); } catch(e) { console.error('renderOspfAreas error:', e); }
  9101. try { renderOspfAreaRanges(); } catch(e) { console.error('renderOspfAreaRanges error:', e); }
  9102. try { renderOspfTemplates(); } catch(e) { console.error('renderOspfTemplates error:', e); }
  9103. try { renderOspfLiveInterfaces(); } catch(e) { console.error('renderOspfLiveInterfaces error:', e); }
  9104. try { renderOspfStaticNbrs(); } catch(e) { console.error('renderOspfStaticNbrs error:', e); }
  9105. try { renderOspfNeighbors(); } catch(e) { console.error('renderOspfNeighbors error:', e); }
  9106. try { renderOspfLSA(); } catch(e) { console.error('renderOspfLSA error:', e); }
  9107. try { renderRipInstances(); } catch(e) { console.error('renderRipInstances error:', e); }
  9108. try { renderRipInterfaces(); } catch(e) { console.error('renderRipInterfaces error:', e); }
  9109. try { renderRipNeighbors(); } catch(e) { console.error('renderRipNeighbors error:', e); }
  9110. try { renderRipRoutes(); } catch(e) { console.error('renderRipRoutes error:', e); }
  9111. try { renderBfdConfig(); } catch(e) { console.error('renderBfdConfig error:', e); }
  9112. try { renderBfdInterfaces(); } catch(e) { console.error('renderBfdInterfaces error:', e); }
  9113. try { renderBfdPeers(); } catch(e) { console.error('renderBfdPeers error:', e); }
  9114. try { renderBfdSessions(); } catch(e) { console.error('renderBfdSessions error:', e); }
  9115. try { renderBabelInstances(); } catch(e) { console.error('renderBabelInstances error:', e); }
  9116. try { renderBabelInterfaces(); } catch(e) { console.error('renderBabelInterfaces error:', e); }
  9117. try { renderBabelLiveInterfaces(); } catch(e) { console.error('renderBabelLiveInterfaces error:', e); }
  9118. try { renderBabelNeighbors(); } catch(e) { console.error('renderBabelNeighbors error:', e); }
  9119. try { renderBabelRoutes(); } catch(e) { console.error('renderBabelRoutes error:', e); }
  9120. try { renderRAdvInstances(); } catch(e) { console.error('renderRAdvInstances error:', e); }
  9121. try { renderRAdvInterfaces(); } catch(e) { console.error('renderRAdvInterfaces error:', e); }
  9122. try { renderEigrpInstances(); } catch(e) { console.error('renderEigrpInstances error:', e); }
  9123. try { renderEigrpNetworks(); } catch(e) { console.error('renderEigrpNetworks error:', e); }
  9124. try { renderEigrpInterfaces(); } catch(e) { console.error('renderEigrpInterfaces error:', e); }
  9125. try { renderEigrpNeighbors(); } catch(e) { console.error('renderEigrpNeighbors error:', e); }
  9126. try { renderEigrpTopology(); } catch(e) { console.error('renderEigrpTopology error:', e); }
  9127. try { renderRoutingFilters(); } catch(e) { console.error('renderRoutingFilters error:', e); }
  9128. try { updateBadges(); } catch(e) { console.error('updateBadges error:', e); }
  9129. if (showToastMsg) showToast('Refreshed', 'Dynamic routing telemetry updated', 'info');
  9130. } catch (err) {
  9131. console.error('Failed to load dynamic routing:', err);
  9132. if (showToastMsg) showToast('Notice', 'Unable to refresh dynamic routing telemetry', 'warning');
  9133. }
  9134. }
  9135. async function loadOspfAll() {
  9136. await loadDynamicRouting(true);
  9137. }
  9138. function renderBgpStatusPill() {
  9139. const pills = document.querySelectorAll('.bgp-live-status-pill');
  9140. pills.forEach(pill => {
  9141. const inst = state.bgpInstance;
  9142. if (!inst || !inst.enabled) {
  9143. 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';
  9144. pill.innerText = 'BGP DISABLED';
  9145. } else if (inst.running) {
  9146. 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';
  9147. pill.innerText = `BGP ACTIVE (AS ${inst.as})`;
  9148. } else {
  9149. 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';
  9150. pill.innerText = 'BGP STARTING...';
  9151. }
  9152. });
  9153. }
  9154. function renderBgpPeers() {
  9155. const tbody = document.getElementById('bgp-peers-table-body');
  9156. if (!tbody) return;
  9157. const empty = document.getElementById('bgp-peers-empty');
  9158. const countBadge = document.getElementById('bgp-peers-count-badge');
  9159. const navBadge = document.getElementById('dyn-badge-bgp-peers');
  9160. const peers = state.bgpPeers || [];
  9161. if (countBadge) countBadge.innerText = `${peers.length} Peers`;
  9162. if (navBadge) navBadge.innerText = peers.length;
  9163. if (peers.length === 0) {
  9164. tbody.innerHTML = '';
  9165. if (empty) empty.classList.remove('hidden');
  9166. return;
  9167. }
  9168. if (empty) empty.classList.add('hidden');
  9169. const sig = peers.map(p => `${p.name}:${p.state}:${p.uptime}:${p.prefix_received}:${p.prefix_sent}:${p.disabled}`).join(';');
  9170. if (tbody.dataset.sig === sig) return;
  9171. tbody.dataset.sig = sig;
  9172. tbody.innerHTML = peers.map(p => {
  9173. let flagA = !p.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  9174. let flagE = p.state === 'Established' ? '<span class="text-emerald-400 font-bold ml-1" title="Established">E</span>' : '';
  9175. let flagX = p.disabled ? '<span class="text-rose-400 font-bold ml-1" title="Disabled">X</span>' : '';
  9176. let stateBadge = '';
  9177. if (p.disabled) {
  9178. 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>';
  9179. } else if (p.state === 'Established') {
  9180. 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>';
  9181. } else if (p.state === 'Connect' || p.state === 'Active') {
  9182. 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>`;
  9183. } else {
  9184. 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>`;
  9185. }
  9186. return `
  9187. <tr class="hover:bg-slate-800/40 transition">
  9188. <td class="py-2.5 px-3 text-center tracking-wider">${flagA}${flagE}${flagX}</td>
  9189. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(p.name)}</td>
  9190. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(p.remote_address)}</td>
  9191. <td class="py-2.5 px-3">
  9192. <div class="font-bold text-slate-200">AS ${p.remote_as}</div>
  9193. ${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>`}
  9194. </td>
  9195. <td class="py-2.5 px-3">${stateBadge}</td>
  9196. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(p.uptime || '-')}</td>
  9197. <td class="py-2.5 px-3 text-slate-300">
  9198. <span class="text-emerald-400 font-bold">↓ ${p.prefix_received || 0}</span> /
  9199. <span class="text-blue-400 font-bold">↑ ${p.prefix_sent || 0}</span>
  9200. </td>
  9201. <td class="py-2.5 px-3 font-mono text-[11px] whitespace-nowrap">
  9202. ${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> ` : ''}
  9203. ${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>` : ''}
  9204. ${!p.in_filter && !p.out_filter ? '<span class="text-slate-600">-</span>' : ''}
  9205. </td>
  9206. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(p.comment || '')}</td>
  9207. <td class="py-2.5 px-3 text-right space-x-1.5 whitespace-nowrap font-sans">
  9208. <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'}">
  9209. ${p.disabled ? 'Enable' : 'Disable'}
  9210. </button>
  9211. <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">
  9212. Edit
  9213. </button>
  9214. <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">
  9215. Delete
  9216. </button>
  9217. </td>
  9218. </tr>
  9219. `;
  9220. }).join('');
  9221. }
  9222. function renderBgpNetworks() {
  9223. const tbody = document.getElementById('bgp-nets-table-body');
  9224. if (!tbody) return;
  9225. const empty = document.getElementById('bgp-nets-empty');
  9226. const countBadge = document.getElementById('bgp-nets-count-badge');
  9227. const navBadge = document.getElementById('dyn-badge-bgp-nets');
  9228. const nets = state.bgpNets || [];
  9229. if (countBadge) countBadge.innerText = `${nets.length} Networks`;
  9230. if (navBadge) navBadge.innerText = nets.length;
  9231. if (nets.length === 0) {
  9232. tbody.innerHTML = '';
  9233. if (empty) empty.classList.remove('hidden');
  9234. return;
  9235. }
  9236. if (empty) empty.classList.add('hidden');
  9237. const sig = nets.map(n => `${n.network}:${n.disabled}:${n.comment}`).join(';');
  9238. if (tbody.dataset.sig === sig) return;
  9239. tbody.dataset.sig = sig;
  9240. tbody.innerHTML = nets.map(n => `
  9241. <tr class="hover:bg-slate-800/40 transition">
  9242. <td class="py-2.5 px-3 font-semibold text-purple-300 font-mono">${escapeHtml(n.network)}</td>
  9243. <td class="py-2.5 px-3">
  9244. ${n.disabled
  9245. ? '<span class="px-2 py-0.5 rounded-full text-[10px] bg-slate-800 text-slate-400 border border-slate-700">Disabled</span>'
  9246. : '<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>'}
  9247. </td>
  9248. <td class="py-2.5 px-3">
  9249. ${n.disabled
  9250. ? '<span class="text-slate-600 font-mono text-[10px]">-</span>'
  9251. : '<span class="px-2 py-0.5 rounded text-[10px] bg-slate-800 text-cyan-300 border border-cyan-800/40 font-mono">blackhole (dist 255)</span>'}
  9252. </td>
  9253. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(n.comment || '')}</td>
  9254. <td class="py-2.5 px-3 text-right space-x-1 font-sans">
  9255. <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">
  9256. Delete
  9257. </button>
  9258. </td>
  9259. </tr>
  9260. `).join('');
  9261. }
  9262. function renderBgpRoutes() {
  9263. const tbody = document.getElementById('bgp-routes-table-body');
  9264. if (!tbody) return;
  9265. const empty = document.getElementById('bgp-routes-empty');
  9266. const countBadge = document.getElementById('bgp-routes-count-badge');
  9267. const navBadge = document.getElementById('dyn-badge-bgp-routes');
  9268. const routes = state.bgpRoutes || [];
  9269. if (countBadge) countBadge.innerText = `${routes.length} Routes`;
  9270. if (navBadge) navBadge.innerText = routes.length;
  9271. if (routes.length === 0) {
  9272. tbody.innerHTML = '';
  9273. if (empty) empty.classList.remove('hidden');
  9274. return;
  9275. }
  9276. if (empty) empty.classList.add('hidden');
  9277. const sig = routes.map(r => `${r.prefix}:${r.next_hop}:${r.metric}:${r.path}`).join(';');
  9278. if (tbody.dataset.sig === sig) return;
  9279. tbody.dataset.sig = sig;
  9280. tbody.innerHTML = routes.map(r => `
  9281. <tr class="hover:bg-slate-800/40 transition">
  9282. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.prefix)}</td>
  9283. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(r.next_hop || '-')}</td>
  9284. <td class="py-2.5 px-3 text-slate-300">${r.metric}</td>
  9285. <td class="py-2.5 px-3 text-slate-300">${r.weight}</td>
  9286. <td class="py-2.5 px-3 text-amber-300">${escapeHtml(r.path || 'i')}</td>
  9287. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.origin || 'IGP')}</td>
  9288. </tr>
  9289. `).join('');
  9290. }
  9291. // =========================================================================
  9292. // DEBTIK v7 OSPF TABLE RENDERING & SORTING
  9293. // =========================================================================
  9294. function sortOspfTable(tab, col) {
  9295. if (!state.ospfSort) state.ospfSort = {};
  9296. if (!state.ospfSort[tab]) state.ospfSort[tab] = { col: col, asc: true };
  9297. if (state.ospfSort[tab].col === col) {
  9298. state.ospfSort[tab].asc = !state.ospfSort[tab].asc;
  9299. } else {
  9300. state.ospfSort[tab].col = col;
  9301. state.ospfSort[tab].asc = true;
  9302. }
  9303. const asc = state.ospfSort[tab].asc;
  9304. let list = [];
  9305. if (tab === 'instances') list = state.ospfInstances || [];
  9306. else if (tab === 'areas') list = state.ospfAreas || [];
  9307. else if (tab === 'ranges') list = state.ospfAreaRanges || [];
  9308. else if (tab === 'templates') list = state.ospfTemplates || [];
  9309. else if (tab === 'live_ifaces') list = state.ospfLiveInterfaces || [];
  9310. else if (tab === 'snbrs') list = state.ospfStaticNbrs || [];
  9311. else if (tab === 'neighbors') list = state.ospfNeighbors || [];
  9312. else if (tab === 'lsa') list = state.ospfLSA || [];
  9313. list.sort((a, b) => {
  9314. let valA = a[col] ?? '';
  9315. let valB = b[col] ?? '';
  9316. if (typeof valA === 'number' && typeof valB === 'number') {
  9317. return asc ? valA - valB : valB - valA;
  9318. }
  9319. return asc ? String(valA).localeCompare(String(valB)) : String(valB).localeCompare(String(valA));
  9320. });
  9321. if (tab === 'instances') renderOspfInstances();
  9322. else if (tab === 'areas') renderOspfAreas();
  9323. else if (tab === 'ranges') renderOspfAreaRanges();
  9324. else if (tab === 'templates') renderOspfTemplates();
  9325. else if (tab === 'live_ifaces') renderOspfLiveInterfaces();
  9326. else if (tab === 'snbrs') renderOspfStaticNbrs();
  9327. else if (tab === 'neighbors') renderOspfNeighbors();
  9328. else if (tab === 'lsa') renderOspfLSA();
  9329. }
  9330. function selectOspfRow(tab, id) {
  9331. if (!state.selectedOspfRow) state.selectedOspfRow = {};
  9332. state.selectedOspfRow[tab] = id;
  9333. if (tab === 'instances') {
  9334. renderOspfInstances();
  9335. const btnEn = document.getElementById('btn-ospf-inst-enable');
  9336. const btnDis = document.getElementById('btn-ospf-inst-disable');
  9337. const btnRem = document.getElementById('btn-ospf-inst-remove');
  9338. const btnCom = document.getElementById('btn-ospf-inst-comment');
  9339. if (btnEn) btnEn.disabled = false;
  9340. if (btnDis) btnDis.disabled = false;
  9341. if (btnRem) btnRem.disabled = false;
  9342. if (btnCom) btnCom.disabled = false;
  9343. } else if (tab === 'areas') {
  9344. renderOspfAreas();
  9345. const btnEn = document.getElementById('btn-ospf-area-enable');
  9346. const btnDis = document.getElementById('btn-ospf-area-disable');
  9347. const btnRem = document.getElementById('btn-ospf-area-remove');
  9348. const btnCom = document.getElementById('btn-ospf-area-comment');
  9349. if (btnEn) btnEn.disabled = false;
  9350. if (btnDis) btnDis.disabled = false;
  9351. if (btnRem) btnRem.disabled = false;
  9352. if (btnCom) btnCom.disabled = false;
  9353. } else if (tab === 'ranges') {
  9354. renderOspfAreaRanges();
  9355. const btnEn = document.getElementById('btn-ospf-range-enable');
  9356. const btnDis = document.getElementById('btn-ospf-range-disable');
  9357. const btnRem = document.getElementById('btn-ospf-range-remove');
  9358. const btnCom = document.getElementById('btn-ospf-range-comment');
  9359. if (btnEn) btnEn.disabled = false;
  9360. if (btnDis) btnDis.disabled = false;
  9361. if (btnRem) btnRem.disabled = false;
  9362. if (btnCom) btnCom.disabled = false;
  9363. } else if (tab === 'templates') {
  9364. renderOspfTemplates();
  9365. const btnEn = document.getElementById('btn-ospf-tmpl-enable');
  9366. const btnDis = document.getElementById('btn-ospf-tmpl-disable');
  9367. const btnRem = document.getElementById('btn-ospf-tmpl-remove');
  9368. const btnCom = document.getElementById('btn-ospf-tmpl-comment');
  9369. if (btnEn) btnEn.disabled = false;
  9370. if (btnDis) btnDis.disabled = false;
  9371. if (btnRem) btnRem.disabled = false;
  9372. if (btnCom) btnCom.disabled = false;
  9373. } else if (tab === 'snbrs') {
  9374. renderOspfStaticNbrs();
  9375. const btnEn = document.getElementById('btn-ospf-snbr-enable');
  9376. const btnDis = document.getElementById('btn-ospf-snbr-disable');
  9377. const btnRem = document.getElementById('btn-ospf-snbr-remove');
  9378. const btnCom = document.getElementById('btn-ospf-snbr-comment');
  9379. if (btnEn) btnEn.disabled = false;
  9380. if (btnDis) btnDis.disabled = false;
  9381. if (btnRem) btnRem.disabled = false;
  9382. if (btnCom) btnCom.disabled = false;
  9383. }
  9384. }
  9385. // TAB 1: INSTANCES
  9386. function renderOspfInstances() {
  9387. const tbody = document.getElementById('ospf-instances-table-body');
  9388. if (!tbody) return;
  9389. const countEl = document.getElementById('ospf-instances-footer-count');
  9390. const filter = (document.getElementById('filter-ospf-instances')?.value || '').toLowerCase();
  9391. let list = state.ospfInstances || [];
  9392. if (filter) {
  9393. list = list.filter(i => (i.name || '').toLowerCase().includes(filter) || (i.router_id || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  9394. }
  9395. if (countEl) countEl.innerText = list.length;
  9396. const selId = state.selectedOspfRow?.instances;
  9397. tbody.innerHTML = list.map((inst, idx) => {
  9398. const isSel = inst.id === selId;
  9399. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  9400. const flagD = inst.disabled
  9401. ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>'
  9402. : (inst.running
  9403. ? '<span class="text-emerald-400 font-bold" title="Running (R)">R</span>'
  9404. : '<span class="text-amber-400 font-bold" title="Inactive (I)">I</span>');
  9405. const redist = [];
  9406. if (inst.redistribute_connected) redist.push('conn');
  9407. if (inst.redistribute_static) redist.push('static');
  9408. if (inst.redistribute_bgp) redist.push('bgp');
  9409. if (inst.redistribute_default || (inst.originate_default && inst.originate_default !== 'never')) {
  9410. redist.push('default');
  9411. }
  9412. const origDef = inst.originate_default || (inst.redistribute_default ? 'if-installed' : 'never');
  9413. const origBadge = origDef === 'always'
  9414. ? '<span class="px-1.5 py-0.5 rounded text-[10px] bg-amber-500/20 text-amber-300 font-bold border border-amber-500/30">always</span>'
  9415. : (origDef === 'if-installed'
  9416. ? '<span class="px-1.5 py-0.5 rounded text-[10px] bg-sky-500/20 text-sky-300 font-bold border border-sky-500/30">if-installed</span>'
  9417. : '<span class="text-slate-500 text-[10px]">never</span>');
  9418. const filterBadges = [];
  9419. if (inst.in_filter) filterBadges.push(`<span class="px-1.5 py-0.5 rounded text-[10px] bg-blue-950 text-blue-300 border border-blue-800/50" title="In Filter">IN: ${escapeHtml(inst.in_filter)}</span>`);
  9420. if (inst.out_filter) filterBadges.push(`<span class="px-1.5 py-0.5 rounded text-[10px] bg-purple-950 text-purple-300 border border-purple-800/50" title="Out Filter">OUT: ${escapeHtml(inst.out_filter)}</span>`);
  9421. return `
  9422. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('instances', '${inst.id}')" ondblclick="openEditOspfInstanceModal('${inst.id}')">
  9423. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  9424. <td class="py-1.5 px-3 w-12 text-center">${flagD}</td>
  9425. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(inst.comment || '')}</td>
  9426. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  9427. <span class="text-sky-400">↳</span> <span>${escapeHtml(inst.name || 'Default')}</span>
  9428. ${filterBadges.join(' ')}
  9429. </td>
  9430. <td class="py-1.5 px-3">${inst.version || 2}</td>
  9431. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(inst.vrf || 'main')}</td>
  9432. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(inst.router_id || '192.168.131.56')}</td>
  9433. <td class="py-1.5 px-3 font-mono text-slate-300">${redist.join(', ') || '-'}</td>
  9434. <td class="py-1.5 px-3">${origBadge}</td>
  9435. </tr>
  9436. `;
  9437. }).join('');
  9438. }
  9439. // TAB 2: AREAS
  9440. function renderOspfAreas() {
  9441. const tbody = document.getElementById('ospf-areas-table-body');
  9442. if (!tbody) return;
  9443. const countEl = document.getElementById('ospf-areas-footer-count');
  9444. const filter = (document.getElementById('filter-ospf-areas')?.value || '').toLowerCase();
  9445. let list = state.ospfAreas || [];
  9446. if (filter) {
  9447. list = list.filter(a => (a.name || '').toLowerCase().includes(filter) || (a.area_id || '').toLowerCase().includes(filter) || (a.comment || '').toLowerCase().includes(filter));
  9448. }
  9449. if (countEl) countEl.innerText = list.length;
  9450. const selId = state.selectedOspfRow?.areas;
  9451. tbody.innerHTML = list.map((a, idx) => {
  9452. const isSel = a.id === selId;
  9453. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  9454. const flagD = a.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  9455. return `
  9456. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('areas', '${a.id}')" ondblclick="openEditOspfAreaModal('${a.id}')">
  9457. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  9458. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🌐'}</td>
  9459. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(a.comment || '')}</td>
  9460. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  9461. <span class="text-sky-400">↳</span> <span>${escapeHtml(a.name || 'Default')}</span>
  9462. </td>
  9463. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(a.instance || 'Default')}</td>
  9464. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(a.area_id || '0.0.0.0')}</td>
  9465. <td class="py-1.5 px-3 font-mono text-slate-400">${escapeHtml(a.area_type || 'default')}</td>
  9466. </tr>
  9467. `;
  9468. }).join('');
  9469. }
  9470. // TAB 3: AREA RANGES
  9471. function renderOspfAreaRanges() {
  9472. const tbody = document.getElementById('ospf-ranges-table-body');
  9473. if (!tbody) return;
  9474. const countEl = document.getElementById('ospf-ranges-footer-count');
  9475. const filter = (document.getElementById('filter-ospf-area-ranges')?.value || '').toLowerCase();
  9476. let list = state.ospfAreaRanges || [];
  9477. if (filter) {
  9478. list = list.filter(r => (r.prefix || '').toLowerCase().includes(filter) || (r.area || '').toLowerCase().includes(filter) || (r.comment || '').toLowerCase().includes(filter));
  9479. }
  9480. if (countEl) countEl.innerText = list.length;
  9481. const selId = state.selectedOspfRow?.['area-ranges'];
  9482. tbody.innerHTML = list.map((r, idx) => {
  9483. const isSel = r.id === selId;
  9484. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  9485. const flagD = r.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  9486. return `
  9487. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('ranges', '${r.id}')" ondblclick="openEditOspfAreaRangeModal('${r.id}')">
  9488. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  9489. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🏷'}</td>
  9490. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(r.comment || '')}</td>
  9491. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(r.area || 'Default')}</td>
  9492. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(r.prefix || '')}</td>
  9493. <td class="py-1.5 px-3">${r.cost || 1}</td>
  9494. <td class="py-1.5 px-3">${r.advertise !== false ? 'yes' : 'no'}</td>
  9495. </tr>
  9496. `;
  9497. }).join('');
  9498. }
  9499. // TAB 4: INTERFACE TEMPLATES
  9500. function renderOspfTemplates() {
  9501. const tbody = document.getElementById('ospf-templates-table-body');
  9502. if (!tbody) return;
  9503. const countEl = document.getElementById('ospf-templates-footer-count');
  9504. const filter = (document.getElementById('filter-ospf-templates')?.value || '').toLowerCase();
  9505. let list = state.ospfTemplates || [];
  9506. if (filter) {
  9507. list = list.filter(t => (t.interfaces || t.interface || '').toLowerCase().includes(filter) || (t.networks || t.network || '').toLowerCase().includes(filter) || (t.comment || '').toLowerCase().includes(filter));
  9508. }
  9509. if (countEl) countEl.innerText = list.length;
  9510. const selId = state.selectedOspfRow?.templates;
  9511. tbody.innerHTML = list.map((t, idx) => {
  9512. const isSel = t.id === selId;
  9513. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  9514. const ifaces = t.interfaces || t.interface || 'all';
  9515. const nets = t.networks || t.network || '';
  9516. const flagD = t.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  9517. return `
  9518. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('templates', '${t.id}')" ondblclick="openEditOspfTemplateModal('${t.id}')">
  9519. <td class="py-1.5 px-3 w-8 text-center text-slate-500 font-bold">${idx}</td>
  9520. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🔀'}</td>
  9521. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(t.comment || '')}</td>
  9522. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  9523. <span class="text-sky-400">↳</span> <span>${escapeHtml(ifaces)}</span>
  9524. </td>
  9525. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(t.area || 'Default')}</td>
  9526. <td class="py-1.5 px-3 font-mono text-sky-300">${escapeHtml(nets)}</td>
  9527. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(t.network_type || 'broadcast')}</td>
  9528. <td class="py-1.5 px-3">${t.cost || 1}</td>
  9529. <td class="py-1.5 px-3">${t.priority || 128}</td>
  9530. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(t.auth || t.auth_type || '')}</td>
  9531. </tr>
  9532. `;
  9533. }).join('');
  9534. }
  9535. // TAB 5: LIVE INTERFACES
  9536. function renderOspfLiveInterfaces() {
  9537. const tbody = document.getElementById('ospf-live-interfaces-table-body');
  9538. if (!tbody) return;
  9539. const countEl = document.getElementById('ospf-live-interfaces-footer-count');
  9540. const filter = (document.getElementById('filter-ospf-interfaces')?.value || '').toLowerCase();
  9541. let list = state.ospfLiveInterfaces || [];
  9542. if (filter) {
  9543. list = list.filter(i => (i.interface || '').toLowerCase().includes(filter) || (i.address || '').toLowerCase().includes(filter) || (i.state || '').toLowerCase().includes(filter));
  9544. }
  9545. if (countEl) countEl.innerText = list.length;
  9546. tbody.innerHTML = list.map(i => `
  9547. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  9548. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(i.flags || 'D')}</td>
  9549. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(i.interface || '')}</td>
  9550. <td class="py-1.5 px-3 font-mono text-sky-300 font-medium">${escapeHtml(i.address || '')}</td>
  9551. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(i.area || 'Default')}</td>
  9552. <td class="py-1.5 px-3 text-center text-slate-400">${i.instance_id || 0}</td>
  9553. <td class="py-1.5 px-3 font-mono text-amber-300 lowercase">${escapeHtml(i.state || 'waiting')}</td>
  9554. <td class="py-1.5 px-3">${i.cost || 1}</td>
  9555. <td class="py-1.5 px-3">${i.priority || 128}</td>
  9556. </tr>
  9557. `).join('');
  9558. }
  9559. // TAB 6: STATIC NEIGHBORS
  9560. function renderOspfStaticNbrs() {
  9561. const tbody = document.getElementById('ospf-snbrs-table-body');
  9562. if (!tbody) return;
  9563. const countEl = document.getElementById('ospf-snbrs-footer-count');
  9564. const filter = (document.getElementById('filter-ospf-static-nbrs')?.value || '').toLowerCase();
  9565. let list = state.ospfStaticNbrs || [];
  9566. if (filter) {
  9567. list = list.filter(n => (n.address || '').toLowerCase().includes(filter) || (n.area || '').toLowerCase().includes(filter) || (n.comment || '').toLowerCase().includes(filter));
  9568. }
  9569. if (countEl) countEl.innerText = list.length;
  9570. const selId = state.selectedOspfRow?.['static-nbrs'];
  9571. tbody.innerHTML = list.map((n, idx) => {
  9572. const isSel = n.id === selId;
  9573. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  9574. const flagD = n.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  9575. return `
  9576. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('snbrs', '${n.id}')" ondblclick="openEditOspfStaticNbrModal('${n.id}')">
  9577. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  9578. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '📡'}</td>
  9579. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(n.comment || '')}</td>
  9580. <td class="py-1.5 px-3 font-semibold font-mono text-sky-300">${escapeHtml(n.address || '')}</td>
  9581. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(n.area || 'Default')}</td>
  9582. <td class="py-1.5 px-3">${n.poll_interval || 120}s</td>
  9583. <td class="py-1.5 px-3">${n.cost || 1}</td>
  9584. </tr>
  9585. `;
  9586. }).join('');
  9587. }
  9588. // TAB 7: LIVE NEIGHBORS
  9589. function renderOspfNeighbors() {
  9590. const tbody = document.getElementById('ospf-neighbors-table-body');
  9591. if (!tbody) return;
  9592. const countEl = document.getElementById('ospf-neighbors-footer-count');
  9593. const filter = (document.getElementById('filter-ospf-neighbors')?.value || '').toLowerCase();
  9594. let list = state.ospfNeighbors || [];
  9595. if (filter) {
  9596. list = list.filter(n => (n.address || '').toLowerCase().includes(filter) || (n.state || '').toLowerCase().includes(filter) || (n.instance || '').toLowerCase().includes(filter));
  9597. }
  9598. if (countEl) countEl.innerText = list.length;
  9599. tbody.innerHTML = list.map(n => `
  9600. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  9601. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(n.flags || 'D')}</td>
  9602. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(n.comment || '')}</td>
  9603. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  9604. <span class="text-sky-400">↳</span> <span>${escapeHtml(n.instance || 'Default')}</span>
  9605. </td>
  9606. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(n.area || 'Default')}</td>
  9607. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(n.address || '')}</td>
  9608. <td class="py-1.5 px-3 font-mono font-bold text-emerald-400">${escapeHtml(n.state || 'Full')}</td>
  9609. <td class="py-1.5 px-3 text-slate-400">${n.state_changes ?? 6}</td>
  9610. </tr>
  9611. `).join('');
  9612. }
  9613. // TAB 8: LINK-STATE DATABASE (LSA)
  9614. function renderOspfLSA() {
  9615. const tbody = document.getElementById('ospf-lsa-table-body');
  9616. if (!tbody) return;
  9617. const countEl = document.getElementById('ospf-lsa-footer-count');
  9618. const filter = (document.getElementById('filter-ospf-lsa')?.value || '').toLowerCase();
  9619. let list = state.ospfLSA || [];
  9620. if (filter) {
  9621. list = list.filter(l => (l.type || '').toLowerCase().includes(filter) || (l.originator || '').toLowerCase().includes(filter) || (l.id || '').toLowerCase().includes(filter));
  9622. }
  9623. if (countEl) countEl.innerText = list.length;
  9624. tbody.innerHTML = list.map(l => `
  9625. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  9626. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(l.flags || 'D')}</td>
  9627. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  9628. <span class="text-sky-400">↳</span> <span>${escapeHtml(l.instance || 'Default')}</span>
  9629. </td>
  9630. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(l.area || 'Default')}</td>
  9631. <td class="py-1.5 px-3 font-mono text-amber-300">${escapeHtml(l.type || 'router')}</td>
  9632. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(l.originator || '')}</td>
  9633. <td class="py-1.5 px-3 font-mono text-sky-300 font-medium">${escapeHtml(l.id || '')}</td>
  9634. <td class="py-1.5 px-3 text-slate-500">${escapeHtml(l.link || '')}</td>
  9635. <td class="py-1.5 px-3 text-slate-500">${l.link_index ?? 0}</td>
  9636. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(l.sequence || '')}</td>
  9637. <td class="py-1.5 px-3 text-slate-400">${l.age ?? 0}</td>
  9638. </tr>
  9639. `).join('');
  9640. }
  9641. function renderOspfStatusPill() {
  9642. // Maintained for backward compatibility
  9643. const pill = document.getElementById('ospf-live-status-pill');
  9644. if (!pill) return;
  9645. 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';
  9646. pill.innerText = 'OSPF ACTIVE';
  9647. }
  9648. function renderOspfInterfaces() {
  9649. renderOspfTemplates();
  9650. }
  9651. function renderOspfRoutes() {
  9652. // Routes retained in background
  9653. }
  9654. // BGP Modals & Actions
  9655. function openBgpInstanceModal() {
  9656. const inst = state.bgpInstance || { enabled: false, as: 65001, router_id: '192.168.131.56', hold_time: 180, keepalive_time: 60 };
  9657. document.getElementById('modal-bgp-enabled').checked = !!inst.enabled;
  9658. document.getElementById('modal-bgp-as').value = inst.as || 65001;
  9659. document.getElementById('modal-bgp-router-id').value = inst.router_id || '';
  9660. document.getElementById('modal-bgp-keepalive').value = inst.keepalive_time || 60;
  9661. document.getElementById('modal-bgp-holdtime').value = inst.hold_time || 180;
  9662. document.getElementById('modal-bgp-redist-conn').checked = !!inst.redistribute_connected;
  9663. document.getElementById('modal-bgp-redist-static').checked = !!inst.redistribute_static;
  9664. document.getElementById('modal-bgp-redist-ospf').checked = !!inst.redistribute_ospf;
  9665. document.getElementById('modal-bgp-in-filter').value = inst.in_filter || '';
  9666. document.getElementById('modal-bgp-out-filter').value = inst.out_filter || '';
  9667. document.getElementById('bgp-instance-modal').classList.remove('hidden');
  9668. }
  9669. function closeBgpInstanceModal() {
  9670. document.getElementById('bgp-instance-modal').classList.add('hidden');
  9671. }
  9672. async function submitBgpInstance(e) {
  9673. e.preventDefault();
  9674. const payload = {
  9675. enabled: document.getElementById('modal-bgp-enabled').checked,
  9676. as: parseInt(document.getElementById('modal-bgp-as').value, 10),
  9677. router_id: document.getElementById('modal-bgp-router-id').value.trim(),
  9678. keepalive_time: parseInt(document.getElementById('modal-bgp-keepalive').value, 10),
  9679. hold_time: parseInt(document.getElementById('modal-bgp-holdtime').value, 10),
  9680. in_filter: (document.getElementById('modal-bgp-in-filter')?.value || '').trim(),
  9681. out_filter: (document.getElementById('modal-bgp-out-filter')?.value || '').trim(),
  9682. redistribute_connected: document.getElementById('modal-bgp-redist-conn').checked,
  9683. redistribute_static: document.getElementById('modal-bgp-redist-static').checked,
  9684. redistribute_ospf: document.getElementById('modal-bgp-redist-ospf').checked
  9685. };
  9686. try {
  9687. const res = await fetch(`${API_BASE}/routing/bgp/instance`, {
  9688. method: 'POST',
  9689. headers: { 'Content-Type': 'application/json' },
  9690. body: JSON.stringify(payload)
  9691. });
  9692. if (res.ok) {
  9693. closeBgpInstanceModal();
  9694. showToast('Success', 'BGP instance configuration updated', 'success');
  9695. loadDynamicRouting();
  9696. } else {
  9697. const err = await res.json();
  9698. showToast('Error', err.error || 'Failed to update BGP instance', 'error');
  9699. }
  9700. } catch (err) {
  9701. showToast('Error', err.message, 'error');
  9702. }
  9703. }
  9704. // ----------------- BGP Peer Connection Modal (DebTik v7) -----------------
  9705. function switchBgpPeerModalTab(tab) {
  9706. // Normalize legacy tab names
  9707. if (tab === 'extra' || tab === 'filter') tab = 'filters';
  9708. if (tab === 'attributes') tab = 'networks';
  9709. const tabs = ['general', 'filters', 'networks'];
  9710. tabs.forEach(t => {
  9711. const pane = document.getElementById(`bgp-peer-tab-${t}`);
  9712. const btn = document.getElementById(`bgp-peer-tab-btn-${t}`);
  9713. if (t === tab) {
  9714. if (pane) pane.classList.remove('hidden');
  9715. if (btn) btn.className = 'px-4 py-2 text-xs font-bold border-b-2 border-cyan-500 text-white transition';
  9716. } else {
  9717. if (pane) pane.classList.add('hidden');
  9718. 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';
  9719. }
  9720. });
  9721. }
  9722. function addOutputNetworkRow(val = '') {
  9723. const container = document.getElementById('modal-bgp-output-networks-container');
  9724. if (!container) return;
  9725. const row = document.createElement('div');
  9726. row.className = 'flex items-center gap-2 output-net-row';
  9727. row.innerHTML = `
  9728. <input type="text" value="${escapeHtml(val)}" placeholder="e.g. 192.168.100.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">
  9729. <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>
  9730. `;
  9731. container.appendChild(row);
  9732. }
  9733. function parseBgpTime(val) {
  9734. if (!val) return 0;
  9735. val = String(val).trim();
  9736. if (val.includes(':')) {
  9737. const parts = val.split(':').map(x => parseInt(x, 10) || 0);
  9738. if (parts.length === 3) return parts[0] * 3600 + parts[1] * 60 + parts[2];
  9739. if (parts.length === 2) return parts[0] * 60 + parts[1];
  9740. }
  9741. return parseInt(val, 10) || 0;
  9742. }
  9743. function formatBgpTime(secs) {
  9744. if (!secs || secs <= 0) return '30';
  9745. return String(secs);
  9746. }
  9747. function populateBgpRoutingTables() {
  9748. const sel = document.getElementById('modal-bgp-peer-routing-table');
  9749. if (!sel) return;
  9750. const cur = sel.value || 'main';
  9751. sel.innerHTML = '<option value="main">main</option>';
  9752. (state.routingTables || []).forEach(t => {
  9753. if (t.name !== 'main') {
  9754. const opt = document.createElement('option');
  9755. opt.value = t.name;
  9756. opt.innerText = t.name;
  9757. sel.appendChild(opt);
  9758. }
  9759. });
  9760. sel.value = cur;
  9761. }
  9762. function populateBgpLocalAddrDatalist() {
  9763. const dlBgp = document.getElementById('bgp-peer-local-addr-datalist');
  9764. if (!dlBgp) return;
  9765. const addrs = [];
  9766. (state.interfaces || []).forEach(iface => {
  9767. if (iface.ip) addrs.push(iface.ip.split('/')[0]);
  9768. (iface.addresses || []).forEach(a => addrs.push(a.split('/')[0]));
  9769. });
  9770. dlBgp.innerHTML = Array.from(new Set(addrs.filter(Boolean))).map(ip => `<option value="${escapeHtml(ip)}">`).join('');
  9771. }
  9772. function openAddBgpPeerModal() {
  9773. document.getElementById('bgp-peer-form').reset();
  9774. document.getElementById('modal-bgp-peer-id').value = '';
  9775. document.getElementById('bgp-peer-modal-title').innerText = 'New BGP Connection...';
  9776. populateBgpLocalAddrDatalist();
  9777. // General Tab
  9778. document.getElementById('modal-bgp-peer-enabled').checked = true;
  9779. document.getElementById('modal-bgp-peer-name').value = '';
  9780. document.getElementById('modal-bgp-peer-comment').value = '';
  9781. if (document.getElementById('modal-bgp-peer-local-as')) document.getElementById('modal-bgp-peer-local-as').value = '';
  9782. if (document.getElementById('modal-bgp-peer-remote-addr')) document.getElementById('modal-bgp-peer-remote-addr').value = '';
  9783. if (document.getElementById('modal-bgp-peer-remote-port')) document.getElementById('modal-bgp-peer-remote-port').value = '';
  9784. if (document.getElementById('modal-bgp-peer-remote-as')) document.getElementById('modal-bgp-peer-remote-as').value = '';
  9785. if (document.getElementById('modal-bgp-peer-local-addr')) document.getElementById('modal-bgp-peer-local-addr').value = '';
  9786. if (document.getElementById('modal-bgp-peer-local-port')) document.getElementById('modal-bgp-peer-local-port').value = '';
  9787. if (document.getElementById('modal-bgp-peer-local-role')) document.getElementById('modal-bgp-peer-local-role').value = 'ebgp';
  9788. if (document.getElementById('modal-bgp-peer-password')) document.getElementById('modal-bgp-peer-password').value = '';
  9789. if (document.getElementById('modal-bgp-peer-multihop')) document.getElementById('modal-bgp-peer-multihop').checked = false;
  9790. if (document.getElementById('modal-bgp-peer-passive')) document.getElementById('modal-bgp-peer-passive').checked = false;
  9791. if (document.getElementById('modal-bgp-peer-nexthop-self')) document.getElementById('modal-bgp-peer-nexthop-self').checked = false;
  9792. if (document.getElementById('modal-bgp-peer-use-bfd')) document.getElementById('modal-bgp-peer-use-bfd').checked = false;
  9793. if (document.getElementById('modal-bgp-peer-holdtime')) document.getElementById('modal-bgp-peer-holdtime').value = '30';
  9794. if (document.getElementById('modal-bgp-peer-keepalive')) document.getElementById('modal-bgp-peer-keepalive').value = '10';
  9795. // Filters Tab
  9796. populateFilterChainsDatalist();
  9797. if (document.getElementById('modal-bgp-peer-in-filter')) document.getElementById('modal-bgp-peer-in-filter').value = '';
  9798. if (document.getElementById('modal-bgp-peer-out-filter')) document.getElementById('modal-bgp-peer-out-filter').value = '';
  9799. if (document.getElementById('modal-bgp-peer-redist-conn')) document.getElementById('modal-bgp-peer-redist-conn').checked = false;
  9800. if (document.getElementById('modal-bgp-peer-redist-static')) document.getElementById('modal-bgp-peer-redist-static').checked = true;
  9801. if (document.getElementById('modal-bgp-peer-redist-ospf')) document.getElementById('modal-bgp-peer-redist-ospf').checked = false;
  9802. if (document.getElementById('modal-bgp-peer-default-orig')) document.getElementById('modal-bgp-peer-default-orig').checked = false;
  9803. // Advertised Networks Tab
  9804. const container = document.getElementById('modal-bgp-output-networks-container');
  9805. if (container) {
  9806. container.innerHTML = '';
  9807. addOutputNetworkRow('');
  9808. }
  9809. const removeBtn = document.getElementById('modal-btn-remove-peer');
  9810. if (removeBtn) removeBtn.classList.add('hidden');
  9811. switchBgpPeerModalTab('general');
  9812. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  9813. }
  9814. function populateFilterChainsDatalist() {
  9815. const dl = document.getElementById('filter-chains-list');
  9816. if (!dl) return;
  9817. const chains = new Set();
  9818. (state.routingFilters || []).forEach(f => {
  9819. if (f.chain) chains.add(f.chain);
  9820. });
  9821. if (chains.size === 0) {
  9822. chains.add('awmn');
  9823. chains.add('Internal');
  9824. chains.add('bgp-in');
  9825. chains.add('bgp-out');
  9826. }
  9827. dl.innerHTML = '';
  9828. chains.forEach(c => {
  9829. const opt = document.createElement('option');
  9830. opt.value = c;
  9831. dl.appendChild(opt);
  9832. });
  9833. }
  9834. function openEditBgpPeerModal(id) {
  9835. const p = (state.bgpPeers || []).find(item => item.id === id);
  9836. if (!p) return;
  9837. populateFilterChainsDatalist();
  9838. populateBgpLocalAddrDatalist();
  9839. document.getElementById('modal-bgp-peer-id').value = p.id;
  9840. document.getElementById('bgp-peer-modal-title').innerText = p.name || p.id;
  9841. // General Tab
  9842. document.getElementById('modal-bgp-peer-enabled').checked = p.enabled !== false && !p.disabled;
  9843. document.getElementById('modal-bgp-peer-name').value = p.name || '';
  9844. document.getElementById('modal-bgp-peer-comment').value = p.comment || '';
  9845. if (document.getElementById('modal-bgp-peer-local-as')) document.getElementById('modal-bgp-peer-local-as').value = p.local_as || '';
  9846. if (document.getElementById('modal-bgp-peer-remote-addr')) document.getElementById('modal-bgp-peer-remote-addr').value = p.remote_address || '';
  9847. if (document.getElementById('modal-bgp-peer-remote-port')) document.getElementById('modal-bgp-peer-remote-port').value = p.remote_port || '';
  9848. if (document.getElementById('modal-bgp-peer-remote-as')) document.getElementById('modal-bgp-peer-remote-as').value = p.remote_as || '';
  9849. if (document.getElementById('modal-bgp-peer-local-addr')) document.getElementById('modal-bgp-peer-local-addr').value = p.local_address || '';
  9850. if (document.getElementById('modal-bgp-peer-local-port')) document.getElementById('modal-bgp-peer-local-port').value = p.local_port || '';
  9851. if (document.getElementById('modal-bgp-peer-local-role')) document.getElementById('modal-bgp-peer-local-role').value = p.local_role || 'ebgp';
  9852. if (document.getElementById('modal-bgp-peer-password')) document.getElementById('modal-bgp-peer-password').value = p.password || '';
  9853. if (document.getElementById('modal-bgp-peer-multihop')) document.getElementById('modal-bgp-peer-multihop').checked = !!p.multihop;
  9854. // Passive mode
  9855. const isPassive = !!p.passive || (p.connect === false && p.listen !== false);
  9856. if (document.getElementById('modal-bgp-peer-passive')) document.getElementById('modal-bgp-peer-passive').checked = isPassive;
  9857. // Next-hop self
  9858. const isNexthopSelf = !!p.nexthop_self || p.nexthop_choice === 'force-self';
  9859. if (document.getElementById('modal-bgp-peer-nexthop-self')) document.getElementById('modal-bgp-peer-nexthop-self').checked = isNexthopSelf;
  9860. if (document.getElementById('modal-bgp-peer-use-bfd')) document.getElementById('modal-bgp-peer-use-bfd').checked = !!p.use_bfd;
  9861. if (document.getElementById('modal-bgp-peer-holdtime')) document.getElementById('modal-bgp-peer-holdtime').value = p.hold_time ? String(p.hold_time) : '30';
  9862. if (document.getElementById('modal-bgp-peer-keepalive')) document.getElementById('modal-bgp-peer-keepalive').value = p.keepalive_time ? String(p.keepalive_time) : '10';
  9863. // Filters Tab
  9864. if (document.getElementById('modal-bgp-peer-in-filter')) document.getElementById('modal-bgp-peer-in-filter').value = p.in_filter || '';
  9865. if (document.getElementById('modal-bgp-peer-out-filter')) document.getElementById('modal-bgp-peer-out-filter').value = p.out_filter || '';
  9866. if (document.getElementById('modal-bgp-peer-redist-conn')) document.getElementById('modal-bgp-peer-redist-conn').checked = !!p.redist_connected;
  9867. if (document.getElementById('modal-bgp-peer-redist-static')) document.getElementById('modal-bgp-peer-redist-static').checked = p.redist_static !== false;
  9868. if (document.getElementById('modal-bgp-peer-redist-ospf')) document.getElementById('modal-bgp-peer-redist-ospf').checked = !!p.redist_ospf;
  9869. if (document.getElementById('modal-bgp-peer-default-orig')) document.getElementById('modal-bgp-peer-default-orig').checked = !!p.default_originate;
  9870. // Advertised Networks Tab
  9871. const container = document.getElementById('modal-bgp-output-networks-container');
  9872. if (container) {
  9873. container.innerHTML = '';
  9874. if (p.output_networks && p.output_networks.length > 0) {
  9875. p.output_networks.forEach(net => addOutputNetworkRow(net));
  9876. } else {
  9877. addOutputNetworkRow('');
  9878. }
  9879. }
  9880. const removeBtn = document.getElementById('modal-btn-remove-peer');
  9881. if (removeBtn) removeBtn.classList.remove('hidden');
  9882. switchBgpPeerModalTab('general');
  9883. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  9884. }
  9885. function copyCurrentBgpPeer() {
  9886. document.getElementById('modal-bgp-peer-id').value = '';
  9887. const nameEl = document.getElementById('modal-bgp-peer-name');
  9888. if (nameEl) nameEl.value = (nameEl.value || 'peer') + '-copy';
  9889. document.getElementById('bgp-peer-modal-title').innerText = 'New BGP Connection...';
  9890. const removeBtn = document.getElementById('modal-btn-remove-peer');
  9891. if (removeBtn) removeBtn.classList.add('hidden');
  9892. showToast('Cloned', 'BGP connection copied to new draft', 'info');
  9893. }
  9894. function removeCurrentBgpPeer() {
  9895. const id = document.getElementById('modal-bgp-peer-id')?.value;
  9896. if (!id) return;
  9897. deleteBgpPeer(id);
  9898. closeBgpPeerModal();
  9899. }
  9900. function closeBgpPeerModal() {
  9901. document.getElementById('bgp-peer-modal').classList.add('hidden');
  9902. }
  9903. function getBgpPeerFormData() {
  9904. const netInputs = document.querySelectorAll('#modal-bgp-output-networks-container .output-net-row input');
  9905. const outputNetworks = [];
  9906. netInputs.forEach(inp => {
  9907. const v = inp.value.trim();
  9908. if (v) outputNetworks.push(v);
  9909. });
  9910. const enabled = document.getElementById('modal-bgp-peer-enabled').checked;
  9911. const isPassive = document.getElementById('modal-bgp-peer-passive')?.checked || false;
  9912. const isNexthopSelf = document.getElementById('modal-bgp-peer-nexthop-self')?.checked || false;
  9913. const useBfd = document.getElementById('modal-bgp-peer-use-bfd')?.checked || false;
  9914. return {
  9915. id: document.getElementById('modal-bgp-peer-id').value,
  9916. name: document.getElementById('modal-bgp-peer-name').value.trim(),
  9917. enabled: enabled,
  9918. disabled: !enabled,
  9919. comment: document.getElementById('modal-bgp-peer-comment').value.trim(),
  9920. local_as: parseInt(document.getElementById('modal-bgp-peer-local-as')?.value, 10) || 0,
  9921. remote_address: document.getElementById('modal-bgp-peer-remote-addr').value.trim(),
  9922. remote_port: parseInt(document.getElementById('modal-bgp-peer-remote-port').value, 10) || 0,
  9923. remote_as: parseInt(document.getElementById('modal-bgp-peer-remote-as').value, 10) || 0,
  9924. local_address: document.getElementById('modal-bgp-peer-local-addr')?.value.trim() || '',
  9925. local_port: parseInt(document.getElementById('modal-bgp-peer-local-port')?.value, 10) || 0,
  9926. local_role: document.getElementById('modal-bgp-peer-local-role')?.value || 'ebgp',
  9927. password: document.getElementById('modal-bgp-peer-password')?.value || '',
  9928. multihop: document.getElementById('modal-bgp-peer-multihop')?.checked || false,
  9929. use_bfd: useBfd,
  9930. passive: isPassive,
  9931. connect: !isPassive,
  9932. listen: true,
  9933. hold_time: parseBgpTime(document.getElementById('modal-bgp-peer-holdtime')?.value),
  9934. keepalive_time: parseBgpTime(document.getElementById('modal-bgp-peer-keepalive')?.value),
  9935. nexthop_self: isNexthopSelf,
  9936. nexthop_choice: isNexthopSelf ? 'force-self' : 'default',
  9937. in_filter: (document.getElementById('modal-bgp-peer-in-filter')?.value || '').trim(),
  9938. out_filter: (document.getElementById('modal-bgp-peer-out-filter')?.value || '').trim(),
  9939. default_originate: document.getElementById('modal-bgp-peer-default-orig')?.checked || false,
  9940. redist_connected: document.getElementById('modal-bgp-peer-redist-conn')?.checked || false,
  9941. redist_static: document.getElementById('modal-bgp-peer-redist-static')?.checked !== false,
  9942. redist_ospf: document.getElementById('modal-bgp-peer-redist-ospf')?.checked || false,
  9943. output_networks: outputNetworks
  9944. };
  9945. }
  9946. async function submitBgpPeer(e) {
  9947. if (e) e.preventDefault();
  9948. const payload = getBgpPeerFormData();
  9949. try {
  9950. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  9951. method: 'POST',
  9952. headers: { 'Content-Type': 'application/json' },
  9953. body: JSON.stringify(payload)
  9954. });
  9955. if (res.ok) {
  9956. closeBgpPeerModal();
  9957. showToast('Success', 'BGP Connection saved', 'success');
  9958. loadDynamicRouting();
  9959. } else {
  9960. const err = await res.json();
  9961. showToast('Error', err.error || 'Failed to save peer', 'error');
  9962. }
  9963. } catch (err) {
  9964. showToast('Error', err.message, 'error');
  9965. }
  9966. }
  9967. async function applyBgpPeerModal(e) {
  9968. if (e) e.preventDefault();
  9969. const payload = getBgpPeerFormData();
  9970. try {
  9971. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  9972. method: 'POST',
  9973. headers: { 'Content-Type': 'application/json' },
  9974. body: JSON.stringify(payload)
  9975. });
  9976. if (res.ok) {
  9977. const data = await res.json();
  9978. if (data.peer && data.peer.id) {
  9979. document.getElementById('modal-bgp-peer-id').value = data.peer.id;
  9980. document.getElementById('bgp-peer-modal-title').innerText = data.peer.name || data.peer.id;
  9981. document.getElementById('modal-btn-remove-peer')?.classList.remove('hidden');
  9982. }
  9983. showToast('Applied', 'BGP Connection applied', 'success');
  9984. loadDynamicRouting();
  9985. } else {
  9986. const err = await res.json();
  9987. showToast('Error', err.error || 'Failed to apply peer', 'error');
  9988. }
  9989. } catch (err) {
  9990. showToast('Error', err.message, 'error');
  9991. }
  9992. }
  9993. async function deleteBgpPeer(id) {
  9994. if (!confirm('Are you sure you want to delete this BGP peer connection?')) return;
  9995. try {
  9996. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9997. if (res.ok) {
  9998. showToast('Deleted', 'BGP peer removed', 'success');
  9999. loadDynamicRouting();
  10000. }
  10001. } catch (err) {
  10002. showToast('Error', err.message, 'error');
  10003. }
  10004. }
  10005. async function toggleBgpPeerState(id, disabled) {
  10006. try {
  10007. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}/state`, {
  10008. method: 'POST',
  10009. headers: { 'Content-Type': 'application/json' },
  10010. body: JSON.stringify({ disabled })
  10011. });
  10012. if (res.ok) {
  10013. showToast('Updated', `Peer ${disabled ? 'disabled' : 'enabled'}`, 'success');
  10014. loadDynamicRouting();
  10015. }
  10016. } catch (err) {
  10017. showToast('Error', err.message, 'error');
  10018. }
  10019. }
  10020. function openAddBgpNetworkModal() {
  10021. document.getElementById('bgp-network-form').reset();
  10022. document.getElementById('modal-bgp-net-id').value = '';
  10023. document.getElementById('bgp-network-modal').classList.remove('hidden');
  10024. }
  10025. function closeBgpNetworkModal() {
  10026. document.getElementById('bgp-network-modal').classList.add('hidden');
  10027. }
  10028. async function submitBgpNetwork(e) {
  10029. e.preventDefault();
  10030. const payload = {
  10031. id: document.getElementById('modal-bgp-net-id').value,
  10032. network: document.getElementById('modal-bgp-net-cidr').value.trim(),
  10033. comment: document.getElementById('modal-bgp-net-comment').value.trim(),
  10034. disabled: document.getElementById('modal-bgp-net-disabled').checked
  10035. };
  10036. try {
  10037. const res = await fetch(`${API_BASE}/routing/bgp/networks`, {
  10038. method: 'POST',
  10039. headers: { 'Content-Type': 'application/json' },
  10040. body: JSON.stringify(payload)
  10041. });
  10042. if (res.ok) {
  10043. closeBgpNetworkModal();
  10044. showToast('Success', 'BGP network advertisement saved', 'success');
  10045. loadDynamicRouting();
  10046. } else {
  10047. const err = await res.json();
  10048. showToast('Error', err.error || 'Failed to save network', 'error');
  10049. }
  10050. } catch (err) {
  10051. showToast('Error', err.message, 'error');
  10052. }
  10053. }
  10054. async function deleteBgpNetwork(id) {
  10055. if (!confirm('Are you sure you want to stop announcing this network?')) return;
  10056. try {
  10057. const res = await fetch(`${API_BASE}/routing/bgp/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10058. if (res.ok) {
  10059. showToast('Deleted', 'Network advertisement removed', 'success');
  10060. loadDynamicRouting();
  10061. }
  10062. } catch (err) {
  10063. showToast('Error', err.message, 'error');
  10064. }
  10065. }
  10066. // =========================================================================
  10067. // DEBTIK v7 OSPF MODALS & ACTIONS
  10068. // =========================================================================
  10069. // --- 1. OSPF INSTANCE ---
  10070. function openOspfInstanceModal(id = null) {
  10071. const isEdit = !!id;
  10072. const inst = (state.ospfInstances || []).find(i => i.id === id) || {
  10073. id: '',
  10074. name: 'Default',
  10075. version: 2,
  10076. vrf: 'main',
  10077. router_id: '192.168.131.56',
  10078. routing_table: 'main',
  10079. enabled: true,
  10080. redistribute_connected: false,
  10081. redistribute_static: true,
  10082. redistribute_bgp: false,
  10083. comment: ''
  10084. };
  10085. document.getElementById('ospf-instance-modal-title').innerText = isEdit ? inst.name : 'New...';
  10086. document.getElementById('modal-ospf-inst-id').value = isEdit ? inst.id : '';
  10087. document.getElementById('modal-ospf-inst-enabled').checked = !inst.disabled;
  10088. document.getElementById('modal-ospf-inst-comment').value = inst.comment || '';
  10089. document.getElementById('modal-ospf-inst-name').value = inst.name || 'Default';
  10090. document.getElementById('modal-ospf-inst-version').value = inst.version || 2;
  10091. document.getElementById('modal-ospf-inst-vrf').value = inst.vrf || 'main';
  10092. document.getElementById('modal-ospf-inst-router-id').value = inst.router_id || '';
  10093. document.getElementById('modal-ospf-inst-routing-table').value = inst.routing_table || 'main';
  10094. document.getElementById('modal-ospf-inst-redist-conn').checked = !!inst.redistribute_connected;
  10095. document.getElementById('modal-ospf-inst-redist-static').checked = inst.redistribute_static !== false;
  10096. document.getElementById('modal-ospf-inst-redist-bgp').checked = !!inst.redistribute_bgp;
  10097. const isDefaultRedist = !!inst.redistribute_default || (inst.originate_default && inst.originate_default !== 'never');
  10098. const origMode = inst.originate_default || (inst.redistribute_default ? 'if-installed' : 'never');
  10099. document.getElementById('modal-ospf-inst-redist-default').checked = isDefaultRedist;
  10100. document.getElementById('modal-ospf-inst-originate-default').value = origMode;
  10101. document.getElementById('modal-ospf-inst-default-metric').value = inst.default_metric || '';
  10102. document.getElementById('modal-ospf-inst-in-filter').value = inst.in_filter || '';
  10103. document.getElementById('modal-ospf-inst-out-filter').value = inst.out_filter || '';
  10104. const btnRem = document.getElementById('btn-ospf-inst-modal-remove');
  10105. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  10106. document.getElementById('ospf-instance-modal').classList.remove('hidden');
  10107. }
  10108. function toggleOspfDefaultModeUI() {
  10109. const isChecked = document.getElementById('modal-ospf-inst-redist-default')?.checked;
  10110. const select = document.getElementById('modal-ospf-inst-originate-default');
  10111. if (!select) return;
  10112. if (isChecked) {
  10113. if (select.value === 'never') select.value = 'if-installed';
  10114. } else {
  10115. select.value = 'never';
  10116. }
  10117. }
  10118. function onOspfOriginateDefaultChange() {
  10119. const val = document.getElementById('modal-ospf-inst-originate-default')?.value;
  10120. const chk = document.getElementById('modal-ospf-inst-redist-default');
  10121. if (chk) chk.checked = val !== 'never';
  10122. }
  10123. function openEditOspfInstanceModal(id) {
  10124. openOspfInstanceModal(id);
  10125. }
  10126. function closeOspfInstanceModal() {
  10127. document.getElementById('ospf-instance-modal').classList.add('hidden');
  10128. }
  10129. async function submitOspfInstance(e) {
  10130. if (e) e.preventDefault();
  10131. const payload = {
  10132. id: document.getElementById('modal-ospf-inst-id').value,
  10133. name: document.getElementById('modal-ospf-inst-name').value.trim() || 'Default',
  10134. version: parseInt(document.getElementById('modal-ospf-inst-version').value, 10) || 2,
  10135. vrf: document.getElementById('modal-ospf-inst-vrf').value.trim() || 'main',
  10136. router_id: document.getElementById('modal-ospf-inst-router-id').value.trim(),
  10137. routing_table: document.getElementById('modal-ospf-inst-routing-table').value.trim() || 'main',
  10138. enabled: document.getElementById('modal-ospf-inst-enabled').checked,
  10139. disabled: !document.getElementById('modal-ospf-inst-enabled').checked,
  10140. comment: document.getElementById('modal-ospf-inst-comment').value.trim(),
  10141. redistribute_connected: document.getElementById('modal-ospf-inst-redist-conn').checked,
  10142. redistribute_static: document.getElementById('modal-ospf-inst-redist-static').checked,
  10143. redistribute_bgp: document.getElementById('modal-ospf-inst-redist-bgp').checked,
  10144. redistribute_default: document.getElementById('modal-ospf-inst-redist-default').checked,
  10145. originate_default: document.getElementById('modal-ospf-inst-originate-default').value,
  10146. default_metric: parseInt(document.getElementById('modal-ospf-inst-default-metric').value, 10) || 0,
  10147. in_filter: (document.getElementById('modal-ospf-inst-in-filter')?.value || '').trim(),
  10148. out_filter: (document.getElementById('modal-ospf-inst-out-filter')?.value || '').trim()
  10149. };
  10150. try {
  10151. const res = await fetch(`${API_BASE}/routing/ospf/instances`, {
  10152. method: 'POST',
  10153. headers: { 'Content-Type': 'application/json' },
  10154. body: JSON.stringify(payload)
  10155. });
  10156. if (res.ok) {
  10157. closeOspfInstanceModal();
  10158. showToast('Saved', 'OSPF instance updated', 'success');
  10159. loadDynamicRouting();
  10160. } else {
  10161. const err = await res.json();
  10162. showToast('Error', err.error || 'Failed to save OSPF instance', 'error');
  10163. }
  10164. } catch (err) {
  10165. showToast('Error', err.message, 'error');
  10166. }
  10167. }
  10168. function applyOspfInstanceForm() {
  10169. submitOspfInstance(null);
  10170. }
  10171. function copyOspfInstance() {
  10172. document.getElementById('modal-ospf-inst-id').value = '';
  10173. document.getElementById('modal-ospf-inst-name').value += '-copy';
  10174. document.getElementById('ospf-instance-modal-title').innerText = 'New...';
  10175. showToast('Copied', 'Duplicated as new OSPF instance', 'info');
  10176. }
  10177. async function deleteCurrentOspfInstance() {
  10178. const id = document.getElementById('modal-ospf-inst-id').value;
  10179. if (!id) return;
  10180. if (!confirm('Are you sure you want to remove this OSPF instance?')) return;
  10181. try {
  10182. const res = await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10183. if (res.ok) {
  10184. closeOspfInstanceModal();
  10185. showToast('Removed', 'OSPF instance deleted', 'success');
  10186. loadDynamicRouting();
  10187. } else {
  10188. throw new Error(await responseError(res));
  10189. }
  10190. } catch (err) {
  10191. showToast('Error', err.message, 'error');
  10192. }
  10193. }
  10194. async function enableSelectedOspfInstance() {
  10195. const id = state.selectedOspfRow?.instances;
  10196. if (!id) return;
  10197. if (!await routingMutation(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}/state`, {
  10198. method: 'POST',
  10199. headers: { 'Content-Type': 'application/json' },
  10200. body: JSON.stringify({ disabled: false })
  10201. })) return;
  10202. loadDynamicRouting();
  10203. }
  10204. async function disableSelectedOspfInstance() {
  10205. const id = state.selectedOspfRow?.instances;
  10206. if (!id) return;
  10207. if (!await routingMutation(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}/state`, {
  10208. method: 'POST',
  10209. headers: { 'Content-Type': 'application/json' },
  10210. body: JSON.stringify({ disabled: true })
  10211. })) return;
  10212. loadDynamicRouting();
  10213. }
  10214. async function removeSelectedOspfInstance() {
  10215. const id = state.selectedOspfRow?.instances;
  10216. if (!id) return;
  10217. if (!confirm('Delete selected OSPF instance?')) return;
  10218. if (!await routingMutation(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}`, { method: 'DELETE' })) return;
  10219. loadDynamicRouting();
  10220. }
  10221. async function promptCommentOspfInstance() {
  10222. const id = state.selectedOspfRow?.instances;
  10223. if (!id) return;
  10224. const inst = (state.ospfInstances || []).find(i => i.id === id);
  10225. if (!inst) return;
  10226. const comment = prompt('Enter comment for OSPF instance:', inst.comment || '');
  10227. if (comment === null) return;
  10228. const updated = {...inst, comment};
  10229. if (!await routingMutation(`${API_BASE}/routing/ospf/instances`, {
  10230. method: 'POST',
  10231. headers: { 'Content-Type': 'application/json' },
  10232. body: JSON.stringify(updated)
  10233. })) return;
  10234. loadDynamicRouting();
  10235. }
  10236. // --- 2. OSPF AREA ---
  10237. function populateOspfAreaDropdowns() {
  10238. const instSelect = document.getElementById('modal-ospf-area-instance');
  10239. if (instSelect) {
  10240. const cur = instSelect.value;
  10241. instSelect.innerHTML = (state.ospfInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)}</option>`).join('');
  10242. if (instSelect.innerHTML === '') instSelect.innerHTML = '<option value="Default">Default</option>';
  10243. if (cur) instSelect.value = cur;
  10244. }
  10245. }
  10246. function openOspfAreaModal(id = null) {
  10247. const isEdit = !!id;
  10248. populateOspfAreaDropdowns();
  10249. const area = (state.ospfAreas || []).find(a => a.id === id) || {
  10250. id: '',
  10251. name: 'Default',
  10252. instance: 'Default',
  10253. area_id: '0.0.0.0',
  10254. area_type: 'default',
  10255. default_cost: 1,
  10256. no_summaries: false,
  10257. disabled: false,
  10258. comment: ''
  10259. };
  10260. document.getElementById('ospf-area-modal-title').innerText = isEdit ? area.name : 'New...';
  10261. document.getElementById('modal-ospf-area-id').value = isEdit ? area.id : '';
  10262. document.getElementById('modal-ospf-area-enabled').checked = !area.disabled;
  10263. document.getElementById('modal-ospf-area-comment').value = area.comment || '';
  10264. document.getElementById('modal-ospf-area-name').value = area.name || 'Default';
  10265. document.getElementById('modal-ospf-area-instance').value = area.instance || 'Default';
  10266. document.getElementById('modal-ospf-area-areaid').value = area.area_id || '0.0.0.0';
  10267. document.getElementById('modal-ospf-area-type').value = area.area_type || 'default';
  10268. document.getElementById('modal-ospf-area-default-cost').value = area.default_cost || 1;
  10269. document.getElementById('modal-ospf-area-no-summaries').checked = !!area.no_summaries;
  10270. const btnRem = document.getElementById('btn-ospf-area-modal-remove');
  10271. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  10272. document.getElementById('ospf-area-modal').classList.remove('hidden');
  10273. }
  10274. function openEditOspfAreaModal(id) {
  10275. openOspfAreaModal(id);
  10276. }
  10277. function closeOspfAreaModal() {
  10278. document.getElementById('ospf-area-modal').classList.add('hidden');
  10279. }
  10280. async function submitOspfArea(e) {
  10281. if (e) e.preventDefault();
  10282. const payload = {
  10283. id: document.getElementById('modal-ospf-area-id').value,
  10284. name: document.getElementById('modal-ospf-area-name').value.trim() || 'Default',
  10285. instance: document.getElementById('modal-ospf-area-instance').value.trim() || 'Default',
  10286. area_id: document.getElementById('modal-ospf-area-areaid').value.trim() || '0.0.0.0',
  10287. area_type: document.getElementById('modal-ospf-area-type').value,
  10288. default_cost: parseInt(document.getElementById('modal-ospf-area-default-cost').value, 10) || 1,
  10289. no_summaries: document.getElementById('modal-ospf-area-no-summaries').checked,
  10290. disabled: !document.getElementById('modal-ospf-area-enabled').checked,
  10291. comment: document.getElementById('modal-ospf-area-comment').value.trim()
  10292. };
  10293. try {
  10294. const res = await fetch(`${API_BASE}/routing/ospf/areas`, {
  10295. method: 'POST',
  10296. headers: { 'Content-Type': 'application/json' },
  10297. body: JSON.stringify(payload)
  10298. });
  10299. if (res.ok) {
  10300. closeOspfAreaModal();
  10301. showToast('Saved', 'OSPF area saved', 'success');
  10302. loadDynamicRouting();
  10303. } else {
  10304. const err = await res.json();
  10305. showToast('Error', err.error || 'Failed to save area', 'error');
  10306. }
  10307. } catch (err) {
  10308. showToast('Error', err.message, 'error');
  10309. }
  10310. }
  10311. function applyOspfAreaForm() {
  10312. submitOspfArea(null);
  10313. }
  10314. function copyOspfArea() {
  10315. document.getElementById('modal-ospf-area-id').value = '';
  10316. document.getElementById('modal-ospf-area-name').value += '-copy';
  10317. document.getElementById('ospf-area-modal-title').innerText = 'New...';
  10318. showToast('Copied', 'Duplicated as new OSPF area', 'info');
  10319. }
  10320. async function deleteCurrentOspfArea() {
  10321. const id = document.getElementById('modal-ospf-area-id').value;
  10322. if (!id) return;
  10323. if (!confirm('Are you sure you want to remove this OSPF area?')) return;
  10324. try {
  10325. const res = await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10326. if (res.ok) {
  10327. closeOspfAreaModal();
  10328. showToast('Removed', 'OSPF area deleted', 'success');
  10329. loadDynamicRouting();
  10330. } else {
  10331. throw new Error(await responseError(res));
  10332. }
  10333. } catch (err) {
  10334. showToast('Error', err.message, 'error');
  10335. }
  10336. }
  10337. async function enableSelectedOspfArea() {
  10338. const id = state.selectedOspfRow?.areas;
  10339. if (!id) return;
  10340. if (!await routingMutation(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}/state`, {
  10341. method: 'POST',
  10342. headers: { 'Content-Type': 'application/json' },
  10343. body: JSON.stringify({ disabled: false })
  10344. })) return;
  10345. loadDynamicRouting();
  10346. }
  10347. async function disableSelectedOspfArea() {
  10348. const id = state.selectedOspfRow?.areas;
  10349. if (!id) return;
  10350. if (!await routingMutation(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}/state`, {
  10351. method: 'POST',
  10352. headers: { 'Content-Type': 'application/json' },
  10353. body: JSON.stringify({ disabled: true })
  10354. })) return;
  10355. loadDynamicRouting();
  10356. }
  10357. async function removeSelectedOspfArea() {
  10358. const id = state.selectedOspfRow?.areas;
  10359. if (!id) return;
  10360. if (!confirm('Delete selected OSPF area?')) return;
  10361. if (!await routingMutation(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' })) return;
  10362. loadDynamicRouting();
  10363. }
  10364. async function promptCommentOspfArea() {
  10365. const id = state.selectedOspfRow?.areas;
  10366. if (!id) return;
  10367. const area = (state.ospfAreas || []).find(a => a.id === id);
  10368. if (!area) return;
  10369. const comment = prompt('Enter comment for OSPF area:', area.comment || '');
  10370. if (comment === null) return;
  10371. const updated = {...area, comment};
  10372. if (!await routingMutation(`${API_BASE}/routing/ospf/areas`, {
  10373. method: 'POST',
  10374. headers: { 'Content-Type': 'application/json' },
  10375. body: JSON.stringify(updated)
  10376. })) return;
  10377. loadDynamicRouting();
  10378. }
  10379. // --- 3. OSPF AREA RANGE ---
  10380. function populateAreaRangeDropdowns() {
  10381. const select = document.getElementById('modal-ospf-range-area');
  10382. if (select) {
  10383. const cur = select.value;
  10384. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  10385. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  10386. if (cur) select.value = cur;
  10387. }
  10388. }
  10389. function openOspfAreaRangeModal(id = null) {
  10390. const isEdit = !!id;
  10391. populateAreaRangeDropdowns();
  10392. const r = (state.ospfAreaRanges || []).find(it => it.id === id) || {
  10393. id: '',
  10394. area: 'Default',
  10395. prefix: '',
  10396. cost: 1,
  10397. advertise: true,
  10398. disabled: false,
  10399. comment: ''
  10400. };
  10401. document.getElementById('ospf-area-range-modal-title').innerText = isEdit ? r.prefix : 'New...';
  10402. document.getElementById('modal-ospf-range-id').value = isEdit ? r.id : '';
  10403. document.getElementById('modal-ospf-range-enabled').checked = !r.disabled;
  10404. document.getElementById('modal-ospf-range-comment').value = r.comment || '';
  10405. document.getElementById('modal-ospf-range-area').value = r.area || 'Default';
  10406. document.getElementById('modal-ospf-range-prefix').value = r.prefix || '';
  10407. document.getElementById('modal-ospf-range-cost').value = r.cost || 1;
  10408. document.getElementById('modal-ospf-range-advertise').checked = r.advertise !== false;
  10409. const btnRem = document.getElementById('btn-ospf-range-modal-remove');
  10410. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  10411. document.getElementById('ospf-area-range-modal').classList.remove('hidden');
  10412. }
  10413. function openEditOspfAreaRangeModal(id) {
  10414. openOspfAreaRangeModal(id);
  10415. }
  10416. function closeOspfAreaRangeModal() {
  10417. document.getElementById('ospf-area-range-modal').classList.add('hidden');
  10418. }
  10419. async function submitOspfAreaRange(e) {
  10420. if (e) e.preventDefault();
  10421. const payload = {
  10422. id: document.getElementById('modal-ospf-range-id').value,
  10423. area: document.getElementById('modal-ospf-range-area').value,
  10424. prefix: document.getElementById('modal-ospf-range-prefix').value.trim(),
  10425. cost: parseInt(document.getElementById('modal-ospf-range-cost').value, 10) || 1,
  10426. advertise: document.getElementById('modal-ospf-range-advertise').checked,
  10427. disabled: !document.getElementById('modal-ospf-range-enabled').checked,
  10428. comment: document.getElementById('modal-ospf-range-comment').value.trim()
  10429. };
  10430. try {
  10431. const res = await fetch(`${API_BASE}/routing/ospf/area-ranges`, {
  10432. method: 'POST',
  10433. headers: { 'Content-Type': 'application/json' },
  10434. body: JSON.stringify(payload)
  10435. });
  10436. if (res.ok) {
  10437. closeOspfAreaRangeModal();
  10438. showToast('Saved', 'Area range saved', 'success');
  10439. loadDynamicRouting();
  10440. } else {
  10441. const err = await res.json();
  10442. showToast('Error', err.error || 'Failed to save area range', 'error');
  10443. }
  10444. } catch (err) {
  10445. showToast('Error', err.message, 'error');
  10446. }
  10447. }
  10448. function applyOspfAreaRangeForm() {
  10449. submitOspfAreaRange(null);
  10450. }
  10451. async function deleteCurrentOspfAreaRange() {
  10452. const id = document.getElementById('modal-ospf-range-id').value;
  10453. if (!id) return;
  10454. if (!confirm('Delete this area range?')) return;
  10455. try {
  10456. if (!await routingMutation(`${API_BASE}/routing/ospf/area-ranges/${encodeURIComponent(id)}`, { method: 'DELETE' })) return;
  10457. closeOspfAreaRangeModal();
  10458. showToast('Removed', 'Area range removed', 'success');
  10459. loadDynamicRouting();
  10460. } catch (err) {
  10461. showToast('Error', err.message, 'error');
  10462. }
  10463. }
  10464. async function enableSelectedOspfAreaRange() {
  10465. const id = state.selectedOspfRow?.['area-ranges'];
  10466. if (!id) return;
  10467. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  10468. if (!r) return;
  10469. const updated = {...r, disabled: false};
  10470. if (!await routingMutation(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(updated) })) return;
  10471. loadDynamicRouting();
  10472. }
  10473. async function disableSelectedOspfAreaRange() {
  10474. const id = state.selectedOspfRow?.['area-ranges'];
  10475. if (!id) return;
  10476. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  10477. if (!r) return;
  10478. const updated = {...r, disabled: true};
  10479. if (!await routingMutation(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(updated) })) return;
  10480. loadDynamicRouting();
  10481. }
  10482. async function removeSelectedOspfAreaRange() {
  10483. const id = state.selectedOspfRow?.['area-ranges'];
  10484. if (!id) return;
  10485. if (!confirm('Delete selected area range?')) return;
  10486. if (!await routingMutation(`${API_BASE}/routing/ospf/area-ranges/${encodeURIComponent(id)}`, { method: 'DELETE' })) return;
  10487. loadDynamicRouting();
  10488. }
  10489. async function promptCommentOspfAreaRange() {
  10490. const id = state.selectedOspfRow?.['area-ranges'];
  10491. if (!id) return;
  10492. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  10493. if (!r) return;
  10494. const comment = prompt('Enter comment for area range:', r.comment || '');
  10495. if (comment === null) return;
  10496. const updated = {...r, comment};
  10497. if (!await routingMutation(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(updated) })) return;
  10498. loadDynamicRouting();
  10499. }
  10500. // --- 4. OSPF INTERFACE TEMPLATE ---
  10501. function switchOspfTemplateTab(tab) {
  10502. const tabGen = document.getElementById('ospf-tmpl-tab-general');
  10503. const tabAuth = document.getElementById('ospf-tmpl-tab-auth');
  10504. const btnGen = document.getElementById('ospf-tmpl-tab-btn-general');
  10505. const btnAuth = document.getElementById('ospf-tmpl-tab-btn-auth');
  10506. if (tab === 'general') {
  10507. if (tabGen) tabGen.classList.remove('hidden');
  10508. if (tabAuth) tabAuth.classList.add('hidden');
  10509. if (btnGen) btnGen.className = 'px-4 py-2 text-xs font-bold border-b-2 border-sky-500 text-white transition';
  10510. 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';
  10511. } else {
  10512. if (tabGen) tabGen.classList.add('hidden');
  10513. if (tabAuth) tabAuth.classList.remove('hidden');
  10514. 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';
  10515. if (btnAuth) btnAuth.className = 'px-4 py-2 text-xs font-bold border-b-2 border-sky-500 text-white transition';
  10516. }
  10517. }
  10518. function populateTemplateAreaDropdowns() {
  10519. const select = document.getElementById('modal-ospf-tmpl-area');
  10520. if (select) {
  10521. const cur = select.value;
  10522. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  10523. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  10524. if (cur) select.value = cur;
  10525. }
  10526. }
  10527. function openOspfTemplateModal(id = null) {
  10528. const isEdit = !!id;
  10529. populateTemplateAreaDropdowns();
  10530. switchOspfTemplateTab('general');
  10531. const dl = document.getElementById('ospf-tmpl-iface-datalist');
  10532. if (dl) {
  10533. dl.innerHTML = '<option value="*"><option value="all">' + (state.interfaces || []).map(i => `<option value="${escapeHtml(i.name)}">`).join('');
  10534. }
  10535. const tmpl = (state.ospfTemplates || []).find(t => t.id === id) || {
  10536. id: '',
  10537. interfaces: '',
  10538. area: 'Default',
  10539. networks: '',
  10540. network_type: 'broadcast',
  10541. cost: 1,
  10542. priority: 128,
  10543. passive: false,
  10544. hello_interval: 10,
  10545. dead_interval: 40,
  10546. auth: 'none',
  10547. auth_key: '',
  10548. disabled: false,
  10549. comment: ''
  10550. };
  10551. document.getElementById('ospf-template-modal-title').innerText = isEdit ? (tmpl.interfaces || tmpl.networks || 'Template') : 'New...';
  10552. document.getElementById('modal-ospf-tmpl-id').value = isEdit ? tmpl.id : '';
  10553. document.getElementById('modal-ospf-tmpl-enabled').checked = !tmpl.disabled;
  10554. document.getElementById('modal-ospf-tmpl-comment').value = tmpl.comment || '';
  10555. document.getElementById('modal-ospf-tmpl-interfaces').value = tmpl.interfaces || tmpl.interface || '';
  10556. document.getElementById('modal-ospf-tmpl-area').value = tmpl.area || 'Default';
  10557. document.getElementById('modal-ospf-tmpl-networks').value = tmpl.networks || tmpl.network || '';
  10558. document.getElementById('modal-ospf-tmpl-net-type').value = tmpl.network_type || 'broadcast';
  10559. document.getElementById('modal-ospf-tmpl-cost').value = tmpl.cost || 1;
  10560. document.getElementById('modal-ospf-tmpl-priority').value = tmpl.priority || 128;
  10561. document.getElementById('modal-ospf-tmpl-passive').checked = !!tmpl.passive;
  10562. if (document.getElementById('modal-ospf-tmpl-bfd')) document.getElementById('modal-ospf-tmpl-bfd').checked = !!tmpl.use_bfd;
  10563. document.getElementById('modal-ospf-tmpl-hello').value = tmpl.hello_interval || 10;
  10564. document.getElementById('modal-ospf-tmpl-dead').value = tmpl.dead_interval || 40;
  10565. document.getElementById('modal-ospf-tmpl-auth').value = tmpl.auth || tmpl.auth_type || 'none';
  10566. document.getElementById('modal-ospf-tmpl-auth-key').value = tmpl.auth_key || '';
  10567. const btnRem = document.getElementById('btn-ospf-tmpl-modal-remove');
  10568. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  10569. document.getElementById('ospf-template-modal').classList.remove('hidden');
  10570. }
  10571. function openEditOspfTemplateModal(id) {
  10572. openOspfTemplateModal(id);
  10573. }
  10574. function closeOspfTemplateModal() {
  10575. document.getElementById('ospf-template-modal').classList.add('hidden');
  10576. }
  10577. async function submitOspfTemplate(e) {
  10578. if (e) e.preventDefault();
  10579. const payload = {
  10580. id: document.getElementById('modal-ospf-tmpl-id').value,
  10581. interfaces: document.getElementById('modal-ospf-tmpl-interfaces').value.trim(),
  10582. interface: document.getElementById('modal-ospf-tmpl-interfaces').value.trim(),
  10583. area: document.getElementById('modal-ospf-tmpl-area').value,
  10584. networks: document.getElementById('modal-ospf-tmpl-networks').value.trim(),
  10585. network: document.getElementById('modal-ospf-tmpl-networks').value.trim(),
  10586. network_type: document.getElementById('modal-ospf-tmpl-net-type').value,
  10587. cost: parseInt(document.getElementById('modal-ospf-tmpl-cost').value, 10) || 1,
  10588. priority: parseInt(document.getElementById('modal-ospf-tmpl-priority').value, 10) || 128,
  10589. passive: document.getElementById('modal-ospf-tmpl-passive').checked,
  10590. use_bfd: document.getElementById('modal-ospf-tmpl-bfd')?.checked || false,
  10591. hello_interval: parseInt(document.getElementById('modal-ospf-tmpl-hello').value, 10) || 10,
  10592. dead_interval: parseInt(document.getElementById('modal-ospf-tmpl-dead').value, 10) || 40,
  10593. auth: document.getElementById('modal-ospf-tmpl-auth').value,
  10594. auth_type: document.getElementById('modal-ospf-tmpl-auth').value,
  10595. auth_key: document.getElementById('modal-ospf-tmpl-auth-key').value,
  10596. disabled: !document.getElementById('modal-ospf-tmpl-enabled').checked,
  10597. comment: document.getElementById('modal-ospf-tmpl-comment').value.trim()
  10598. };
  10599. try {
  10600. const res = await fetch(`${API_BASE}/routing/ospf/templates`, {
  10601. method: 'POST',
  10602. headers: { 'Content-Type': 'application/json' },
  10603. body: JSON.stringify(payload)
  10604. });
  10605. if (res.ok) {
  10606. closeOspfTemplateModal();
  10607. showToast('Saved', 'Interface template saved', 'success');
  10608. loadDynamicRouting();
  10609. } else {
  10610. const err = await res.json();
  10611. showToast('Error', err.error || 'Failed to save interface template', 'error');
  10612. }
  10613. } catch (err) {
  10614. showToast('Error', err.message, 'error');
  10615. }
  10616. }
  10617. function applyOspfTemplateForm() {
  10618. submitOspfTemplate(null);
  10619. }
  10620. function copyOspfTemplate() {
  10621. document.getElementById('modal-ospf-tmpl-id').value = '';
  10622. document.getElementById('ospf-template-modal-title').innerText = 'New...';
  10623. showToast('Copied', 'Duplicated as new template', 'info');
  10624. }
  10625. async function deleteCurrentOspfTemplate() {
  10626. const id = document.getElementById('modal-ospf-tmpl-id').value;
  10627. if (!id) return;
  10628. if (!confirm('Delete this interface template?')) return;
  10629. try {
  10630. if (!await routingMutation(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' })) return;
  10631. closeOspfTemplateModal();
  10632. showToast('Removed', 'Interface template deleted', 'success');
  10633. loadDynamicRouting();
  10634. } catch (err) {
  10635. showToast('Error', err.message, 'error');
  10636. }
  10637. }
  10638. async function enableSelectedOspfTemplate() {
  10639. const id = state.selectedOspfRow?.templates;
  10640. if (!id) return;
  10641. if (!await routingMutation(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  10642. method: 'POST',
  10643. headers: { 'Content-Type': 'application/json' },
  10644. body: JSON.stringify({ disabled: false })
  10645. })) return;
  10646. loadDynamicRouting();
  10647. }
  10648. async function disableSelectedOspfTemplate() {
  10649. const id = state.selectedOspfRow?.templates;
  10650. if (!id) return;
  10651. if (!await routingMutation(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  10652. method: 'POST',
  10653. headers: { 'Content-Type': 'application/json' },
  10654. body: JSON.stringify({ disabled: true })
  10655. })) return;
  10656. loadDynamicRouting();
  10657. }
  10658. async function removeSelectedOspfTemplate() {
  10659. const id = state.selectedOspfRow?.templates;
  10660. if (!id) return;
  10661. if (!confirm('Delete selected interface template?')) return;
  10662. if (!await routingMutation(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' })) return;
  10663. loadDynamicRouting();
  10664. }
  10665. async function promptCommentOspfTemplate() {
  10666. const id = state.selectedOspfRow?.templates;
  10667. if (!id) return;
  10668. const tmpl = (state.ospfTemplates || []).find(t => t.id === id);
  10669. if (!tmpl) return;
  10670. const comment = prompt('Enter comment for template:', tmpl.comment || '');
  10671. if (comment === null) return;
  10672. const updated = {...tmpl, comment};
  10673. if (!await routingMutation(`${API_BASE}/routing/ospf/templates`, {
  10674. method: 'POST',
  10675. headers: { 'Content-Type': 'application/json' },
  10676. body: JSON.stringify(updated)
  10677. })) return;
  10678. loadDynamicRouting();
  10679. }
  10680. // --- 5. OSPF STATIC NEIGHBOR ---
  10681. function populateStaticNbrAreaDropdowns() {
  10682. const select = document.getElementById('modal-ospf-snbr-area');
  10683. if (select) {
  10684. const cur = select.value;
  10685. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  10686. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  10687. if (cur) select.value = cur;
  10688. }
  10689. }
  10690. function openOspfStaticNbrModal(id = null) {
  10691. const isEdit = !!id;
  10692. populateStaticNbrAreaDropdowns();
  10693. const nbr = (state.ospfStaticNbrs || []).find(n => n.id === id) || {
  10694. id: '',
  10695. address: '',
  10696. area: 'Default',
  10697. poll_interval: 120,
  10698. cost: 1,
  10699. disabled: false,
  10700. comment: ''
  10701. };
  10702. document.getElementById('ospf-static-nbr-modal-title').innerText = isEdit ? nbr.address : 'New...';
  10703. document.getElementById('modal-ospf-snbr-id').value = isEdit ? nbr.id : '';
  10704. document.getElementById('modal-ospf-snbr-enabled').checked = !nbr.disabled;
  10705. document.getElementById('modal-ospf-snbr-comment').value = nbr.comment || '';
  10706. document.getElementById('modal-ospf-snbr-address').value = nbr.address || '';
  10707. document.getElementById('modal-ospf-snbr-area').value = nbr.area || 'Default';
  10708. document.getElementById('modal-ospf-snbr-poll').value = nbr.poll_interval || 120;
  10709. document.getElementById('modal-ospf-snbr-cost').value = nbr.cost || 1;
  10710. const btnRem = document.getElementById('btn-ospf-snbr-modal-remove');
  10711. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  10712. document.getElementById('ospf-static-nbr-modal').classList.remove('hidden');
  10713. }
  10714. function openEditOspfStaticNbrModal(id) {
  10715. openOspfStaticNbrModal(id);
  10716. }
  10717. function closeOspfStaticNbrModal() {
  10718. document.getElementById('ospf-static-nbr-modal').classList.add('hidden');
  10719. }
  10720. async function submitOspfStaticNbr(e) {
  10721. if (e) e.preventDefault();
  10722. const payload = {
  10723. id: document.getElementById('modal-ospf-snbr-id').value,
  10724. address: document.getElementById('modal-ospf-snbr-address').value.trim(),
  10725. area: document.getElementById('modal-ospf-snbr-area').value,
  10726. poll_interval: parseInt(document.getElementById('modal-ospf-snbr-poll').value, 10) || 120,
  10727. cost: parseInt(document.getElementById('modal-ospf-snbr-cost').value, 10) || 1,
  10728. disabled: !document.getElementById('modal-ospf-snbr-enabled').checked,
  10729. comment: document.getElementById('modal-ospf-snbr-comment').value.trim()
  10730. };
  10731. try {
  10732. const res = await fetch(`${API_BASE}/routing/ospf/static-neighbors`, {
  10733. method: 'POST',
  10734. headers: { 'Content-Type': 'application/json' },
  10735. body: JSON.stringify(payload)
  10736. });
  10737. if (res.ok) {
  10738. closeOspfStaticNbrModal();
  10739. showToast('Saved', 'Static neighbor saved', 'success');
  10740. loadDynamicRouting();
  10741. } else {
  10742. const err = await res.json();
  10743. showToast('Error', err.error || 'Failed to save static neighbor', 'error');
  10744. }
  10745. } catch (err) {
  10746. showToast('Error', err.message, 'error');
  10747. }
  10748. }
  10749. function applyOspfStaticNbrForm() {
  10750. submitOspfStaticNbr(null);
  10751. }
  10752. async function deleteCurrentOspfStaticNbr() {
  10753. const id = document.getElementById('modal-ospf-snbr-id').value;
  10754. if (!id) return;
  10755. if (!confirm('Delete this static neighbor?')) return;
  10756. try {
  10757. if (!await routingMutation(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}`, { method: 'DELETE' })) return;
  10758. closeOspfStaticNbrModal();
  10759. showToast('Removed', 'Static neighbor removed', 'success');
  10760. loadDynamicRouting();
  10761. } catch (err) {
  10762. showToast('Error', err.message, 'error');
  10763. }
  10764. }
  10765. async function enableSelectedOspfStaticNbr() {
  10766. const id = state.selectedOspfRow?.['static-nbrs'];
  10767. if (!id) return;
  10768. if (!await routingMutation(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: false }) })) return;
  10769. loadDynamicRouting();
  10770. }
  10771. async function disableSelectedOspfStaticNbr() {
  10772. const id = state.selectedOspfRow?.['static-nbrs'];
  10773. if (!id) return;
  10774. if (!await routingMutation(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: true }) })) return;
  10775. loadDynamicRouting();
  10776. }
  10777. async function removeSelectedOspfStaticNbr() {
  10778. const id = state.selectedOspfRow?.['static-nbrs'];
  10779. if (!id) return;
  10780. if (!confirm('Delete selected static neighbor?')) return;
  10781. if (!await routingMutation(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}`, { method: 'DELETE' })) return;
  10782. loadDynamicRouting();
  10783. }
  10784. async function promptCommentOspfStaticNbr() {
  10785. const id = state.selectedOspfRow?.['static-nbrs'];
  10786. if (!id) return;
  10787. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  10788. if (!n) return;
  10789. const comment = prompt('Enter comment for static neighbor:', n.comment || '');
  10790. if (comment === null) return;
  10791. const updated = {...n, comment};
  10792. if (!await routingMutation(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(updated) })) return;
  10793. loadDynamicRouting();
  10794. }
  10795. // Backward-compat aliases
  10796. function openAddOspfInterfaceModal() { openOspfTemplateModal(); }
  10797. function openEditOspfInterfaceModal(id) { openEditOspfTemplateModal(id); }
  10798. function closeOspfInterfaceModal() { closeOspfTemplateModal(); }
  10799. function submitOspfInterface(e) { submitOspfTemplate(e); }
  10800. async function deleteOspfInterface(id) {
  10801. if (await routingMutation(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' })) await loadDynamicRouting();
  10802. }
  10803. function toggleOspfInterfaceState(id, disabled) {
  10804. fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  10805. method: 'POST',
  10806. headers: { 'Content-Type': 'application/json' },
  10807. body: JSON.stringify({ disabled })
  10808. }).then(() => loadDynamicRouting());
  10809. }
  10810. function openAddOspfAreaModal() { openOspfAreaModal(); }
  10811. function deleteOspfArea(id) {
  10812. fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' }).then(() => loadDynamicRouting());
  10813. }
  10814. // ============================================================================
  10815. // ==================== MIKROTIK BRIDGE SUBSYSTEM ==============================
  10816. // ============================================================================
  10817. function switchBridgeSubTab(tab) {
  10818. state.bridgeSubTab = tab;
  10819. const tabs = ['bridges', 'ports', 'vlans', 'hosts'];
  10820. tabs.forEach(t => {
  10821. const panel = document.getElementById(`bridge-subtab-${t}`);
  10822. const btn = document.getElementById(`bridge-subtab-btn-${t}`);
  10823. if (panel) {
  10824. if (t === tab) panel.classList.remove('hidden');
  10825. else panel.classList.add('hidden');
  10826. }
  10827. if (btn) {
  10828. if (t === tab) {
  10829. 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';
  10830. } else {
  10831. 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';
  10832. }
  10833. }
  10834. });
  10835. const addBtn = document.getElementById('bridge-top-action-btn');
  10836. if (addBtn) {
  10837. if (tab === 'bridges') addBtn.innerHTML = '<span>+ Add Bridge</span>';
  10838. else if (tab === 'ports') addBtn.innerHTML = '<span>+ Add Port</span>';
  10839. else if (tab === 'vlans') addBtn.innerHTML = '<span>+ Add VLAN Entry</span>';
  10840. else if (tab === 'hosts') addBtn.innerHTML = '<span>🔄 Refresh MACs</span>';
  10841. }
  10842. if (tab === 'hosts') loadBridgeHosts();
  10843. setTimeout(initTableSorting, 50);
  10844. }
  10845. function openCurrentBridgeModal() {
  10846. if (state.bridgeSubTab === 'bridges') openAddBridgeModal();
  10847. else if (state.bridgeSubTab === 'ports') openAddBridgePortModal();
  10848. else if (state.bridgeSubTab === 'vlans') openAddBridgeVLANModal();
  10849. else if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  10850. }
  10851. async function loadBridge() {
  10852. try {
  10853. const [bridgesRes, portsRes, vlansRes, summaryRes, eoipRes, vxlanRes, vlanIfacesRes] = await Promise.all([
  10854. fetch(`${API_BASE}/bridge/bridges`),
  10855. fetch(`${API_BASE}/bridge/ports`),
  10856. fetch(`${API_BASE}/bridge/vlans`),
  10857. fetch(`${API_BASE}/bridge/summary`),
  10858. fetch(`${API_BASE}/vpn/eoip`),
  10859. fetch(`${API_BASE}/vpn/vxlan`),
  10860. fetch(`${API_BASE}/vlans`)
  10861. ]);
  10862. if (bridgesRes.ok) state.bridges = await bridgesRes.json();
  10863. if (portsRes.ok) state.bridgePorts = await portsRes.json();
  10864. if (vlansRes.ok) state.bridgeVLANs = await vlansRes.json();
  10865. if (summaryRes.ok) state.bridgeSummary = await summaryRes.json();
  10866. if (eoipRes && eoipRes.ok) state.eoipTunnels = await eoipRes.json();
  10867. if (vxlanRes && vxlanRes.ok) state.vxlanTunnels = await vxlanRes.json();
  10868. if (vlanIfacesRes && vlanIfacesRes.ok) state.vlans = await vlanIfacesRes.json();
  10869. // Badges & Stats
  10870. const bBridges = document.getElementById('bridge-badge-bridges');
  10871. if (bBridges) bBridges.innerText = (state.bridges || []).length;
  10872. const bPorts = document.getElementById('bridge-badge-ports');
  10873. if (bPorts) bPorts.innerText = (state.bridgePorts || []).length;
  10874. const bVlans = document.getElementById('bridge-badge-vlans');
  10875. if (bVlans) bVlans.innerText = (state.bridgeVLANs || []).length;
  10876. const bHosts = document.getElementById('bridge-badge-hosts');
  10877. if (bHosts) bHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  10878. const sBr = document.getElementById('bridge-stat-bridges');
  10879. if (sBr) sBr.innerText = (state.bridges || []).length;
  10880. const sPorts = document.getElementById('bridge-stat-ports');
  10881. if (sPorts) sPorts.innerText = (state.bridgePorts || []).length;
  10882. const sHosts = document.getElementById('bridge-stat-hosts');
  10883. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  10884. renderBridges();
  10885. renderBridgePorts();
  10886. renderBridgeVLANs();
  10887. if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  10888. } catch (err) {
  10889. console.error('Failed to load bridge subsystem:', err);
  10890. }
  10891. }
  10892. // ----------------- Bridges -----------------
  10893. function renderBridges() {
  10894. const tbody = document.getElementById('bridge-table-body');
  10895. const empty = document.getElementById('bridge-empty-bridges');
  10896. const countBadge = document.getElementById('bridge-count-badge');
  10897. if (!tbody) return;
  10898. tbody.innerHTML = '';
  10899. const bridges = state.bridges || [];
  10900. if (countBadge) countBadge.innerText = `${bridges.length} Bridges`;
  10901. if (bridges.length === 0) {
  10902. empty?.classList.remove('hidden');
  10903. return;
  10904. }
  10905. empty?.classList.add('hidden');
  10906. bridges.forEach((b, idx) => {
  10907. const tr = document.createElement('tr');
  10908. tr.className = `hover:bg-slate-800/40 transition text-xs ${b.disabled ? 'opacity-50' : ''}`;
  10909. // Format IP addresses pill list
  10910. let ipsHtml = '<span class="text-slate-600 font-sans">None</span>';
  10911. if (b.ip_addresses && b.ip_addresses.length > 0) {
  10912. ipsHtml = b.ip_addresses.map(ip => `
  10913. <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">
  10914. <span>${ip}</span>
  10915. <button onclick="deleteBridgeIP('${b.id}', '${ip}')" class="text-slate-500 hover:text-rose-400 font-bold ml-0.5">×</button>
  10916. </span>
  10917. `).join(' ');
  10918. }
  10919. const runningFlag = b.running ? '<span class="text-emerald-400 font-bold" title="Running (R)">R</span>' : '<span class="text-slate-600">-</span>';
  10920. const disabledFlag = b.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '';
  10921. const flagDisplay = `${runningFlag}${disabledFlag ? ' ' + disabledFlag : ''}`;
  10922. tr.innerHTML = `
  10923. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  10924. <td class="py-2.5 px-3 text-center font-mono">${flagDisplay}</td>
  10925. <td class="py-2.5 px-3 font-bold text-white text-sm">
  10926. <span class="text-sky-400 mr-1.5">🌉</span>${b.name}
  10927. </td>
  10928. <td class="py-2.5 px-3 text-slate-300">${b.mtu}</td>
  10929. <td class="py-2.5 px-3 font-mono text-slate-300 text-[11px]">${b.mac_address || '-'}</td>
  10930. <td class="py-2.5 px-3">
  10931. <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>
  10932. </td>
  10933. <td class="py-2.5 px-3 text-center">
  10934. ${b.vlan_filtering ? '<span class="text-emerald-400 font-bold">yes</span>' : '<span class="text-slate-500">no</span>'}
  10935. </td>
  10936. <td class="py-2.5 px-3 font-mono">${b.pvid || 1}</td>
  10937. <td class="py-2.5 px-3">
  10938. <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>
  10939. </td>
  10940. <td class="py-2.5 px-3">
  10941. <div class="flex items-center gap-1.5 flex-wrap">
  10942. ${ipsHtml}
  10943. <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>
  10944. </div>
  10945. </td>
  10946. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  10947. <span class="text-emerald-400">↓ ${b.rx_human || '0 B'}</span> / <span class="text-cyan-400">↑ ${b.tx_human || '0 B'}</span>
  10948. </td>
  10949. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${b.comment || ''}">${b.comment || '-'}</td>
  10950. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  10951. <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>
  10952. <button onclick="openEditBridgeModal('${b.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  10953. <button onclick="deleteBridge('${b.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  10954. </td>
  10955. `;
  10956. tbody.appendChild(tr);
  10957. });
  10958. }
  10959. function openAddBridgeModal() {
  10960. document.getElementById('bridge-modal-title').innerText = 'Add Bridge Interface';
  10961. document.getElementById('bridge-modal-id').value = '';
  10962. document.getElementById('bridge-modal-name').value = 'bridge1';
  10963. document.getElementById('bridge-modal-name').disabled = false;
  10964. document.getElementById('bridge-modal-mtu').value = '1500';
  10965. document.getElementById('bridge-modal-mac').value = '';
  10966. document.getElementById('bridge-modal-stp').value = 'stp';
  10967. document.getElementById('bridge-modal-priority').value = '32768';
  10968. document.getElementById('bridge-modal-vlanfiltering').checked = false;
  10969. document.getElementById('bridge-modal-pvid').value = '1';
  10970. document.getElementById('bridge-modal-fastforward').checked = true;
  10971. document.getElementById('bridge-modal-comment').value = '';
  10972. document.getElementById('bridge-modal-disabled').checked = false;
  10973. toggleBridgeModalVlanFiltering();
  10974. document.getElementById('bridge-modal').classList.remove('hidden');
  10975. }
  10976. function openEditBridgeModal(id) {
  10977. const b = (state.bridges || []).find(x => x.id === id);
  10978. if (!b) return;
  10979. document.getElementById('bridge-modal-title').innerText = `Edit Bridge (${b.name})`;
  10980. document.getElementById('bridge-modal-id').value = b.id;
  10981. document.getElementById('bridge-modal-name').value = b.name;
  10982. document.getElementById('bridge-modal-name').disabled = true;
  10983. document.getElementById('bridge-modal-mtu').value = b.mtu || 1500;
  10984. document.getElementById('bridge-modal-mac').value = b.mac_address || '';
  10985. document.getElementById('bridge-modal-stp').value = b.stp || 'stp';
  10986. document.getElementById('bridge-modal-priority').value = b.priority || 32768;
  10987. document.getElementById('bridge-modal-vlanfiltering').checked = !!b.vlan_filtering;
  10988. document.getElementById('bridge-modal-pvid').value = b.pvid || 1;
  10989. document.getElementById('bridge-modal-fastforward').checked = b.fast_forward !== false;
  10990. document.getElementById('bridge-modal-comment').value = b.comment || '';
  10991. document.getElementById('bridge-modal-disabled').checked = !!b.disabled;
  10992. toggleBridgeModalVlanFiltering();
  10993. document.getElementById('bridge-modal').classList.remove('hidden');
  10994. }
  10995. function closeBridgeModal() {
  10996. document.getElementById('bridge-modal').classList.add('hidden');
  10997. }
  10998. function toggleBridgeModalVlanFiltering() {
  10999. const chk = document.getElementById('bridge-modal-vlanfiltering').checked;
  11000. const pvidBox = document.getElementById('bridge-modal-pvid-box');
  11001. if (pvidBox) {
  11002. if (chk) pvidBox.classList.remove('opacity-40');
  11003. else pvidBox.classList.add('opacity-40');
  11004. }
  11005. }
  11006. async function submitSaveBridge(e) {
  11007. e.preventDefault();
  11008. const id = document.getElementById('bridge-modal-id').value;
  11009. const name = document.getElementById('bridge-modal-name').value.trim();
  11010. const mtu = parseInt(document.getElementById('bridge-modal-mtu').value, 10) || 1500;
  11011. const mac = document.getElementById('bridge-modal-mac').value.trim();
  11012. const stp = document.getElementById('bridge-modal-stp').value;
  11013. const priority = parseInt(document.getElementById('bridge-modal-priority').value, 10) || 32768;
  11014. const vlanFiltering = document.getElementById('bridge-modal-vlanfiltering').checked;
  11015. const pvid = parseInt(document.getElementById('bridge-modal-pvid').value, 10) || 1;
  11016. const fastForward = document.getElementById('bridge-modal-fastforward').checked;
  11017. const comment = document.getElementById('bridge-modal-comment').value.trim();
  11018. const disabled = document.getElementById('bridge-modal-disabled').checked;
  11019. try {
  11020. const res = await fetch(`${API_BASE}/bridge/bridges`, {
  11021. method: 'POST',
  11022. headers: { 'Content-Type': 'application/json' },
  11023. body: JSON.stringify({
  11024. id,
  11025. name,
  11026. mtu,
  11027. mac_address: mac,
  11028. stp,
  11029. priority,
  11030. vlan_filtering: vlanFiltering,
  11031. pvid,
  11032. fast_forward: fastForward,
  11033. comment,
  11034. disabled
  11035. })
  11036. });
  11037. if (res.ok) {
  11038. showToast('Bridge Saved', `Bridge ${name} configured`, 'success');
  11039. closeBridgeModal();
  11040. loadBridge();
  11041. fetchData(false);
  11042. } else {
  11043. const err = await res.json();
  11044. showToast('Error', err.error || err.message || 'Failed to save bridge', 'error');
  11045. }
  11046. } catch (err) {
  11047. showToast('Error', err.message, 'error');
  11048. }
  11049. }
  11050. async function toggleBridgeState(id, disabled) {
  11051. try {
  11052. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/state`, {
  11053. method: 'POST',
  11054. headers: { 'Content-Type': 'application/json' },
  11055. body: JSON.stringify({ disabled })
  11056. });
  11057. if (res.ok) {
  11058. loadBridge();
  11059. fetchData(false);
  11060. }
  11061. } catch (err) {
  11062. showToast('Error', err.message, 'error');
  11063. }
  11064. }
  11065. async function deleteBridge(id) {
  11066. const b = (state.bridges || []).find(x => x.id === id);
  11067. const name = b ? b.name : id;
  11068. if (!confirm(`Are you sure you want to delete bridge '${name}'? All member ports will be detached.`)) return;
  11069. try {
  11070. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11071. if (res.ok) {
  11072. showToast('Deleted', `Bridge ${name} deleted`, 'success');
  11073. loadBridge();
  11074. fetchData(false);
  11075. } else {
  11076. const err = await res.json();
  11077. showToast('Error', err.error || err.message || 'Failed to delete bridge', 'error');
  11078. }
  11079. } catch (err) {
  11080. showToast('Error', err.message, 'error');
  11081. }
  11082. }
  11083. // ----------------- Bridge IP Assignments -----------------
  11084. function openAddBridgeIPModal(id, name) {
  11085. document.getElementById('bridge-ip-modal-id').value = id;
  11086. document.getElementById('bridge-ip-modal-sub').innerText = name;
  11087. document.getElementById('bridge-ip-modal-cidr').value = '';
  11088. document.getElementById('bridge-ip-modal').classList.remove('hidden');
  11089. }
  11090. function closeBridgeIPModal() {
  11091. document.getElementById('bridge-ip-modal').classList.add('hidden');
  11092. }
  11093. async function submitAddBridgeIP(e) {
  11094. e.preventDefault();
  11095. const id = document.getElementById('bridge-ip-modal-id').value;
  11096. const ip = document.getElementById('bridge-ip-modal-cidr').value.trim();
  11097. try {
  11098. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  11099. method: 'POST',
  11100. headers: { 'Content-Type': 'application/json' },
  11101. body: JSON.stringify({ ip })
  11102. });
  11103. if (res.ok) {
  11104. showToast('IP Assigned', `${ip} assigned to bridge`, 'success');
  11105. closeBridgeIPModal();
  11106. loadBridge();
  11107. fetchData(false);
  11108. } else {
  11109. const err = await res.json();
  11110. showToast('Error', err.error || err.message || 'Failed to add IP', 'error');
  11111. }
  11112. } catch (err) {
  11113. showToast('Error', err.message, 'error');
  11114. }
  11115. }
  11116. async function deleteBridgeIP(id, ip) {
  11117. if (!confirm(`Remove IP address ${ip} from bridge?`)) return;
  11118. try {
  11119. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  11120. method: 'DELETE',
  11121. headers: { 'Content-Type': 'application/json' },
  11122. body: JSON.stringify({ ip })
  11123. });
  11124. if (res.ok) {
  11125. showToast('IP Removed', `${ip} removed from bridge`, 'success');
  11126. loadBridge();
  11127. fetchData(false);
  11128. }
  11129. } catch (err) {
  11130. showToast('Error', err.message, 'error');
  11131. }
  11132. }
  11133. // ----------------- Bridge Ports -----------------
  11134. function renderBridgePorts() {
  11135. const tbody = document.getElementById('bridge-ports-table-body');
  11136. const empty = document.getElementById('bridge-empty-ports');
  11137. const countBadge = document.getElementById('bridge-ports-count-badge');
  11138. const filterBridge = document.getElementById('bridge-ports-filter-bridge')?.value || '';
  11139. if (!tbody) return;
  11140. tbody.innerHTML = '';
  11141. // Update filter select
  11142. populateBridgeSelect('bridge-ports-filter-bridge', filterBridge, true);
  11143. const ports = (state.bridgePorts || []).filter(p => !filterBridge || p.bridge === filterBridge);
  11144. if (countBadge) countBadge.innerText = `${ports.length} Ports`;
  11145. if (ports.length === 0) {
  11146. empty?.classList.remove('hidden');
  11147. return;
  11148. }
  11149. empty?.classList.add('hidden');
  11150. ports.forEach((p, idx) => {
  11151. const tr = document.createElement('tr');
  11152. tr.className = `hover:bg-slate-800/40 transition text-xs ${p.disabled ? 'opacity-50' : ''}`;
  11153. const disabledFlag = p.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  11154. tr.innerHTML = `
  11155. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  11156. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  11157. <td class="py-2.5 px-3 font-bold text-white text-sm">
  11158. <span class="text-emerald-400 mr-1.5">🔌</span>${p.interface}
  11159. </td>
  11160. <td class="py-2.5 px-3 font-semibold text-sky-400">${p.bridge}</td>
  11161. <td class="py-2.5 px-3 font-mono">${p.pvid || 1}</td>
  11162. <td class="py-2.5 px-3 text-slate-300">${p.frame_types}</td>
  11163. <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>
  11164. <td class="py-2.5 px-3">
  11165. ${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>'}
  11166. </td>
  11167. <td class="py-2.5 px-3">
  11168. <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>
  11169. </td>
  11170. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${p.comment || ''}">${p.comment || '-'}</td>
  11171. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  11172. <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>
  11173. <button onclick="openEditBridgePortModal('${p.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  11174. <button onclick="deleteBridgePort('${p.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  11175. </td>
  11176. `;
  11177. tbody.appendChild(tr);
  11178. });
  11179. }
  11180. function openAddBridgePortModal() {
  11181. document.getElementById('bridge-port-modal-title').innerText = 'Add Port to Bridge';
  11182. document.getElementById('bridge-port-modal-id').value = '';
  11183. populateBridgeSelect('bridge-port-modal-bridge');
  11184. populateBridgePortCandidateSelect('bridge-port-modal-interface');
  11185. document.getElementById('bridge-port-modal-pvid').value = '1';
  11186. document.getElementById('bridge-port-modal-frametypes').value = 'admit-all';
  11187. document.getElementById('bridge-port-modal-ingressfiltering').checked = false;
  11188. document.getElementById('bridge-port-modal-horizon').value = '0';
  11189. document.getElementById('bridge-port-modal-pathcost').value = '10';
  11190. document.getElementById('bridge-port-modal-priority').value = '128';
  11191. document.getElementById('bridge-port-modal-learn').checked = true;
  11192. document.getElementById('bridge-port-modal-comment').value = '';
  11193. document.getElementById('bridge-port-modal-disabled').checked = false;
  11194. document.getElementById('bridge-port-modal').classList.remove('hidden');
  11195. }
  11196. function openEditBridgePortModal(id) {
  11197. const p = (state.bridgePorts || []).find(x => x.id === id);
  11198. if (!p) return;
  11199. document.getElementById('bridge-port-modal-title').innerText = `Edit Bridge Port (${p.interface})`;
  11200. document.getElementById('bridge-port-modal-id').value = p.id;
  11201. populateBridgeSelect('bridge-port-modal-bridge', p.bridge);
  11202. populateBridgePortCandidateSelect('bridge-port-modal-interface', p.interface);
  11203. document.getElementById('bridge-port-modal-pvid').value = p.pvid || 1;
  11204. document.getElementById('bridge-port-modal-frametypes').value = p.frame_types || 'admit-all';
  11205. document.getElementById('bridge-port-modal-ingressfiltering').checked = !!p.ingress_filtering;
  11206. document.getElementById('bridge-port-modal-horizon').value = p.horizon || 0;
  11207. document.getElementById('bridge-port-modal-pathcost').value = p.path_cost || 10;
  11208. document.getElementById('bridge-port-modal-priority').value = p.priority || 128;
  11209. document.getElementById('bridge-port-modal-learn').checked = p.learn !== false;
  11210. document.getElementById('bridge-port-modal-comment').value = p.comment || '';
  11211. document.getElementById('bridge-port-modal-disabled').checked = !!p.disabled;
  11212. document.getElementById('bridge-port-modal').classList.remove('hidden');
  11213. }
  11214. function closeBridgePortModal() {
  11215. document.getElementById('bridge-port-modal').classList.add('hidden');
  11216. }
  11217. async function submitSaveBridgePort(e) {
  11218. e.preventDefault();
  11219. const id = document.getElementById('bridge-port-modal-id').value;
  11220. const bridge = document.getElementById('bridge-port-modal-bridge').value;
  11221. const iface = document.getElementById('bridge-port-modal-interface').value;
  11222. const pvid = parseInt(document.getElementById('bridge-port-modal-pvid').value, 10) || 1;
  11223. const frameTypes = document.getElementById('bridge-port-modal-frametypes').value;
  11224. const ingressFiltering = document.getElementById('bridge-port-modal-ingressfiltering').checked;
  11225. const horizon = parseInt(document.getElementById('bridge-port-modal-horizon').value, 10) || 0;
  11226. const pathCost = parseInt(document.getElementById('bridge-port-modal-pathcost').value, 10) || 10;
  11227. const priority = parseInt(document.getElementById('bridge-port-modal-priority').value, 10) || 128;
  11228. const learn = document.getElementById('bridge-port-modal-learn').checked;
  11229. const comment = document.getElementById('bridge-port-modal-comment').value.trim();
  11230. const disabled = document.getElementById('bridge-port-modal-disabled').checked;
  11231. try {
  11232. const res = await fetch(`${API_BASE}/bridge/ports`, {
  11233. method: 'POST',
  11234. headers: { 'Content-Type': 'application/json' },
  11235. body: JSON.stringify({
  11236. id,
  11237. bridge,
  11238. interface: iface,
  11239. pvid,
  11240. frame_types: frameTypes,
  11241. ingress_filtering: ingressFiltering,
  11242. horizon,
  11243. path_cost: pathCost,
  11244. priority,
  11245. learn,
  11246. comment,
  11247. disabled
  11248. })
  11249. });
  11250. if (res.ok) {
  11251. showToast('Port Attached', `${iface} added to ${bridge}`, 'success');
  11252. closeBridgePortModal();
  11253. loadBridge();
  11254. fetchData(false);
  11255. } else {
  11256. const err = await res.json();
  11257. showToast('Error', err.error || err.message || 'Failed to save port', 'error');
  11258. }
  11259. } catch (err) {
  11260. showToast('Error', err.message, 'error');
  11261. }
  11262. }
  11263. async function toggleBridgePortState(id, disabled) {
  11264. try {
  11265. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}/state`, {
  11266. method: 'POST',
  11267. headers: { 'Content-Type': 'application/json' },
  11268. body: JSON.stringify({ disabled })
  11269. });
  11270. if (res.ok) {
  11271. loadBridge();
  11272. fetchData(false);
  11273. }
  11274. } catch (err) {
  11275. showToast('Error', err.message, 'error');
  11276. }
  11277. }
  11278. async function deleteBridgePort(id) {
  11279. const p = (state.bridgePorts || []).find(x => x.id === id);
  11280. const iface = p ? p.interface : id;
  11281. if (!confirm(`Detach interface '${iface}' from bridge?`)) return;
  11282. try {
  11283. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11284. if (res.ok) {
  11285. showToast('Port Detached', `${iface} removed from bridge`, 'success');
  11286. loadBridge();
  11287. fetchData(false);
  11288. }
  11289. } catch (err) {
  11290. showToast('Error', err.message, 'error');
  11291. }
  11292. }
  11293. // ----------------- Bridge VLANs -----------------
  11294. function renderBridgeVLANs() {
  11295. const tbody = document.getElementById('bridge-vlans-table-body');
  11296. const empty = document.getElementById('bridge-empty-vlans');
  11297. const countBadge = document.getElementById('bridge-vlans-count-badge');
  11298. const filterBridge = document.getElementById('bridge-vlans-filter-bridge')?.value || '';
  11299. if (!tbody) return;
  11300. tbody.innerHTML = '';
  11301. populateBridgeSelect('bridge-vlans-filter-bridge', filterBridge, true);
  11302. const vlans = (state.bridgeVLANs || []).filter(v => !filterBridge || v.bridge === filterBridge);
  11303. if (countBadge) countBadge.innerText = `${vlans.length} Entries`;
  11304. if (vlans.length === 0) {
  11305. empty?.classList.remove('hidden');
  11306. return;
  11307. }
  11308. empty?.classList.add('hidden');
  11309. vlans.forEach((v, idx) => {
  11310. const tr = document.createElement('tr');
  11311. tr.className = `hover:bg-slate-800/40 transition text-xs ${v.disabled ? 'opacity-50' : ''}`;
  11312. const taggedHtml = (v.tagged && v.tagged.length > 0)
  11313. ? 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(' ')
  11314. : '<span class="text-slate-600">none</span>';
  11315. const untaggedHtml = (v.untagged && v.untagged.length > 0)
  11316. ? 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(' ')
  11317. : '<span class="text-slate-600">none</span>';
  11318. const disabledFlag = v.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  11319. tr.innerHTML = `
  11320. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  11321. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  11322. <td class="py-2.5 px-3 font-semibold text-sky-400">${v.bridge}</td>
  11323. <td class="py-2.5 px-3 font-bold text-white font-mono text-sm">${v.vlan_ids}</td>
  11324. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${taggedHtml}</div></td>
  11325. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${untaggedHtml}</div></td>
  11326. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${v.comment || ''}">${v.comment || '-'}</td>
  11327. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  11328. <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>
  11329. <button onclick="openEditBridgeVLANModal('${v.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  11330. <button onclick="deleteBridgeVLAN('${v.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  11331. </td>
  11332. `;
  11333. tbody.appendChild(tr);
  11334. });
  11335. }
  11336. function openAddBridgeVLANModal() {
  11337. document.getElementById('bridge-vlan-modal-title').innerText = 'Add Bridge VLAN Entry';
  11338. document.getElementById('bridge-vlan-modal-id').value = '';
  11339. populateBridgeSelect('bridge-vlan-modal-bridge');
  11340. document.getElementById('bridge-vlan-modal-vlanids').value = '';
  11341. document.getElementById('bridge-vlan-modal-comment').value = '';
  11342. document.getElementById('bridge-vlan-modal-disabled').checked = false;
  11343. updateBridgeVlanPortCheckboxes();
  11344. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  11345. }
  11346. function openEditBridgeVLANModal(id) {
  11347. const v = (state.bridgeVLANs || []).find(x => x.id === id);
  11348. if (!v) return;
  11349. document.getElementById('bridge-vlan-modal-title').innerText = `Edit Bridge VLAN (${v.vlan_ids})`;
  11350. document.getElementById('bridge-vlan-modal-id').value = v.id;
  11351. populateBridgeSelect('bridge-vlan-modal-bridge', v.bridge);
  11352. document.getElementById('bridge-vlan-modal-vlanids').value = v.vlan_ids;
  11353. document.getElementById('bridge-vlan-modal-comment').value = v.comment || '';
  11354. document.getElementById('bridge-vlan-modal-disabled').checked = !!v.disabled;
  11355. updateBridgeVlanPortCheckboxes(v.tagged || [], v.untagged || []);
  11356. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  11357. }
  11358. function closeBridgeVlanModal() {
  11359. document.getElementById('bridge-vlan-modal').classList.add('hidden');
  11360. }
  11361. function updateBridgeVlanPortCheckboxes(taggedSelected = [], untaggedSelected = []) {
  11362. const selBridge = document.getElementById('bridge-vlan-modal-bridge')?.value || '';
  11363. const taggedBox = document.getElementById('bridge-vlan-tagged-ports');
  11364. const untaggedBox = document.getElementById('bridge-vlan-untagged-ports');
  11365. if (!taggedBox || !untaggedBox) return;
  11366. // Ports belonging to the selected bridge
  11367. const memberPorts = (state.bridgePorts || []).filter(p => !selBridge || p.bridge === selBridge);
  11368. if (memberPorts.length === 0) {
  11369. taggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  11370. untaggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  11371. return;
  11372. }
  11373. taggedBox.innerHTML = memberPorts.map(p => `
  11374. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  11375. <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">
  11376. <span>${p.interface}</span>
  11377. </label>
  11378. `).join('');
  11379. untaggedBox.innerHTML = memberPorts.map(p => `
  11380. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  11381. <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">
  11382. <span>${p.interface}</span>
  11383. </label>
  11384. `).join('');
  11385. }
  11386. async function submitSaveBridgeVLAN(e) {
  11387. e.preventDefault();
  11388. const id = document.getElementById('bridge-vlan-modal-id').value;
  11389. const bridge = document.getElementById('bridge-vlan-modal-bridge').value;
  11390. const vlanIDs = document.getElementById('bridge-vlan-modal-vlanids').value.trim();
  11391. const comment = document.getElementById('bridge-vlan-modal-comment').value.trim();
  11392. const disabled = document.getElementById('bridge-vlan-modal-disabled').checked;
  11393. const tagged = Array.from(document.querySelectorAll('input[name="bvlan-tagged"]:checked')).map(x => x.value);
  11394. const untagged = Array.from(document.querySelectorAll('input[name="bvlan-untagged"]:checked')).map(x => x.value);
  11395. try {
  11396. const res = await fetch(`${API_BASE}/bridge/vlans`, {
  11397. method: 'POST',
  11398. headers: { 'Content-Type': 'application/json' },
  11399. body: JSON.stringify({
  11400. id,
  11401. bridge,
  11402. vlan_ids: vlanIDs,
  11403. tagged,
  11404. untagged,
  11405. comment,
  11406. disabled
  11407. })
  11408. });
  11409. if (res.ok) {
  11410. showToast('VLAN Entry Saved', `VLAN ${vlanIDs} configured on ${bridge}`, 'success');
  11411. closeBridgeVlanModal();
  11412. loadBridge();
  11413. } else {
  11414. const err = await res.json();
  11415. showToast('Error', err.error || err.message || 'Failed to save VLAN entry', 'error');
  11416. }
  11417. } catch (err) {
  11418. showToast('Error', err.message, 'error');
  11419. }
  11420. }
  11421. async function toggleBridgeVLANState(id, disabled) {
  11422. try {
  11423. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}/state`, {
  11424. method: 'POST',
  11425. headers: { 'Content-Type': 'application/json' },
  11426. body: JSON.stringify({ disabled })
  11427. });
  11428. if (res.ok) loadBridge();
  11429. } catch (err) {
  11430. showToast('Error', err.message, 'error');
  11431. }
  11432. }
  11433. async function deleteBridgeVLAN(id) {
  11434. if (!confirm('Delete this bridge VLAN entry?')) return;
  11435. try {
  11436. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11437. if (res.ok) {
  11438. showToast('Deleted', 'VLAN entry removed from bridge', 'success');
  11439. loadBridge();
  11440. }
  11441. } catch (err) {
  11442. showToast('Error', err.message, 'error');
  11443. }
  11444. }
  11445. // ----------------- Hosts / MAC Table -----------------
  11446. async function loadBridgeHosts() {
  11447. const filterBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || '';
  11448. populateBridgeSelect('bridge-hosts-filter-bridge', filterBridge, true);
  11449. try {
  11450. const url = filterBridge ? `${API_BASE}/bridge/hosts?bridge=${encodeURIComponent(filterBridge)}` : `${API_BASE}/bridge/hosts`;
  11451. const res = await fetch(url);
  11452. if (res.ok) {
  11453. state.bridgeHosts = await res.json();
  11454. renderBridgeHosts();
  11455. }
  11456. } catch (err) {
  11457. console.error('Failed to load bridge hosts:', err);
  11458. }
  11459. }
  11460. function renderBridgeHosts() {
  11461. const tbody = document.getElementById('bridge-hosts-table-body');
  11462. const empty = document.getElementById('bridge-empty-hosts');
  11463. const countBadge = document.getElementById('bridge-hosts-count-badge');
  11464. const search = (document.getElementById('bridge-hosts-search')?.value || '').toLowerCase().trim();
  11465. if (!tbody) return;
  11466. tbody.innerHTML = '';
  11467. const hosts = (state.bridgeHosts || []).filter(h => {
  11468. if (!search) return true;
  11469. return (h.mac || '').toLowerCase().includes(search) || (h.interface || '').toLowerCase().includes(search) || (h.bridge || '').toLowerCase().includes(search);
  11470. });
  11471. if (countBadge) countBadge.innerText = `${hosts.length} Hosts`;
  11472. if (hosts.length === 0) {
  11473. empty?.classList.remove('hidden');
  11474. return;
  11475. }
  11476. empty?.classList.add('hidden');
  11477. hosts.forEach(h => {
  11478. const tr = document.createElement('tr');
  11479. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  11480. let flagBadges = '';
  11481. 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>';
  11482. 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>';
  11483. 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>';
  11484. tr.innerHTML = `
  11485. <td class="py-2.5 px-3 font-mono font-bold text-white text-sm">${h.mac}</td>
  11486. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${h.interface || '-'}</td>
  11487. <td class="py-2.5 px-3 font-mono text-sky-400">${h.bridge || '-'}</td>
  11488. <td class="py-2.5 px-3 font-mono">${h.vlan_id || 1}</td>
  11489. <td class="py-2.5 px-3 font-mono text-slate-400">${h.age ? h.age.toFixed(1) + 's' : '-'}</td>
  11490. <td class="py-2.5 px-3">${flagBadges}</td>
  11491. `;
  11492. tbody.appendChild(tr);
  11493. });
  11494. }
  11495. async function flushBridgeHosts() {
  11496. const selBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || (state.bridges[0] ? state.bridges[0].name : '');
  11497. if (!selBridge) {
  11498. showToast('Notice', 'Please select a bridge to flush dynamic MACs', 'info');
  11499. return;
  11500. }
  11501. if (!confirm(`Flush all dynamic learned MAC addresses on bridge '${selBridge}'?`)) return;
  11502. try {
  11503. const res = await fetch(`${API_BASE}/bridge/hosts/flush`, {
  11504. method: 'POST',
  11505. headers: { 'Content-Type': 'application/json' },
  11506. body: JSON.stringify({ bridge: selBridge })
  11507. });
  11508. if (res.ok) {
  11509. showToast('FDB Flushed', `Dynamic MACs flushed on ${selBridge}`, 'success');
  11510. loadBridgeHosts();
  11511. }
  11512. } catch (err) {
  11513. showToast('Error', err.message, 'error');
  11514. }
  11515. }
  11516. // ----------------- Helpers -----------------
  11517. function populateBridgeSelect(selectId, currentVal = '', includeAll = false) {
  11518. const sel = document.getElementById(selectId);
  11519. if (!sel) return;
  11520. const prevVal = currentVal || sel.value;
  11521. sel.innerHTML = includeAll ? '<option value="">All Bridges</option>' : '';
  11522. (state.bridges || []).forEach(b => {
  11523. const opt = document.createElement('option');
  11524. opt.value = b.name;
  11525. opt.innerText = `${b.name} (${b.ports_count} ports)`;
  11526. if (b.name === prevVal) opt.selected = true;
  11527. sel.appendChild(opt);
  11528. });
  11529. }
  11530. function populateBridgePortCandidateSelect(selectId, currentVal = '') {
  11531. const sel = document.getElementById(selectId);
  11532. if (!sel) return;
  11533. sel.innerHTML = '<option value="">(Select Interface...)</option>';
  11534. // 1. Physical Interfaces
  11535. const grpPhys = document.createElement('optgroup');
  11536. grpPhys.label = 'Physical Interfaces';
  11537. (state.interfaces || []).filter(i => i.type !== 'bridge' && i.type !== 'vlan' && i.type !== 'loopback').forEach(i => {
  11538. const opt = document.createElement('option');
  11539. opt.value = i.name;
  11540. opt.innerText = `${i.name} (${i.role || i.type})`;
  11541. if (i.name === currentVal) opt.selected = true;
  11542. grpPhys.appendChild(opt);
  11543. });
  11544. if (grpPhys.children.length > 0) sel.appendChild(grpPhys);
  11545. // 2. VLAN Sub-interfaces
  11546. const grpVlans = document.createElement('optgroup');
  11547. grpVlans.label = 'VLAN Sub-interfaces (802.1Q)';
  11548. (state.vlans || []).forEach(v => {
  11549. const opt = document.createElement('option');
  11550. opt.value = v.name;
  11551. opt.innerText = `${v.name} (VLAN ${v.vlan_id})`;
  11552. if (v.name === currentVal) opt.selected = true;
  11553. grpVlans.appendChild(opt);
  11554. });
  11555. if (grpVlans.children.length > 0) sel.appendChild(grpVlans);
  11556. // 3. EoIP Tunnels (MikroTik EoIP bridging!)
  11557. const grpEoip = document.createElement('optgroup');
  11558. grpEoip.label = 'EoIP Tunnels (Layer 2 VPN)';
  11559. (state.eoipTunnels || []).forEach(t => {
  11560. const opt = document.createElement('option');
  11561. opt.value = t.name;
  11562. opt.innerText = `${t.name} (Tunnel ID: ${t.tunnel_id} -> ${t.remote_address})`;
  11563. if (t.name === currentVal) opt.selected = true;
  11564. grpEoip.appendChild(opt);
  11565. });
  11566. if (grpEoip.children.length > 0) sel.appendChild(grpEoip);
  11567. // 4. VXLAN Tunnels (MikroTik VXLAN bridging!)
  11568. const grpVxlan = document.createElement('optgroup');
  11569. grpVxlan.label = 'VXLAN Tunnels (Layer 2 Overlay)';
  11570. (state.vxlanTunnels || []).forEach(t => {
  11571. const opt = document.createElement('option');
  11572. opt.value = t.name;
  11573. opt.innerText = `${t.name} (VNI: ${t.vni}, Port: ${t.port})`;
  11574. if (t.name === currentVal) opt.selected = true;
  11575. grpVxlan.appendChild(opt);
  11576. });
  11577. if (grpVxlan.children.length > 0) sel.appendChild(grpVxlan);
  11578. }
  11579. // -------------------------------------------------------------
  11580. // DebTik Routing Filters Management (/routing filter)
  11581. // -------------------------------------------------------------
  11582. if (!state.activeRoutingFilterTab) state.activeRoutingFilterTab = 'rules';
  11583. if (!state.selectedFilterRow) state.selectedFilterRow = {};
  11584. if (!state.rfSort) state.rfSort = {};
  11585. function switchRoutingFilterTab(tab) {
  11586. state.activeRoutingFilterTab = tab;
  11587. const tabs = ['rules', 'community-lists', 'as-lists'];
  11588. tabs.forEach(t => {
  11589. const btn = document.getElementById(`tab-rf-${t}`);
  11590. const content = document.getElementById(`tab-content-rf-${t}`);
  11591. if (btn) {
  11592. if (t === tab) {
  11593. 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';
  11594. } else {
  11595. btn.className = 'px-3 py-1 text-xs font-semibold rounded text-slate-400 hover:text-white hover:bg-slate-800 transition';
  11596. }
  11597. }
  11598. if (content) {
  11599. if (t === tab) content.classList.remove('hidden');
  11600. else content.classList.add('hidden');
  11601. }
  11602. });
  11603. const chainContainer = document.getElementById('rf-chain-filter-container');
  11604. if (chainContainer) {
  11605. if (tab === 'rules') chainContainer.classList.remove('hidden');
  11606. else chainContainer.classList.add('hidden');
  11607. }
  11608. renderRoutingFilters();
  11609. }
  11610. function selectFilterRow(tab, id) {
  11611. if (state.selectedFilterRow[tab] === id) {
  11612. delete state.selectedFilterRow[tab];
  11613. } else {
  11614. state.selectedFilterRow[tab] = id;
  11615. }
  11616. if (tab === 'rules') renderRoutingFilterRules();
  11617. else if (tab === 'community-lists') renderRoutingFilterCommunityLists();
  11618. else if (tab === 'as-lists') renderRoutingFilterASLists();
  11619. }
  11620. function openRoutingFilterNewModal() {
  11621. const tab = state.activeRoutingFilterTab || 'rules';
  11622. if (tab === 'rules') openAddRoutingFilterModal();
  11623. else if (tab === 'community-lists') openAddCommunityListModal();
  11624. else if (tab === 'as-lists') openAddASListModal();
  11625. }
  11626. function toggleSelectedRoutingFilter(disabled) {
  11627. const tab = state.activeRoutingFilterTab || 'rules';
  11628. const id = state.selectedFilterRow[tab];
  11629. if (!id) {
  11630. showToast('Select Row', 'Please click on a row to select it first', 'info');
  11631. return;
  11632. }
  11633. if (tab === 'rules') toggleRoutingFilterState(id, disabled);
  11634. else if (tab === 'community-lists') toggleCommunityListState(id, disabled);
  11635. else if (tab === 'as-lists') toggleASListState(id, disabled);
  11636. }
  11637. function removeSelectedRoutingFilter() {
  11638. const tab = state.activeRoutingFilterTab || 'rules';
  11639. const id = state.selectedFilterRow[tab];
  11640. if (!id) {
  11641. showToast('Select Row', 'Please click on a row to select it first', 'info');
  11642. return;
  11643. }
  11644. if (tab === 'rules') deleteRoutingFilter(id);
  11645. else if (tab === 'community-lists') deleteCommunityList(id);
  11646. else if (tab === 'as-lists') deleteASList(id);
  11647. }
  11648. function searchRoutingFilters(q) {
  11649. state.rfSearchQuery = (q || '').trim().toLowerCase();
  11650. renderRoutingFilters();
  11651. }
  11652. function sortFilterTable(tab, col) {
  11653. if (!state.rfSort) state.rfSort = {};
  11654. if (!state.rfSort[tab]) state.rfSort[tab] = { col: col, asc: true };
  11655. if (state.rfSort[tab].col === col) {
  11656. state.rfSort[tab].asc = !state.rfSort[tab].asc;
  11657. } else {
  11658. state.rfSort[tab].col = col;
  11659. state.rfSort[tab].asc = true;
  11660. }
  11661. const asc = state.rfSort[tab].asc;
  11662. let list = [];
  11663. if (tab === 'rules') list = state.routingFilters || [];
  11664. else if (tab === 'community-lists') list = state.routingCommunityLists || [];
  11665. else if (tab === 'as-lists') list = state.routingASLists || [];
  11666. list.sort((a, b) => {
  11667. let valA = a[col] ?? '';
  11668. let valB = b[col] ?? '';
  11669. if (col === 'flags') {
  11670. valA = a.disabled ? 'X' : 'A';
  11671. valB = b.disabled ? 'X' : 'A';
  11672. }
  11673. if (typeof valA === 'number' && typeof valB === 'number') {
  11674. return asc ? valA - valB : valB - valA;
  11675. }
  11676. return asc ? String(valA).localeCompare(String(valB)) : String(valB).localeCompare(String(valA));
  11677. });
  11678. const allCols = ['flags', 'rule_order', 'chain', 'rule', 'name', 'communities', 'range', 'regexp', 'comment'];
  11679. allCols.forEach(c => {
  11680. const el = document.getElementById(`sort-icon-${tab}-${c}`);
  11681. if (el) el.innerText = (c === col) ? (asc ? '▲' : '▼') : '';
  11682. });
  11683. if (tab === 'rules') renderRoutingFilterRules();
  11684. else if (tab === 'community-lists') renderRoutingFilterCommunityLists();
  11685. else if (tab === 'as-lists') renderRoutingFilterASLists();
  11686. }
  11687. function renderRoutingFilters() {
  11688. const navBadge = document.getElementById('badge-filters-count');
  11689. const allRules = state.routingFilters || [];
  11690. if (navBadge) navBadge.innerText = allRules.length;
  11691. // Populate chain filter select options and datalist
  11692. const chainSelect = document.getElementById('routing-filter-chain-select');
  11693. const chainDatalist = document.getElementById('dl-routing-chains');
  11694. const uniqueChains = Array.from(new Set(allRules.map(r => r.chain).filter(Boolean))).sort();
  11695. if (chainSelect) {
  11696. const currentVal = state.filterChainSelected || 'all';
  11697. chainSelect.innerHTML = `<option value="all">All Chains (${allRules.length})</option>` +
  11698. uniqueChains.map(ch => {
  11699. const count = allRules.filter(r => r.chain === ch).length;
  11700. return `<option value="${escapeHtml(ch)}"${currentVal === ch ? ' selected' : ''}>${escapeHtml(ch)} (${count})</option>`;
  11701. }).join('');
  11702. chainSelect.value = currentVal;
  11703. }
  11704. if (chainDatalist) {
  11705. chainDatalist.innerHTML = uniqueChains.map(ch => `<option value="${escapeHtml(ch)}">`).join('');
  11706. }
  11707. renderRoutingFilterRules();
  11708. renderRoutingFilterCommunityLists();
  11709. renderRoutingFilterASLists();
  11710. }
  11711. function filterRoutingFiltersByChain(chain) {
  11712. state.filterChainSelected = chain;
  11713. renderRoutingFilters();
  11714. }
  11715. // -------------------------------------------------------------
  11716. // TAB 1: RULES (/routing filter rule)
  11717. // -------------------------------------------------------------
  11718. function renderRoutingFilterRules() {
  11719. const tbody = document.getElementById('routing-filter-rules-tbody');
  11720. if (!tbody) return;
  11721. const empty = document.getElementById('rf-rules-empty');
  11722. const statusCount = document.getElementById('rf-status-count');
  11723. let list = (state.routingFilters || []).slice();
  11724. if (state.filterChainSelected && state.filterChainSelected !== 'all') {
  11725. list = list.filter(r => r.chain === state.filterChainSelected);
  11726. }
  11727. const q = state.rfSearchQuery;
  11728. if (q) {
  11729. list = list.filter(r =>
  11730. (r.chain && r.chain.toLowerCase().includes(q)) ||
  11731. (r.rule && r.rule.toLowerCase().includes(q)) ||
  11732. (r.prefix && r.prefix.toLowerCase().includes(q)) ||
  11733. (r.comment && r.comment.toLowerCase().includes(q))
  11734. );
  11735. }
  11736. if (!state.rfSort?.['rules']) {
  11737. list.sort((a, b) => {
  11738. if (a.chain !== b.chain) return (a.chain || '').localeCompare(b.chain || '');
  11739. return (a.rule_order || 0) - (b.rule_order || 0);
  11740. });
  11741. }
  11742. if (statusCount && (state.activeRoutingFilterTab === 'rules' || !state.activeRoutingFilterTab)) {
  11743. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  11744. }
  11745. if (list.length === 0) {
  11746. tbody.innerHTML = '';
  11747. if (empty) empty.classList.remove('hidden');
  11748. return;
  11749. }
  11750. if (empty) empty.classList.add('hidden');
  11751. tbody.innerHTML = list.map(r => {
  11752. const isSelected = state.selectedFilterRow?.['rules'] === r.id;
  11753. const flagA = !r.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  11754. const flagX = r.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  11755. const flagC = r.comment ? '<span class="text-amber-400 font-bold ml-1" title="Comment">C</span>' : '';
  11756. let ruleDisplay = '';
  11757. if (r.rule && r.rule.trim() !== '') {
  11758. ruleDisplay = `<span class="text-emerald-400 font-mono font-medium">${escapeHtml(r.rule)}</span>`;
  11759. } else {
  11760. let conds = [];
  11761. if (r.prefix) conds.push(`dst in ${escapeHtml(r.prefix)}`);
  11762. if (r.match_protocol && r.match_protocol !== 'any') conds.push(`protocol ${escapeHtml(r.match_protocol)}`);
  11763. let act = r.action || 'accept';
  11764. ruleDisplay = `<span class="text-slate-300 font-mono">if (${conds.length ? conds.join(' && ') : 'true'}) { ${escapeHtml(act)}; }</span>`;
  11765. }
  11766. return `
  11767. <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'}">
  11768. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}${flagC}</td>
  11769. <td class="py-2 px-2 font-mono text-slate-400 font-bold">${r.rule_order || 10}</td>
  11770. <td class="py-2 px-3">
  11771. <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>
  11772. </td>
  11773. <td class="py-2 px-3 break-all max-w-xl">${ruleDisplay}</td>
  11774. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(r.comment || '')}</td>
  11775. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  11776. <button onclick="event.stopPropagation(); 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>
  11777. <button onclick="event.stopPropagation(); 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>
  11778. <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'}">
  11779. ${r.disabled ? 'Enable' : 'Disable'}
  11780. </button>
  11781. <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">
  11782. Edit
  11783. </button>
  11784. <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">
  11785. ✕
  11786. </button>
  11787. </td>
  11788. </tr>
  11789. `;
  11790. }).join('');
  11791. }
  11792. // -------------------------------------------------------------
  11793. // TAB 2: COMMUNITY LISTS (/routing filter community-list)
  11794. // -------------------------------------------------------------
  11795. function renderRoutingFilterCommunityLists() {
  11796. const tbody = document.getElementById('routing-filter-comm-lists-tbody');
  11797. if (!tbody) return;
  11798. const empty = document.getElementById('rf-comm-lists-empty');
  11799. const statusCount = document.getElementById('rf-status-count');
  11800. let list = (state.routingCommunityLists || []).slice();
  11801. const q = state.rfSearchQuery;
  11802. if (q) {
  11803. list = list.filter(cl =>
  11804. (cl.name && cl.name.toLowerCase().includes(q)) ||
  11805. (cl.comment && cl.comment.toLowerCase().includes(q)) ||
  11806. (cl.communities && cl.communities.some(c => c.toLowerCase().includes(q)))
  11807. );
  11808. }
  11809. if (statusCount && state.activeRoutingFilterTab === 'community-lists') {
  11810. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  11811. }
  11812. if (list.length === 0) {
  11813. tbody.innerHTML = '';
  11814. if (empty) empty.classList.remove('hidden');
  11815. return;
  11816. }
  11817. if (empty) empty.classList.add('hidden');
  11818. tbody.innerHTML = list.map(cl => {
  11819. const isSelected = state.selectedFilterRow?.['community-lists'] === cl.id;
  11820. const flagA = !cl.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  11821. const flagX = cl.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  11822. const commBadges = (cl.communities || []).map(c =>
  11823. `<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>`
  11824. ).join(' ');
  11825. return `
  11826. <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'}">
  11827. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  11828. <td class="py-2 px-3 font-mono font-bold text-white">${escapeHtml(cl.name)}</td>
  11829. <td class="py-2 px-3 space-x-1">${commBadges || '<span class="text-slate-600">-</span>'}</td>
  11830. <td class="py-2 px-3 font-mono text-slate-400">${escapeHtml(cl.regexp || '-')}</td>
  11831. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(cl.comment || '')}</td>
  11832. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  11833. <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'}">
  11834. ${cl.disabled ? 'Enable' : 'Disable'}
  11835. </button>
  11836. <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">
  11837. Edit
  11838. </button>
  11839. <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">
  11840. ✕
  11841. </button>
  11842. </td>
  11843. </tr>
  11844. `;
  11845. }).join('');
  11846. }
  11847. // -------------------------------------------------------------
  11848. // TAB 4: AS LISTS (/routing filter num-list)
  11849. // -------------------------------------------------------------
  11850. function renderRoutingFilterASLists() {
  11851. const tbody = document.getElementById('routing-filter-as-lists-tbody');
  11852. if (!tbody) return;
  11853. const empty = document.getElementById('rf-as-lists-empty');
  11854. const statusCount = document.getElementById('rf-status-count');
  11855. let list = (state.routingASLists || []).slice();
  11856. const q = state.rfSearchQuery;
  11857. if (q) {
  11858. list = list.filter(al =>
  11859. (al.name && al.name.toLowerCase().includes(q)) ||
  11860. (al.range && al.range.toLowerCase().includes(q)) ||
  11861. (al.comment && al.comment.toLowerCase().includes(q))
  11862. );
  11863. }
  11864. if (statusCount && state.activeRoutingFilterTab === 'as-lists') {
  11865. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  11866. }
  11867. if (list.length === 0) {
  11868. tbody.innerHTML = '';
  11869. if (empty) empty.classList.remove('hidden');
  11870. return;
  11871. }
  11872. if (empty) empty.classList.add('hidden');
  11873. tbody.innerHTML = list.map(al => {
  11874. const isSelected = state.selectedFilterRow?.['as-lists'] === al.id;
  11875. const flagA = !al.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  11876. const flagX = al.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  11877. return `
  11878. <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'}">
  11879. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  11880. <td class="py-2 px-3 font-mono font-bold text-white">${escapeHtml(al.name)}</td>
  11881. <td class="py-2 px-3 font-mono text-purple-300">${escapeHtml(al.range)}</td>
  11882. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(al.comment || '')}</td>
  11883. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  11884. <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'}">
  11885. ${al.disabled ? 'Enable' : 'Disable'}
  11886. </button>
  11887. <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">
  11888. Edit
  11889. </button>
  11890. <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">
  11891. ✕
  11892. </button>
  11893. </td>
  11894. </tr>
  11895. `;
  11896. }).join('');
  11897. }
  11898. // -------------------------------------------------------------
  11899. // SNIPPETS & WIZARD HELPERS
  11900. // -------------------------------------------------------------
  11901. function insertRuleSnippet(type) {
  11902. const textarea = document.getElementById('modal-rf-rule');
  11903. if (!textarea) return;
  11904. let snippet = '';
  11905. switch (type) {
  11906. case 'accept-default':
  11907. snippet = 'if (dst in 0.0.0.0/0) { accept; }';
  11908. break;
  11909. case 'drop-rfc1918':
  11910. snippet = 'if (dst in 10.0.0.0/8 || dst in 172.16.0.0/12 || dst in 192.168.0.0/16) { reject; }';
  11911. break;
  11912. case 'len-24':
  11913. snippet = 'if (dst-len > 24) { reject; }';
  11914. break;
  11915. case 'local-pref-150':
  11916. snippet = 'if (dst in 10.0.0.0/8) { set bgp-local-pref 150; accept; }';
  11917. break;
  11918. case 'as-prepend-2':
  11919. snippet = 'set bgp-path-prepend 2; accept;';
  11920. break;
  11921. case 'set-comm':
  11922. snippet = 'set bgp-communities.add 65000:100; accept;';
  11923. break;
  11924. case 'match-comm':
  11925. snippet = 'if (bgp-communities includes 65000:100) { accept; }';
  11926. break;
  11927. case 'reject-all':
  11928. snippet = 'reject;';
  11929. break;
  11930. }
  11931. if (!snippet) return;
  11932. if (!textarea.value.trim()) {
  11933. textarea.value = snippet;
  11934. } else {
  11935. textarea.value = textarea.value.trim() + '\n' + snippet;
  11936. }
  11937. }
  11938. function generateScriptFromWizard() {
  11939. const pfx = (document.getElementById('modal-rf-prefix')?.value || '').trim();
  11940. const pfxLen = (document.getElementById('modal-rf-prefix-len')?.value || '').trim();
  11941. const proto = document.getElementById('modal-rf-protocol')?.value || 'any';
  11942. const asp = (document.getElementById('modal-rf-as-path')?.value || '').trim();
  11943. const comm = (document.getElementById('modal-rf-community')?.value || '').trim();
  11944. const act = document.getElementById('modal-rf-action')?.value || 'accept';
  11945. const lp = parseInt(document.getElementById('modal-rf-set-local-pref')?.value, 10) || 0;
  11946. const prep = parseInt(document.getElementById('modal-rf-set-as-prepend')?.value, 10) || 0;
  11947. const conds = [];
  11948. if (pfx) {
  11949. if (pfxLen) {
  11950. if (pfxLen.includes('-')) {
  11951. const parts = pfxLen.split('-');
  11952. conds.push(`dst in ${pfx}{${parts[0].trim()},${parts[1].trim()}}`);
  11953. } else {
  11954. conds.push(`dst in ${pfx} && dst-len >= ${pfxLen}`);
  11955. }
  11956. } else {
  11957. conds.push(`dst in ${pfx}`);
  11958. }
  11959. }
  11960. if (proto && proto !== 'any') {
  11961. conds.push(`protocol ${proto}`);
  11962. }
  11963. if (asp) {
  11964. conds.push(`bgp-as-path "${asp}"`);
  11965. }
  11966. if (comm) {
  11967. conds.push(`bgp-communities includes ${comm}`);
  11968. }
  11969. const actions = [];
  11970. if (lp > 0) actions.push(`set bgp-local-pref ${lp};`);
  11971. if (prep > 0) actions.push(`set bgp-path-prepend ${prep};`);
  11972. if (act && act !== 'passthrough') {
  11973. actions.push(`${act};`);
  11974. }
  11975. let code = '';
  11976. if (conds.length > 0) {
  11977. code = `if (${conds.join(' && ')}) {\n ${actions.join(' ')}\n}`;
  11978. } else {
  11979. code = actions.join(' ');
  11980. }
  11981. const textarea = document.getElementById('modal-rf-rule');
  11982. if (textarea) textarea.value = code;
  11983. }
  11984. // -------------------------------------------------------------
  11985. // MODAL CRUD: RULES (/routing filter rule)
  11986. // -------------------------------------------------------------
  11987. function openAddRoutingFilterModal(defaultChain = '') {
  11988. const form = document.getElementById('routing-filter-form');
  11989. if (form) form.reset();
  11990. const idEl = document.getElementById('modal-rf-id');
  11991. if (idEl) idEl.value = '';
  11992. const titleEl = document.getElementById('modal-rf-title');
  11993. if (titleEl) titleEl.innerText = 'Add Routing Filter Rule';
  11994. const chainEl = document.getElementById('modal-rf-chain');
  11995. if (chainEl) chainEl.value = defaultChain || (state.filterChainSelected && state.filterChainSelected !== 'all' ? state.filterChainSelected : 'bgp-in');
  11996. const orderEl = document.getElementById('modal-rf-order');
  11997. if (orderEl) orderEl.value = ((state.routingFilters || []).length + 1) * 10;
  11998. const ruleEl = document.getElementById('modal-rf-rule');
  11999. if (ruleEl) ruleEl.value = 'if (dst in 10.0.0.0/8) { set bgp-local-pref 150; accept; }';
  12000. const disEl = document.getElementById('modal-rf-disabled');
  12001. if (disEl) disEl.checked = false;
  12002. const modal = document.getElementById('modal-routing-filter');
  12003. if (modal) modal.classList.remove('hidden');
  12004. }
  12005. function openEditRoutingFilterModal(id) {
  12006. const r = (state.routingFilters || []).find(item => item.id === id);
  12007. if (!r) return;
  12008. const idEl = document.getElementById('modal-rf-id');
  12009. if (idEl) idEl.value = r.id;
  12010. const titleEl = document.getElementById('modal-rf-title');
  12011. if (titleEl) titleEl.innerText = 'Edit Routing Filter Rule';
  12012. const chainEl = document.getElementById('modal-rf-chain');
  12013. if (chainEl) chainEl.value = r.chain || '';
  12014. const orderEl = document.getElementById('modal-rf-order');
  12015. if (orderEl) orderEl.value = r.rule_order || 10;
  12016. const ruleEl = document.getElementById('modal-rf-rule');
  12017. if (ruleEl) {
  12018. if (r.rule) {
  12019. ruleEl.value = r.rule;
  12020. } else {
  12021. let conds = [];
  12022. if (r.prefix) conds.push(`dst in ${r.prefix}`);
  12023. if (r.match_protocol && r.match_protocol !== 'any') conds.push(`protocol ${r.match_protocol}`);
  12024. let act = r.action || 'accept';
  12025. ruleEl.value = `if (${conds.length ? conds.join(' && ') : 'true'}) { ${act}; }`;
  12026. }
  12027. }
  12028. const comEl = document.getElementById('modal-rf-comment');
  12029. if (comEl) comEl.value = r.comment || '';
  12030. const disEl = document.getElementById('modal-rf-disabled');
  12031. if (disEl) disEl.checked = !!r.disabled;
  12032. const modal = document.getElementById('modal-routing-filter');
  12033. if (modal) modal.classList.remove('hidden');
  12034. }
  12035. function closeRoutingFilterModal() {
  12036. const modal = document.getElementById('modal-routing-filter');
  12037. if (modal) modal.classList.add('hidden');
  12038. }
  12039. async function submitRoutingFilter(e) {
  12040. if (e) e.preventDefault();
  12041. const payload = {
  12042. id: document.getElementById('modal-rf-id').value,
  12043. chain: document.getElementById('modal-rf-chain').value.trim(),
  12044. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  12045. rule: document.getElementById('modal-rf-rule').value.trim(),
  12046. comment: document.getElementById('modal-rf-comment').value.trim(),
  12047. disabled: document.getElementById('modal-rf-disabled').checked
  12048. };
  12049. try {
  12050. const res = await fetch(`${API_BASE}/routing/filters`, {
  12051. method: 'POST',
  12052. headers: { 'Content-Type': 'application/json' },
  12053. body: JSON.stringify(payload)
  12054. });
  12055. if (res.ok) {
  12056. closeRoutingFilterModal();
  12057. showToast('Success', 'Routing filter rule saved', 'success');
  12058. loadDynamicRouting();
  12059. } else {
  12060. const err = await res.json();
  12061. showToast('Error', err.error || 'Failed to save filter rule', 'error');
  12062. }
  12063. } catch (err) {
  12064. showToast('Error', err.message, 'error');
  12065. }
  12066. }
  12067. async function applyRoutingFilterForm() {
  12068. const payload = {
  12069. id: document.getElementById('modal-rf-id').value,
  12070. chain: document.getElementById('modal-rf-chain').value.trim(),
  12071. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  12072. rule: document.getElementById('modal-rf-rule').value.trim(),
  12073. comment: document.getElementById('modal-rf-comment').value.trim(),
  12074. disabled: document.getElementById('modal-rf-disabled').checked
  12075. };
  12076. try {
  12077. const res = await fetch(`${API_BASE}/routing/filters`, {
  12078. method: 'POST',
  12079. headers: { 'Content-Type': 'application/json' },
  12080. body: JSON.stringify(payload)
  12081. });
  12082. if (res.ok) {
  12083. const data = await res.json();
  12084. if (data.id) document.getElementById('modal-rf-id').value = data.id;
  12085. showToast('Applied', 'Routing filter configuration applied', 'success');
  12086. loadDynamicRouting();
  12087. } else {
  12088. const err = await res.json();
  12089. showToast('Error', err.error || 'Failed to apply filter rule', 'error');
  12090. }
  12091. } catch (err) {
  12092. showToast('Error', err.message, 'error');
  12093. }
  12094. }
  12095. async function moveRoutingFilterOrder(id, delta) {
  12096. const dir = delta < 0 ? 'up' : 'down';
  12097. try {
  12098. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}/move`, {
  12099. method: 'POST',
  12100. headers: { 'Content-Type': 'application/json' },
  12101. body: JSON.stringify({ direction: dir })
  12102. });
  12103. if (!res.ok) {
  12104. const err = await res.json().catch(() => ({}));
  12105. showToast('Error', err.error || 'Failed to move filter rule', 'error');
  12106. return;
  12107. }
  12108. await loadDynamicRouting(false);
  12109. } catch (e) {
  12110. showToast('Error', e.message, 'error');
  12111. }
  12112. }
  12113. async function moveSelectedRoutingFilter(delta) {
  12114. const id = state.selectedFilterRow?.['rules'];
  12115. if (!id) {
  12116. showToast('Notice', 'Please select a routing filter rule first', 'info');
  12117. return;
  12118. }
  12119. await moveRoutingFilterOrder(id, delta);
  12120. }
  12121. async function deleteRoutingFilter(id) {
  12122. if (!confirm('Are you sure you want to delete this routing filter rule?')) return;
  12123. try {
  12124. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12125. if (res.ok) {
  12126. showToast('Deleted', 'Routing filter rule removed', 'info');
  12127. loadDynamicRouting();
  12128. } else {
  12129. const err = await res.json();
  12130. showToast('Error', err.error || 'Failed to delete rule', 'error');
  12131. }
  12132. } catch (err) {
  12133. showToast('Error', err.message, 'error');
  12134. }
  12135. }
  12136. async function toggleRoutingFilterState(id, disabled) {
  12137. try {
  12138. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}/state`, {
  12139. method: 'POST',
  12140. headers: { 'Content-Type': 'application/json' },
  12141. body: JSON.stringify({ disabled })
  12142. });
  12143. if (res.ok) {
  12144. showToast('Status Updated', `Rule ${disabled ? 'disabled' : 'enabled'}`, 'info');
  12145. loadDynamicRouting();
  12146. } else {
  12147. const err = await res.json();
  12148. showToast('Error', err.error || 'Failed to toggle rule state', 'error');
  12149. }
  12150. } catch (err) {
  12151. showToast('Error', err.message, 'error');
  12152. }
  12153. }
  12154. // -------------------------------------------------------------
  12155. // MODAL CRUD: COMMUNITY LISTS (/routing filter community-list)
  12156. // -------------------------------------------------------------
  12157. function openAddCommunityListModal() {
  12158. document.getElementById('modal-rf-cl-id').value = '';
  12159. document.getElementById('modal-rf-cl-title').innerText = 'Add BGP Community List';
  12160. document.getElementById('modal-rf-cl-name').value = '';
  12161. document.getElementById('modal-rf-cl-communities').value = '';
  12162. document.getElementById('modal-rf-cl-regexp').value = '';
  12163. document.getElementById('modal-rf-cl-comment').value = '';
  12164. document.getElementById('modal-rf-cl-disabled').checked = false;
  12165. document.getElementById('modal-rf-community-list').classList.remove('hidden');
  12166. }
  12167. function openEditCommunityListModal(id) {
  12168. const cl = (state.routingCommunityLists || []).find(item => item.id === id);
  12169. if (!cl) return;
  12170. document.getElementById('modal-rf-cl-id').value = cl.id;
  12171. document.getElementById('modal-rf-cl-title').innerText = 'Edit BGP Community List';
  12172. document.getElementById('modal-rf-cl-name').value = cl.name || '';
  12173. document.getElementById('modal-rf-cl-communities').value = (cl.communities || []).join(', ');
  12174. document.getElementById('modal-rf-cl-regexp').value = cl.regexp || '';
  12175. document.getElementById('modal-rf-cl-comment').value = cl.comment || '';
  12176. document.getElementById('modal-rf-cl-disabled').checked = !!cl.disabled;
  12177. document.getElementById('modal-rf-community-list').classList.remove('hidden');
  12178. }
  12179. function closeCommunityListModal() {
  12180. document.getElementById('modal-rf-community-list').classList.add('hidden');
  12181. }
  12182. async function submitCommunityList(e) {
  12183. e.preventDefault();
  12184. const rawComms = document.getElementById('modal-rf-cl-communities').value;
  12185. const comms = rawComms.split(',').map(c => c.trim()).filter(Boolean);
  12186. const payload = {
  12187. id: document.getElementById('modal-rf-cl-id').value,
  12188. name: document.getElementById('modal-rf-cl-name').value.trim(),
  12189. communities: comms,
  12190. regexp: document.getElementById('modal-rf-cl-regexp').value.trim(),
  12191. comment: document.getElementById('modal-rf-cl-comment').value.trim(),
  12192. disabled: document.getElementById('modal-rf-cl-disabled').checked
  12193. };
  12194. try {
  12195. const res = await fetch(`${API_BASE}/routing/filters/community-lists`, {
  12196. method: 'POST',
  12197. headers: { 'Content-Type': 'application/json' },
  12198. body: JSON.stringify(payload)
  12199. });
  12200. if (res.ok) {
  12201. closeCommunityListModal();
  12202. showToast('Success', 'Community list saved', 'success');
  12203. loadDynamicRouting();
  12204. } else {
  12205. const err = await res.json();
  12206. showToast('Error', err.error || 'Failed to save community list', 'error');
  12207. }
  12208. } catch (err) {
  12209. showToast('Error', err.message, 'error');
  12210. }
  12211. }
  12212. async function deleteCommunityList(id) {
  12213. if (!confirm('Are you sure you want to delete this community list?')) return;
  12214. try {
  12215. const res = await fetch(`${API_BASE}/routing/filters/community-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12216. if (res.ok) {
  12217. showToast('Deleted', 'Community list removed', 'info');
  12218. loadDynamicRouting();
  12219. } else {
  12220. const err = await res.json();
  12221. showToast('Error', err.error || 'Failed to delete community list', 'error');
  12222. }
  12223. } catch (err) {
  12224. showToast('Error', err.message, 'error');
  12225. }
  12226. }
  12227. async function toggleCommunityListState(id, disabled) {
  12228. try {
  12229. const res = await fetch(`${API_BASE}/routing/filters/community-lists/${encodeURIComponent(id)}/state`, {
  12230. method: 'POST',
  12231. headers: { 'Content-Type': 'application/json' },
  12232. body: JSON.stringify({ disabled })
  12233. });
  12234. if (res.ok) {
  12235. showToast('Status Updated', `Community list ${disabled ? 'disabled' : 'enabled'}`, 'info');
  12236. loadDynamicRouting();
  12237. } else {
  12238. const err = await res.json();
  12239. showToast('Error', err.error || 'Failed to update community list state', 'error');
  12240. }
  12241. } catch (err) {
  12242. showToast('Error', err.message, 'error');
  12243. }
  12244. }
  12245. // -------------------------------------------------------------
  12246. // MODAL CRUD: AS LISTS (/routing filter num-list)
  12247. // -------------------------------------------------------------
  12248. function openAddASListModal() {
  12249. document.getElementById('modal-rf-al-id').value = '';
  12250. document.getElementById('modal-rf-al-title').innerText = 'Add AS Number List';
  12251. document.getElementById('modal-rf-al-name').value = '';
  12252. document.getElementById('modal-rf-al-range').value = '';
  12253. document.getElementById('modal-rf-al-comment').value = '';
  12254. document.getElementById('modal-rf-al-disabled').checked = false;
  12255. document.getElementById('modal-rf-as-list').classList.remove('hidden');
  12256. }
  12257. function openEditASListModal(id) {
  12258. const al = (state.routingASLists || []).find(item => item.id === id);
  12259. if (!al) return;
  12260. document.getElementById('modal-rf-al-id').value = al.id;
  12261. document.getElementById('modal-rf-al-title').innerText = 'Edit AS Number List';
  12262. document.getElementById('modal-rf-al-name').value = al.name || '';
  12263. document.getElementById('modal-rf-al-range').value = al.range || '';
  12264. document.getElementById('modal-rf-al-comment').value = al.comment || '';
  12265. document.getElementById('modal-rf-al-disabled').checked = !!al.disabled;
  12266. document.getElementById('modal-rf-as-list').classList.remove('hidden');
  12267. }
  12268. function closeASListModal() {
  12269. document.getElementById('modal-rf-as-list').classList.add('hidden');
  12270. }
  12271. async function submitASList(e) {
  12272. e.preventDefault();
  12273. const payload = {
  12274. id: document.getElementById('modal-rf-al-id').value,
  12275. name: document.getElementById('modal-rf-al-name').value.trim(),
  12276. range: document.getElementById('modal-rf-al-range').value.trim(),
  12277. comment: document.getElementById('modal-rf-al-comment').value.trim(),
  12278. disabled: document.getElementById('modal-rf-al-disabled').checked
  12279. };
  12280. try {
  12281. const res = await fetch(`${API_BASE}/routing/filters/as-lists`, {
  12282. method: 'POST',
  12283. headers: { 'Content-Type': 'application/json' },
  12284. body: JSON.stringify(payload)
  12285. });
  12286. if (res.ok) {
  12287. closeASListModal();
  12288. showToast('Success', 'AS number list saved', 'success');
  12289. loadDynamicRouting();
  12290. } else {
  12291. const err = await res.json();
  12292. showToast('Error', err.error || 'Failed to save AS list', 'error');
  12293. }
  12294. } catch (err) {
  12295. showToast('Error', err.message, 'error');
  12296. }
  12297. }
  12298. async function deleteASList(id) {
  12299. if (!confirm('Are you sure you want to delete this AS list?')) return;
  12300. try {
  12301. const res = await fetch(`${API_BASE}/routing/filters/as-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12302. if (res.ok) {
  12303. showToast('Deleted', 'AS list removed', 'info');
  12304. loadDynamicRouting();
  12305. } else {
  12306. const err = await res.json();
  12307. showToast('Error', err.error || 'Failed to delete AS list', 'error');
  12308. }
  12309. } catch (err) {
  12310. showToast('Error', err.message, 'error');
  12311. }
  12312. }
  12313. async function toggleASListState(id, disabled) {
  12314. try {
  12315. const res = await fetch(`${API_BASE}/routing/filters/as-lists/${encodeURIComponent(id)}/state`, {
  12316. method: 'POST',
  12317. headers: { 'Content-Type': 'application/json' },
  12318. body: JSON.stringify({ disabled })
  12319. });
  12320. if (res.ok) {
  12321. showToast('Status Updated', `AS list ${disabled ? 'disabled' : 'enabled'}`, 'info');
  12322. loadDynamicRouting();
  12323. } else {
  12324. const err = await res.json();
  12325. showToast('Error', err.error || 'Failed to update AS list state', 'error');
  12326. }
  12327. } catch (err) {
  12328. showToast('Error', err.message, 'error');
  12329. }
  12330. }
  12331. // ==========================================
  12332. // TROUBLESHOOT & DIAGNOSTIC TOOLS (/tool)
  12333. // ==========================================
  12334. async function loadNetworkOverview() {
  12335. const container = document.getElementById('tools-overview');
  12336. const timestamp = document.getElementById('tools-overview-time');
  12337. if (!container || !timestamp) return;
  12338. timestamp.textContent = 'Refreshing overview...';
  12339. const current = {};
  12340. container._overviewRequest = current;
  12341. const requests = [
  12342. ['Interfaces', '/interfaces'], ['System', '/system/status'], ['Routes', '/routes'],
  12343. ['DNS', '/dns/status'], ['WireGuard peers', '/vpn/wireguard/peers'], ['AeroTUN', '/vpn/aerotun/tunnels']
  12344. ];
  12345. const results = await Promise.all(requests.map(async ([label, path]) => {
  12346. try {
  12347. const response = await fetch(API_BASE + path);
  12348. if (!response.ok) throw new Error(await responseError(response));
  12349. return {label, data: await response.json()};
  12350. } catch (error) { return {label, error: error.message || 'Request failed'}; }
  12351. }));
  12352. // A later refresh supersedes an earlier response.
  12353. if (container._overviewRequest !== current) return;
  12354. container.replaceChildren();
  12355. for (const result of results) {
  12356. const card = document.createElement('div');
  12357. card.className = 'rounded border border-slate-700 bg-slate-950/50 p-3';
  12358. const title = document.createElement('div');
  12359. title.className = 'text-xs font-bold text-slate-200 mb-1';
  12360. title.textContent = result.label;
  12361. const detail = document.createElement('div');
  12362. detail.className = 'text-xs text-slate-400 whitespace-pre-wrap break-words';
  12363. detail.textContent = result.error ? `Unavailable: ${result.error}` : formatNetworkOverview(result.label, result.data);
  12364. card.append(title, detail); container.append(card);
  12365. }
  12366. timestamp.textContent = `Updated ${new Date().toLocaleTimeString()} · each section reports its own errors`;
  12367. }
  12368. function formatNetworkOverview(label, data) {
  12369. if (label === 'System') return `Default gateway: ${data.default_gateway || 'not reported'}`;
  12370. if (label === 'DNS') return `Active resolvers: ${(data.active_servers || []).join(', ') || 'none reported'}\nDNS service: ${data.service_running ? 'running' : 'not running'}`;
  12371. if (!Array.isArray(data)) return 'Unexpected response';
  12372. if (label === 'Routes') return `${data.length} routes reported. Open Routing for details.`;
  12373. if (!data.length) return 'None reported';
  12374. if (label === 'Interfaces') return data.map(i => `${i.name}: ${i.operstate || i.state || 'unknown'} · ${[...(i.ipv4 || []), ...(i.ipv6 || [])].join(', ') || 'no addresses'}`).join('\n');
  12375. if (label === 'WireGuard peers') return data.map(p => `${p.interface || '?'} / ${p.name || p.public_key || '?'}: ${p.disabled ? 'disabled' : 'enabled'} · last handshake ${p.latest_handshake || 'not reported'}`).join('\n');
  12376. if (label === 'AeroTUN') return data.map(t => `${t.name || '?'}: ${t.disabled ? 'disabled' : t.connected ? 'connected' : t.running ? 'running, not connected' : 'stopped'}`).join('\n');
  12377. return 'Unavailable';
  12378. }
  12379. function loadToolsView() {
  12380. loadNetworkOverview();
  12381. populateToolsInterfaces();
  12382. switchToolsSubTab(state.activeToolsSubTab || 'ping');
  12383. }
  12384. function populateToolsInterfaces() {
  12385. const pingSel = document.getElementById('tools-ping-iface');
  12386. const traceSel = document.getElementById('tools-tr-iface');
  12387. let opts = '<option value="">Auto (Default Route)</option>';
  12388. if (Array.isArray(state.interfaces)) {
  12389. state.interfaces.forEach(iface => {
  12390. if (iface.name) {
  12391. opts += `<option value="${escapeHtml(iface.name)}">${escapeHtml(iface.name)}${iface.ip_address ? ' (' + escapeHtml(iface.ip_address) + ')' : ''}</option>`;
  12392. }
  12393. });
  12394. }
  12395. if (pingSel) {
  12396. const cur = pingSel.value;
  12397. pingSel.innerHTML = opts;
  12398. if (cur) pingSel.value = cur;
  12399. }
  12400. if (traceSel) {
  12401. const cur = traceSel.value;
  12402. traceSel.innerHTML = opts;
  12403. if (cur) traceSel.value = cur;
  12404. }
  12405. }
  12406. function switchToolsSubTab(subTab) {
  12407. state.activeToolsSubTab = subTab;
  12408. const tabs = ['ping', 'traceroute', 'mtr', 'dns', 'port'];
  12409. tabs.forEach(t => {
  12410. const btn = document.getElementById(`tools-subtab-btn-${t}`);
  12411. const view = document.getElementById(`tools-view-${t}`);
  12412. if (btn) {
  12413. if (t === subTab) {
  12414. 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';
  12415. } else {
  12416. 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';
  12417. }
  12418. }
  12419. if (view) {
  12420. if (t === subTab) {
  12421. view.classList.remove('hidden');
  12422. } else {
  12423. view.classList.add('hidden');
  12424. }
  12425. }
  12426. });
  12427. }
  12428. function setPortPreset(port) {
  12429. const input = document.getElementById('tools-port-num');
  12430. if (input) input.value = port;
  12431. }
  12432. let pingAbortController = null;
  12433. let tracerouteAbortController = null;
  12434. function clearPingTable() {
  12435. const tbody = document.getElementById('tools-ping-tbody');
  12436. if (tbody) tbody.innerHTML = '';
  12437. const rawEl = document.getElementById('tools-ping-raw');
  12438. if (rawEl) rawEl.innerText = '';
  12439. const sentEl = document.getElementById('tools-ping-stat-sent');
  12440. if (sentEl) sentEl.innerText = '0';
  12441. const recvEl = document.getElementById('tools-ping-stat-recv');
  12442. if (recvEl) recvEl.innerText = '0';
  12443. const lossEl = document.getElementById('tools-ping-stat-loss');
  12444. if (lossEl) lossEl.innerText = '0%';
  12445. const avgEl = document.getElementById('tools-ping-stat-avg');
  12446. if (avgEl) avgEl.innerText = '0 ms';
  12447. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  12448. if (minMaxEl) minMaxEl.innerText = '-';
  12449. const badge = document.getElementById('tools-ping-status-badge');
  12450. if (badge) {
  12451. badge.className = '';
  12452. badge.innerText = '';
  12453. }
  12454. }
  12455. function clearTracerouteTable() {
  12456. const tbody = document.getElementById('tools-tr-tbody');
  12457. if (tbody) tbody.innerHTML = '';
  12458. const rawEl = document.getElementById('tools-tr-raw');
  12459. if (rawEl) rawEl.innerText = '';
  12460. const statHops = document.getElementById('tools-tr-hops-count');
  12461. if (statHops) statHops.innerText = '0 Hops';
  12462. }
  12463. function resetPingButton() {
  12464. const btn = document.getElementById('tools-ping-btn');
  12465. const btnText = document.getElementById('tools-ping-btn-text');
  12466. const spinner = document.getElementById('tools-ping-spinner');
  12467. if (btn) {
  12468. btn.disabled = false;
  12469. 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';
  12470. }
  12471. if (btnText) btnText.innerText = 'Start Ping';
  12472. if (spinner) spinner.classList.add('hidden');
  12473. }
  12474. function setPingRunningButton() {
  12475. const btn = document.getElementById('tools-ping-btn');
  12476. const btnText = document.getElementById('tools-ping-btn-text');
  12477. const spinner = document.getElementById('tools-ping-spinner');
  12478. if (btn) {
  12479. btn.disabled = false;
  12480. 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';
  12481. }
  12482. if (btnText) btnText.innerText = 'Stop Ping';
  12483. if (spinner) spinner.classList.remove('hidden');
  12484. }
  12485. function resetTracerouteButton() {
  12486. const btn = document.getElementById('tools-tr-btn');
  12487. const btnText = document.getElementById('tools-tr-btn-text');
  12488. const spinner = document.getElementById('tools-tr-spinner');
  12489. if (btn) {
  12490. btn.disabled = false;
  12491. 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';
  12492. }
  12493. if (btnText) btnText.innerText = 'Start Traceroute';
  12494. if (spinner) spinner.classList.add('hidden');
  12495. }
  12496. function setTracerouteRunningButton() {
  12497. const btn = document.getElementById('tools-tr-btn');
  12498. const btnText = document.getElementById('tools-tr-btn-text');
  12499. const spinner = document.getElementById('tools-tr-spinner');
  12500. if (btn) {
  12501. btn.disabled = false;
  12502. 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';
  12503. }
  12504. if (btnText) btnText.innerText = 'Stop Traceroute';
  12505. if (spinner) spinner.classList.remove('hidden');
  12506. }
  12507. async function executePing(e) {
  12508. if (e) e.preventDefault();
  12509. // If already running, clicking the button stops the stream!
  12510. if (pingAbortController) {
  12511. pingAbortController.abort();
  12512. pingAbortController = null;
  12513. resetPingButton();
  12514. showToast('Ping Stopped', 'Live ping stopped by user', 'info');
  12515. return;
  12516. }
  12517. const target = document.getElementById('tools-ping-target')?.value?.trim();
  12518. const count = parseInt(document.getElementById('tools-ping-count')?.value || '4', 10);
  12519. const size = parseInt(document.getElementById('tools-ping-size')?.value || '56', 10);
  12520. const timeout = parseInt(document.getElementById('tools-ping-timeout')?.value || '3', 10);
  12521. const iface = document.getElementById('tools-ping-iface')?.value || '';
  12522. const dontFrag = document.getElementById('tools-ping-df')?.checked || false;
  12523. if (!target) {
  12524. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  12525. return;
  12526. }
  12527. clearPingTable();
  12528. const resCard = document.getElementById('tools-ping-results');
  12529. if (resCard) resCard.classList.remove('hidden');
  12530. pingAbortController = new AbortController();
  12531. setPingRunningButton();
  12532. try {
  12533. const res = await fetch(`${API_BASE}/tools/ping/stream`, {
  12534. method: 'POST',
  12535. headers: { 'Content-Type': 'application/json' },
  12536. body: JSON.stringify({
  12537. target,
  12538. count,
  12539. size,
  12540. timeout,
  12541. interface: iface,
  12542. dont_frag: dontFrag
  12543. }),
  12544. signal: pingAbortController.signal
  12545. });
  12546. if (!res.ok) {
  12547. const errText = await res.text();
  12548. showToast('Ping Error', errText || 'Failed to start live ping', 'error');
  12549. resetPingButton();
  12550. pingAbortController = null;
  12551. return;
  12552. }
  12553. const reader = res.body.getReader();
  12554. const decoder = new TextDecoder('utf-8');
  12555. let buffer = '';
  12556. while (true) {
  12557. const { done, value } = await reader.read();
  12558. if (done) break;
  12559. buffer += decoder.decode(value, { stream: true });
  12560. const blocks = buffer.split('\n\n');
  12561. buffer = blocks.pop() || '';
  12562. for (const block of blocks) {
  12563. const trimmed = block.trim();
  12564. if (!trimmed) continue;
  12565. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  12566. try {
  12567. const evt = JSON.parse(line);
  12568. handleLivePingEvent(evt);
  12569. } catch (parseErr) {
  12570. console.warn('Ping SSE parse error:', parseErr, line);
  12571. }
  12572. }
  12573. }
  12574. } catch (err) {
  12575. if (err.name === 'AbortError') {
  12576. // User aborted normally
  12577. } else {
  12578. showToast('Ping Error', err.message, 'error');
  12579. }
  12580. } finally {
  12581. pingAbortController = null;
  12582. resetPingButton();
  12583. }
  12584. }
  12585. function handleLivePingEvent(evt) {
  12586. const sentEl = document.getElementById('tools-ping-stat-sent');
  12587. const recvEl = document.getElementById('tools-ping-stat-recv');
  12588. const lossEl = document.getElementById('tools-ping-stat-loss');
  12589. const avgEl = document.getElementById('tools-ping-stat-avg');
  12590. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  12591. const badge = document.getElementById('tools-ping-status-badge');
  12592. const tbody = document.getElementById('tools-ping-tbody');
  12593. const rawEl = document.getElementById('tools-ping-raw');
  12594. if (evt.raw && rawEl) {
  12595. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  12596. rawEl.scrollTop = rawEl.scrollHeight;
  12597. }
  12598. if (evt.type === 'reply') {
  12599. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  12600. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  12601. if (lossEl && evt.packet_loss_pct !== undefined) {
  12602. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  12603. lossEl.className = evt.packet_loss_pct === 0
  12604. ? 'text-base font-bold font-mono text-emerald-400 mt-1'
  12605. : (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');
  12606. }
  12607. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  12608. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  12609. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  12610. }
  12611. if (badge) {
  12612. if (evt.packet_loss_pct === 0) {
  12613. 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';
  12614. badge.innerText = '100% OK';
  12615. } else {
  12616. 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';
  12617. badge.innerText = `${evt.packet_loss_pct.toFixed(0)}% LOSS`;
  12618. }
  12619. }
  12620. if (tbody) {
  12621. const tr = document.createElement('tr');
  12622. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  12623. tr.innerHTML = `
  12624. <td class="py-2 px-3 text-slate-300">#${evt.seq}</td>
  12625. <td class="py-2 px-3 font-semibold text-white">${escapeHtml(evt.from)}</td>
  12626. <td class="py-2 px-3 text-slate-400">${evt.bytes} bytes</td>
  12627. <td class="py-2 px-3 text-slate-300">${evt.ttl}</td>
  12628. <td class="py-2 px-3 font-bold text-amber-300">${evt.time_ms.toFixed(2)} ms</td>
  12629. <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>
  12630. `;
  12631. tbody.appendChild(tr);
  12632. }
  12633. } else if (evt.type === 'timeout') {
  12634. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  12635. if (lossEl && evt.packet_loss_pct !== undefined) {
  12636. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  12637. 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';
  12638. }
  12639. if (badge) {
  12640. 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';
  12641. badge.innerText = `${evt.packet_loss_pct?.toFixed(0) || 100}% LOSS`;
  12642. }
  12643. if (tbody) {
  12644. const tr = document.createElement('tr');
  12645. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs opacity-75';
  12646. tr.innerHTML = `
  12647. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  12648. <td class="py-2 px-3 font-semibold text-slate-500 italic">Request timed out</td>
  12649. <td class="py-2 px-3 text-slate-600">--</td>
  12650. <td class="py-2 px-3 text-slate-600">--</td>
  12651. <td class="py-2 px-3 font-bold text-slate-500">* * *</td>
  12652. <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>
  12653. `;
  12654. tbody.appendChild(tr);
  12655. }
  12656. } else if (evt.type === 'unreach') {
  12657. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  12658. if (lossEl && evt.packet_loss_pct !== undefined) {
  12659. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  12660. lossEl.className = 'text-base font-bold font-mono text-rose-400 mt-1';
  12661. }
  12662. if (badge) {
  12663. 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';
  12664. badge.innerText = 'UNREACHABLE';
  12665. }
  12666. if (tbody) {
  12667. const tr = document.createElement('tr');
  12668. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  12669. tr.innerHTML = `
  12670. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  12671. <td class="py-2 px-3 font-semibold text-rose-400">${escapeHtml(evt.from || 'Gateway')}</td>
  12672. <td class="py-2 px-3 text-slate-600">--</td>
  12673. <td class="py-2 px-3 text-slate-600">--</td>
  12674. <td class="py-2 px-3 font-bold text-rose-400 text-xs">${escapeHtml(evt.message || 'Unreachable')}</td>
  12675. <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>
  12676. `;
  12677. tbody.appendChild(tr);
  12678. }
  12679. } else if (evt.type === 'stats') {
  12680. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  12681. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  12682. if (lossEl && evt.packet_loss_pct !== undefined) lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  12683. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  12684. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  12685. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  12686. }
  12687. } else if (evt.type === 'done') {
  12688. 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');
  12689. }
  12690. }
  12691. async function executeTraceroute(e) {
  12692. if (e) e.preventDefault();
  12693. if (tracerouteAbortController) {
  12694. tracerouteAbortController.abort();
  12695. tracerouteAbortController = null;
  12696. resetTracerouteButton();
  12697. showToast('Traceroute Stopped', 'Traceroute stopped by user', 'info');
  12698. return;
  12699. }
  12700. const target = document.getElementById('tools-tr-target')?.value?.trim();
  12701. const maxHops = parseInt(document.getElementById('tools-tr-maxhops')?.value || '15', 10);
  12702. const protocol = document.getElementById('tools-tr-proto')?.value || 'icmp';
  12703. const iface = document.getElementById('tools-tr-iface')?.value || '';
  12704. const resolve = document.getElementById('tools-tr-resolve')?.checked || false;
  12705. if (!target) {
  12706. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  12707. return;
  12708. }
  12709. clearTracerouteTable();
  12710. const resCard = document.getElementById('tools-tr-results');
  12711. if (resCard) resCard.classList.remove('hidden');
  12712. tracerouteAbortController = new AbortController();
  12713. setTracerouteRunningButton();
  12714. try {
  12715. const res = await fetch(`${API_BASE}/tools/traceroute/stream`, {
  12716. method: 'POST',
  12717. headers: { 'Content-Type': 'application/json' },
  12718. body: JSON.stringify({
  12719. target,
  12720. max_hops: maxHops,
  12721. protocol,
  12722. interface: iface,
  12723. resolve
  12724. }),
  12725. signal: tracerouteAbortController.signal
  12726. });
  12727. if (!res.ok) {
  12728. const errText = await res.text();
  12729. showToast('Traceroute Error', errText || 'Failed to start traceroute', 'error');
  12730. resetTracerouteButton();
  12731. tracerouteAbortController = null;
  12732. return;
  12733. }
  12734. const reader = res.body.getReader();
  12735. const decoder = new TextDecoder('utf-8');
  12736. let buffer = '';
  12737. while (true) {
  12738. const { done, value } = await reader.read();
  12739. if (done) break;
  12740. buffer += decoder.decode(value, { stream: true });
  12741. const blocks = buffer.split('\n\n');
  12742. buffer = blocks.pop() || '';
  12743. for (const block of blocks) {
  12744. const trimmed = block.trim();
  12745. if (!trimmed) continue;
  12746. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  12747. try {
  12748. const evt = JSON.parse(line);
  12749. handleLiveTracerouteEvent(evt);
  12750. } catch (parseErr) {
  12751. console.warn('Traceroute SSE parse error:', parseErr, line);
  12752. }
  12753. }
  12754. }
  12755. } catch (err) {
  12756. if (err.name === 'AbortError') {
  12757. // User aborted normally
  12758. } else {
  12759. showToast('Traceroute Error', err.message, 'error');
  12760. }
  12761. } finally {
  12762. tracerouteAbortController = null;
  12763. resetTracerouteButton();
  12764. }
  12765. }
  12766. function handleLiveTracerouteEvent(evt) {
  12767. const statHops = document.getElementById('tools-tr-hops-count');
  12768. const tbody = document.getElementById('tools-tr-tbody');
  12769. const rawEl = document.getElementById('tools-tr-raw');
  12770. if (evt.raw && rawEl) {
  12771. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  12772. rawEl.scrollTop = rawEl.scrollHeight;
  12773. }
  12774. if (evt.hops_count !== undefined && statHops) {
  12775. statHops.innerText = `${evt.hops_count} Hops`;
  12776. }
  12777. if (evt.type === 'hop' && evt.hop && tbody) {
  12778. const h = evt.hop;
  12779. const isTimeout = h.status === 'timeout' || (!h.ip && !h.host);
  12780. const rtt1 = Array.isArray(h.times_ms) && h.times_ms[0] ? `${h.times_ms[0]} ms` : (isTimeout ? '*' : '--');
  12781. const rtt2 = Array.isArray(h.times_ms) && h.times_ms[1] ? `${h.times_ms[1]} ms` : (isTimeout ? '*' : '--');
  12782. const displayHost = h.host && h.host !== h.ip ? `${escapeHtml(h.host)} (${escapeHtml(h.ip || '')})` : escapeHtml(h.ip || (isTimeout ? 'Request timed out' : '--'));
  12783. const tr = document.createElement('tr');
  12784. tr.className = `hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs ${isTimeout ? 'opacity-60' : ''}`;
  12785. tr.innerHTML = `
  12786. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  12787. <td class="py-2.5 px-3 font-semibold ${isTimeout ? 'text-slate-500 italic' : 'text-cyan-300'}">${displayHost}</td>
  12788. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt1)}</td>
  12789. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt2)}</td>
  12790. <td class="py-2.5 px-3 text-right">
  12791. ${isTimeout
  12792. ? '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-slate-800 text-slate-400 border border-slate-700">TIMEOUT</span>'
  12793. : '<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>'}
  12794. </td>
  12795. `;
  12796. tbody.appendChild(tr);
  12797. } else if (evt.type === 'done') {
  12798. showToast('Traceroute Finished', `Traced ${evt.hops_count || 0} hops`, 'info');
  12799. }
  12800. }
  12801. async function executeMTR(e) {
  12802. if (e) e.preventDefault();
  12803. const target = document.getElementById('tools-mtr-target')?.value?.trim();
  12804. const cycles = parseInt(document.getElementById('tools-mtr-count')?.value || '3', 10);
  12805. if (!target) {
  12806. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  12807. return;
  12808. }
  12809. const btn = document.getElementById('tools-mtr-btn');
  12810. const spinner = document.getElementById('tools-mtr-spinner');
  12811. if (btn) btn.disabled = true;
  12812. if (spinner) spinner.classList.remove('hidden');
  12813. try {
  12814. const res = await fetch(`${API_BASE}/tools/mtr`, {
  12815. method: 'POST',
  12816. headers: { 'Content-Type': 'application/json' },
  12817. body: JSON.stringify({ target, count: cycles })
  12818. });
  12819. const data = await res.json();
  12820. if (!res.ok) {
  12821. showToast('MTR Error', data.error || 'Failed to execute MTR', 'error');
  12822. return;
  12823. }
  12824. const resCard = document.getElementById('tools-mtr-results');
  12825. if (resCard) resCard.classList.remove('hidden');
  12826. const hopsCount = Array.isArray(data.hops) ? data.hops.length : 0;
  12827. const statHops = document.getElementById('tools-mtr-hops-count');
  12828. if (statHops) statHops.innerText = `${hopsCount} Hops`;
  12829. const tbody = document.getElementById('tools-mtr-tbody');
  12830. if (tbody) {
  12831. if (hopsCount > 0) {
  12832. tbody.innerHTML = data.hops.map(h => {
  12833. 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');
  12834. return `
  12835. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  12836. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  12837. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(h.host || '--')}</td>
  12838. <td class="py-2.5 px-3 ${lossClass}">${h.loss_pct.toFixed(1)}%</td>
  12839. <td class="py-2.5 px-3 text-slate-300">${h.sent}</td>
  12840. <td class="py-2.5 px-3 text-slate-300">${h.last_ms.toFixed(1)}</td>
  12841. <td class="py-2.5 px-3 font-bold text-amber-300">${h.avg_ms.toFixed(1)}</td>
  12842. <td class="py-2.5 px-3 text-emerald-400">${h.best_ms.toFixed(1)}</td>
  12843. <td class="py-2.5 px-3 text-rose-400">${h.wrst_ms.toFixed(1)}</td>
  12844. <td class="py-2.5 px-3 text-slate-400">${h.stdev_ms.toFixed(1)}</td>
  12845. </tr>
  12846. `;
  12847. }).join('');
  12848. } else {
  12849. tbody.innerHTML = `<tr><td colspan="9" class="p-4 text-center text-xs text-rose-400 font-mono">No MTR data collected</td></tr>`;
  12850. }
  12851. }
  12852. const rawEl = document.getElementById('tools-mtr-raw');
  12853. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  12854. showToast('MTR Finished', `Report completed (${hopsCount} hops discovered)`, 'info');
  12855. } catch (err) {
  12856. showToast('MTR Error', err.message, 'error');
  12857. } finally {
  12858. if (btn) btn.disabled = false;
  12859. if (spinner) spinner.classList.add('hidden');
  12860. }
  12861. }
  12862. async function executeDNS(e) {
  12863. if (e) e.preventDefault();
  12864. const domain = document.getElementById('tools-dns-domain')?.value?.trim();
  12865. const type = document.getElementById('tools-dns-type')?.value || 'A';
  12866. const server = document.getElementById('tools-dns-server')?.value?.trim() || '';
  12867. if (!domain) {
  12868. showToast('Input Required', 'Please enter a hostname or domain', 'warning');
  12869. return;
  12870. }
  12871. const btn = document.getElementById('tools-dns-btn');
  12872. const spinner = document.getElementById('tools-dns-spinner');
  12873. if (btn) btn.disabled = true;
  12874. if (spinner) spinner.classList.remove('hidden');
  12875. try {
  12876. const res = await fetch(`${API_BASE}/tools/dns`, {
  12877. method: 'POST',
  12878. headers: { 'Content-Type': 'application/json' },
  12879. body: JSON.stringify({ domain, type, server })
  12880. });
  12881. const data = await res.json();
  12882. if (!res.ok) {
  12883. showToast('DNS Error', data.error || 'Failed to resolve DNS query', 'error');
  12884. return;
  12885. }
  12886. const resCard = document.getElementById('tools-dns-results');
  12887. if (resCard) resCard.classList.remove('hidden');
  12888. const metaEl = document.getElementById('tools-dns-meta');
  12889. if (metaEl) metaEl.innerText = `Resolved in ${data.query_time_ms ?? 0} ms via ${escapeHtml(data.server || 'System DNS')}`;
  12890. const tbody = document.getElementById('tools-dns-tbody');
  12891. if (tbody) {
  12892. if (Array.isArray(data.records) && data.records.length > 0) {
  12893. tbody.innerHTML = data.records.map(r => `
  12894. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  12895. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.name)}</td>
  12896. <td class="py-2.5 px-3 text-slate-400">${r.ttl}s</td>
  12897. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.class || 'IN')}</td>
  12898. <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>
  12899. <td class="py-2.5 px-3 font-bold text-amber-300 break-all">${escapeHtml(r.value)}</td>
  12900. </tr>
  12901. `).join('');
  12902. } else {
  12903. 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>`;
  12904. }
  12905. }
  12906. const rawEl = document.getElementById('tools-dns-raw');
  12907. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  12908. showToast('DNS Lookup Done', `Resolved ${domain} in ${data.query_time_ms} ms`, 'success');
  12909. } catch (err) {
  12910. showToast('DNS Error', err.message, 'error');
  12911. } finally {
  12912. if (btn) btn.disabled = false;
  12913. if (spinner) spinner.classList.add('hidden');
  12914. }
  12915. }
  12916. async function executePortProbe(e) {
  12917. if (e) e.preventDefault();
  12918. const target = document.getElementById('tools-port-target')?.value?.trim();
  12919. const port = parseInt(document.getElementById('tools-port-num')?.value || '80', 10);
  12920. const timeout = parseInt(document.getElementById('tools-port-timeout')?.value || '3', 10);
  12921. if (!target || !port) {
  12922. showToast('Input Required', 'Please enter a target host and TCP port', 'warning');
  12923. return;
  12924. }
  12925. const btn = document.getElementById('tools-port-btn');
  12926. const spinner = document.getElementById('tools-port-spinner');
  12927. if (btn) btn.disabled = true;
  12928. if (spinner) spinner.classList.remove('hidden');
  12929. try {
  12930. const res = await fetch(`${API_BASE}/tools/port-probe`, {
  12931. method: 'POST',
  12932. headers: { 'Content-Type': 'application/json' },
  12933. body: JSON.stringify({ target, port, timeout })
  12934. });
  12935. const data = await res.json();
  12936. if (!res.ok) {
  12937. showToast('Probe Error', data.error || 'Failed to probe TCP port', 'error');
  12938. return;
  12939. }
  12940. const resCard = document.getElementById('tools-port-results');
  12941. if (resCard) resCard.classList.remove('hidden');
  12942. const banner = document.getElementById('tools-port-banner');
  12943. const icon = document.getElementById('tools-port-icon');
  12944. const title = document.getElementById('tools-port-title');
  12945. const sub = document.getElementById('tools-port-sub');
  12946. const latency = document.getElementById('tools-port-latency');
  12947. if (data.open) {
  12948. if (banner) banner.className = 'rounded-xl p-5 border bg-emerald-950/30 border-emerald-800/50 flex items-center justify-between';
  12949. if (icon) {
  12950. 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';
  12951. icon.innerText = '✓';
  12952. }
  12953. if (title) {
  12954. title.className = 'text-sm font-bold text-emerald-300';
  12955. title.innerText = `PORT ${port} OPEN / LISTENING`;
  12956. }
  12957. if (sub) {
  12958. sub.className = 'text-xs mt-0.5 font-mono text-emerald-400/80';
  12959. sub.innerText = `TCP 3-way handshake established with ${escapeHtml(target)}:${port}${data.service ? ' (' + escapeHtml(data.service) + ')' : ''}`;
  12960. }
  12961. if (latency) {
  12962. latency.className = 'text-base font-bold font-mono text-emerald-300';
  12963. latency.innerText = `${data.latency_ms.toFixed(2)} ms`;
  12964. }
  12965. } else {
  12966. if (banner) banner.className = 'rounded-xl p-5 border bg-rose-950/30 border-rose-800/50 flex items-center justify-between';
  12967. if (icon) {
  12968. 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';
  12969. icon.innerText = '✕';
  12970. }
  12971. if (title) {
  12972. title.className = 'text-sm font-bold text-rose-300';
  12973. title.innerText = `PORT ${port} CLOSED / FILTERED`;
  12974. }
  12975. if (sub) {
  12976. sub.className = 'text-xs mt-0.5 font-mono text-rose-400/80';
  12977. sub.innerText = `Connection failed or timed out to ${escapeHtml(target)}:${port}`;
  12978. }
  12979. if (latency) {
  12980. latency.className = 'text-base font-bold font-mono text-slate-500';
  12981. latency.innerText = '--';
  12982. }
  12983. }
  12984. const rawEl = document.getElementById('tools-port-raw');
  12985. 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'}`);
  12986. showToast('Probe Complete', `Port ${port} is ${data.open ? 'OPEN' : 'CLOSED'}`, data.open ? 'success' : 'warning');
  12987. } catch (err) {
  12988. showToast('Probe Error', err.message, 'error');
  12989. } finally {
  12990. if (btn) btn.disabled = false;
  12991. if (spinner) spinner.classList.add('hidden');
  12992. }
  12993. }
  12994. // ==========================================
  12995. // DHCP CLIENT (/ip dhcp-client) CONTROLLER
  12996. // ==========================================
  12997. async function loadDHCPClients(showToastMsg = false) {
  12998. try {
  12999. const [clientsRes, sumRes] = await Promise.all([
  13000. fetch(`${API_BASE}/dhcp/clients`),
  13001. fetch(`${API_BASE}/dhcp/clients/summary`)
  13002. ]);
  13003. if (clientsRes.ok) {
  13004. state.dhcpClients = await clientsRes.json();
  13005. }
  13006. if (sumRes.ok) {
  13007. state.dhcpSummary = await sumRes.json();
  13008. }
  13009. renderDHCPClients();
  13010. updateDHCPSummaryCards();
  13011. const bDhcp = document.getElementById('badge-dhcp-client-count');
  13012. if (bDhcp && state.dhcpSummary) {
  13013. bDhcp.innerText = state.dhcpSummary.total_clients || 0;
  13014. }
  13015. if (showToastMsg) {
  13016. showToast('Refreshed', 'DHCP Client telemetry updated', 'info');
  13017. }
  13018. } catch (err) {
  13019. console.error('Failed to load DHCP clients:', err);
  13020. if (showToastMsg) {
  13021. showToast('Notice', 'Unable to fetch DHCP client status', 'warning');
  13022. }
  13023. }
  13024. }
  13025. function updateDHCPSummaryCards() {
  13026. const sum = state.dhcpSummary || {
  13027. total_clients: (state.dhcpClients || []).length,
  13028. bound_clients: (state.dhcpClients || []).filter(c => c.status === 'bound').length,
  13029. searching_clients: (state.dhcpClients || []).filter(c => c.status === 'searching').length,
  13030. disabled_clients: (state.dhcpClients || []).filter(c => !c.enabled).length
  13031. };
  13032. const totalEl = document.getElementById('dhcp-stat-total');
  13033. const boundEl = document.getElementById('dhcp-stat-bound');
  13034. const searchEl = document.getElementById('dhcp-stat-searching');
  13035. const disEl = document.getElementById('dhcp-stat-disabled');
  13036. if (totalEl) totalEl.innerText = sum.total_clients ?? 0;
  13037. if (boundEl) boundEl.innerText = sum.bound_clients ?? 0;
  13038. if (searchEl) searchEl.innerText = sum.searching_clients ?? 0;
  13039. if (disEl) disEl.innerText = sum.disabled_clients ?? 0;
  13040. }
  13041. function renderDHCPClients() {
  13042. const tbody = document.getElementById('dhcp-clients-tbody');
  13043. const emptyState = document.getElementById('dhcp-clients-empty');
  13044. if (!tbody) return;
  13045. const clients = Array.isArray(state.dhcpClients) ? state.dhcpClients : [];
  13046. if (clients.length === 0) {
  13047. tbody.innerHTML = '';
  13048. if (emptyState) emptyState.classList.remove('hidden');
  13049. return;
  13050. }
  13051. if (emptyState) emptyState.classList.add('hidden');
  13052. const sig = clients.map(c => `${c.id}:${c.status}:${c.ip_address}:${c.gateway}:${c.enabled}`).join(';');
  13053. if (tbody.dataset.sig === sig) return;
  13054. tbody.dataset.sig = sig;
  13055. tbody.innerHTML = clients.map(c => {
  13056. let statusBadge = '';
  13057. if (!c.enabled) {
  13058. 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>';
  13059. } else if (c.status === 'bound') {
  13060. 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>';
  13061. } else if (c.status === 'searching') {
  13062. 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>';
  13063. } else if (c.status === 'stopped') {
  13064. 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>';
  13065. } else {
  13066. 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>`;
  13067. }
  13068. 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>';
  13069. const gwDisplay = c.gateway ? `<span class="text-slate-300">${escapeHtml(c.gateway)}</span>` : '<span class="text-slate-600">--</span>';
  13070. const srvDisplay = c.dhcp_server ? `<span class="text-slate-300">${escapeHtml(c.dhcp_server)}</span>` : '<span class="text-slate-600">--</span>';
  13071. 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>';
  13072. const expDisplay = c.expires_in ? `<span class="text-purple-300">${escapeHtml(c.expires_in)}</span>` : '<span class="text-slate-600">--</span>';
  13073. // Option flags
  13074. const flags = [];
  13075. 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>');
  13076. 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>');
  13077. 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>');
  13078. 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>`);
  13079. return `
  13080. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 text-xs transition">
  13081. <td class="py-3 px-4">
  13082. <div class="flex items-center gap-2">
  13083. <span class="font-bold text-white text-sm">${escapeHtml(c.interface)}</span>
  13084. ${c.comment ? `<span class="text-[11px] text-slate-400 font-sans italic">(${escapeHtml(c.comment)})</span>` : ''}
  13085. </div>
  13086. </td>
  13087. <td class="py-3 px-4">${statusBadge}</td>
  13088. <td class="py-3 px-4 font-mono">${ipDisplay}</td>
  13089. <td class="py-3 px-4 font-mono">${gwDisplay}</td>
  13090. <td class="py-3 px-4 font-mono">${srvDisplay}</td>
  13091. <td class="py-3 px-4 font-mono text-[11px]">${dnsDisplay}</td>
  13092. <td class="py-3 px-4 font-mono text-[11px]">${expDisplay}</td>
  13093. <td class="py-3 px-4">
  13094. <div class="flex flex-wrap gap-1 font-mono">${flags.join('')}</div>
  13095. </td>
  13096. <td class="py-3 px-4 text-right space-x-1.5 font-sans whitespace-nowrap">
  13097. ${c.enabled ? `
  13098. <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>
  13099. <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>
  13100. <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>
  13101. ` : `
  13102. <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>
  13103. `}
  13104. <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>
  13105. <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>
  13106. </td>
  13107. </tr>
  13108. `;
  13109. }).join('');
  13110. }
  13111. function openDHCPClientModal(clientId = null) {
  13112. const modal = document.getElementById('modal-dhcp-client');
  13113. if (!modal) return;
  13114. const title = document.getElementById('modal-dhcp-title');
  13115. const idInput = document.getElementById('modal-dhcp-id');
  13116. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  13117. const distInput = document.getElementById('modal-dhcp-distance');
  13118. const commentInput = document.getElementById('modal-dhcp-comment');
  13119. const defRouteCheck = document.getElementById('modal-dhcp-def-route');
  13120. const peerDnsCheck = document.getElementById('modal-dhcp-peer-dns');
  13121. const peerNtpCheck = document.getElementById('modal-dhcp-peer-ntp');
  13122. const enabledCheck = document.getElementById('modal-dhcp-enabled');
  13123. // Populate interfaces
  13124. if (ifaceSelect) {
  13125. let opts = '<option value="">Select interface...</option>';
  13126. const allIfaces = state.interfaces || [];
  13127. const allVlans = state.vlans || [];
  13128. const usedIfaces = new Set((state.dhcpClients || []).map(c => c.interface));
  13129. // Group 1: Physical & Bridge Interfaces
  13130. opts += '<optgroup label="Physical & Bridge Interfaces">';
  13131. allIfaces.filter(i => supportsDHCPClient(i)).forEach(i => {
  13132. const isConfigured = usedIfaces.has(i.name) ? ' (Configured)' : '';
  13133. opts += `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)} [${escapeHtml(i.role || i.type)}]${isConfigured}</option>`;
  13134. });
  13135. opts += '</optgroup>';
  13136. // Group 2: VLAN Interfaces
  13137. if (allVlans.length > 0) {
  13138. opts += '<optgroup label="802.1Q VLAN Sub-interfaces">';
  13139. allVlans.forEach(v => {
  13140. const isConfigured = usedIfaces.has(v.name) ? ' (Configured)' : '';
  13141. opts += `<option value="${escapeHtml(v.name)}">${escapeHtml(v.name)} (VLAN ${v.vlan_id})${isConfigured}</option>`;
  13142. });
  13143. opts += '</optgroup>';
  13144. }
  13145. ifaceSelect.innerHTML = opts;
  13146. }
  13147. if (clientId) {
  13148. const client = (state.dhcpClients || []).find(c => c.id === clientId);
  13149. if (client) {
  13150. if (title) title.innerText = `Edit DHCP Client: ${client.interface}`;
  13151. if (idInput) idInput.value = client.id;
  13152. if (ifaceSelect) {
  13153. ifaceSelect.value = client.interface;
  13154. ifaceSelect.disabled = true; // interface cannot be changed on edit
  13155. }
  13156. if (distInput) distInput.value = client.default_route_distance || 1;
  13157. if (commentInput) commentInput.value = client.comment || '';
  13158. if (defRouteCheck) defRouteCheck.checked = client.add_default_route !== false;
  13159. if (peerDnsCheck) peerDnsCheck.checked = client.use_peer_dns !== false;
  13160. if (peerNtpCheck) peerNtpCheck.checked = client.use_peer_ntp !== false;
  13161. if (enabledCheck) enabledCheck.checked = client.enabled !== false;
  13162. }
  13163. } else {
  13164. if (title) title.innerText = 'Add DHCP Client';
  13165. if (idInput) idInput.value = '';
  13166. if (ifaceSelect) {
  13167. ifaceSelect.value = '';
  13168. ifaceSelect.disabled = false;
  13169. }
  13170. if (distInput) distInput.value = 1;
  13171. if (commentInput) commentInput.value = '';
  13172. if (defRouteCheck) defRouteCheck.checked = true;
  13173. if (peerDnsCheck) peerDnsCheck.checked = true;
  13174. if (peerNtpCheck) peerNtpCheck.checked = true;
  13175. if (enabledCheck) enabledCheck.checked = true;
  13176. }
  13177. modal.classList.remove('hidden');
  13178. }
  13179. function openDHCPClientModalForIface(ifaceName) {
  13180. openDHCPClientModal();
  13181. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  13182. if (ifaceSelect && ifaceName) {
  13183. ifaceSelect.value = ifaceName;
  13184. }
  13185. }
  13186. function closeDHCPClientModal() {
  13187. const modal = document.getElementById('modal-dhcp-client');
  13188. if (modal) modal.classList.add('hidden');
  13189. }
  13190. async function submitSaveDHCPClient(e) {
  13191. if (e) e.preventDefault();
  13192. const id = document.getElementById('modal-dhcp-id')?.value;
  13193. const iface = document.getElementById('modal-dhcp-iface')?.value?.trim();
  13194. const distance = parseInt(document.getElementById('modal-dhcp-distance')?.value || '1', 10);
  13195. const comment = document.getElementById('modal-dhcp-comment')?.value?.trim() || '';
  13196. const defRoute = document.getElementById('modal-dhcp-def-route')?.checked ?? true;
  13197. const peerDns = document.getElementById('modal-dhcp-peer-dns')?.checked ?? true;
  13198. const peerNtp = document.getElementById('modal-dhcp-peer-ntp')?.checked ?? true;
  13199. const enabled = document.getElementById('modal-dhcp-enabled')?.checked ?? true;
  13200. if (!id && !iface) {
  13201. showToast('Input Required', 'Please select an interface for the DHCP client', 'warning');
  13202. return;
  13203. }
  13204. try {
  13205. let res;
  13206. if (id) {
  13207. // PUT update
  13208. res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  13209. method: 'PUT',
  13210. headers: { 'Content-Type': 'application/json' },
  13211. body: JSON.stringify({
  13212. enabled,
  13213. add_default_route: defRoute,
  13214. default_route_distance: distance,
  13215. use_peer_dns: peerDns,
  13216. use_peer_ntp: peerNtp,
  13217. comment
  13218. })
  13219. });
  13220. } else {
  13221. // POST create
  13222. res = await fetch(`${API_BASE}/dhcp/clients`, {
  13223. method: 'POST',
  13224. headers: { 'Content-Type': 'application/json' },
  13225. body: JSON.stringify({
  13226. interface: iface,
  13227. enabled,
  13228. add_default_route: defRoute,
  13229. default_route_distance: distance,
  13230. use_peer_dns: peerDns,
  13231. use_peer_ntp: peerNtp,
  13232. comment
  13233. })
  13234. });
  13235. }
  13236. const data = await res.json();
  13237. if (!res.ok) {
  13238. showToast('Error', data.error || 'Failed to save DHCP client', 'error');
  13239. return;
  13240. }
  13241. closeDHCPClientModal();
  13242. showToast('Success', id ? 'DHCP Client updated successfully' : `DHCP Client activated on ${iface}`, 'success');
  13243. await loadDHCPClients();
  13244. fetchData(); // refresh interfaces list with new lease/status
  13245. } catch (err) {
  13246. showToast('Error', err.message, 'error');
  13247. }
  13248. }
  13249. async function toggleDHCPClientState(id, enabled) {
  13250. try {
  13251. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/state`, {
  13252. method: 'POST',
  13253. headers: { 'Content-Type': 'application/json' },
  13254. body: JSON.stringify({ enabled })
  13255. });
  13256. const data = await res.json();
  13257. if (!res.ok) {
  13258. showToast('Error', data.error || 'Failed to toggle client state', 'error');
  13259. return;
  13260. }
  13261. showToast('Updated', `DHCP client ${enabled ? 'enabled' : 'disabled'}`, 'info');
  13262. await loadDHCPClients();
  13263. fetchData();
  13264. } catch (err) {
  13265. showToast('Error', err.message, 'error');
  13266. }
  13267. }
  13268. async function renewDHCPClient(id) {
  13269. try {
  13270. showToast('Renewing...', 'Requesting DHCP lease renewal from upstream server', 'info');
  13271. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/renew`, {
  13272. method: 'POST'
  13273. });
  13274. const data = await res.json();
  13275. if (!res.ok) {
  13276. showToast('Error', data.error || 'Failed to renew lease', 'error');
  13277. return;
  13278. }
  13279. showToast('Lease Renewed', 'DHCP renewal signal sent successfully', 'success');
  13280. setTimeout(() => {
  13281. loadDHCPClients();
  13282. fetchData();
  13283. }, 1500);
  13284. } catch (err) {
  13285. showToast('Error', err.message, 'error');
  13286. }
  13287. }
  13288. async function releaseDHCPClient(id) {
  13289. try {
  13290. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/release`, {
  13291. method: 'POST'
  13292. });
  13293. const data = await res.json();
  13294. if (!res.ok) {
  13295. showToast('Error', data.error || 'Failed to release lease', 'error');
  13296. return;
  13297. }
  13298. showToast('Lease Released', 'DHCP lease released from upstream server', 'info');
  13299. await loadDHCPClients();
  13300. fetchData();
  13301. } catch (err) {
  13302. showToast('Error', err.message, 'error');
  13303. }
  13304. }
  13305. async function deleteDHCPClient(id, ifaceName) {
  13306. if (!confirm(`Are you sure you want to remove the DHCP Client on ${ifaceName}? The interface will release its dynamic IP.`)) {
  13307. return;
  13308. }
  13309. try {
  13310. const res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  13311. method: 'DELETE'
  13312. });
  13313. const data = await res.json();
  13314. if (!res.ok) {
  13315. showToast('Error', data.error || 'Failed to delete DHCP client', 'error');
  13316. return;
  13317. }
  13318. showToast('Deleted', `DHCP client removed from ${ifaceName}`, 'info');
  13319. await loadDHCPClients();
  13320. fetchData();
  13321. } catch (err) {
  13322. showToast('Error', err.message, 'error');
  13323. }
  13324. }
  13325. // ==================== DHCP SERVER (/ip dhcp-server) ====================
  13326. async function loadDHCPServer(populate = true) {
  13327. try {
  13328. const [sumRes, srvRes, netRes, leaseRes, optRes] = await Promise.all([
  13329. fetch(`${API_BASE}/dhcp-server/summary`),
  13330. fetch(`${API_BASE}/dhcp-server/servers`),
  13331. fetch(`${API_BASE}/dhcp-server/networks`),
  13332. fetch(`${API_BASE}/dhcp-server/leases`),
  13333. fetch(`${API_BASE}/dhcp-server/options`)
  13334. ]);
  13335. if (sumRes.ok) state.dhcpServerSummary = await sumRes.json();
  13336. if (srvRes.ok) state.dhcpServers = await srvRes.json();
  13337. if (netRes.ok) state.dhcpNetworks = await netRes.json();
  13338. if (leaseRes.ok) state.dhcpLeases = await leaseRes.json();
  13339. if (optRes.ok) state.dhcpOptions = await optRes.json();
  13340. const sum = state.dhcpServerSummary || {};
  13341. const srvs = state.dhcpServers || [];
  13342. const nets = state.dhcpNetworks || [];
  13343. const leases = state.dhcpLeases || [];
  13344. const opts = state.dhcpOptions || [];
  13345. // KPI Cards
  13346. const statActive = document.getElementById('dhcp-server-stat-active');
  13347. if (statActive) {
  13348. const activeCount = srvs.filter(s => s.running).length;
  13349. statActive.innerText = `${activeCount} / ${srvs.length}`;
  13350. }
  13351. const statLeases = document.getElementById('dhcp-server-stat-leases');
  13352. if (statLeases) {
  13353. statLeases.innerText = leases.length;
  13354. }
  13355. const statLeasesSub = document.getElementById('dhcp-server-stat-leases-sub');
  13356. if (statLeasesSub) {
  13357. const dyn = leases.filter(l => l.dynamic).length;
  13358. const st = leases.filter(l => !l.dynamic).length;
  13359. statLeasesSub.innerText = `${dyn} dynamic, ${st} static`;
  13360. }
  13361. const statNetworks = document.getElementById('dhcp-server-stat-networks');
  13362. if (statNetworks) {
  13363. statNetworks.innerText = nets.length;
  13364. }
  13365. // Subtab Badges
  13366. const bSrv = document.getElementById('dhcp-server-tab-badge-servers');
  13367. if (bSrv) bSrv.innerText = srvs.length;
  13368. const bNet = document.getElementById('dhcp-server-tab-badge-networks');
  13369. if (bNet) bNet.innerText = nets.length;
  13370. const bLease = document.getElementById('dhcp-server-tab-badge-leases');
  13371. if (bLease) bLease.innerText = leases.length;
  13372. const bOpt = document.getElementById('dhcp-server-tab-badge-options');
  13373. if (bOpt) bOpt.innerText = opts.length;
  13374. // Sidebar Badge
  13375. const sideBadge = document.getElementById('badge-dhcp-server-count');
  13376. if (sideBadge) sideBadge.innerText = leases.length || srvs.length;
  13377. renderCurrentDHCPServerTab();
  13378. } catch (err) {
  13379. console.error('Failed to load DHCP Server:', err);
  13380. }
  13381. }
  13382. function switchDHCPServerTab(tab) {
  13383. state.dhcpServerTab = tab;
  13384. const tabs = ['servers', 'networks', 'leases', 'options'];
  13385. tabs.forEach(t => {
  13386. const panel = document.getElementById(`dhcp-server-subtab-${t}`);
  13387. const btn = document.getElementById(`dhcp-server-tab-btn-${t}`);
  13388. if (panel) {
  13389. if (t === tab) panel.classList.remove('hidden');
  13390. else panel.classList.add('hidden');
  13391. }
  13392. if (btn) {
  13393. if (t === tab) {
  13394. 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';
  13395. } else {
  13396. 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';
  13397. }
  13398. }
  13399. });
  13400. const addBtn = document.getElementById('dhcp-server-primary-add-btn');
  13401. if (addBtn) {
  13402. if (tab === 'servers') addBtn.innerHTML = '<span>+ Add Server</span>';
  13403. else if (tab === 'networks') addBtn.innerHTML = '<span>+ Add Network</span>';
  13404. else if (tab === 'leases') addBtn.innerHTML = '<span>+ Add Static Lease</span>';
  13405. else if (tab === 'options') addBtn.innerHTML = '<span>+ Add Option</span>';
  13406. }
  13407. renderCurrentDHCPServerTab();
  13408. }
  13409. function handleDHCPServerPrimaryAdd() {
  13410. const tab = state.dhcpServerTab || 'servers';
  13411. if (tab === 'servers') openAddDHCPServerModal();
  13412. else if (tab === 'networks') openAddDHCPNetworkModal();
  13413. else if (tab === 'leases') openAddDHCPStaticLeaseModal();
  13414. else if (tab === 'options') openAddDHCPOptionModal();
  13415. }
  13416. function renderCurrentDHCPServerTab() {
  13417. const tab = state.dhcpServerTab || 'servers';
  13418. if (tab === 'servers') renderDHCPServers();
  13419. else if (tab === 'networks') renderDHCPNetworks();
  13420. else if (tab === 'leases') renderDHCPLeases();
  13421. else if (tab === 'options') renderDHCPOptions();
  13422. }
  13423. function renderDHCPServers() {
  13424. const tbody = document.getElementById('dhcp-server-tbody');
  13425. const empty = document.getElementById('dhcp-server-empty');
  13426. if (!tbody) return;
  13427. const servers = state.dhcpServers || [];
  13428. if (servers.length === 0) {
  13429. tbody.innerHTML = '';
  13430. empty?.classList.remove('hidden');
  13431. return;
  13432. }
  13433. empty?.classList.add('hidden');
  13434. const sig = servers.map(s => `${s.id}:${s.running}:${s.disabled}:${s.active_leases}:${s.interface}`).join(';');
  13435. if (tbody.dataset.sig === sig) return;
  13436. tbody.dataset.sig = sig;
  13437. tbody.innerHTML = '';
  13438. servers.forEach(s => {
  13439. const tr = document.createElement('tr');
  13440. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  13441. tr.innerHTML = `
  13442. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(s.running, s.disabled)}</td>
  13443. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(s.name)}</td>
  13444. <td class="py-2.5 px-3 font-mono text-cyan-400 font-semibold">${escapeHtml(s.interface)}</td>
  13445. <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>
  13446. <td class="py-2.5 px-3 font-mono text-emerald-400">${escapeHtml(s.address_pool)}</td>
  13447. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(s.lease_time || '12h')}</td>
  13448. <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>
  13449. <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>
  13450. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]" title="${escapeHtml(s.comment || '')}">${escapeHtml(s.comment || '-')}</td>
  13451. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  13452. <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>
  13453. <button onclick="openEditDHCPServerModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  13454. <button onclick="deleteDHCPServer('${s.id}', '${escapeHtml(s.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  13455. </td>
  13456. `;
  13457. tbody.appendChild(tr);
  13458. });
  13459. }
  13460. function renderDHCPNetworks() {
  13461. const tbody = document.getElementById('dhcp-networks-tbody');
  13462. const empty = document.getElementById('dhcp-networks-empty');
  13463. if (!tbody) return;
  13464. tbody.innerHTML = '';
  13465. const networks = state.dhcpNetworks || [];
  13466. if (networks.length === 0) {
  13467. empty?.classList.remove('hidden');
  13468. return;
  13469. }
  13470. empty?.classList.add('hidden');
  13471. networks.forEach(n => {
  13472. const tr = document.createElement('tr');
  13473. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  13474. const dnsStr = (n.dns_servers || []).join(', ') || '-';
  13475. const optionsChips = (n.dhcp_options || []).map(optId => {
  13476. const opt = (state.dhcpOptions || []).find(o => o.id === optId);
  13477. if (!opt) return '';
  13478. 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>`;
  13479. }).filter(Boolean).join('');
  13480. tr.innerHTML = `
  13481. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${escapeHtml(n.address)}</td>
  13482. <td class="py-2.5 px-3 font-mono text-cyan-300 font-semibold">${escapeHtml(n.gateway || '-')}</td>
  13483. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(n.netmask || '-')}</td>
  13484. <td class="py-2.5 px-3 font-mono text-slate-300 truncate max-w-[140px]" title="${escapeHtml(dnsStr)}">${escapeHtml(dnsStr)}</td>
  13485. <td class="py-2.5 px-3 font-mono text-slate-400">${escapeHtml(n.domain || '-')}</td>
  13486. <td class="py-2.5 px-3 font-mono">${optionsChips || '<span class="text-slate-600 font-sans">-</span>'}</td>
  13487. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(n.comment || '')}">${escapeHtml(n.comment || '-')}</td>
  13488. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  13489. <button onclick="openEditDHCPNetworkModal('${n.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  13490. <button onclick="deleteDHCPNetwork('${n.id}', '${escapeHtml(n.address)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  13491. </td>
  13492. `;
  13493. tbody.appendChild(tr);
  13494. });
  13495. }
  13496. function renderDHCPLeases() {
  13497. const tbody = document.getElementById('dhcp-leases-tbody');
  13498. const empty = document.getElementById('dhcp-leases-empty');
  13499. if (!tbody) return;
  13500. tbody.innerHTML = '';
  13501. const leases = state.dhcpLeases || [];
  13502. if (leases.length === 0) {
  13503. empty?.classList.remove('hidden');
  13504. return;
  13505. }
  13506. empty?.classList.add('hidden');
  13507. leases.forEach(l => {
  13508. const tr = document.createElement('tr');
  13509. tr.className = `hover:bg-slate-800/40 transition text-xs ${l.disabled ? 'opacity-50' : ''}`;
  13510. 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>';
  13511. const statusBadge = l.status === 'bound'
  13512. ? '<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>'
  13513. : l.status === 'static'
  13514. ? '<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>'
  13515. : '<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>';
  13516. const makeStaticBtn = l.dynamic
  13517. ? `<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>`
  13518. : `<button onclick="deleteDHCPStaticLease('${l.id}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Remove</button>`;
  13519. tr.innerHTML = `
  13520. <td class="py-2.5 px-3 text-center">${flag}</td>
  13521. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(l.address)}</td>
  13522. <td class="py-2.5 px-3 font-mono text-cyan-300">${escapeHtml(l.mac_address)}</td>
  13523. <td class="py-2.5 px-3 font-sans text-slate-200 font-medium">${escapeHtml(l.hostname || '*')}</td>
  13524. <td class="py-2.5 px-3 font-mono text-slate-400">${escapeHtml(l.server || 'all')}</td>
  13525. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(l.expires_in || 'never')}</td>
  13526. <td class="py-2.5 px-3">${statusBadge}</td>
  13527. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(l.comment || '')}">${escapeHtml(l.comment || '-')}</td>
  13528. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  13529. ${makeStaticBtn}
  13530. </td>
  13531. `;
  13532. tbody.appendChild(tr);
  13533. });
  13534. }
  13535. function renderDHCPOptions() {
  13536. const tbody = document.getElementById('dhcp-options-tbody');
  13537. const empty = document.getElementById('dhcp-options-empty');
  13538. if (!tbody) return;
  13539. tbody.innerHTML = '';
  13540. const options = state.dhcpOptions || [];
  13541. if (options.length === 0) {
  13542. empty?.classList.remove('hidden');
  13543. return;
  13544. }
  13545. empty?.classList.add('hidden');
  13546. options.forEach(o => {
  13547. const tr = document.createElement('tr');
  13548. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  13549. tr.innerHTML = `
  13550. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(o.name)}</td>
  13551. <td class="py-2.5 px-3 font-bold text-cyan-400 font-mono">${o.code}</td>
  13552. <td class="py-2.5 px-3 font-mono text-emerald-400 break-all max-w-xs">${escapeHtml(o.value)}</td>
  13553. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-xs" title="${escapeHtml(o.comment || '')}">${escapeHtml(o.comment || '-')}</td>
  13554. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  13555. <button onclick="openEditDHCPOptionModal('${o.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  13556. <button onclick="deleteDHCPOption('${o.id}', '${escapeHtml(o.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  13557. </td>
  13558. `;
  13559. tbody.appendChild(tr);
  13560. });
  13561. }
  13562. // ==================== MODALS & ACTIONS: SERVER ====================
  13563. function populateDHCPNetworkSelect(elemId, selectedVal) {
  13564. const sel = document.getElementById(elemId);
  13565. if (!sel) return;
  13566. sel.innerHTML = '<option value="">Select network subnet...</option>';
  13567. const networks = state.dhcpNetworks || [];
  13568. networks.forEach(n => {
  13569. const opt = document.createElement('option');
  13570. opt.value = n.address;
  13571. opt.innerText = `${n.address} (Gateway: ${n.gateway || 'None'}${n.comment ? ' - ' + n.comment : ''})`;
  13572. if (selectedVal && (selectedVal === n.address || selectedVal === n.id)) {
  13573. opt.selected = true;
  13574. }
  13575. sel.appendChild(opt);
  13576. });
  13577. }
  13578. function onDHCPServerNetworkChange() {
  13579. const netSel = document.getElementById('dhcp-server-modal-network');
  13580. if (!netSel) return;
  13581. const netVal = netSel.value;
  13582. if (!netVal) return;
  13583. const poolInput = document.getElementById('dhcp-server-modal-pool');
  13584. if (!poolInput) return;
  13585. // Auto-calculate suggested address pool based on subnet CIDR
  13586. const parts = netVal.split('/');
  13587. const ip = parts[0];
  13588. const cidr = parseInt(parts[1] || '24', 10);
  13589. if (cidr === 24) {
  13590. const octets = ip.split('.');
  13591. if (octets.length === 4) {
  13592. const base = `${octets[0]}.${octets[1]}.${octets[2]}`;
  13593. poolInput.value = `${base}.10-${base}.254`;
  13594. }
  13595. }
  13596. }
  13597. function openAddDHCPServerModal() {
  13598. document.getElementById('dhcp-server-modal-title').innerText = 'Add DHCP Server';
  13599. document.getElementById('dhcp-server-modal-id').value = '';
  13600. document.getElementById('dhcp-server-modal-name').value = `dhcp${(state.dhcpServers || []).length + 1}`;
  13601. document.getElementById('dhcp-server-modal-pool').value = '192.168.88.10-192.168.88.254';
  13602. document.getElementById('dhcp-server-modal-leasetime').value = '12h';
  13603. document.getElementById('dhcp-server-modal-comment').value = '';
  13604. document.getElementById('dhcp-server-modal-authoritative').checked = true;
  13605. document.getElementById('dhcp-server-modal-disabled').checked = false;
  13606. populateDHCPIfaceSelect('dhcp-server-modal-iface', '');
  13607. const networks = state.dhcpNetworks || [];
  13608. const defaultNet = networks.length > 0 ? networks[0].address : '';
  13609. populateDHCPNetworkSelect('dhcp-server-modal-network', defaultNet);
  13610. if (defaultNet) {
  13611. onDHCPServerNetworkChange();
  13612. }
  13613. document.getElementById('dhcp-server-instance-modal').classList.remove('hidden');
  13614. }
  13615. function openEditDHCPServerModal(id) {
  13616. const s = (state.dhcpServers || []).find(item => item.id === id);
  13617. if (!s) return;
  13618. document.getElementById('dhcp-server-modal-title').innerText = `Edit DHCP Server (${s.name})`;
  13619. document.getElementById('dhcp-server-modal-id').value = s.id;
  13620. document.getElementById('dhcp-server-modal-name').value = s.name;
  13621. document.getElementById('dhcp-server-modal-pool').value = s.address_pool;
  13622. document.getElementById('dhcp-server-modal-leasetime').value = s.lease_time || '12h';
  13623. document.getElementById('dhcp-server-modal-comment').value = s.comment || '';
  13624. document.getElementById('dhcp-server-modal-authoritative').checked = s.authoritative !== false;
  13625. document.getElementById('dhcp-server-modal-disabled').checked = !!s.disabled;
  13626. populateDHCPIfaceSelect('dhcp-server-modal-iface', s.interface);
  13627. populateDHCPNetworkSelect('dhcp-server-modal-network', s.network || '');
  13628. document.getElementById('dhcp-server-instance-modal').classList.remove('hidden');
  13629. }
  13630. function closeDHCPServerModal() {
  13631. document.getElementById('dhcp-server-instance-modal').classList.add('hidden');
  13632. }
  13633. async function submitSaveDHCPServer(e) {
  13634. e.preventDefault();
  13635. const id = document.getElementById('dhcp-server-modal-id').value;
  13636. const name = document.getElementById('dhcp-server-modal-name').value.trim();
  13637. const iface = document.getElementById('dhcp-server-modal-iface').value;
  13638. const network = document.getElementById('dhcp-server-modal-network').value.trim();
  13639. const pool = document.getElementById('dhcp-server-modal-pool').value.trim();
  13640. const leaseTime = document.getElementById('dhcp-server-modal-leasetime').value.trim() || '12h';
  13641. const comment = document.getElementById('dhcp-server-modal-comment').value.trim();
  13642. const authoritative = document.getElementById('dhcp-server-modal-authoritative').checked;
  13643. const disabled = document.getElementById('dhcp-server-modal-disabled').checked;
  13644. try {
  13645. const res = await fetch(`${API_BASE}/dhcp-server/servers`, {
  13646. method: 'POST',
  13647. headers: { 'Content-Type': 'application/json' },
  13648. body: JSON.stringify({
  13649. id,
  13650. name,
  13651. interface: iface,
  13652. network,
  13653. address_pool: pool,
  13654. lease_time: leaseTime,
  13655. authoritative,
  13656. disabled,
  13657. comment
  13658. })
  13659. });
  13660. if (res.ok) {
  13661. showToast('DHCP Server Saved', `Server ${name} configured successfully`, 'success');
  13662. closeDHCPServerModal();
  13663. loadDHCPServer(false);
  13664. fetchData(false);
  13665. } else {
  13666. const err = await res.text();
  13667. showToast('Error', err, 'error');
  13668. }
  13669. } catch (err) {
  13670. showToast('Error', err.message, 'error');
  13671. }
  13672. }
  13673. async function toggleDHCPServerState(id, disabled) {
  13674. try {
  13675. const res = await fetch(`${API_BASE}/dhcp-server/servers/${encodeURIComponent(id)}/state`, {
  13676. method: 'POST',
  13677. headers: { 'Content-Type': 'application/json' },
  13678. body: JSON.stringify({ disabled })
  13679. });
  13680. if (res.ok) {
  13681. showToast('State Updated', disabled ? 'Server disabled' : 'Server enabled', 'info');
  13682. loadDHCPServer(false);
  13683. fetchData(false);
  13684. }
  13685. } catch (err) {
  13686. showToast('Error', err.message, 'error');
  13687. }
  13688. }
  13689. async function deleteDHCPServer(id, name) {
  13690. if (!confirm(`Are you sure you want to delete DHCP Server "${name}"?`)) return;
  13691. try {
  13692. const res = await fetch(`${API_BASE}/dhcp-server/servers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  13693. if (res.ok) {
  13694. showToast('Deleted', `DHCP Server ${name} removed`, 'success');
  13695. loadDHCPServer(false);
  13696. fetchData(false);
  13697. }
  13698. } catch (err) {
  13699. showToast('Error', err.message, 'error');
  13700. }
  13701. }
  13702. // ==================== MODALS & ACTIONS: NETWORKS ====================
  13703. function openAddDHCPNetworkModal() {
  13704. document.getElementById('dhcp-network-modal-title').innerText = 'Add DHCP Network';
  13705. document.getElementById('dhcp-network-modal-id').value = '';
  13706. document.getElementById('dhcp-network-modal-address').value = '192.168.88.0/24';
  13707. document.getElementById('dhcp-network-modal-gateway').value = '192.168.88.1';
  13708. document.getElementById('dhcp-network-modal-dns').value = '192.168.88.1, 1.1.1.1, 8.8.8.8';
  13709. document.getElementById('dhcp-network-modal-domain').value = 'lan';
  13710. document.getElementById('dhcp-network-modal-netmask').value = '';
  13711. document.getElementById('dhcp-network-modal-comment').value = '';
  13712. renderDHCPNetworkOptionsCheckboxes([]);
  13713. document.getElementById('dhcp-network-modal').classList.remove('hidden');
  13714. }
  13715. function openEditDHCPNetworkModal(id) {
  13716. const n = (state.dhcpNetworks || []).find(item => item.id === id);
  13717. if (!n) return;
  13718. document.getElementById('dhcp-network-modal-title').innerText = `Edit DHCP Network (${n.address})`;
  13719. document.getElementById('dhcp-network-modal-id').value = n.id;
  13720. document.getElementById('dhcp-network-modal-address').value = n.address;
  13721. document.getElementById('dhcp-network-modal-gateway').value = n.gateway || '';
  13722. document.getElementById('dhcp-network-modal-dns').value = (n.dns_servers || []).join(', ');
  13723. document.getElementById('dhcp-network-modal-domain').value = n.domain || '';
  13724. document.getElementById('dhcp-network-modal-netmask').value = n.netmask || '';
  13725. document.getElementById('dhcp-network-modal-comment').value = n.comment || '';
  13726. renderDHCPNetworkOptionsCheckboxes(n.dhcp_options || []);
  13727. document.getElementById('dhcp-network-modal').classList.remove('hidden');
  13728. }
  13729. function renderDHCPNetworkOptionsCheckboxes(selectedIds) {
  13730. const container = document.getElementById('dhcp-network-modal-options-list');
  13731. if (!container) return;
  13732. container.innerHTML = '';
  13733. const opts = state.dhcpOptions || [];
  13734. if (opts.length === 0) {
  13735. container.innerHTML = '<span class="text-slate-500 text-[11px] col-span-2">No custom options configured. Add some in the "Options" tab.</span>';
  13736. return;
  13737. }
  13738. opts.forEach(o => {
  13739. const isChecked = selectedIds.includes(o.id);
  13740. const label = document.createElement('label');
  13741. label.className = 'flex items-center space-x-2 text-slate-300 hover:text-white cursor-pointer';
  13742. label.innerHTML = `
  13743. <input type="checkbox" name="dhcp-net-opt" value="${o.id}" ${isChecked ? 'checked' : ''} class="rounded bg-slate-800 border-slate-700 text-emerald-600">
  13744. <span class="truncate" title="${escapeHtml(o.name)} (Code ${o.code})">${escapeHtml(o.name)} <span class="text-cyan-400">#${o.code}</span></span>
  13745. `;
  13746. container.appendChild(label);
  13747. });
  13748. }
  13749. function closeDHCPNetworkModal() {
  13750. document.getElementById('dhcp-network-modal').classList.add('hidden');
  13751. }
  13752. async function submitSaveDHCPNetwork(e) {
  13753. e.preventDefault();
  13754. const id = document.getElementById('dhcp-network-modal-id').value;
  13755. const address = document.getElementById('dhcp-network-modal-address').value.trim();
  13756. const gateway = document.getElementById('dhcp-network-modal-gateway').value.trim();
  13757. const dnsStr = document.getElementById('dhcp-network-modal-dns').value.trim();
  13758. const domain = document.getElementById('dhcp-network-modal-domain').value.trim();
  13759. const netmask = document.getElementById('dhcp-network-modal-netmask').value.trim();
  13760. const comment = document.getElementById('dhcp-network-modal-comment').value.trim();
  13761. const selectedOpts = [];
  13762. document.querySelectorAll('input[name="dhcp-net-opt"]:checked').forEach(cb => selectedOpts.push(cb.value));
  13763. const dnsServers = dnsStr ? dnsStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  13764. try {
  13765. const res = await fetch(`${API_BASE}/dhcp-server/networks`, {
  13766. method: 'POST',
  13767. headers: { 'Content-Type': 'application/json' },
  13768. body: JSON.stringify({
  13769. id,
  13770. address,
  13771. gateway,
  13772. netmask,
  13773. dns_servers: dnsServers,
  13774. domain,
  13775. dhcp_options: selectedOpts,
  13776. comment
  13777. })
  13778. });
  13779. if (res.ok) {
  13780. showToast('Network Saved', `Subnet ${address} configured successfully`, 'success');
  13781. closeDHCPNetworkModal();
  13782. loadDHCPServer(false);
  13783. fetchData(false);
  13784. } else {
  13785. const err = await res.text();
  13786. showToast('Error', err, 'error');
  13787. }
  13788. } catch (err) {
  13789. showToast('Error', err.message, 'error');
  13790. }
  13791. }
  13792. async function deleteDHCPNetwork(id, addr) {
  13793. if (!confirm(`Are you sure you want to delete DHCP Network "${addr}"?`)) return;
  13794. try {
  13795. const res = await fetch(`${API_BASE}/dhcp-server/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  13796. if (res.ok) {
  13797. showToast('Deleted', `Network ${addr} removed`, 'success');
  13798. loadDHCPServer(false);
  13799. fetchData(false);
  13800. }
  13801. } catch (err) {
  13802. showToast('Error', err.message, 'error');
  13803. }
  13804. }
  13805. // ==================== MODALS & ACTIONS: LEASES ====================
  13806. function openAddDHCPStaticLeaseModal() {
  13807. document.getElementById('dhcp-static-lease-modal-title').innerText = 'Add Static Lease Reservation';
  13808. document.getElementById('dhcp-static-lease-modal-id').value = '';
  13809. document.getElementById('dhcp-static-lease-modal-mac').value = '';
  13810. document.getElementById('dhcp-static-lease-modal-ip').value = '';
  13811. document.getElementById('dhcp-static-lease-modal-hostname').value = '';
  13812. document.getElementById('dhcp-static-lease-modal-server').value = 'all';
  13813. document.getElementById('dhcp-static-lease-modal-comment').value = '';
  13814. document.getElementById('dhcp-static-lease-modal-disabled').checked = false;
  13815. document.getElementById('dhcp-static-lease-modal').classList.remove('hidden');
  13816. }
  13817. function closeDHCPStaticLeaseModal() {
  13818. document.getElementById('dhcp-static-lease-modal').classList.add('hidden');
  13819. }
  13820. async function submitSaveDHCPStaticLease(e) {
  13821. e.preventDefault();
  13822. const id = document.getElementById('dhcp-static-lease-modal-id').value;
  13823. const mac = document.getElementById('dhcp-static-lease-modal-mac').value.trim();
  13824. const ip = document.getElementById('dhcp-static-lease-modal-ip').value.trim();
  13825. const hostname = document.getElementById('dhcp-static-lease-modal-hostname').value.trim();
  13826. const server = document.getElementById('dhcp-static-lease-modal-server').value.trim() || 'all';
  13827. const comment = document.getElementById('dhcp-static-lease-modal-comment').value.trim();
  13828. const disabled = document.getElementById('dhcp-static-lease-modal-disabled').checked;
  13829. try {
  13830. const res = await fetch(`${API_BASE}/dhcp-server/leases/static`, {
  13831. method: 'POST',
  13832. headers: { 'Content-Type': 'application/json' },
  13833. body: JSON.stringify({
  13834. id,
  13835. mac_address: mac,
  13836. address: ip,
  13837. hostname,
  13838. server,
  13839. comment,
  13840. disabled
  13841. })
  13842. });
  13843. if (res.ok) {
  13844. showToast('Static Lease Saved', `IP ${ip} reserved for ${mac}`, 'success');
  13845. closeDHCPStaticLeaseModal();
  13846. loadDHCPServer(false);
  13847. fetchData(false);
  13848. } else {
  13849. const err = await res.text();
  13850. showToast('Error', err, 'error');
  13851. }
  13852. } catch (err) {
  13853. showToast('Error', err.message, 'error');
  13854. }
  13855. }
  13856. async function deleteDHCPStaticLease(id) {
  13857. if (!confirm('Are you sure you want to remove this static reservation?')) return;
  13858. try {
  13859. const res = await fetch(`${API_BASE}/dhcp-server/leases/${encodeURIComponent(id)}`, { method: 'DELETE' });
  13860. if (res.ok) {
  13861. showToast('Deleted', 'Static lease removed', 'success');
  13862. loadDHCPServer(false);
  13863. fetchData(false);
  13864. }
  13865. } catch (err) {
  13866. showToast('Error', err.message, 'error');
  13867. }
  13868. }
  13869. async function makeDHCPLeaseStatic(mac, ip, hostname, comment) {
  13870. try {
  13871. const res = await fetch(`${API_BASE}/dhcp-server/leases/make-static`, {
  13872. method: 'POST',
  13873. headers: { 'Content-Type': 'application/json' },
  13874. body: JSON.stringify({
  13875. mac_address: mac,
  13876. address: ip,
  13877. hostname,
  13878. comment: comment || 'Converted to static'
  13879. })
  13880. });
  13881. if (res.ok) {
  13882. showToast('Lease Made Static', `IP ${ip} permanently reserved for ${mac}`, 'success');
  13883. loadDHCPServer(false);
  13884. fetchData(false);
  13885. } else {
  13886. const err = await res.text();
  13887. showToast('Error', err, 'error');
  13888. }
  13889. } catch (err) {
  13890. showToast('Error', err.message, 'error');
  13891. }
  13892. }
  13893. // ==================== MODALS & ACTIONS: OPTIONS ====================
  13894. function openAddDHCPOptionModal() {
  13895. document.getElementById('dhcp-option-modal-title').innerText = 'Add DHCP Option';
  13896. document.getElementById('dhcp-option-modal-id').value = '';
  13897. document.getElementById('dhcp-option-modal-name').value = '';
  13898. document.getElementById('dhcp-option-modal-code').value = '';
  13899. document.getElementById('dhcp-option-modal-value').value = '';
  13900. document.getElementById('dhcp-option-modal-comment').value = '';
  13901. document.getElementById('dhcp-option-modal').classList.remove('hidden');
  13902. }
  13903. function openEditDHCPOptionModal(id) {
  13904. const o = (state.dhcpOptions || []).find(item => item.id === id);
  13905. if (!o) return;
  13906. document.getElementById('dhcp-option-modal-title').innerText = `Edit DHCP Option (${o.name})`;
  13907. document.getElementById('dhcp-option-modal-id').value = o.id;
  13908. document.getElementById('dhcp-option-modal-name').value = o.name;
  13909. document.getElementById('dhcp-option-modal-code').value = o.code;
  13910. document.getElementById('dhcp-option-modal-value').value = o.value;
  13911. document.getElementById('dhcp-option-modal-comment').value = o.comment || '';
  13912. document.getElementById('dhcp-option-modal').classList.remove('hidden');
  13913. }
  13914. function closeDHCPOptionModal() {
  13915. document.getElementById('dhcp-option-modal').classList.add('hidden');
  13916. }
  13917. async function submitSaveDHCPOption(e) {
  13918. e.preventDefault();
  13919. const id = document.getElementById('dhcp-option-modal-id').value;
  13920. const name = document.getElementById('dhcp-option-modal-name').value.trim();
  13921. const code = parseInt(document.getElementById('dhcp-option-modal-code').value);
  13922. const value = document.getElementById('dhcp-option-modal-value').value.trim();
  13923. const comment = document.getElementById('dhcp-option-modal-comment').value.trim();
  13924. try {
  13925. const res = await fetch(`${API_BASE}/dhcp-server/options`, {
  13926. method: 'POST',
  13927. headers: { 'Content-Type': 'application/json' },
  13928. body: JSON.stringify({ id, name, code, value, comment })
  13929. });
  13930. if (res.ok) {
  13931. showToast('Option Saved', `DHCP option ${name} (#${code}) configured`, 'success');
  13932. closeDHCPOptionModal();
  13933. loadDHCPServer(false);
  13934. fetchData(false);
  13935. } else {
  13936. const err = await res.text();
  13937. showToast('Error', err, 'error');
  13938. }
  13939. } catch (err) {
  13940. showToast('Error', err.message, 'error');
  13941. }
  13942. }
  13943. async function deleteDHCPOption(id, name) {
  13944. if (!confirm(`Are you sure you want to delete DHCP Option "${name}"?`)) return;
  13945. try {
  13946. const res = await fetch(`${API_BASE}/dhcp-server/options/${encodeURIComponent(id)}`, { method: 'DELETE' });
  13947. if (res.ok) {
  13948. showToast('Deleted', `Option ${name} removed`, 'success');
  13949. loadDHCPServer(false);
  13950. fetchData(false);
  13951. }
  13952. } catch (err) {
  13953. showToast('Error', err.message, 'error');
  13954. }
  13955. }
  13956. // ==================== WIZARD: DHCP SETUP (MikroTik style) ====================
  13957. function openDHCPServerSetupModal() {
  13958. populateDHCPIfaceSelect('dhcp-wizard-iface', '');
  13959. onDHCPWizardIfaceChange();
  13960. document.getElementById('dhcp-setup-wizard-modal').classList.remove('hidden');
  13961. }
  13962. function closeDHCPServerSetupModal() {
  13963. document.getElementById('dhcp-setup-wizard-modal').classList.add('hidden');
  13964. }
  13965. function onDHCPWizardIfaceChange() {
  13966. const ifaceName = document.getElementById('dhcp-wizard-iface').value;
  13967. const iface = (state.interfaces || []).find(i => i.name === ifaceName);
  13968. let ip = '192.168.88.1';
  13969. let prefix = '24';
  13970. if (iface && iface.ip_address) {
  13971. const parts = iface.ip_address.split('/');
  13972. ip = parts[0];
  13973. if (parts.length > 1) prefix = parts[1];
  13974. }
  13975. // Calculate subnet base (e.g. 192.168.88.0/24)
  13976. const ipParts = ip.split('.');
  13977. if (ipParts.length === 4) {
  13978. const baseSpace = `${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.0/${prefix}`;
  13979. const pool = `${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.10-${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.254`;
  13980. document.getElementById('dhcp-wizard-space').value = baseSpace;
  13981. document.getElementById('dhcp-wizard-gateway').value = ip;
  13982. document.getElementById('dhcp-wizard-pool').value = pool;
  13983. document.getElementById('dhcp-wizard-dns').value = `${ip}, 1.1.1.1, 8.8.8.8`;
  13984. document.getElementById('dhcp-wizard-ntp').value = `${ip}`;
  13985. }
  13986. }
  13987. async function submitDHCPServerSetupWizard(e) {
  13988. e.preventDefault();
  13989. const iface = document.getElementById('dhcp-wizard-iface').value;
  13990. const space = document.getElementById('dhcp-wizard-space').value.trim();
  13991. const gw = document.getElementById('dhcp-wizard-gateway').value.trim();
  13992. const pool = document.getElementById('dhcp-wizard-pool').value.trim();
  13993. const dnsStr = document.getElementById('dhcp-wizard-dns').value.trim();
  13994. const leaseTime = document.getElementById('dhcp-wizard-leasetime').value.trim() || '12h';
  13995. const ntpStr = document.getElementById('dhcp-wizard-ntp').value.trim();
  13996. const tftp = document.getElementById('dhcp-wizard-tftp').value.trim();
  13997. const dnsServers = dnsStr ? dnsStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  13998. const ntpServers = ntpStr ? ntpStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  13999. try {
  14000. const res = await fetch(`${API_BASE}/dhcp-server/setup`, {
  14001. method: 'POST',
  14002. headers: { 'Content-Type': 'application/json' },
  14003. body: JSON.stringify({
  14004. interface: iface,
  14005. address_space: space,
  14006. gateway: gw,
  14007. address_pool: pool,
  14008. dns_servers: dnsServers,
  14009. lease_time: leaseTime,
  14010. ntp_servers: ntpServers,
  14011. next_server: tftp
  14012. })
  14013. });
  14014. if (res.ok) {
  14015. showToast('DHCP Setup Complete', `DHCP Server setup finished on ${iface}`, 'success');
  14016. closeDHCPServerSetupModal();
  14017. loadDHCPServer(false);
  14018. fetchData(false);
  14019. } else {
  14020. const err = await res.text();
  14021. showToast('Error', err, 'error');
  14022. }
  14023. } catch (err) {
  14024. showToast('Error', err.message, 'error');
  14025. }
  14026. }
  14027. function populateDHCPIfaceSelect(elemId, selectedVal) {
  14028. const sel = document.getElementById(elemId);
  14029. if (!sel) return;
  14030. sel.innerHTML = '<option value="">Select interface...</option>';
  14031. const ifaces = state.interfaces || [];
  14032. ifaces.forEach(i => {
  14033. if (i.name === 'lo') return;
  14034. const opt = document.createElement('option');
  14035. opt.value = i.name;
  14036. const ipStr = i.ip_address ? ` (${i.ip_address})` : '';
  14037. opt.textContent = `${i.name}${ipStr} [${i.role || i.type || 'interface'}]`;
  14038. if (i.name === selectedVal) opt.selected = true;
  14039. sel.appendChild(opt);
  14040. });
  14041. }
  14042. // ==================== UNIVERSAL TABLE ORDERING / SORTING (WINBOX / WEBFIG STYLE) ====================
  14043. function initTableSorting() {
  14044. document.querySelectorAll('table').forEach(setupSortableTable);
  14045. }
  14046. function setupSortableTable(table) {
  14047. const thead = table.querySelector('thead');
  14048. const tbody = table.querySelector('tbody');
  14049. if (!thead || !tbody) return;
  14050. const headerRows = thead.querySelectorAll('tr');
  14051. if (headerRows.length === 0) return;
  14052. const ths = headerRows[headerRows.length - 1].querySelectorAll('th');
  14053. ths.forEach((th, colIdx) => {
  14054. if (th._sortBound) return;
  14055. th._sortBound = true;
  14056. const rawText = th.innerText.trim().toLowerCase();
  14057. const isActionsCol = rawText === 'actions' || (rawText === 'action' && th.classList.contains('text-right'));
  14058. const isCheckboxCol = !!th.querySelector('input[type="checkbox"]');
  14059. const isExpandCol = (th.classList.contains('w-8') || th.classList.contains('w-6')) && !rawText;
  14060. const isExplicitNoSort = th.classList.contains('no-sort') || th.getAttribute('data-sortable') === 'false';
  14061. if (isActionsCol || isCheckboxCol || isExpandCol || isExplicitNoSort) {
  14062. return;
  14063. }
  14064. th.classList.add('table-sortable', 'group');
  14065. if (!th.title) th.title = 'Click to sort (Ascending / Descending / Default)';
  14066. let icon = th.querySelector('.table-sort-icon');
  14067. if (!icon) {
  14068. icon = document.createElement('span');
  14069. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  14070. icon.innerHTML = '⇅';
  14071. th.appendChild(icon);
  14072. }
  14073. th.addEventListener('click', (e) => {
  14074. if (e.target.tagName === 'INPUT' || e.target.tagName === 'BUTTON' || e.target.closest('button, input')) return;
  14075. handleHeaderClick(table, th, colIdx);
  14076. });
  14077. });
  14078. if (!tbody._sortObserved) {
  14079. tbody._sortObserved = true;
  14080. let sortDebounceTimer = null;
  14081. const observer = new MutationObserver((mutations) => {
  14082. if (tbody._isSorting) return;
  14083. const hasChildChanges = mutations.some(m => m.type === 'childList' && m.addedNodes.length > 0);
  14084. if (!hasChildChanges) return;
  14085. clearTimeout(sortDebounceTimer);
  14086. sortDebounceTimer = setTimeout(() => {
  14087. if (tbody._isSorting) return;
  14088. if (table._activeSort && table._activeSort.dir !== 'none') {
  14089. applyTableSort(table, table._activeSort.colIdx, table._activeSort.dir, false);
  14090. } else {
  14091. tagOriginalRowOrder(tbody);
  14092. }
  14093. }, 50);
  14094. });
  14095. tbody._sortObserver = observer;
  14096. observer.observe(tbody, { childList: true });
  14097. }
  14098. tagOriginalRowOrder(tbody);
  14099. }
  14100. function tagOriginalRowOrder(tbody) {
  14101. let idx = 0;
  14102. Array.from(tbody.children).forEach(tr => {
  14103. if (!tr.querySelector('td[colspan]')) {
  14104. if (!tr.hasAttribute('data-orig-idx')) {
  14105. tr.setAttribute('data-orig-idx', idx++);
  14106. }
  14107. }
  14108. });
  14109. }
  14110. function handleHeaderClick(table, th, colIdx) {
  14111. const currentSort = table._activeSort || { colIdx: -1, dir: 'none' };
  14112. let newDir = 'asc';
  14113. if (currentSort.colIdx === colIdx) {
  14114. if (currentSort.dir === 'asc') newDir = 'desc';
  14115. else if (currentSort.dir === 'desc') newDir = 'none';
  14116. else newDir = 'asc';
  14117. } else {
  14118. newDir = 'asc';
  14119. }
  14120. table._activeSort = { colIdx, dir: newDir };
  14121. updateHeaderIcons(table, colIdx, newDir);
  14122. applyTableSort(table, colIdx, newDir, true);
  14123. }
  14124. function updateHeaderIcons(table, activeColIdx, dir) {
  14125. const thead = table.querySelector('thead');
  14126. if (!thead) return;
  14127. const ths = thead.querySelectorAll('th');
  14128. ths.forEach((th, idx) => {
  14129. const icon = th.querySelector('.table-sort-icon');
  14130. if (!icon) return;
  14131. if (idx === activeColIdx && dir !== 'none') {
  14132. icon.innerHTML = dir === 'asc' ? '▲' : '▼';
  14133. icon.className = 'table-sort-icon text-cyan-400 font-bold opacity-100';
  14134. th.classList.add('table-sorted-active');
  14135. } else {
  14136. icon.innerHTML = '⇅';
  14137. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  14138. th.classList.remove('table-sorted-active');
  14139. }
  14140. });
  14141. }
  14142. function applyTableSort(table, colIdx, dir, userInitiated) {
  14143. const tbody = table.querySelector('tbody');
  14144. if (!tbody || tbody.children.length <= 1) return;
  14145. tbody._isSorting = true;
  14146. tagOriginalRowOrder(tbody);
  14147. // Group parent rows and any attached drawer/sub-rows
  14148. const groups = [];
  14149. let currentGroup = null;
  14150. Array.from(tbody.children).forEach(tr => {
  14151. if (tr.querySelector('td[colspan]')) {
  14152. if (currentGroup) {
  14153. currentGroup.subRows.push(tr);
  14154. } else {
  14155. groups.push({ mainRow: tr, subRows: [] });
  14156. }
  14157. } else {
  14158. currentGroup = { mainRow: tr, subRows: [] };
  14159. groups.push(currentGroup);
  14160. }
  14161. });
  14162. if (dir === 'none') {
  14163. groups.sort((a, b) => {
  14164. const idxA = parseInt(a.mainRow.getAttribute('data-orig-idx') || '0', 10);
  14165. const idxB = parseInt(b.mainRow.getAttribute('data-orig-idx') || '0', 10);
  14166. return idxA - idxB;
  14167. });
  14168. } else {
  14169. groups.sort((a, b) => {
  14170. const cellA = a.mainRow.children[colIdx];
  14171. const cellB = b.mainRow.children[colIdx];
  14172. const res = compareTableCells(cellA, cellB);
  14173. return dir === 'asc' ? res : -res;
  14174. });
  14175. }
  14176. // Check if rows are already in correct order to avoid modifying DOM
  14177. let alreadyOrdered = true;
  14178. let childIdx = 0;
  14179. for (const g of groups) {
  14180. if (tbody.children[childIdx] !== g.mainRow) {
  14181. alreadyOrdered = false;
  14182. break;
  14183. }
  14184. childIdx++;
  14185. for (const sub of g.subRows) {
  14186. if (tbody.children[childIdx] !== sub) {
  14187. alreadyOrdered = false;
  14188. break;
  14189. }
  14190. childIdx++;
  14191. }
  14192. }
  14193. if (alreadyOrdered) {
  14194. tbody._isSorting = false;
  14195. return;
  14196. }
  14197. // Disconnect observer while re-ordering to prevent recursion and thrashing
  14198. if (tbody._sortObserver) {
  14199. tbody._sortObserver.disconnect();
  14200. }
  14201. // Re-append rows in sorted order
  14202. groups.forEach(g => {
  14203. tbody.appendChild(g.mainRow);
  14204. g.subRows.forEach(sub => tbody.appendChild(sub));
  14205. });
  14206. // Drain any queued mutations and re-connect observer
  14207. if (tbody._sortObserver) {
  14208. tbody._sortObserver.takeRecords();
  14209. tbody._sortObserver.observe(tbody, { childList: true });
  14210. }
  14211. tbody._isSorting = false;
  14212. }
  14213. function getCellRawText(cell) {
  14214. if (!cell) return '';
  14215. if (cell.hasAttribute('data-sort-value')) return cell.getAttribute('data-sort-value');
  14216. const input = cell.querySelector('input, select');
  14217. if (input) {
  14218. if (input.type === 'checkbox') return input.checked ? '1' : '0';
  14219. return input.value;
  14220. }
  14221. return cell.innerText.trim();
  14222. }
  14223. function parseTrafficToNumber(str) {
  14224. const m = str.match(/^([\d.,]+)\s*([KMGTkmgt]?[iI]?[Bb](?:ps|\/s)?)/);
  14225. if (!m) return null;
  14226. const num = parseFloat(m[1].replace(/,/g, ''));
  14227. if (isNaN(num)) return null;
  14228. const unit = m[2].toUpperCase();
  14229. let mult = 1;
  14230. if (unit.startsWith('K')) mult = 1024;
  14231. else if (unit.startsWith('M')) mult = 1024 * 1024;
  14232. else if (unit.startsWith('G')) mult = 1024 * 1024 * 1024;
  14233. else if (unit.startsWith('T')) mult = 1024 * 1024 * 1024 * 1024;
  14234. return num * mult;
  14235. }
  14236. function parseIpToNumber(str) {
  14237. const clean = str.replace(/^[!~]/, '').trim();
  14238. const m = clean.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(?:\/(\d{1,2}))?/);
  14239. if (!m) return null;
  14240. const o1 = parseInt(m[1], 10);
  14241. const o2 = parseInt(m[2], 10);
  14242. const o3 = parseInt(m[3], 10);
  14243. const o4 = parseInt(m[4], 10);
  14244. if (o1 > 255 || o2 > 255 || o3 > 255 || o4 > 255) return null;
  14245. return ((o1 * 256 + o2) * 256 + o3) * 256 + o4;
  14246. }
  14247. function parseCompoundPackets(str) {
  14248. const m = str.match(/^([\d,]+)p/);
  14249. if (!m) return null;
  14250. return parseInt(m[1].replace(/,/g, ''), 10);
  14251. }
  14252. function compareTableCells(cellA, cellB) {
  14253. const a = getCellRawText(cellA);
  14254. const b = getCellRawText(cellB);
  14255. if (a === '' && b !== '') return 1;
  14256. if (b === '' && a !== '') return -1;
  14257. if (a === b) return 0;
  14258. // 1. IP Addresses / CIDR
  14259. const ipA = parseIpToNumber(a);
  14260. const ipB = parseIpToNumber(b);
  14261. if (ipA !== null && ipB !== null) return ipA - ipB;
  14262. // 2. Packet counts (e.g. "1,250p / 45 KB")
  14263. const pktA = parseCompoundPackets(a);
  14264. const pktB = parseCompoundPackets(b);
  14265. if (pktA !== null && pktB !== null) return pktA - pktB;
  14266. // 3. Traffic / Throughput / Bytes (e.g. "1.2 MB", "500 KiB", "10 Gbps")
  14267. const trafA = parseTrafficToNumber(a);
  14268. const trafB = parseTrafficToNumber(b);
  14269. if (trafA !== null && trafB !== null) return trafA - trafB;
  14270. // 4. Numbers with '#' or formatted with commas (e.g. "#1", "24", "1,200")
  14271. const cleanNumA = a.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  14272. const cleanNumB = b.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  14273. const numA = Number(cleanNumA);
  14274. const numB = Number(cleanNumB);
  14275. if (!isNaN(numA) && !isNaN(numB) && cleanNumA !== '' && cleanNumB !== '') {
  14276. return numA - numB;
  14277. }
  14278. // 5. Natural case-insensitive string compare
  14279. return a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' });
  14280. }
  14281. // ==================== VRRP HIGH AVAILABILITY CONTROLLER ====================
  14282. async function loadVRRP(showToastNotification = false) {
  14283. try {
  14284. const [instRes, sumRes] = await Promise.all([
  14285. fetch(`${API_BASE}/vrrp/instances`),
  14286. fetch(`${API_BASE}/vrrp/summary`)
  14287. ]);
  14288. if (instRes.ok) {
  14289. state.vrrpInstances = await instRes.json();
  14290. renderVRRP();
  14291. }
  14292. if (sumRes.ok) {
  14293. state.vrrpSummary = await sumRes.json();
  14294. renderVRRPSummary();
  14295. }
  14296. if (showToastNotification) {
  14297. showToast('Refreshed', 'VRRP telemetry refreshed', 'info');
  14298. }
  14299. } catch (err) {
  14300. console.error('Failed to load VRRP:', err);
  14301. }
  14302. }
  14303. function renderVRRPSummary() {
  14304. const s = state.vrrpSummary || { total_instances: 0, master_instances: 0, backup_instances: 0 };
  14305. const elTotal = document.getElementById('vrrp-stat-total');
  14306. if (elTotal) elTotal.innerText = s.total_instances || 0;
  14307. const elMaster = document.getElementById('vrrp-stat-master');
  14308. if (elMaster) elMaster.innerText = s.master_instances || 0;
  14309. const elBackup = document.getElementById('vrrp-stat-backup');
  14310. if (elBackup) elBackup.innerText = s.backup_instances || 0;
  14311. const bCount = document.getElementById('badge-vrrp-count');
  14312. if (bCount) bCount.innerText = s.total_instances || 0;
  14313. const dot = document.getElementById('badge-vrrp-dot');
  14314. if (dot) {
  14315. if (s.master_instances > 0) {
  14316. dot.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  14317. } else if (s.backup_instances > 0) {
  14318. dot.className = 'w-2 h-2 rounded-full bg-sky-400';
  14319. } else {
  14320. dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  14321. }
  14322. }
  14323. }
  14324. function renderVRRP() {
  14325. const tbody = document.getElementById('vrrp-table-tbody');
  14326. const empty = document.getElementById('vrrp-table-empty');
  14327. if (!tbody) return;
  14328. tbody.innerHTML = '';
  14329. const instances = state.vrrpInstances || [];
  14330. if (instances.length === 0) {
  14331. empty?.classList.remove('hidden');
  14332. return;
  14333. }
  14334. empty?.classList.add('hidden');
  14335. instances.forEach(inst => {
  14336. const tr = document.createElement('tr');
  14337. tr.className = `hover:bg-slate-800/40 transition text-xs ${inst.disabled ? 'opacity-50' : ''}`;
  14338. // Render Flag: M (Master), B (Backup), F (Fault), X (Disabled)
  14339. 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>`;
  14340. if (inst.disabled) {
  14341. 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>`;
  14342. } else if (inst.state === 'MASTER') {
  14343. 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>`;
  14344. } else if (inst.state === 'BACKUP') {
  14345. 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>`;
  14346. } else if (inst.state === 'FAULT') {
  14347. 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>`;
  14348. }
  14349. // Render State Badge
  14350. let stateBadge = `<span class="px-2 py-0.5 rounded text-[10px] bg-slate-800 text-slate-400 border border-slate-700">DISABLED</span>`;
  14351. if (!inst.disabled) {
  14352. if (inst.state === 'MASTER') {
  14353. 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>`;
  14354. } else if (inst.state === 'BACKUP') {
  14355. 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>`;
  14356. } else if (inst.state === 'FAULT') {
  14357. 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>`;
  14358. }
  14359. }
  14360. const vipsStr = (inst.virtual_ips || []).join(', ') || '-';
  14361. tr.innerHTML = `
  14362. <td class="py-2.5 px-3 text-center">${flagHtml}</td>
  14363. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(inst.name)}</td>
  14364. <td class="py-2.5 px-3 font-mono text-cyan-400 font-semibold">${escapeHtml(inst.interface)}</td>
  14365. <td class="py-2.5 px-3 font-mono font-bold text-center text-white">${inst.vrid}</td>
  14366. <td class="py-2.5 px-3 font-mono text-center text-slate-300 font-semibold">${inst.priority}</td>
  14367. <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>
  14368. <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>
  14369. <td class="py-2.5 px-3 font-mono text-slate-400 text-[11px]">${escapeHtml(inst.virtual_mac || '-')}</td>
  14370. <td class="py-2.5 px-3 text-center">${stateBadge}</td>
  14371. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]" title="${escapeHtml(inst.comment || '')}">${escapeHtml(inst.comment || '-')}</td>
  14372. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  14373. <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>
  14374. <button onclick="openEditVRRPModal('${inst.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  14375. <button onclick="deleteVRRP('${inst.id}', '${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  14376. </td>
  14377. `;
  14378. tbody.appendChild(tr);
  14379. });
  14380. }
  14381. function populateVRRPIfaceSelect(elemId, selectedIface) {
  14382. const sel = document.getElementById(elemId);
  14383. if (!sel) return;
  14384. sel.innerHTML = '<option value="">Select interface...</option>';
  14385. const ifaces = state.interfaces || [];
  14386. ifaces.forEach(i => {
  14387. const opt = document.createElement('option');
  14388. opt.value = i.name;
  14389. opt.innerText = `${i.name} (${i.type || 'net'}${i.ip ? ' - ' + i.ip : ''})`;
  14390. if (selectedIface && selectedIface === i.name) opt.selected = true;
  14391. sel.appendChild(opt);
  14392. });
  14393. }
  14394. function openAddVRRPModal() {
  14395. document.getElementById('modal-vrrp-title').innerText = 'Add VRRP Instance';
  14396. document.getElementById('modal-vrrp-id').value = '';
  14397. document.getElementById('modal-vrrp-name').value = `vrrp${(state.vrrpInstances || []).length + 1}`;
  14398. document.getElementById('modal-vrrp-vrid').value = 10 + (state.vrrpInstances || []).length;
  14399. document.getElementById('modal-vrrp-priority').value = 100;
  14400. document.getElementById('modal-vrrp-vip').value = '192.168.88.254/24';
  14401. document.getElementById('modal-vrrp-version').value = '3';
  14402. document.getElementById('modal-vrrp-interval').value = 1;
  14403. document.getElementById('modal-vrrp-authtype').value = 'none';
  14404. document.getElementById('modal-vrrp-authpass').value = '';
  14405. document.getElementById('modal-vrrp-comment').value = '';
  14406. document.getElementById('modal-vrrp-preempt').checked = true;
  14407. document.getElementById('modal-vrrp-disabled').checked = false;
  14408. populateVRRPIfaceSelect('modal-vrrp-iface', '');
  14409. document.getElementById('modal-vrrp-instance').classList.remove('hidden');
  14410. }
  14411. function openEditVRRPModal(id) {
  14412. const inst = (state.vrrpInstances || []).find(item => item.id === id);
  14413. if (!inst) return;
  14414. document.getElementById('modal-vrrp-title').innerText = `Edit VRRP Instance (${inst.name})`;
  14415. document.getElementById('modal-vrrp-id').value = inst.id;
  14416. document.getElementById('modal-vrrp-name').value = inst.name;
  14417. document.getElementById('modal-vrrp-vrid').value = inst.vrid;
  14418. document.getElementById('modal-vrrp-priority').value = inst.priority;
  14419. document.getElementById('modal-vrrp-vip').value = (inst.virtual_ips || []).join(', ');
  14420. document.getElementById('modal-vrrp-version').value = String(inst.version || 3);
  14421. document.getElementById('modal-vrrp-interval').value = inst.interval || 1;
  14422. document.getElementById('modal-vrrp-authtype').value = inst.auth_type || 'none';
  14423. document.getElementById('modal-vrrp-authpass').value = inst.auth_password || '';
  14424. document.getElementById('modal-vrrp-comment').value = inst.comment || '';
  14425. document.getElementById('modal-vrrp-preempt').checked = inst.preempt !== false;
  14426. document.getElementById('modal-vrrp-disabled').checked = !!inst.disabled;
  14427. populateVRRPIfaceSelect('modal-vrrp-iface', inst.interface);
  14428. document.getElementById('modal-vrrp-instance').classList.remove('hidden');
  14429. }
  14430. function closeVRRPModal() {
  14431. document.getElementById('modal-vrrp-instance').classList.add('hidden');
  14432. }
  14433. async function submitSaveVRRP(e) {
  14434. e.preventDefault();
  14435. const id = document.getElementById('modal-vrrp-id').value;
  14436. const name = document.getElementById('modal-vrrp-name').value.trim();
  14437. const iface = document.getElementById('modal-vrrp-iface').value;
  14438. const vrid = parseInt(document.getElementById('modal-vrrp-vrid').value, 10) || 1;
  14439. const priority = parseInt(document.getElementById('modal-vrrp-priority').value, 10) || 100;
  14440. const vipRaw = document.getElementById('modal-vrrp-vip').value.trim();
  14441. const version = parseInt(document.getElementById('modal-vrrp-version').value, 10) || 3;
  14442. const interval = parseInt(document.getElementById('modal-vrrp-interval').value, 10) || 1;
  14443. const authType = document.getElementById('modal-vrrp-authtype').value;
  14444. const authPass = document.getElementById('modal-vrrp-authpass').value.trim();
  14445. const comment = document.getElementById('modal-vrrp-comment').value.trim();
  14446. const preempt = document.getElementById('modal-vrrp-preempt').checked;
  14447. const disabled = document.getElementById('modal-vrrp-disabled').checked;
  14448. const vips = vipRaw.split(',').map(s => s.trim()).filter(Boolean);
  14449. try {
  14450. const res = await fetch(`${API_BASE}/vrrp/instances`, {
  14451. method: 'POST',
  14452. headers: { 'Content-Type': 'application/json' },
  14453. body: JSON.stringify({
  14454. id,
  14455. name,
  14456. interface: iface,
  14457. vrid,
  14458. priority,
  14459. virtual_ips: vips,
  14460. version,
  14461. interval,
  14462. auth_type: authType,
  14463. auth_password: authPass,
  14464. comment,
  14465. preempt,
  14466. disabled
  14467. })
  14468. });
  14469. if (res.ok) {
  14470. showToast('VRRP Saved', `VRRP instance ${name} configured`, 'success');
  14471. closeVRRPModal();
  14472. loadVRRP(false);
  14473. fetchData(false);
  14474. } else {
  14475. const err = await res.text();
  14476. showToast('Error', err, 'error');
  14477. }
  14478. } catch (err) {
  14479. showToast('Error', err.message, 'error');
  14480. }
  14481. }
  14482. async function deleteVRRP(id, name) {
  14483. if (!confirm(`Delete VRRP instance "${name}"?`)) return;
  14484. try {
  14485. const res = await fetch(`${API_BASE}/vrrp/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  14486. if (res.ok) {
  14487. showToast('Deleted', `VRRP instance ${name} removed`, 'info');
  14488. loadVRRP(false);
  14489. fetchData(false);
  14490. } else {
  14491. const err = await res.text();
  14492. showToast('Error', err, 'error');
  14493. }
  14494. } catch (err) {
  14495. showToast('Error', err.message, 'error');
  14496. }
  14497. }
  14498. async function toggleVRRPState(id, disabled) {
  14499. try {
  14500. const res = await fetch(`${API_BASE}/vrrp/instances/${encodeURIComponent(id)}/state`, {
  14501. method: 'POST',
  14502. headers: { 'Content-Type': 'application/json' },
  14503. body: JSON.stringify({ disabled })
  14504. });
  14505. if (res.ok) {
  14506. showToast('State Updated', disabled ? 'VRRP disabled' : 'VRRP enabled', 'info');
  14507. loadVRRP(false);
  14508. fetchData(false);
  14509. } else {
  14510. const err = await res.text();
  14511. showToast('Error', err, 'error');
  14512. }
  14513. } catch (err) {
  14514. showToast('Error', err.message, 'error');
  14515. }
  14516. }
  14517. // Global observer for dynamically injected tables (e.g. inside modals or drawers)
  14518. if (typeof MutationObserver !== 'undefined' && typeof document !== 'undefined') {
  14519. let docSortDebounce = null;
  14520. const docTableObserver = new MutationObserver((mutations) => {
  14521. let needsInit = false;
  14522. for (const m of mutations) {
  14523. for (const node of m.addedNodes) {
  14524. if (node.nodeType === 1) {
  14525. if (node.tagName === 'TABLE' && !node.closest('tbody, thead')) {
  14526. needsInit = true;
  14527. break;
  14528. } else if (node.querySelector && !node.closest('table') && node.querySelector('table')) {
  14529. needsInit = true;
  14530. break;
  14531. }
  14532. }
  14533. }
  14534. if (needsInit) break;
  14535. }
  14536. if (needsInit) {
  14537. clearTimeout(docSortDebounce);
  14538. docSortDebounce = setTimeout(initTableSorting, 100);
  14539. }
  14540. });
  14541. docTableObserver.observe(document.body || document.documentElement, { childList: true, subtree: true });
  14542. }
  14543. // =========================================================================
  14544. // BANDWIDTH TEST (BwTest) BENCHMARK ENGINE
  14545. // =========================================================================
  14546. const bwtestState = {
  14547. running: false,
  14548. pollTimer: null,
  14549. eventSource: null,
  14550. chartPoints: [],
  14551. maxChartPoints: 60,
  14552. serverConfig: null,
  14553. peakTx: 0,
  14554. peakRx: 0,
  14555. targetDuration: 10,
  14556. lastSampleElapsed: -1,
  14557. sessionID: null
  14558. };
  14559. async function loadBwTestView() {
  14560. resizeBwTestCanvas();
  14561. await Promise.all([fetchBwTestServerStatus(), loadBwTestHistory(), checkActiveBwTest()]);
  14562. }
  14563. async function fetchBwTestServerStatus() {
  14564. try {
  14565. const res = await fetch(`${API_BASE}/tools/bwtest/server`);
  14566. if (!res.ok) return;
  14567. const s = await res.json();
  14568. bwtestState.serverConfig = s;
  14569. // Update indicator and badges
  14570. const indicator = document.getElementById('bwtest-server-indicator');
  14571. const badge = document.getElementById('bwtest-server-badge');
  14572. const sideBadge = document.getElementById('badge-bwtest-server');
  14573. if (s.enabled && s.running) {
  14574. if (indicator) indicator.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  14575. if (badge) {
  14576. badge.innerText = `Port ${s.port} (Active)`;
  14577. badge.className = 'text-emerald-400 font-bold';
  14578. }
  14579. if (sideBadge) {
  14580. sideBadge.innerText = s.port;
  14581. 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';
  14582. }
  14583. } else {
  14584. if (indicator) indicator.className = 'w-2 h-2 rounded-full bg-slate-600';
  14585. if (badge) {
  14586. badge.innerText = `Disabled`;
  14587. badge.className = 'text-slate-500 font-bold';
  14588. }
  14589. if (sideBadge) {
  14590. sideBadge.innerText = 'Off';
  14591. sideBadge.className = 'text-[10px] bg-slate-800 text-slate-500 border border-slate-700 px-1.5 py-0.2 rounded-full font-mono';
  14592. }
  14593. }
  14594. // Modal fields
  14595. const toggle = document.getElementById('bwtest-server-enable-toggle');
  14596. const serverModal = document.getElementById('modal-bwtest-server');
  14597. const editing = serverModal && !serverModal.classList.contains('hidden');
  14598. if (toggle && !editing) toggle.checked = !!s.enabled;
  14599. const portInp = document.getElementById('bwtest-server-port-input');
  14600. if (portInp && !editing) portInp.value = s.port || 2000;
  14601. const actSess = document.getElementById('bwtest-modal-active-sessions');
  14602. if (actSess) actSess.innerText = s.active_sessions || 0;
  14603. const totServ = document.getElementById('bwtest-modal-total-served');
  14604. if (totServ) totServ.innerText = s.total_sessions_served || 0;
  14605. const totBytes = document.getElementById('bwtest-modal-total-bytes');
  14606. if (totBytes) totBytes.innerText = formatBytes(s.total_bytes_processed || 0);
  14607. } catch (err) {
  14608. console.error('Failed to fetch BwTest server status:', err);
  14609. }
  14610. }
  14611. function openBwTestServerModal() {
  14612. const cfg = bwtestState.serverConfig;
  14613. if (cfg) {
  14614. document.getElementById('bwtest-server-enable-toggle').checked = !!cfg.enabled;
  14615. document.getElementById('bwtest-server-port-input').value = cfg.port || 2000;
  14616. }
  14617. fetchBwTestServerStatus();
  14618. document.getElementById('modal-bwtest-server')?.classList.remove('hidden');
  14619. }
  14620. function closeBwTestServerModal() {
  14621. document.getElementById('modal-bwtest-server')?.classList.add('hidden');
  14622. }
  14623. async function submitBwTestServerSettings(e) {
  14624. e.preventDefault();
  14625. const enabled = document.getElementById('bwtest-server-enable-toggle').checked;
  14626. const port = parseInt(document.getElementById('bwtest-server-port-input').value, 10) || 2000;
  14627. try {
  14628. const res = await fetch(`${API_BASE}/tools/bwtest/server`, {
  14629. method: 'POST',
  14630. headers: { 'Content-Type': 'application/json' },
  14631. body: JSON.stringify({ enabled, port, listen_addr: '0.0.0.0', allow_anonymous: true })
  14632. });
  14633. if (!res.ok) {
  14634. const err = await res.json();
  14635. throw new Error(err.error || 'Failed to update server configuration');
  14636. }
  14637. showToast('BwTest Server', `Bandwidth Test server updated (Port ${port})`, 'success');
  14638. closeBwTestServerModal();
  14639. fetchBwTestServerStatus();
  14640. } catch (err) {
  14641. showToast('Server Configuration Error', err.message, 'error');
  14642. }
  14643. }
  14644. function setBwTestTarget(target) {
  14645. const inp = document.getElementById('bwtest-input-target');
  14646. if (inp) inp.value = target;
  14647. }
  14648. function setBwTestProtocol(proto) {
  14649. const hiddenInp = document.getElementById('bwtest-input-protocol');
  14650. if (hiddenInp) hiddenInp.value = proto;
  14651. const btnUdp = document.getElementById('bwtest-proto-udp');
  14652. const btnTcp = document.getElementById('bwtest-proto-tcp');
  14653. const badge = document.getElementById('bwtest-proto-badge');
  14654. const pktField = document.getElementById('bwtest-field-pktsize');
  14655. 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';
  14656. 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';
  14657. 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';
  14658. if (proto === 'udp') {
  14659. if (btnUdp) {
  14660. btnUdp.className = activeUdpCls;
  14661. const dot = btnUdp.querySelector('span');
  14662. if (dot) dot.className = 'w-2 h-2 rounded-full bg-emerald-400';
  14663. }
  14664. if (btnTcp) {
  14665. btnTcp.className = inactiveCls;
  14666. const dot = btnTcp.querySelector('span');
  14667. if (dot) dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  14668. }
  14669. if (badge) {
  14670. badge.innerText = 'UDP Mode (RFC 3550 Jitter + Loss %)';
  14671. badge.className = 'text-[10px] font-mono text-emerald-400 bg-emerald-500/10 px-2 py-0.5 rounded border border-emerald-500/20';
  14672. }
  14673. if (pktField) pktField.classList.remove('opacity-40');
  14674. } else {
  14675. if (btnUdp) {
  14676. btnUdp.className = inactiveCls;
  14677. const dot = btnUdp.querySelector('span');
  14678. if (dot) dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  14679. }
  14680. if (btnTcp) {
  14681. btnTcp.className = activeTcpCls;
  14682. const dot = btnTcp.querySelector('span');
  14683. if (dot) dot.className = 'w-2 h-2 rounded-full bg-blue-400';
  14684. }
  14685. if (badge) {
  14686. badge.innerText = 'TCP Mode (Sliding Window Throughput)';
  14687. badge.className = 'text-[10px] font-mono text-blue-400 bg-blue-500/10 px-2 py-0.5 rounded border border-blue-500/20';
  14688. }
  14689. if (pktField) pktField.classList.add('opacity-40');
  14690. }
  14691. }
  14692. function setBwTestDirection(dir) {
  14693. const hiddenInp = document.getElementById('bwtest-input-direction');
  14694. if (hiddenInp) hiddenInp.value = dir;
  14695. const btnBoth = document.getElementById('bwtest-dir-both');
  14696. const btnTx = document.getElementById('bwtest-dir-tx');
  14697. const btnRx = document.getElementById('bwtest-dir-rx');
  14698. 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';
  14699. 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';
  14700. if (btnBoth) btnBoth.className = dir === 'both' ? activeCls : inactiveCls;
  14701. if (btnTx) btnTx.className = dir === 'tx' ? activeCls : inactiveCls;
  14702. if (btnRx) btnRx.className = dir === 'rx' ? activeCls : inactiveCls;
  14703. }
  14704. function setBwTestLimit(bps) {
  14705. const sel = document.getElementById('bwtest-input-limit');
  14706. if (sel) sel.value = String(bps);
  14707. }
  14708. async function checkActiveBwTest() {
  14709. try {
  14710. const res = await fetch(`${API_BASE}/tools/bwtest/status`);
  14711. if (!res.ok) return;
  14712. const st = await res.json();
  14713. if (st.running) {
  14714. setBwTestRunningUI(true);
  14715. processBwTestStatus(st);
  14716. startBwTestTelemetry();
  14717. }
  14718. } catch (err) {
  14719. console.error('Failed to check active BwTest:', err);
  14720. }
  14721. }
  14722. async function startBwTest(e) {
  14723. if (e && e.preventDefault) e.preventDefault();
  14724. const target = document.getElementById('bwtest-input-target').value.trim() || '127.0.0.1';
  14725. const port = parseInt(document.getElementById('bwtest-input-port').value, 10) || 2000;
  14726. const direction = document.getElementById('bwtest-input-direction').value || 'both';
  14727. const protocol = document.getElementById('bwtest-input-protocol').value || 'udp';
  14728. const bandwidth_limit = parseInt(document.getElementById('bwtest-input-limit').value, 10) || 0;
  14729. const packet_size = parseInt(document.getElementById('bwtest-input-pktsize').value, 10) || 1472;
  14730. const streams = parseInt(document.getElementById('bwtest-input-streams').value, 10) || 1;
  14731. const duration = parseInt(document.getElementById('bwtest-input-duration').value, 10);
  14732. bwtestState.targetDuration = duration;
  14733. bwtestState.chartPoints = [];
  14734. bwtestState.peakTx = 0;
  14735. bwtestState.peakRx = 0;
  14736. bwtestState.lastSampleElapsed = -1;
  14737. bwtestState.sessionID = null;
  14738. // Clear UI elements
  14739. document.getElementById('bwtest-stat-tx-mbps').innerText = '0.00';
  14740. document.getElementById('bwtest-stat-tx-peak').innerText = '0.00 Mbps';
  14741. document.getElementById('bwtest-stat-tx-pkts').innerText = '0';
  14742. document.getElementById('bwtest-stat-rx-mbps').innerText = '0.00';
  14743. document.getElementById('bwtest-stat-rx-peak').innerText = '0.00 Mbps';
  14744. document.getElementById('bwtest-stat-rx-pkts').innerText = '0';
  14745. document.getElementById('bwtest-stat-loss').innerText = '0.0%';
  14746. document.getElementById('bwtest-stat-jitter').innerText = '0.00 ms';
  14747. document.getElementById('bwtest-stat-time').innerText = '0.0s';
  14748. document.getElementById('bwtest-stat-data').innerText = '0.0 MB';
  14749. document.getElementById('bwtest-stat-target-dur').innerText = duration > 0 ? `/ ${duration}s` : '/ ∞';
  14750. const tbody = document.getElementById('bwtest-samples-tbody');
  14751. if (tbody) tbody.innerHTML = '';
  14752. document.getElementById('bwtest-sample-count').innerText = '0 samples';
  14753. setBwTestRunningUI(true);
  14754. try {
  14755. const res = await fetch(`${API_BASE}/tools/bwtest/start`, {
  14756. method: 'POST',
  14757. headers: { 'Content-Type': 'application/json' },
  14758. body: JSON.stringify({
  14759. target,
  14760. port,
  14761. direction,
  14762. protocol,
  14763. bandwidth_limit,
  14764. packet_size,
  14765. streams,
  14766. duration
  14767. })
  14768. });
  14769. if (!res.ok) {
  14770. const err = await res.json();
  14771. throw new Error(err.error || 'Failed to start bandwidth test');
  14772. }
  14773. showToast('Benchmark Started', `Target: ${target}:${port} (${direction.toUpperCase()}, ${protocol.toUpperCase()})`, 'info');
  14774. startBwTestTelemetry();
  14775. } catch (err) {
  14776. setBwTestRunningUI(false);
  14777. showToast('Start Failed', err.message, 'error');
  14778. }
  14779. }
  14780. function setBwTestRunningUI(running) {
  14781. bwtestState.running = running;
  14782. const startBtn = document.getElementById('bwtest-btn-start');
  14783. const stopBtn = document.getElementById('bwtest-btn-stop');
  14784. const badge = document.getElementById('bwtest-run-status-badge');
  14785. const ph = document.getElementById('bwtest-chart-placeholder');
  14786. if (running) {
  14787. if (startBtn) {
  14788. startBtn.disabled = true;
  14789. startBtn.classList.add('opacity-50', 'cursor-not-allowed');
  14790. }
  14791. if (stopBtn) {
  14792. stopBtn.disabled = false;
  14793. stopBtn.classList.remove('opacity-40');
  14794. }
  14795. if (badge) {
  14796. badge.innerText = 'TESTING...';
  14797. 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';
  14798. }
  14799. if (ph) ph.style.display = 'none';
  14800. } else {
  14801. if (startBtn) {
  14802. startBtn.disabled = false;
  14803. startBtn.classList.remove('opacity-50', 'cursor-not-allowed');
  14804. }
  14805. if (stopBtn) {
  14806. stopBtn.disabled = true;
  14807. stopBtn.classList.add('opacity-40');
  14808. }
  14809. if (badge) {
  14810. badge.innerText = 'IDLE';
  14811. badge.className = 'px-2 py-0.5 rounded text-[10px] font-mono bg-slate-800 text-slate-400 border border-slate-700 font-semibold';
  14812. }
  14813. }
  14814. }
  14815. async function stopBwTest() {
  14816. try {
  14817. const res = await fetch(`${API_BASE}/tools/bwtest/stop`, { method: 'POST' });
  14818. if (!res.ok) throw new Error(await responseError(res));
  14819. showToast('Stop Requested', 'Waiting for the bandwidth test to finish', 'info');
  14820. if (!bwtestState.pollTimer) startBwTestTelemetry();
  14821. } catch (err) {
  14822. showToast('Stop Failed', err.message, 'error');
  14823. }
  14824. }
  14825. async function responseError(res) {
  14826. const text = await res.text();
  14827. try { const data = JSON.parse(text); return data.message || (typeof data.error === 'string' ? data.error : null) || `HTTP ${res.status}`; }
  14828. catch { return text || `HTTP ${res.status}`; }
  14829. }
  14830. function processBwTestStatus(st) {
  14831. if (st.session_id && bwtestState.sessionID !== st.session_id) {
  14832. bwtestState.sessionID = st.session_id;
  14833. bwtestState.lastSampleElapsed = -1;
  14834. }
  14835. for (const sample of st.recent_samples || []) {
  14836. if (sample.elapsed_sec > (bwtestState.lastSampleElapsed ?? -1)) {
  14837. handleBwTestSample(sample);
  14838. bwtestState.lastSampleElapsed = sample.elapsed_sec;
  14839. }
  14840. }
  14841. if (!st.running) {
  14842. if (bwtestState.pollTimer) clearInterval(bwtestState.pollTimer);
  14843. bwtestState.pollTimer = null;
  14844. setBwTestRunningUI(false);
  14845. handleBwTestFinish(st.summary, st.error);
  14846. }
  14847. }
  14848. function startBwTestTelemetry() {
  14849. if (!state.currentUser) return;
  14850. if (bwtestState.pollTimer) clearInterval(bwtestState.pollTimer);
  14851. let busy = false;
  14852. const poll = async () => {
  14853. if (busy || !state.currentUser || document.hidden) return;
  14854. busy = true;
  14855. try {
  14856. const res = await fetch(`${API_BASE}/tools/bwtest/status`);
  14857. if (!res.ok) throw new Error(await responseError(res));
  14858. processBwTestStatus(await res.json());
  14859. } catch (err) {
  14860. console.error('BwTest polling error:', err);
  14861. } finally { busy = false; }
  14862. };
  14863. bwtestState.pollTimer = setInterval(poll, 400);
  14864. poll();
  14865. }
  14866. function handleBwTestSample(s) {
  14867. if (!s) return;
  14868. const payloadHint = document.getElementById('bwtest-effective-payload');
  14869. if (payloadHint && s.packet_size) payloadHint.innerText = `Effective datagram: ${s.packet_size} bytes`;
  14870. const txMbps = s.tx_mbps || 0;
  14871. const rxMbps = s.rx_mbps || 0;
  14872. if (txMbps > bwtestState.peakTx) bwtestState.peakTx = txMbps;
  14873. if (rxMbps > bwtestState.peakRx) bwtestState.peakRx = rxMbps;
  14874. // KPI updates
  14875. const elTx = document.getElementById('bwtest-stat-tx-mbps');
  14876. if (elTx) {
  14877. elTx.innerText = txMbps.toFixed(2);
  14878. elTx.title = `Confirmed by peer; locally offered: ${(s.offered_tx_mbps || 0).toFixed(2)} Mbps`;
  14879. }
  14880. const elTxPeak = document.getElementById('bwtest-stat-tx-peak');
  14881. if (elTxPeak) elTxPeak.innerText = `${bwtestState.peakTx.toFixed(2)} Mbps`;
  14882. const elTxPkts = document.getElementById('bwtest-stat-tx-pkts');
  14883. if (elTxPkts) elTxPkts.innerText = s.tx_packets || 0;
  14884. const elRx = document.getElementById('bwtest-stat-rx-mbps');
  14885. if (elRx) elRx.innerText = rxMbps.toFixed(2);
  14886. const elRxPeak = document.getElementById('bwtest-stat-rx-peak');
  14887. if (elRxPeak) elRxPeak.innerText = `${bwtestState.peakRx.toFixed(2)} Mbps`;
  14888. const elRxPkts = document.getElementById('bwtest-stat-rx-pkts');
  14889. if (elRxPkts) elRxPkts.innerText = s.rx_packets || 0;
  14890. const elLoss = document.getElementById('bwtest-stat-loss');
  14891. if (elLoss) {
  14892. elLoss.innerText = `${(s.loss_pct || 0).toFixed(1)}%`;
  14893. elLoss.className = (s.loss_pct > 1.0) ? 'text-2xl font-bold text-rose-400' : 'text-2xl font-bold text-emerald-400';
  14894. }
  14895. const elLostPkts = document.getElementById('bwtest-stat-lost-pkts');
  14896. if (elLostPkts) elLostPkts.innerText = s.lost_packets || 0;
  14897. const elJitter = document.getElementById('bwtest-stat-jitter');
  14898. if (elJitter) elJitter.innerText = `${(s.jitter_ms || 0).toFixed(2)} ms`;
  14899. const elTime = document.getElementById('bwtest-stat-time');
  14900. if (elTime) elTime.innerText = `${(s.elapsed_sec || 0).toFixed(1)}s`;
  14901. const elData = document.getElementById('bwtest-stat-data');
  14902. if (elData) elData.innerText = formatBytes((s.tx_bytes || 0) + (s.rx_bytes || 0));
  14903. const elGraphRate = document.getElementById('bwtest-graph-rate');
  14904. if (elGraphRate) elGraphRate.innerText = `TX: ${txMbps.toFixed(1)} Mbps • RX: ${rxMbps.toFixed(1)} Mbps`;
  14905. // Append point to chart buffer
  14906. bwtestState.chartPoints.push({
  14907. elapsed: s.elapsed_sec || 0,
  14908. tx: txMbps,
  14909. rx: rxMbps
  14910. });
  14911. if (bwtestState.chartPoints.length > bwtestState.maxChartPoints) {
  14912. bwtestState.chartPoints.shift();
  14913. }
  14914. drawBwTestChart();
  14915. // Add row to breakdown table
  14916. const tbody = document.getElementById('bwtest-samples-tbody');
  14917. if (tbody) {
  14918. const tr = document.createElement('tr');
  14919. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  14920. tr.innerHTML = `
  14921. <td class="py-1.5 px-3 font-semibold text-white">${(s.elapsed_sec || 0).toFixed(1)}s</td>
  14922. <td class="py-1.5 px-3 font-bold text-cyan-400">${txMbps.toFixed(2)} Mbps</td>
  14923. <td class="py-1.5 px-3 font-bold text-purple-400">${rxMbps.toFixed(2)} Mbps</td>
  14924. <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>
  14925. <td class="py-1.5 px-3 text-slate-300">${(s.jitter_ms || 0).toFixed(2)} ms</td>
  14926. <td class="py-1.5 px-3 text-slate-400">${formatBytes((s.tx_bytes || 0) + (s.rx_bytes || 0))}</td>
  14927. `;
  14928. tbody.insertBefore(tr, tbody.firstChild);
  14929. const countEl = document.getElementById('bwtest-sample-count');
  14930. if (countEl) countEl.innerText = `${tbody.children.length} samples`;
  14931. }
  14932. }
  14933. function handleBwTestFinish(summary, error) {
  14934. const badge = document.getElementById('bwtest-run-status-badge');
  14935. if (error) {
  14936. showToast('Benchmark Error', error, 'error');
  14937. if (badge) {
  14938. badge.innerText = 'ERROR';
  14939. 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';
  14940. }
  14941. } else if (summary) {
  14942. const avgTx = summary.avg_tx_mbps.toFixed(1);
  14943. const avgRx = summary.avg_rx_mbps.toFixed(1);
  14944. showToast('Benchmark Complete', `Average TX: ${avgTx} Mbps | RX: ${avgRx} Mbps (Loss: ${summary.avg_loss_pct.toFixed(1)}%)`, 'success');
  14945. if (badge) {
  14946. badge.innerText = 'COMPLETED';
  14947. 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';
  14948. }
  14949. }
  14950. loadBwTestHistory();
  14951. fetchBwTestServerStatus();
  14952. }
  14953. function resizeBwTestCanvas() {
  14954. const canvas = document.getElementById('bwtest-chart');
  14955. if (!canvas || !canvas.parentElement) return;
  14956. const rect = canvas.parentElement.getBoundingClientRect();
  14957. const dpr = window.devicePixelRatio || 1;
  14958. canvas.width = rect.width * dpr;
  14959. canvas.height = rect.height * dpr;
  14960. const ctx = canvas.getContext('2d');
  14961. ctx.scale(dpr, dpr);
  14962. drawBwTestChart();
  14963. }
  14964. window.addEventListener('resize', () => {
  14965. if (state.activeTab === 'bwtest') resizeBwTestCanvas();
  14966. });
  14967. function drawBwTestChart() {
  14968. const canvas = document.getElementById('bwtest-chart');
  14969. if (!canvas) return;
  14970. const ctx = canvas.getContext('2d');
  14971. const dpr = window.devicePixelRatio || 1;
  14972. const width = canvas.width / dpr;
  14973. const height = canvas.height / dpr;
  14974. ctx.clearRect(0, 0, width, height);
  14975. const points = bwtestState.chartPoints;
  14976. if (!points || points.length === 0) return;
  14977. // Determine scale ceiling
  14978. let maxRate = 10;
  14979. for (const p of points) {
  14980. if (p.tx > maxRate) maxRate = p.tx;
  14981. if (p.rx > maxRate) maxRate = p.rx;
  14982. }
  14983. maxRate = Math.ceil(maxRate * 1.25); // 25% headroom
  14984. const paddingLeft = 55;
  14985. const paddingBottom = 24;
  14986. const paddingTop = 12;
  14987. const paddingRight = 16;
  14988. const chartW = width - paddingLeft - paddingRight;
  14989. const chartH = height - paddingTop - paddingBottom;
  14990. // Grid Lines and Y-Axis labels
  14991. ctx.strokeStyle = 'rgba(51, 65, 85, 0.4)';
  14992. ctx.lineWidth = 1;
  14993. ctx.fillStyle = '#94a3b8';
  14994. ctx.font = '10px monospace';
  14995. ctx.textAlign = 'right';
  14996. const gridSteps = 4;
  14997. for (let i = 0; i <= gridSteps; i++) {
  14998. const val = (maxRate / gridSteps) * i;
  14999. const y = paddingTop + chartH - (i / gridSteps) * chartH;
  15000. ctx.beginPath();
  15001. ctx.moveTo(paddingLeft, y);
  15002. ctx.lineTo(width - paddingRight, y);
  15003. ctx.stroke();
  15004. ctx.fillText(`${Math.round(val)}M`, paddingLeft - 8, y + 3);
  15005. }
  15006. // Draw TX Line (Cyan #22d3ee)
  15007. drawSeries(ctx, points, p => p.tx, maxRate, paddingLeft, paddingTop, chartW, chartH, '#22d3ee', 'rgba(34, 211, 238, 0.15)');
  15008. // Draw RX Line (Purple #a855f7)
  15009. drawSeries(ctx, points, p => p.rx, maxRate, paddingLeft, paddingTop, chartW, chartH, '#a855f7', 'rgba(168, 85, 247, 0.15)');
  15010. }
  15011. function drawSeries(ctx, points, valFn, maxVal, left, top, w, h, strokeColor, fillColor) {
  15012. if (points.length < 2) return;
  15013. const stepX = w / Math.max(points.length - 1, 1);
  15014. // Gradient area fill
  15015. const grad = ctx.createLinearGradient(0, top, 0, top + h);
  15016. grad.addColorStop(0, fillColor);
  15017. grad.addColorStop(1, 'rgba(0, 0, 0, 0)');
  15018. ctx.beginPath();
  15019. points.forEach((p, idx) => {
  15020. const x = left + idx * stepX;
  15021. const val = valFn(p);
  15022. const y = top + h - (val / maxVal) * h;
  15023. if (idx === 0) {
  15024. ctx.moveTo(x, y);
  15025. } else {
  15026. ctx.lineTo(x, y);
  15027. }
  15028. });
  15029. // Complete path for fill
  15030. ctx.lineTo(left + (points.length - 1) * stepX, top + h);
  15031. ctx.lineTo(left, top + h);
  15032. ctx.closePath();
  15033. ctx.fillStyle = grad;
  15034. ctx.fill();
  15035. // Draw line stroke
  15036. ctx.beginPath();
  15037. ctx.lineWidth = 2.5;
  15038. ctx.strokeStyle = strokeColor;
  15039. points.forEach((p, idx) => {
  15040. const x = left + idx * stepX;
  15041. const val = valFn(p);
  15042. const y = top + h - (val / maxVal) * h;
  15043. if (idx === 0) {
  15044. ctx.moveTo(x, y);
  15045. } else {
  15046. ctx.lineTo(x, y);
  15047. }
  15048. });
  15049. ctx.stroke();
  15050. // Draw end point halo
  15051. const lastP = points[points.length - 1];
  15052. const lastX = left + (points.length - 1) * stepX;
  15053. const lastY = top + h - (valFn(lastP) / maxVal) * h;
  15054. ctx.fillStyle = strokeColor;
  15055. ctx.beginPath();
  15056. ctx.arc(lastX, lastY, 4, 0, 2 * Math.PI);
  15057. ctx.fill();
  15058. }
  15059. async function loadBwTestHistory() {
  15060. try {
  15061. const res = await fetch(`${API_BASE}/tools/bwtest/history`);
  15062. if (!res.ok) return;
  15063. const list = await res.json();
  15064. renderBwTestHistory(Array.isArray(list) ? list : []);
  15065. } catch (err) {
  15066. console.error('Failed to load BwTest history:', err);
  15067. }
  15068. }
  15069. function renderBwTestHistory(list) {
  15070. const tbody = document.getElementById('bwtest-history-tbody');
  15071. if (!tbody) return;
  15072. if (list.length === 0) {
  15073. 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>`;
  15074. return;
  15075. }
  15076. tbody.innerHTML = '';
  15077. list.forEach(item => {
  15078. const s = item.summary || {};
  15079. const tr = document.createElement('tr');
  15080. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  15081. const dirBadge = item.direction === 'both'
  15082. ? `<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>`
  15083. : item.direction === 'tx'
  15084. ? `<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>`
  15085. : `<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>`;
  15086. const protoBadge = item.protocol === 'tcp'
  15087. ? `<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>`
  15088. : `<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>`;
  15089. const dateStr = item.timestamp ? new Date(item.timestamp).toLocaleString() : '-';
  15090. tr.innerHTML = `
  15091. <td class="py-2.5 px-4 font-bold text-white font-mono text-[11px]">${escapeHtml(item.id || '-')}</td>
  15092. <td class="py-2.5 px-4 text-emerald-400 font-mono font-medium">${escapeHtml(item.target || '-')}</td>
  15093. <td class="py-2.5 px-4">${protoBadge}</td>
  15094. <td class="py-2.5 px-4">${dirBadge}</td>
  15095. <td class="py-2.5 px-4 text-slate-300">${(s.duration_sec || 0).toFixed(1)}s</td>
  15096. <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>
  15097. <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>
  15098. <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>
  15099. <td class="py-2.5 px-4 text-slate-300 font-mono">${(s.avg_jitter_ms || 0).toFixed(2)} ms</td>
  15100. <td class="py-2.5 px-4 text-slate-400 text-[11px] font-sans">${escapeHtml(dateStr)}</td>
  15101. `;
  15102. tbody.appendChild(tr);
  15103. });
  15104. }
  15105. // ======================== SETTINGS & ROUTER DNS ========================
  15106. state.settingsSubTab = 'dns';
  15107. state.dnsSettings = null;
  15108. state.dnsStaticRecords = [];
  15109. state.dnsStatus = null;
  15110. function switchSettingsSubTab(sub) {
  15111. state.settingsSubTab = sub;
  15112. const btnDns = document.getElementById('btn-settings-subtab-dns');
  15113. const btnSys = document.getElementById('btn-settings-subtab-system');
  15114. const btnBak = document.getElementById('btn-settings-subtab-backup');
  15115. const tabDns = document.getElementById('settings-subtab-dns');
  15116. const tabSys = document.getElementById('settings-subtab-system');
  15117. const tabBak = document.getElementById('settings-subtab-backup');
  15118. const activeClass = 'px-3.5 py-1.5 rounded-lg text-xs font-semibold bg-cyan-600 text-white transition flex items-center gap-1.5 cursor-pointer';
  15119. const inactiveClass = '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 cursor-pointer';
  15120. if (btnDns) btnDns.className = inactiveClass;
  15121. if (btnSys) btnSys.className = inactiveClass;
  15122. if (btnBak) btnBak.className = inactiveClass;
  15123. tabDns?.classList.add('hidden');
  15124. tabSys?.classList.add('hidden');
  15125. tabBak?.classList.add('hidden');
  15126. if (sub === 'dns') {
  15127. if (btnDns) btnDns.className = activeClass;
  15128. tabDns?.classList.remove('hidden');
  15129. loadDNSSettings();
  15130. } else if (sub === 'system') {
  15131. if (btnSys) btnSys.className = activeClass;
  15132. tabSys?.classList.remove('hidden');
  15133. loadSystemSettings();
  15134. } else if (sub === 'backup') {
  15135. if (btnBak) btnBak.className = activeClass;
  15136. tabBak?.classList.remove('hidden');
  15137. loadBackupList();
  15138. }
  15139. }
  15140. async function loadSettingsData(showLoading = false) {
  15141. if (state.settingsSubTab === 'system') {
  15142. await loadSystemSettings();
  15143. } else if (state.settingsSubTab === 'backup') {
  15144. await loadBackupList();
  15145. } else {
  15146. await loadDNSSettings();
  15147. }
  15148. }
  15149. async function loadDNSSettings() {
  15150. try {
  15151. const [settingsRes, staticRes, statusRes] = await Promise.all([
  15152. fetch(`${API_BASE}/dns/settings`),
  15153. fetch(`${API_BASE}/dns/static`),
  15154. fetch(`${API_BASE}/dns/status`)
  15155. ]);
  15156. if (settingsRes.ok) {
  15157. state.dnsSettings = await settingsRes.json();
  15158. populateDNSSettingsForm(state.dnsSettings);
  15159. }
  15160. if (staticRes.ok) {
  15161. state.dnsStaticRecords = await staticRes.json();
  15162. renderStaticDNSList();
  15163. }
  15164. if (statusRes.ok) {
  15165. state.dnsStatus = await statusRes.json();
  15166. updateDNSStatusView(state.dnsStatus);
  15167. }
  15168. } catch (err) {
  15169. console.error('Failed to load DNS settings:', err);
  15170. }
  15171. }
  15172. function populateDNSSettingsForm(s) {
  15173. if (!s) return;
  15174. const dnsForm = document.getElementById('form-dns-settings');
  15175. const isEditing = dnsForm && (dnsForm.contains(document.activeElement) || dnsForm.dataset.dirty === 'true');
  15176. const dynamicEl = document.getElementById('dns-dynamic-servers-list');
  15177. if (dynamicEl) {
  15178. if (Array.isArray(s.dynamic_servers) && s.dynamic_servers.length > 0) {
  15179. 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(' ');
  15180. } else {
  15181. dynamicEl.innerText = 'None';
  15182. }
  15183. }
  15184. // If user is actively typing or editing in the form, do not overwrite their inputs!
  15185. if (isEditing) return;
  15186. const serversInput = document.getElementById('dns-servers-input');
  15187. if (serversInput) serversInput.value = (s.servers || []).join(', ');
  15188. const cacheSizeInput = document.getElementById('dns-cache-size-input');
  15189. if (cacheSizeInput) cacheSizeInput.value = s.cache_size || 2048;
  15190. const domainInput = document.getElementById('dns-domain-input');
  15191. if (domainInput) domainInput.value = s.domain || '';
  15192. const allowRemoteInput = document.getElementById('dns-allow-remote-input');
  15193. if (allowRemoteInput) allowRemoteInput.checked = s.allow_remote_requests !== false;
  15194. }
  15195. function updateDNSStatusView(st) {
  15196. if (!st) return;
  15197. const preview = document.getElementById('dns-resolv-preview');
  15198. if (preview) preview.innerText = st.resolv_conf_content || '(empty)';
  15199. const pillText = document.getElementById('dns-live-status-text');
  15200. const pill = document.getElementById('dns-live-status-pill');
  15201. if (pill && pillText) {
  15202. if (st.service_running) {
  15203. 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';
  15204. pillText.innerText = 'DNS Service Active';
  15205. } else {
  15206. 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';
  15207. pillText.innerText = 'DNS Service Inactive';
  15208. }
  15209. }
  15210. }
  15211. function appendDNSPreset(preset) {
  15212. const input = document.getElementById('dns-servers-input');
  15213. if (!input) return;
  15214. const dnsForm = document.getElementById('form-dns-settings');
  15215. if (dnsForm) dnsForm.dataset.dirty = 'true';
  15216. const current = input.value.trim();
  15217. if (!current) {
  15218. input.value = preset;
  15219. } else {
  15220. const existing = current.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  15221. const toAdd = preset.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  15222. toAdd.forEach(ip => {
  15223. if (!existing.includes(ip)) existing.push(ip);
  15224. });
  15225. input.value = existing.join(', ');
  15226. }
  15227. }
  15228. async function saveDNSSettings(e) {
  15229. e.preventDefault();
  15230. const rawServers = document.getElementById('dns-servers-input')?.value || '';
  15231. const servers = rawServers.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  15232. if (servers.length === 0) {
  15233. showToast('Validation Error', 'Please enter at least one upstream DNS server IP', 'error');
  15234. return;
  15235. }
  15236. const cacheSize = parseInt(document.getElementById('dns-cache-size-input')?.value || '2048', 10);
  15237. const domain = (document.getElementById('dns-domain-input')?.value || '').trim();
  15238. const allowRemote = document.getElementById('dns-allow-remote-input')?.checked ?? true;
  15239. try {
  15240. const res = await fetch(`${API_BASE}/dns/settings`, {
  15241. method: 'POST',
  15242. headers: { 'Content-Type': 'application/json' },
  15243. body: JSON.stringify({
  15244. servers: servers,
  15245. cache_size: cacheSize,
  15246. domain: domain,
  15247. allow_remote_requests: allowRemote
  15248. })
  15249. });
  15250. const data = await res.json();
  15251. if (res.ok) {
  15252. const dnsForm = document.getElementById('form-dns-settings');
  15253. if (dnsForm) dnsForm.dataset.dirty = 'false';
  15254. showToast('DNS Applied', 'Router DNS forwarders and resolver settings updated successfully', 'success');
  15255. loadDNSSettings();
  15256. } else {
  15257. showToast('Error', data.error || data.message || 'Failed to save DNS settings', 'error');
  15258. }
  15259. } catch (err) {
  15260. showToast('Error', err.message, 'error');
  15261. }
  15262. }
  15263. async function flushDNSCache() {
  15264. try {
  15265. const res = await fetch(`${API_BASE}/dns/flush`, { method: 'POST' });
  15266. if (res.ok) {
  15267. showToast('Cache Flushed', 'Router DNS cache cleared and static hosts reloaded', 'success');
  15268. loadDNSSettings();
  15269. } else {
  15270. const err = await res.json();
  15271. showToast('Error', err.error || 'Failed to flush cache', 'error');
  15272. }
  15273. } catch (err) {
  15274. showToast('Error', err.message, 'error');
  15275. }
  15276. }
  15277. function renderStaticDNSList() {
  15278. const tbody = document.getElementById('dns-static-tbody');
  15279. const empty = document.getElementById('dns-static-empty');
  15280. const badge = document.getElementById('dns-static-count-badge');
  15281. if (!tbody) return;
  15282. tbody.innerHTML = '';
  15283. const records = state.dnsStaticRecords || [];
  15284. if (badge) badge.innerText = `${records.length} Records`;
  15285. if (records.length === 0) {
  15286. empty?.classList.remove('hidden');
  15287. return;
  15288. }
  15289. empty?.classList.add('hidden');
  15290. records.forEach(rec => {
  15291. const tr = document.createElement('tr');
  15292. tr.className = `hover:bg-slate-800/40 transition text-xs ${rec.disabled ? 'opacity-50' : ''}`;
  15293. tr.innerHTML = `
  15294. <td class="py-2.5 px-4 font-bold text-white">${escapeHtml(rec.name)}</td>
  15295. <td class="py-2.5 px-4">
  15296. <span class="px-2 py-0.5 rounded text-[10px] font-bold ${
  15297. rec.type === 'CNAME' ? 'bg-purple-950 text-purple-300 border border-purple-800' :
  15298. (rec.type === 'AAAA' ? 'bg-blue-950 text-blue-300 border border-blue-800' : 'bg-cyan-950 text-cyan-300 border border-cyan-800')
  15299. }">
  15300. ${rec.type || 'A'}
  15301. </span>
  15302. </td>
  15303. <td class="py-2.5 px-4 text-emerald-400 font-mono">${escapeHtml(rec.address)}</td>
  15304. <td class="py-2.5 px-4 text-slate-400 font-mono">${rec.ttl || 3600}s</td>
  15305. <td class="py-2.5 px-4 text-slate-400 italic truncate max-w-[140px]">${escapeHtml(rec.comment || '-')}</td>
  15306. <td class="py-2.5 px-4">
  15307. <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'}">
  15308. ${rec.disabled ? 'Disabled' : 'Active'}
  15309. </span>
  15310. </td>
  15311. <td class="py-2.5 px-4 text-right space-x-2 font-sans whitespace-nowrap">
  15312. <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>
  15313. <button onclick="openStaticDNSModal('${rec.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold">Edit</button>
  15314. <button onclick="deleteStaticDNS('${rec.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  15315. </td>
  15316. `;
  15317. tbody.appendChild(tr);
  15318. });
  15319. }
  15320. function openStaticDNSModal(id = null) {
  15321. const modal = document.getElementById('modal-static-dns');
  15322. const title = document.getElementById('modal-static-dns-title');
  15323. const form = document.getElementById('form-static-dns');
  15324. if (!modal || !form) return;
  15325. form.reset();
  15326. document.getElementById('modal-static-dns-id').value = '';
  15327. if (id) {
  15328. const rec = (state.dnsStaticRecords || []).find(r => r.id === id);
  15329. if (rec) {
  15330. if (title) title.innerText = 'Edit Static DNS Record';
  15331. document.getElementById('modal-static-dns-id').value = rec.id;
  15332. document.getElementById('modal-static-dns-name').value = rec.name;
  15333. document.getElementById('modal-static-dns-type').value = rec.type || 'A';
  15334. document.getElementById('modal-static-dns-addr').value = rec.address;
  15335. document.getElementById('modal-static-dns-ttl').value = rec.ttl || 3600;
  15336. document.getElementById('modal-static-dns-comment').value = rec.comment || '';
  15337. document.getElementById('modal-static-dns-disabled').checked = !!rec.disabled;
  15338. }
  15339. } else {
  15340. if (title) title.innerText = 'Add Static DNS Record';
  15341. }
  15342. modal.classList.remove('hidden');
  15343. }
  15344. function closeStaticDNSModal() {
  15345. document.getElementById('modal-static-dns')?.classList.add('hidden');
  15346. }
  15347. async function submitSaveStaticDNS(e) {
  15348. e.preventDefault();
  15349. const id = document.getElementById('modal-static-dns-id')?.value || '';
  15350. const name = (document.getElementById('modal-static-dns-name')?.value || '').trim();
  15351. const type = document.getElementById('modal-static-dns-type')?.value || 'A';
  15352. const address = (document.getElementById('modal-static-dns-addr')?.value || '').trim();
  15353. const ttl = parseInt(document.getElementById('modal-static-dns-ttl')?.value || '3600', 10);
  15354. const comment = (document.getElementById('modal-static-dns-comment')?.value || '').trim();
  15355. const disabled = document.getElementById('modal-static-dns-disabled')?.checked ?? false;
  15356. if (!name || !address) {
  15357. showToast('Validation Error', 'Name and Target Address are required', 'error');
  15358. return;
  15359. }
  15360. try {
  15361. const res = await fetch(`${API_BASE}/dns/static`, {
  15362. method: 'POST',
  15363. headers: { 'Content-Type': 'application/json' },
  15364. body: JSON.stringify({ id, name, type, address, ttl, comment, disabled })
  15365. });
  15366. const data = await res.json();
  15367. if (res.ok) {
  15368. showToast('Static DNS Saved', `Saved record ${name} -> ${address}`, 'success');
  15369. closeStaticDNSModal();
  15370. loadDNSSettings();
  15371. } else {
  15372. showToast('Error', data.error || data.message || 'Failed to save record', 'error');
  15373. }
  15374. } catch (err) {
  15375. showToast('Error', err.message, 'error');
  15376. }
  15377. }
  15378. async function deleteStaticDNS(id) {
  15379. if (!confirm('Are you sure you want to delete this static DNS entry?')) return;
  15380. try {
  15381. const res = await fetch(`${API_BASE}/dns/static/${encodeURIComponent(id)}`, { method: 'DELETE' });
  15382. if (res.ok) {
  15383. showToast('Deleted', 'Static DNS record deleted', 'success');
  15384. loadDNSSettings();
  15385. }
  15386. } catch (err) {
  15387. showToast('Error', err.message, 'error');
  15388. }
  15389. }
  15390. async function toggleStaticDNS(id, disabled) {
  15391. try {
  15392. const res = await fetch(`${API_BASE}/dns/static/${encodeURIComponent(id)}/state`, {
  15393. method: 'POST',
  15394. headers: { 'Content-Type': 'application/json' },
  15395. body: JSON.stringify({ disabled })
  15396. });
  15397. if (res.ok) {
  15398. showToast('Updated', `Record ${disabled ? 'disabled' : 'enabled'}`, 'success');
  15399. loadDNSSettings();
  15400. }
  15401. } catch (err) {
  15402. showToast('Error', err.message, 'error');
  15403. }
  15404. }
  15405. async function loadSystemSettings() {
  15406. try {
  15407. const sysForm = document.getElementById('form-system-settings');
  15408. const isEditing = sysForm && (sysForm.contains(document.activeElement) || sysForm.dataset.dirty === 'true');
  15409. const res = await fetch(`${API_BASE}/system/settings`);
  15410. if (res.ok) {
  15411. const data = await res.json();
  15412. if (!isEditing) {
  15413. const hostInput = document.getElementById('system-hostname-input');
  15414. if (hostInput) hostInput.value = data.hostname || '';
  15415. const tzInput = document.getElementById('system-timezone-input');
  15416. if (tzInput && data.timezone) tzInput.value = data.timezone;
  15417. }
  15418. }
  15419. } catch (err) {
  15420. console.error('Failed to load system settings:', err);
  15421. }
  15422. }
  15423. async function saveSystemSettings(e) {
  15424. e.preventDefault();
  15425. const hostname = (document.getElementById('system-hostname-input')?.value || '').trim();
  15426. const timezone = document.getElementById('system-timezone-input')?.value || 'UTC';
  15427. try {
  15428. const res = await fetch(`${API_BASE}/system/settings`, {
  15429. method: 'POST',
  15430. headers: { 'Content-Type': 'application/json' },
  15431. body: JSON.stringify({ hostname, timezone })
  15432. });
  15433. const data = await res.json();
  15434. if (res.ok) {
  15435. const sysForm = document.getElementById('form-system-settings');
  15436. if (sysForm) sysForm.dataset.dirty = 'false';
  15437. showToast('System Updated', 'Hostname and timezone saved successfully', 'success');
  15438. const sideH = document.getElementById('side-hostname');
  15439. if (sideH) sideH.innerText = data.hostname;
  15440. } else {
  15441. showToast('Error', data.error || 'Failed to save system settings', 'error');
  15442. }
  15443. } catch (err) {
  15444. showToast('Error', err.message, 'error');
  15445. }
  15446. }
  15447. // =============================================================================
  15448. // BACKUP & RESTORE MANAGER
  15449. // =============================================================================
  15450. state.selectedBackupFile = null;
  15451. state.inspectedBackupManifest = null;
  15452. state.pendingRestoreTarget = null;
  15453. state.backupsList = [];
  15454. async function exportBackupDownload() {
  15455. const btn = document.getElementById('btn-export-backup');
  15456. const commentInput = document.getElementById('backup-export-comment');
  15457. const comment = (commentInput?.value || '').trim();
  15458. const originalHtml = btn ? btn.innerHTML : '';
  15459. if (btn) {
  15460. btn.disabled = true;
  15461. btn.innerHTML = `<span class="w-3.5 h-3.5 rounded-full border-2 border-white border-t-transparent animate-spin inline-block"></span> Generating Backup...`;
  15462. }
  15463. try {
  15464. const res = await fetch(`${API_BASE}/system/backup/export?comment=${encodeURIComponent(comment)}`);
  15465. if (!res.ok) {
  15466. const err = await res.json().catch(() => ({}));
  15467. showToast('Export Failed', err.message || 'Failed to generate backup archive', 'error');
  15468. return;
  15469. }
  15470. const blob = await res.blob();
  15471. const disposition = res.headers.get('Content-Disposition') || '';
  15472. let filename = 'debtik-backup.zip';
  15473. const match = disposition.match(/filename="?([^";]+)"?/);
  15474. if (match && match[1]) {
  15475. filename = match[1];
  15476. }
  15477. const blobUrl = window.URL.createObjectURL(blob);
  15478. const a = document.createElement('a');
  15479. a.href = blobUrl;
  15480. a.download = filename;
  15481. document.body.appendChild(a);
  15482. a.click();
  15483. setTimeout(() => {
  15484. window.URL.revokeObjectURL(blobUrl);
  15485. a.remove();
  15486. }, 1000);
  15487. showToast('Backup Created', `Full configuration archive saved as ${filename}`, 'success');
  15488. } catch (err) {
  15489. showToast('Export Error', err.message || 'Network error during download', 'error');
  15490. } finally {
  15491. if (btn) {
  15492. btn.disabled = false;
  15493. btn.innerHTML = originalHtml;
  15494. }
  15495. }
  15496. }
  15497. async function onBackupFileSelected(e) {
  15498. const file = e.target.files?.[0];
  15499. if (!file) return;
  15500. const label = document.getElementById('backup-file-label');
  15501. if (label) {
  15502. label.innerText = `Selected: ${file.name} (${formatBytes(file.size)})`;
  15503. }
  15504. await inspectBackupFile(file);
  15505. }
  15506. async function inspectBackupFile(file) {
  15507. const preview = document.getElementById('backup-inspect-preview');
  15508. const restoreBtn = document.getElementById('btn-restore-backup');
  15509. const formData = new FormData();
  15510. formData.append('backup', file);
  15511. try {
  15512. const res = await fetch(`${API_BASE}/system/backup/inspect`, {
  15513. method: 'POST',
  15514. body: formData
  15515. });
  15516. const data = await res.json();
  15517. if (!res.ok || !data.success || !data.manifest) {
  15518. if (preview) preview.classList.add('hidden');
  15519. if (restoreBtn) restoreBtn.disabled = true;
  15520. showToast('Validation Error', data.message || 'Invalid or corrupted DebTik backup archive', 'error');
  15521. return;
  15522. }
  15523. const mf = data.manifest;
  15524. state.selectedBackupFile = file;
  15525. state.inspectedBackupManifest = mf;
  15526. const vEl = document.getElementById('backup-inspect-version');
  15527. const hEl = document.getElementById('backup-inspect-hostname');
  15528. const fEl = document.getElementById('backup-inspect-files');
  15529. const dEl = document.getElementById('backup-inspect-date');
  15530. const cEl = document.getElementById('backup-inspect-comment');
  15531. if (vEl) vEl.innerText = `DebTik v${escapeHtml(mf.debtik_version || '1.0')}`;
  15532. if (hEl) hEl.innerText = escapeHtml(mf.hostname || 'DebTik');
  15533. if (fEl) fEl.innerText = `${mf.files?.length || 0} items`;
  15534. if (dEl) dEl.innerText = mf.created_at ? new Date(mf.created_at).toLocaleString() : 'N/A';
  15535. if (cEl) cEl.innerText = mf.comment ? `"${escapeHtml(mf.comment)}"` : '';
  15536. if (preview) preview.classList.remove('hidden');
  15537. if (restoreBtn) restoreBtn.disabled = false;
  15538. } catch (err) {
  15539. if (preview) preview.classList.add('hidden');
  15540. if (restoreBtn) restoreBtn.disabled = true;
  15541. showToast('Inspection Failed', err.message || 'Failed to inspect backup file', 'error');
  15542. }
  15543. }
  15544. function confirmRestoreBackup(localFilename = null) {
  15545. const modal = document.getElementById('modal-restore-confirm');
  15546. const details = document.getElementById('modal-restore-details');
  15547. const progress = document.getElementById('modal-restore-progress');
  15548. const cancelBtn = document.getElementById('btn-cancel-restore');
  15549. const execBtn = document.getElementById('btn-execute-restore');
  15550. if (progress) progress.classList.add('hidden');
  15551. if (cancelBtn) cancelBtn.disabled = false;
  15552. if (execBtn) {
  15553. execBtn.disabled = false;
  15554. execBtn.innerText = 'Yes, Restore & Reload';
  15555. }
  15556. if (localFilename) {
  15557. state.pendingRestoreTarget = { type: 'local', filename: localFilename };
  15558. if (details) {
  15559. details.innerHTML = `<div>Source: <span class="text-white font-bold">Local Safety Backup</span></div>
  15560. <div>File: <span class="text-cyan-400 font-bold">${escapeHtml(localFilename)}</span></div>`;
  15561. }
  15562. } else {
  15563. if (!state.selectedBackupFile || !state.inspectedBackupManifest) {
  15564. showToast('Error', 'Please select a valid backup archive first', 'error');
  15565. return;
  15566. }
  15567. state.pendingRestoreTarget = { type: 'file', file: state.selectedBackupFile };
  15568. const mf = state.inspectedBackupManifest;
  15569. if (details) {
  15570. details.innerHTML = `<div>Archive: <span class="text-white font-bold">${escapeHtml(state.selectedBackupFile.name)}</span> (${formatBytes(state.selectedBackupFile.size)})</div>
  15571. <div>Origin Hostname: <span class="text-cyan-400 font-bold">${escapeHtml(mf.hostname)}</span></div>
  15572. <div>Created: <span class="text-slate-300">${mf.created_at ? new Date(mf.created_at).toLocaleString() : 'N/A'}</span></div>
  15573. <div>Files: <span class="text-emerald-400">${mf.files?.length || 0} configuration files</span></div>`;
  15574. }
  15575. }
  15576. if (modal) modal.classList.remove('hidden');
  15577. }
  15578. function closeRestoreModal() {
  15579. const modal = document.getElementById('modal-restore-confirm');
  15580. if (modal) modal.classList.add('hidden');
  15581. }
  15582. async function executeRestoreBackup() {
  15583. const target = state.pendingRestoreTarget;
  15584. if (!target) return;
  15585. const progress = document.getElementById('modal-restore-progress');
  15586. const progressText = document.getElementById('modal-restore-progress-text');
  15587. const cancelBtn = document.getElementById('btn-cancel-restore');
  15588. const execBtn = document.getElementById('btn-execute-restore');
  15589. if (cancelBtn) cancelBtn.disabled = true;
  15590. if (execBtn) execBtn.disabled = true;
  15591. if (progress) progress.classList.remove('hidden');
  15592. if (progressText) progressText.innerText = 'Restoring configuration files into appliance...';
  15593. try {
  15594. let res;
  15595. if (target.type === 'file') {
  15596. const formData = new FormData();
  15597. formData.append('backup', target.file);
  15598. res = await fetch(`${API_BASE}/system/backup/restore`, {
  15599. method: 'POST',
  15600. body: formData
  15601. });
  15602. } else {
  15603. res = await fetch(`${API_BASE}/system/backups/${encodeURIComponent(target.filename)}/restore`, {
  15604. method: 'POST'
  15605. });
  15606. }
  15607. const data = await res.json();
  15608. if (!res.ok || !data.success) {
  15609. showToast('Restore Failed', data.message || 'Error occurred while restoring configuration', 'error');
  15610. if (cancelBtn) cancelBtn.disabled = false;
  15611. if (execBtn) execBtn.disabled = false;
  15612. if (progress) progress.classList.add('hidden');
  15613. return;
  15614. }
  15615. if (progressText) {
  15616. progressText.innerText = 'Configuration applied! DebTik appliance is reloading services, reconnecting...';
  15617. }
  15618. pollAfterRestoreReconnect();
  15619. } catch (err) {
  15620. showToast('Restore Error', err.message || 'Network error during restore', 'error');
  15621. if (cancelBtn) cancelBtn.disabled = false;
  15622. if (execBtn) execBtn.disabled = false;
  15623. if (progress) progress.classList.add('hidden');
  15624. }
  15625. }
  15626. function pollAfterRestoreReconnect() {
  15627. let attempts = 0;
  15628. const maxAttempts = 25;
  15629. const timer = setInterval(async () => {
  15630. attempts++;
  15631. try {
  15632. const res = await fetch(`${API_BASE}/system/status`, { cache: 'no-store' });
  15633. if (res.ok) {
  15634. clearInterval(timer);
  15635. closeRestoreModal();
  15636. showToast('Restoration Complete', 'DebTik configuration restored and appliance is back online!', 'success');
  15637. setTimeout(() => {
  15638. window.location.reload();
  15639. }, 1200);
  15640. }
  15641. } catch (_) {
  15642. // Still restarting, retry
  15643. }
  15644. if (attempts >= maxAttempts) {
  15645. clearInterval(timer);
  15646. closeRestoreModal();
  15647. showToast('Reload Notice', 'Restore applied. Please refresh your browser to re-authenticate.', 'info');
  15648. }
  15649. }, 1500);
  15650. }
  15651. async function loadBackupList() {
  15652. const tbody = document.getElementById('backups-table-tbody');
  15653. const empty = document.getElementById('backups-empty-state');
  15654. if (!tbody) return;
  15655. try {
  15656. const res = await fetch(`${API_BASE}/system/backups`);
  15657. if (!res.ok) return;
  15658. const list = await res.json();
  15659. state.backupsList = list || [];
  15660. renderBackupsTable(state.backupsList);
  15661. } catch (err) {
  15662. console.error('Failed to load backup list:', err);
  15663. }
  15664. }
  15665. function renderBackupsTable(backups) {
  15666. const tbody = document.getElementById('backups-table-tbody');
  15667. const empty = document.getElementById('backups-empty-state');
  15668. if (!tbody) return;
  15669. if (!backups || backups.length === 0) {
  15670. tbody.innerHTML = '';
  15671. if (empty) empty.classList.remove('hidden');
  15672. return;
  15673. }
  15674. if (empty) empty.classList.add('hidden');
  15675. tbody.innerHTML = backups.map(bk => {
  15676. const isAuto = bk.filename && bk.filename.startsWith('pre-restore-');
  15677. const badge = isAuto
  15678. ? `<span class="px-2 py-0.5 rounded text-[9px] font-mono bg-amber-500/10 text-amber-300 border border-amber-500/20">PRE-RESTORE</span>`
  15679. : `<span class="px-2 py-0.5 rounded text-[9px] font-mono bg-cyan-500/10 text-cyan-300 border border-cyan-500/20">MANUAL</span>`;
  15680. const dateStr = bk.mod_time ? new Date(bk.mod_time).toLocaleString() : 'N/A';
  15681. return `<tr class="hover:bg-slate-800/40 transition">
  15682. <td class="py-3 px-4 font-bold text-white flex items-center gap-2">
  15683. ${badge}
  15684. <span>${escapeHtml(bk.filename)}</span>
  15685. </td>
  15686. <td class="py-3 px-4 text-slate-300">${escapeHtml(bk.debtik_version || '1.0')}</td>
  15687. <td class="py-3 px-4 text-cyan-400 font-bold">${escapeHtml(bk.hostname || 'DebTik')}</td>
  15688. <td class="py-3 px-4 text-slate-400">${dateStr}</td>
  15689. <td class="py-3 px-4 text-slate-300">${formatBytes(bk.size)}</td>
  15690. <td class="py-3 px-4 text-slate-400 italic">${escapeHtml(bk.comment || '—')}</td>
  15691. <td class="py-3 px-4 text-right space-x-2">
  15692. <button type="button" onclick="downloadLocalBackup('${escapeHtml(bk.filename)}')"
  15693. class="px-2.5 py-1 rounded-lg text-[11px] font-semibold bg-slate-800 hover:bg-slate-700 text-cyan-400 border border-slate-700 transition cursor-pointer">
  15694. Download
  15695. </button>
  15696. <button type="button" onclick="confirmRestoreBackup('${escapeHtml(bk.filename)}')"
  15697. class="px-2.5 py-1 rounded-lg text-[11px] font-semibold bg-amber-600/20 hover:bg-amber-600/30 text-amber-300 border border-amber-500/30 transition cursor-pointer">
  15698. Restore
  15699. </button>
  15700. </td>
  15701. </tr>`;
  15702. }).join('');
  15703. }
  15704. async function downloadLocalBackup(filename) {
  15705. try {
  15706. const res = await fetch(`${API_BASE}/system/backups/${encodeURIComponent(filename)}`);
  15707. if (!res.ok) {
  15708. showToast('Download Error', 'Failed to retrieve backup file', 'error');
  15709. return;
  15710. }
  15711. const blob = await res.blob();
  15712. const blobUrl = window.URL.createObjectURL(blob);
  15713. const a = document.createElement('a');
  15714. a.href = blobUrl;
  15715. a.download = filename;
  15716. document.body.appendChild(a);
  15717. a.click();
  15718. setTimeout(() => {
  15719. window.URL.revokeObjectURL(blobUrl);
  15720. a.remove();
  15721. }, 1000);
  15722. } catch (err) {
  15723. showToast('Download Error', err.message, 'error');
  15724. }
  15725. }
  15726. // =============================================================================
  15727. // AUTHENTICATION & USER MANAGER
  15728. // =============================================================================
  15729. async function checkAuthStatus() {
  15730. try {
  15731. const res = await originalFetch(`${API_BASE}/auth/me`, {
  15732. headers: {
  15733. 'Authorization': `Bearer ${localStorage.getItem('debtik_token') || ''}`
  15734. }
  15735. });
  15736. if (res.ok) {
  15737. const user = await res.json();
  15738. state.currentUser = user;
  15739. updateUserProfileHeader(user);
  15740. hideLoginScreen();
  15741. state.isPolling = true;
  15742. fetchData();
  15743. initLiveTrafficStream();
  15744. return true;
  15745. } else {
  15746. showLoginScreen(false);
  15747. return false;
  15748. }
  15749. } catch (err) {
  15750. showLoginScreen(false);
  15751. return false;
  15752. }
  15753. }
  15754. function showLoginScreen(isExpired = false) {
  15755. const el = document.getElementById('login-screen');
  15756. if (el) el.classList.remove('hidden');
  15757. const errEl = document.getElementById('login-error');
  15758. const errTxt = document.getElementById('login-error-text');
  15759. if (isExpired && errEl && errTxt) {
  15760. errTxt.innerText = 'Session expired. Please sign in again.';
  15761. errEl.classList.remove('hidden');
  15762. } else if (errEl) {
  15763. errEl.classList.add('hidden');
  15764. }
  15765. const pwInput = document.getElementById('login-password');
  15766. if (pwInput) pwInput.value = '';
  15767. const userInput = document.getElementById('login-username');
  15768. if (userInput && !userInput.value) userInput.focus();
  15769. else if (pwInput) pwInput.focus();
  15770. }
  15771. function hideLoginScreen() {
  15772. const el = document.getElementById('login-screen');
  15773. if (el) el.classList.add('hidden');
  15774. const errEl = document.getElementById('login-error');
  15775. if (errEl) errEl.classList.add('hidden');
  15776. }
  15777. async function handleLoginSubmit(event) {
  15778. event.preventDefault();
  15779. const username = (document.getElementById('login-username')?.value || '').trim();
  15780. const password = document.getElementById('login-password')?.value || '';
  15781. const errEl = document.getElementById('login-error');
  15782. const errTxt = document.getElementById('login-error-text');
  15783. const btn = document.getElementById('login-submit-btn');
  15784. const btnText = document.getElementById('login-btn-text');
  15785. const spinner = document.getElementById('login-btn-spinner');
  15786. if (!username || !password) {
  15787. if (errTxt) errTxt.innerText = 'Username and password are required.';
  15788. if (errEl) errEl.classList.remove('hidden');
  15789. return;
  15790. }
  15791. if (errEl) errEl.classList.add('hidden');
  15792. if (btn) btn.disabled = true;
  15793. if (btnText) btnText.innerText = 'Authenticating...';
  15794. if (spinner) spinner.classList.remove('hidden');
  15795. try {
  15796. const res = await originalFetch(`${API_BASE}/auth/login`, {
  15797. method: 'POST',
  15798. headers: { 'Content-Type': 'application/json' },
  15799. body: JSON.stringify({ username, password })
  15800. });
  15801. const data = await res.json();
  15802. if (res.ok && data.success) {
  15803. localStorage.setItem('debtik_token', data.token);
  15804. state.currentUser = data.user;
  15805. updateUserProfileHeader(data.user);
  15806. hideLoginScreen();
  15807. state.isPolling = true;
  15808. showToast('Authenticated', `Signed in as ${data.user.username}`, 'success');
  15809. const hash = window.location.hash.replace('#', '') || 'dashboard';
  15810. navigate(hash);
  15811. fetchData();
  15812. initLiveTrafficStream();
  15813. // Ensure background telemetry polling is active
  15814. if (!window._telemetryInterval) {
  15815. window._telemetryInterval = setInterval(() => {
  15816. if (state.isPolling && state.currentUser && !document.hidden) {
  15817. fetchData(false);
  15818. }
  15819. }, 5000);
  15820. }
  15821. } else {
  15822. if (errTxt) errTxt.innerText = data.message || 'Invalid username or password';
  15823. if (errEl) errEl.classList.remove('hidden');
  15824. }
  15825. } catch (err) {
  15826. if (errTxt) errTxt.innerText = err.message || 'Failed to connect to router';
  15827. if (errEl) errEl.classList.remove('hidden');
  15828. } finally {
  15829. if (btn) btn.disabled = false;
  15830. if (btnText) btnText.innerText = 'Sign In to Controller';
  15831. if (spinner) spinner.classList.add('hidden');
  15832. }
  15833. }
  15834. async function handleLogoutClick() {
  15835. try {
  15836. await originalFetch(`${API_BASE}/auth/logout`, {
  15837. method: 'POST',
  15838. headers: {
  15839. 'Authorization': `Bearer ${localStorage.getItem('debtik_token') || ''}`
  15840. }
  15841. });
  15842. } catch (e) {}
  15843. stopSessionPolling();
  15844. localStorage.removeItem('debtik_token');
  15845. state.currentUser = null;
  15846. state.isPolling = false;
  15847. if (window._telemetryInterval) {
  15848. clearInterval(window._telemetryInterval);
  15849. window._telemetryInterval = null;
  15850. }
  15851. if (trafficEventSource) {
  15852. trafficEventSource.close();
  15853. trafficEventSource = null;
  15854. }
  15855. if (trafficPollFallback) {
  15856. clearInterval(trafficPollFallback);
  15857. trafficPollFallback = null;
  15858. }
  15859. showLoginScreen(false);
  15860. showToast('Signed Out', 'You have been signed out successfully', 'info');
  15861. }
  15862. function togglePasswordVisibility(id) {
  15863. const input = document.getElementById(id);
  15864. if (!input) return;
  15865. input.type = input.type === 'password' ? 'text' : 'password';
  15866. }
  15867. function toggleUserMenu() {
  15868. const menu = document.getElementById('user-menu-dropdown');
  15869. if (menu) menu.classList.toggle('hidden');
  15870. }
  15871. function closeUserMenu() {
  15872. const menu = document.getElementById('user-menu-dropdown');
  15873. if (menu) menu.classList.add('hidden');
  15874. }
  15875. // Close user menu on outside click
  15876. document.addEventListener('click', (e) => {
  15877. const menu = document.getElementById('user-menu-dropdown');
  15878. if (!menu || menu.classList.contains('hidden')) return;
  15879. if (!e.target.closest('#user-menu-dropdown') && !e.target.closest('button[onclick*="toggleUserMenu"]')) {
  15880. menu.classList.add('hidden');
  15881. }
  15882. });
  15883. function updateUserProfileHeader(user) {
  15884. if (!user) return;
  15885. const navName = document.getElementById('nav-user-name');
  15886. if (navName) navName.innerText = user.username;
  15887. const dropName = document.getElementById('dropdown-user-name');
  15888. if (dropName) dropName.innerText = user.username;
  15889. const navRole = document.getElementById('nav-user-role');
  15890. if (navRole) navRole.innerText = (user.role || 'read').toUpperCase();
  15891. const navAvatar = document.getElementById('nav-user-avatar');
  15892. if (navAvatar) {
  15893. const initials = (user.username || 'AD').slice(0, 2).toUpperCase();
  15894. navAvatar.innerText = initials;
  15895. }
  15896. const statCurUser = document.getElementById('stat-current-user');
  15897. if (statCurUser) statCurUser.innerText = user.username;
  15898. const statCurRole = document.getElementById('stat-current-role');
  15899. if (statCurRole) statCurRole.innerText = (user.role || 'read').toUpperCase();
  15900. // Role permissions UI visibility: hide user management for non-admins
  15901. const isFullAdmin = user.role === 'full';
  15902. const navUsers = document.getElementById('nav-users');
  15903. if (navUsers) {
  15904. if (isFullAdmin) navUsers.classList.remove('hidden');
  15905. else navUsers.classList.add('hidden');
  15906. }
  15907. const dropdownUsers = document.getElementById('dropdown-item-users');
  15908. if (dropdownUsers) {
  15909. if (isFullAdmin) dropdownUsers.classList.remove('hidden');
  15910. else dropdownUsers.classList.add('hidden');
  15911. }
  15912. }
  15913. // ================= User Management CRUD =================
  15914. async function loadUsers(isManual = false) {
  15915. try {
  15916. const res = await fetch(`${API_BASE}/users`);
  15917. if (res.status === 403) {
  15918. const tbody = document.getElementById('users-table-tbody');
  15919. if (tbody) {
  15920. tbody.innerHTML = `
  15921. <tr>
  15922. <td colspan="6" class="p-6 text-center text-amber-400 font-sans">
  15923. <div class="inline-flex items-center gap-2">
  15924. <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>
  15925. <span>Viewing and managing users requires Super Administrator (full) permissions.</span>
  15926. </div>
  15927. </td>
  15928. </tr>
  15929. `;
  15930. }
  15931. return;
  15932. }
  15933. if (res.ok) {
  15934. state.users = await res.json();
  15935. renderUsersTable();
  15936. const totalUsers = document.getElementById('stat-total-users');
  15937. if (totalUsers) totalUsers.innerText = state.users.length;
  15938. const adminCount = state.users.filter(u => u.role === 'full' && !u.disabled).length;
  15939. const adminUsers = document.getElementById('stat-admin-users');
  15940. if (adminUsers) adminUsers.innerText = adminCount;
  15941. const badgeCount = document.getElementById('badge-users-count');
  15942. if (badgeCount) badgeCount.innerText = state.users.length;
  15943. if (isManual) showToast('Refreshed', 'User list updated', 'info');
  15944. }
  15945. } catch (err) {
  15946. console.error('Failed to load users:', err);
  15947. }
  15948. }
  15949. function renderUsersTable() {
  15950. const tbody = document.getElementById('users-table-tbody');
  15951. const emptyState = document.getElementById('users-empty-state');
  15952. if (!tbody) return;
  15953. tbody.innerHTML = '';
  15954. const query = (document.getElementById('users-search-input')?.value || '').trim().toLowerCase();
  15955. const filtered = (state.users || []).filter(u => {
  15956. if (!query) return true;
  15957. return u.username.toLowerCase().includes(query) ||
  15958. (u.role || '').toLowerCase().includes(query) ||
  15959. (u.comment || '').toLowerCase().includes(query);
  15960. });
  15961. if (filtered.length === 0) {
  15962. if (emptyState) emptyState.classList.remove('hidden');
  15963. return;
  15964. }
  15965. if (emptyState) emptyState.classList.add('hidden');
  15966. const currentAuthUser = state.currentUser?.username || '';
  15967. filtered.forEach(u => {
  15968. const isSelf = u.username === currentAuthUser;
  15969. const isFull = u.role === 'full';
  15970. const isWrite = u.role === 'write';
  15971. 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>`;
  15972. if (isFull) {
  15973. 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>`;
  15974. } else if (isWrite) {
  15975. 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>`;
  15976. }
  15977. const statusBadge = u.disabled
  15978. ? `<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>`
  15979. : `<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>`;
  15980. let lastLoginText = 'Never';
  15981. if (u.last_login_at && !u.last_login_at.startsWith('0001-01-01')) {
  15982. const dt = new Date(u.last_login_at);
  15983. lastLoginText = dt.toLocaleString();
  15984. }
  15985. const initials = u.username.slice(0, 2).toUpperCase();
  15986. const tr = document.createElement('tr');
  15987. tr.className = 'hover:bg-slate-800/40 transition group';
  15988. tr.innerHTML = `
  15989. <td class="py-3 px-4">
  15990. <div class="flex items-center gap-3">
  15991. <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">
  15992. ${initials}
  15993. </div>
  15994. <div>
  15995. <div class="font-bold text-white text-xs flex items-center gap-2">
  15996. <span>${escapeHtml(u.username)}</span>
  15997. ${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>' : ''}
  15998. </div>
  15999. <div class="text-[10px] text-slate-500 font-sans">Created: ${u.created_at ? new Date(u.created_at).toLocaleDateString() : '-'}</div>
  16000. </div>
  16001. </div>
  16002. </td>
  16003. <td class="py-3 px-4 font-sans">
  16004. ${roleBadge}
  16005. </td>
  16006. <td class="py-3 px-4 font-sans">
  16007. ${statusBadge}
  16008. </td>
  16009. <td class="py-3 px-4 text-slate-300 font-sans text-xs">
  16010. ${escapeHtml(u.comment) || '<span class="text-slate-600">-</span>'}
  16011. </td>
  16012. <td class="py-3 px-4 text-slate-400 text-xs">
  16013. ${lastLoginText}
  16014. </td>
  16015. <td class="py-3 px-4 text-right space-x-1.5 font-sans">
  16016. <button onclick="openAdminResetPasswordModal('${escapeHtml(u.username)}')"
  16017. class="p-1.5 rounded-lg text-slate-400 hover:text-amber-400 hover:bg-slate-800 transition" title="Reset User Password">
  16018. <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>
  16019. </button>
  16020. <button onclick="openEditUserModal('${escapeHtml(u.username)}')"
  16021. class="p-1.5 rounded-lg text-slate-400 hover:text-cyan-400 hover:bg-slate-800 transition" title="Edit User">
  16022. <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>
  16023. </button>
  16024. ${!isSelf ? `
  16025. <button onclick="deleteUser('${escapeHtml(u.username)}')"
  16026. class="p-1.5 rounded-lg text-slate-400 hover:text-rose-400 hover:bg-slate-800 transition" title="Delete User">
  16027. <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>
  16028. </button>
  16029. ` : ''}
  16030. </td>
  16031. `;
  16032. tbody.appendChild(tr);
  16033. });
  16034. }
  16035. function openAddUserModal() {
  16036. document.getElementById('user-add-username').value = '';
  16037. document.getElementById('user-add-password').value = '';
  16038. document.getElementById('user-add-confirm').value = '';
  16039. document.getElementById('user-add-role').value = 'full';
  16040. document.getElementById('user-add-comment').value = '';
  16041. document.getElementById('modal-add-user')?.classList.remove('hidden');
  16042. document.getElementById('user-add-username')?.focus();
  16043. }
  16044. function closeAddUserModal() {
  16045. document.getElementById('modal-add-user')?.classList.add('hidden');
  16046. }
  16047. async function submitAddUser(event) {
  16048. event.preventDefault();
  16049. const username = (document.getElementById('user-add-username')?.value || '').trim();
  16050. const password = document.getElementById('user-add-password')?.value || '';
  16051. const confirm = document.getElementById('user-add-confirm')?.value || '';
  16052. const role = document.getElementById('user-add-role')?.value || 'full';
  16053. const comment = (document.getElementById('user-add-comment')?.value || '').trim();
  16054. if (password !== confirm) {
  16055. showToast('Validation Error', 'Passwords do not match', 'warning');
  16056. return;
  16057. }
  16058. if (password.length < 4) {
  16059. showToast('Validation Error', 'Password must be at least 4 characters', 'warning');
  16060. return;
  16061. }
  16062. try {
  16063. const res = await fetch(`${API_BASE}/users`, {
  16064. method: 'POST',
  16065. headers: { 'Content-Type': 'application/json' },
  16066. body: JSON.stringify({ username, password, role, comment })
  16067. });
  16068. const data = await res.json();
  16069. if (res.ok) {
  16070. showToast('User Created', `Created user ${username} with ${role.toUpperCase()} permissions`, 'success');
  16071. closeAddUserModal();
  16072. loadUsers(false);
  16073. } else {
  16074. showToast('Error', data.message || 'Failed to create user', 'error');
  16075. }
  16076. } catch (err) {
  16077. showToast('Error', err.message, 'error');
  16078. }
  16079. }
  16080. function openEditUserModal(username) {
  16081. const user = (state.users || []).find(u => u.username === username);
  16082. if (!user) return;
  16083. document.getElementById('user-edit-username').value = user.username;
  16084. document.getElementById('user-edit-username-title').innerText = `@${user.username}`;
  16085. document.getElementById('user-edit-role').value = user.role || 'read';
  16086. document.getElementById('user-edit-comment').value = user.comment || '';
  16087. document.getElementById('user-edit-disabled').checked = !!user.disabled;
  16088. document.getElementById('modal-edit-user')?.classList.remove('hidden');
  16089. }
  16090. function closeEditUserModal() {
  16091. document.getElementById('modal-edit-user')?.classList.add('hidden');
  16092. }
  16093. async function submitEditUser(event) {
  16094. event.preventDefault();
  16095. const username = document.getElementById('user-edit-username')?.value;
  16096. const role = document.getElementById('user-edit-role')?.value || 'read';
  16097. const comment = (document.getElementById('user-edit-comment')?.value || '').trim();
  16098. const disabled = document.getElementById('user-edit-disabled')?.checked || false;
  16099. try {
  16100. const res = await fetch(`${API_BASE}/users/${encodeURIComponent(username)}`, {
  16101. method: 'PUT',
  16102. headers: { 'Content-Type': 'application/json' },
  16103. body: JSON.stringify({ role, comment, disabled })
  16104. });
  16105. const data = await res.json();
  16106. if (res.ok) {
  16107. showToast('User Updated', `Updated settings for ${username}`, 'success');
  16108. closeEditUserModal();
  16109. loadUsers(false);
  16110. // If updated own role/disabled status, refresh self profile
  16111. if (username === state.currentUser?.username) {
  16112. checkAuthStatus();
  16113. }
  16114. } else {
  16115. showToast('Error', data.message || 'Failed to update user', 'error');
  16116. }
  16117. } catch (err) {
  16118. showToast('Error', err.message, 'error');
  16119. }
  16120. }
  16121. function openAdminResetPasswordModal(username) {
  16122. document.getElementById('admin-reset-username').value = username;
  16123. document.getElementById('admin-reset-username-title').innerText = `@${username}`;
  16124. document.getElementById('admin-reset-new-pw').value = '';
  16125. document.getElementById('admin-reset-confirm-pw').value = '';
  16126. document.getElementById('modal-admin-reset-pw')?.classList.remove('hidden');
  16127. document.getElementById('admin-reset-new-pw')?.focus();
  16128. }
  16129. function closeAdminResetPasswordModal() {
  16130. document.getElementById('modal-admin-reset-pw')?.classList.add('hidden');
  16131. }
  16132. async function submitAdminResetPassword(event) {
  16133. event.preventDefault();
  16134. const username = document.getElementById('admin-reset-username')?.value;
  16135. const newPassword = document.getElementById('admin-reset-new-pw')?.value || '';
  16136. const confirm = document.getElementById('admin-reset-confirm-pw')?.value || '';
  16137. if (newPassword !== confirm) {
  16138. showToast('Validation Error', 'Passwords do not match', 'warning');
  16139. return;
  16140. }
  16141. if (newPassword.length < 4) {
  16142. showToast('Validation Error', 'Password must be at least 4 characters', 'warning');
  16143. return;
  16144. }
  16145. try {
  16146. const res = await fetch(`${API_BASE}/users/${encodeURIComponent(username)}/password`, {
  16147. method: 'POST',
  16148. headers: { 'Content-Type': 'application/json' },
  16149. body: JSON.stringify({ new_password: newPassword })
  16150. });
  16151. const data = await res.json();
  16152. if (res.ok) {
  16153. showToast('Password Reset', `Password for user ${username} updated successfully`, 'success');
  16154. closeAdminResetPasswordModal();
  16155. } else {
  16156. showToast('Error', data.message || 'Failed to reset password', 'error');
  16157. }
  16158. } catch (err) {
  16159. showToast('Error', err.message, 'error');
  16160. }
  16161. }
  16162. async function deleteUser(username) {
  16163. if (username === state.currentUser?.username) {
  16164. showToast('Action Forbidden', 'You cannot delete your own account', 'warning');
  16165. return;
  16166. }
  16167. if (!confirm(`Are you sure you want to completely remove user "${username}"?`)) {
  16168. return;
  16169. }
  16170. try {
  16171. const res = await fetch(`${API_BASE}/users/${encodeURIComponent(username)}`, {
  16172. method: 'DELETE'
  16173. });
  16174. const data = await res.json();
  16175. if (res.ok) {
  16176. showToast('User Deleted', `User ${username} has been removed`, 'success');
  16177. loadUsers(false);
  16178. } else {
  16179. showToast('Error', data.message || 'Failed to delete user', 'error');
  16180. }
  16181. } catch (err) {
  16182. showToast('Error', err.message, 'error');
  16183. }
  16184. }
  16185. function openSelfPasswordModal() {
  16186. document.getElementById('self-current-password').value = '';
  16187. document.getElementById('self-new-password').value = '';
  16188. document.getElementById('self-confirm-password').value = '';
  16189. document.getElementById('modal-self-password')?.classList.remove('hidden');
  16190. document.getElementById('self-current-password')?.focus();
  16191. }
  16192. function closeSelfPasswordModal() {
  16193. document.getElementById('modal-self-password')?.classList.add('hidden');
  16194. }
  16195. async function submitSelfPassword(event) {
  16196. event.preventDefault();
  16197. const oldPassword = document.getElementById('self-current-password')?.value || '';
  16198. const newPassword = document.getElementById('self-new-password')?.value || '';
  16199. const confirm = document.getElementById('self-confirm-password')?.value || '';
  16200. if (newPassword !== confirm) {
  16201. showToast('Validation Error', 'New passwords do not match', 'warning');
  16202. return;
  16203. }
  16204. if (newPassword.length < 4) {
  16205. showToast('Validation Error', 'Password must be at least 4 characters', 'warning');
  16206. return;
  16207. }
  16208. try {
  16209. const res = await fetch(`${API_BASE}/auth/change-password`, {
  16210. method: 'POST',
  16211. headers: { 'Content-Type': 'application/json' },
  16212. body: JSON.stringify({ old_password: oldPassword, new_password: newPassword })
  16213. });
  16214. const data = await res.json();
  16215. if (res.ok) {
  16216. showToast('Password Changed', 'Your password has been changed successfully', 'success');
  16217. closeSelfPasswordModal();
  16218. } else {
  16219. showToast('Error', data.message || 'Failed to change password', 'error');
  16220. }
  16221. } catch (err) {
  16222. showToast('Error', err.message, 'error');
  16223. }
  16224. }
  16225. // ==================== MANAGEMENT SERVICES (/ip service) ====================
  16226. state.services = [];
  16227. async function loadServices(manual = false) {
  16228. try {
  16229. const res = await fetch(`${API_BASE}/system/services`);
  16230. if (!res.ok) throw new Error('Failed to load services');
  16231. const data = await res.json();
  16232. state.services = data || [];
  16233. renderServicesTable();
  16234. updateCertificatesBadges();
  16235. if (manual) showToast('Services Updated', 'Service status synchronized', 'success');
  16236. } catch (err) {
  16237. if (manual) showToast('Error', err.message, 'error');
  16238. }
  16239. }
  16240. function renderServicesTable() {
  16241. const tbody = document.getElementById('services-table-body');
  16242. if (!tbody) return;
  16243. if (!state.services || state.services.length === 0) {
  16244. tbody.innerHTML = '<tr><td colspan="5" class="py-6 text-center text-slate-500 text-xs">No services configured.</td></tr>';
  16245. return;
  16246. }
  16247. tbody.innerHTML = state.services.map(s => {
  16248. const isOff = s.disabled;
  16249. const statusBadge = isOff
  16250. ? '<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>'
  16251. : '<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>';
  16252. const toggleBtn = isOff
  16253. ? `<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>`
  16254. : `<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>`;
  16255. let certBadge = '';
  16256. if (s.name === 'www-ssl') {
  16257. if (s.certificate) {
  16258. 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>`;
  16259. } else {
  16260. 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>`;
  16261. }
  16262. }
  16263. const certArg = s.certificate ? `'${escapeHtml(s.certificate)}'` : "''";
  16264. return `
  16265. <tr class="hover:bg-slate-800/40 transition">
  16266. <td class="py-3 px-4 font-bold text-white uppercase">${s.name} ${certBadge}</td>
  16267. <td class="py-3 px-4">
  16268. <div class="flex items-center gap-2">
  16269. <span class="text-cyan-400 font-mono font-bold">${s.port}</span>
  16270. <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">
  16271. <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>
  16272. </button>
  16273. </div>
  16274. </td>
  16275. <td class="py-3 px-4">${statusBadge}</td>
  16276. <td class="py-3 px-4 text-slate-400 text-xs font-sans">${s.comment || '-'}</td>
  16277. <td class="py-3 px-4 text-right">
  16278. <div class="flex items-center justify-end gap-2">
  16279. <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">
  16280. <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>
  16281. <span>Edit</span>
  16282. </button>
  16283. ${toggleBtn}
  16284. </div>
  16285. </td>
  16286. </tr>
  16287. `;
  16288. }).join('');
  16289. }
  16290. function openEditServiceModal(serviceName, currentPort, isDisabled, currentCert = '') {
  16291. document.getElementById('modal-service-name').value = serviceName;
  16292. document.getElementById('modal-service-disabled').value = String(isDisabled);
  16293. document.getElementById('modal-service-display-name').textContent = serviceName.toUpperCase();
  16294. document.getElementById('modal-service-port').value = currentPort;
  16295. const hintEl = document.getElementById('modal-service-port-hint');
  16296. const warnEl = document.getElementById('modal-service-warning');
  16297. const certGroup = document.getElementById('modal-service-cert-group');
  16298. const certSelect = document.getElementById('modal-service-cert-select');
  16299. if (serviceName === 'www') {
  16300. hintEl.textContent = 'Default HTTP web port: 80';
  16301. warnEl.classList.remove('hidden');
  16302. certGroup.classList.add('hidden');
  16303. } else if (serviceName === 'www-ssl') {
  16304. hintEl.textContent = 'Default HTTPS web port: 443';
  16305. warnEl.classList.remove('hidden');
  16306. certGroup.classList.remove('hidden');
  16307. const populateCertOptions = (certs) => {
  16308. certSelect.innerHTML = '<option value="">-- No Certificate Selected --</option>';
  16309. (certs || []).forEach(c => {
  16310. const opt = document.createElement('option');
  16311. opt.value = c.name;
  16312. opt.textContent = `${c.name} (${c.common_name})${c.is_ca ? ' [CA]' : ''}`;
  16313. if (c.name === currentCert) opt.selected = true;
  16314. certSelect.appendChild(opt);
  16315. });
  16316. };
  16317. if (state.certificates && state.certificates.length > 0) {
  16318. populateCertOptions(state.certificates);
  16319. } else {
  16320. loadCertificates(false).then(() => {
  16321. populateCertOptions(state.certificates);
  16322. });
  16323. }
  16324. } else if (serviceName === 'telnet') {
  16325. hintEl.textContent = 'Default Telnet console port: 8282';
  16326. warnEl.classList.add('hidden');
  16327. certGroup.classList.add('hidden');
  16328. } else if (serviceName === 'ssh') {
  16329. hintEl.textContent = 'Default SSH port: 2222';
  16330. warnEl.classList.add('hidden');
  16331. certGroup.classList.add('hidden');
  16332. } else {
  16333. hintEl.textContent = '';
  16334. warnEl.classList.add('hidden');
  16335. certGroup.classList.add('hidden');
  16336. }
  16337. const modal = document.getElementById('modal-service-edit');
  16338. modal.classList.remove('hidden');
  16339. setTimeout(() => document.getElementById('modal-service-port').focus(), 50);
  16340. }
  16341. function closeEditServiceModal() {
  16342. const modal = document.getElementById('modal-service-edit');
  16343. if (modal) modal.classList.add('hidden');
  16344. }
  16345. async function submitSaveServicePort(event) {
  16346. event.preventDefault();
  16347. const name = document.getElementById('modal-service-name').value;
  16348. const disabled = document.getElementById('modal-service-disabled').value === 'true';
  16349. const port = parseInt(document.getElementById('modal-service-port').value, 10);
  16350. if (isNaN(port) || port < 1 || port > 65535) {
  16351. showToast('Invalid Port', 'Port must be a valid number between 1 and 65535', 'error');
  16352. return;
  16353. }
  16354. const certSelect = document.getElementById('modal-service-cert-select');
  16355. const certVal = (name === 'www-ssl' && certSelect) ? certSelect.value : '';
  16356. try {
  16357. const res = await fetch(`${API_BASE}/system/services/${name}`, {
  16358. method: 'POST',
  16359. headers: { 'Content-Type': 'application/json' },
  16360. body: JSON.stringify({ port: port, disabled: disabled, certificate: certVal })
  16361. });
  16362. if (!res.ok) {
  16363. const errData = await res.json();
  16364. throw new Error(errData.message || 'Failed to update service settings');
  16365. }
  16366. closeEditServiceModal();
  16367. showToast('Service Updated', `Service ${name.toUpperCase()} settings saved`, 'success');
  16368. await loadServices();
  16369. } catch (err) {
  16370. showToast('Error', err.message, 'error');
  16371. }
  16372. }
  16373. async function toggleServiceState(serviceName, newDisabled) {
  16374. if (serviceName === 'www' && newDisabled) {
  16375. 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?")) {
  16376. return;
  16377. }
  16378. }
  16379. if (serviceName === 'www-ssl' && !newDisabled) {
  16380. const sslSvc = (state.services || []).find(s => s.name === 'www-ssl');
  16381. if (!sslSvc || !sslSvc.certificate) {
  16382. showToast('Certificate Required', 'Please assign an SSL/TLS certificate to www-ssl before enabling HTTPS.', 'warning');
  16383. openEditServiceModal('www-ssl', sslSvc ? sslSvc.port : 443, false, '');
  16384. return;
  16385. }
  16386. }
  16387. try {
  16388. const res = await fetch(`${API_BASE}/system/services/${serviceName}/state`, {
  16389. method: 'POST',
  16390. headers: { 'Content-Type': 'application/json' },
  16391. body: JSON.stringify({ disabled: newDisabled })
  16392. });
  16393. if (!res.ok) {
  16394. const errData = await res.json();
  16395. throw new Error(errData.message || 'Failed to update service');
  16396. }
  16397. showToast('Service Updated', `Service ${serviceName} is now ${newDisabled ? 'disabled' : 'enabled'}`, 'success');
  16398. await loadServices();
  16399. } catch (err) {
  16400. showToast('Error', err.message, 'error');
  16401. }
  16402. }
  16403. // ==================== SYSTEM LOGS (/log) ====================
  16404. state.logs = [];
  16405. let logsTimer = null;
  16406. async function loadLogs(manual = false) {
  16407. const limitEl = document.getElementById('logs-limit-select');
  16408. const limit = limitEl ? limitEl.value : '100';
  16409. try {
  16410. const res = await fetch(`${API_BASE}/system/logs?limit=${limit}`);
  16411. if (!res.ok) throw new Error('Failed to load logs');
  16412. const data = await res.json();
  16413. state.logs = data.logs || [];
  16414. renderLogsTable();
  16415. if (manual) showToast('Logs Refreshed', `Fetched ${state.logs.length} log records`, 'success');
  16416. } catch (err) {
  16417. if (manual) showToast('Error', err.message, 'error');
  16418. }
  16419. // Setup auto-refresh if enabled and on logs tab
  16420. if (!logsTimer && state.currentUser) {
  16421. logsTimer = setInterval(() => {
  16422. if (state.currentUser && !document.hidden && state.activeTab === 'logs') {
  16423. const auto = document.getElementById('logs-auto-refresh');
  16424. if (auto && auto.checked) {
  16425. loadLogs(false);
  16426. }
  16427. }
  16428. }, 3000);
  16429. }
  16430. }
  16431. function renderLogsTable() {
  16432. const tbody = document.getElementById('logs-table-body');
  16433. if (!tbody) return;
  16434. const search = (document.getElementById('logs-search-input')?.value || '').toLowerCase();
  16435. const topicFilter = (document.getElementById('logs-topic-filter')?.value || '').toLowerCase();
  16436. const filtered = state.logs.filter(entry => {
  16437. if (topicFilter && !entry.topics.toLowerCase().includes(topicFilter)) {
  16438. return false;
  16439. }
  16440. if (search && !entry.message.toLowerCase().includes(search) && !entry.topics.toLowerCase().includes(search)) {
  16441. return false;
  16442. }
  16443. return true;
  16444. });
  16445. if (filtered.length === 0) {
  16446. tbody.innerHTML = '<tr><td colspan="4" class="py-8 text-center text-slate-500 text-xs">No matching log entries found.</td></tr>';
  16447. return;
  16448. }
  16449. tbody.innerHTML = filtered.map(l => {
  16450. let topicColor = 'bg-slate-800 text-slate-300 border-slate-700';
  16451. const topLower = l.topics.toLowerCase();
  16452. if (topLower.includes('auth')) {
  16453. topicColor = 'bg-amber-500/20 text-amber-300 border-amber-500/30';
  16454. } else if (topLower.includes('dhcp')) {
  16455. topicColor = 'bg-cyan-500/20 text-cyan-300 border-cyan-500/30';
  16456. } else if (topLower.includes('route')) {
  16457. topicColor = 'bg-blue-500/20 text-blue-300 border-blue-500/30';
  16458. } else if (topLower.includes('firewall')) {
  16459. topicColor = 'bg-rose-500/20 text-rose-300 border-rose-500/30';
  16460. } else if (topLower.includes('error')) {
  16461. topicColor = 'bg-red-500/20 text-red-300 border-red-500/30';
  16462. } else if (topLower.includes('system')) {
  16463. topicColor = 'bg-emerald-500/20 text-emerald-300 border-emerald-500/30';
  16464. }
  16465. const d = new Date(l.time);
  16466. const timeStr = d.toLocaleDateString('en-US', { month: 'short', day: '2-digit' }) + ' ' + d.toLocaleTimeString('en-US', { hour12: false });
  16467. return `
  16468. <tr class="hover:bg-slate-800/40 transition">
  16469. <td class="py-2 px-3 text-slate-500 font-mono">${l.id}</td>
  16470. <td class="py-2 px-3 text-slate-400 font-mono whitespace-nowrap">${timeStr}</td>
  16471. <td class="py-2 px-3 whitespace-nowrap">
  16472. <span class="px-2 py-0.5 rounded text-[10px] font-bold border ${topicColor}">${l.topics}</span>
  16473. </td>
  16474. <td class="py-2 px-3 text-slate-200 font-mono break-all">${escapeHtml(l.message)}</td>
  16475. </tr>
  16476. `;
  16477. }).join('');
  16478. }
  16479. // ==================== CERTIFICATES & SSL/TLS (/certificate) ====================
  16480. state.certificates = [];
  16481. async function loadCertificates(manual = false) {
  16482. try {
  16483. const res = await fetch(`${API_BASE}/certificates`);
  16484. if (!res.ok) throw new Error('Failed to load certificates');
  16485. state.certificates = await res.json() || [];
  16486. updateCertificatesBadges();
  16487. renderCertificatesTable();
  16488. if (manual) showToast('Certificates Updated', `Loaded ${state.certificates.length} certificates`, 'success');
  16489. } catch (err) {
  16490. if (manual) showToast('Error', err.message, 'error');
  16491. }
  16492. }
  16493. function updateCertificatesBadges() {
  16494. const total = (state.certificates || []).length;
  16495. const caCount = (state.certificates || []).filter(c => c.is_ca).length;
  16496. const bCount = document.getElementById('badge-certs-count');
  16497. if (bCount) bCount.innerText = total;
  16498. const kpiTotal = document.getElementById('kpi-certs-total');
  16499. if (kpiTotal) kpiTotal.innerText = total;
  16500. const kpiCA = document.getElementById('kpi-certs-ca');
  16501. if (kpiCA) kpiCA.innerText = caCount;
  16502. const kpiHttps = document.getElementById('kpi-https-status');
  16503. if (kpiHttps) {
  16504. const sslSvc = (state.services || []).find(s => s.name === 'www-ssl');
  16505. if (sslSvc) {
  16506. if (!sslSvc.disabled) {
  16507. 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>`;
  16508. } else {
  16509. 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>`;
  16510. }
  16511. }
  16512. }
  16513. }
  16514. function renderCertificatesTable() {
  16515. const tbody = document.getElementById('certs-table-body');
  16516. if (!tbody) return;
  16517. if (!state.certificates || state.certificates.length === 0) {
  16518. 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>';
  16519. return;
  16520. }
  16521. tbody.innerHTML = state.certificates.map(c => {
  16522. let typeBadge = '';
  16523. if (c.is_ca) {
  16524. 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>';
  16525. } else if (c.type === 'acme') {
  16526. 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>';
  16527. } else if (c.issuer && c.issuer !== c.common_name) {
  16528. 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>';
  16529. } else {
  16530. 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>';
  16531. }
  16532. const sansHtml = (c.sans && c.sans.length > 0)
  16533. ? 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('')
  16534. : '<span class="text-slate-500">-</span>';
  16535. const validTo = c.valid_to ? new Date(c.valid_to) : null;
  16536. let validStr = '-';
  16537. let validBadge = '';
  16538. if (validTo && !isNaN(validTo.getTime())) {
  16539. const now = new Date();
  16540. const daysLeft = Math.round((validTo - now) / (1000 * 60 * 60 * 24));
  16541. validStr = validTo.toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' });
  16542. if (daysLeft < 0) {
  16543. validBadge = '<span class="ml-1 text-[10px] text-rose-400 font-bold">(Expired)</span>';
  16544. } else if (daysLeft < 30) {
  16545. validBadge = `<span class="ml-1 text-[10px] text-amber-400 font-bold">(${daysLeft}d left)</span>`;
  16546. } else {
  16547. validBadge = `<span class="ml-1 text-[10px] text-slate-400">(${daysLeft}d left)</span>`;
  16548. }
  16549. }
  16550. return `
  16551. <tr class="hover:bg-slate-800/40 transition">
  16552. <td class="py-3 px-4">${typeBadge}</td>
  16553. <td class="py-3 px-4">
  16554. <div class="font-bold text-white">${escapeHtml(c.name)}</div>
  16555. <div class="text-[10px] text-slate-400 font-sans truncate max-w-xs" title="${escapeHtml(c.common_name)}">${escapeHtml(c.common_name)}</div>
  16556. </td>
  16557. <td class="py-3 px-4 text-slate-300 text-xs truncate max-w-xs" title="${escapeHtml(c.issuer || '-')}">${escapeHtml(c.issuer || '-')}</td>
  16558. <td class="py-3 px-4 max-w-xs">${sansHtml}</td>
  16559. <td class="py-3 px-4 whitespace-nowrap text-xs text-slate-300">
  16560. <span>${validStr}</span> ${validBadge}
  16561. ${c.type === 'acme' ? `<div class="text-[10px] ${c.renewal_error ? 'text-rose-400' : 'text-slate-400'}">${c.renewal_error ? 'Renewal failed: ' + escapeHtml(c.renewal_error) : 'Automatic renewal enabled'}</div>` : ''}
  16562. <div class="text-[10px] text-slate-500">${c.key_type || ''}</div>
  16563. </td>
  16564. <td class="py-3 px-4 text-right whitespace-nowrap">
  16565. <div class="flex items-center justify-end gap-1.5">
  16566. <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">
  16567. <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>
  16568. <span>View</span>
  16569. </button>
  16570. <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">
  16571. <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>
  16572. </button>
  16573. </div>
  16574. </td>
  16575. </tr>
  16576. `;
  16577. }).join('');
  16578. }
  16579. // Create CA
  16580. function openCreateCAModal() {
  16581. document.getElementById('form-create-ca').reset();
  16582. document.getElementById('ca-days').value = '3650';
  16583. document.getElementById('ca-org').value = 'DebTik Network Appliance';
  16584. document.getElementById('ca-country').value = 'GR';
  16585. document.getElementById('ca-key-type').value = 'RSA-2048';
  16586. document.getElementById('modal-create-ca').classList.remove('hidden');
  16587. setTimeout(() => document.getElementById('ca-name').focus(), 50);
  16588. }
  16589. function closeCreateCAModal() {
  16590. document.getElementById('modal-create-ca').classList.add('hidden');
  16591. }
  16592. async function submitCreateCA(event) {
  16593. event.preventDefault();
  16594. const payload = {
  16595. name: document.getElementById('ca-name').value.trim(),
  16596. common_name: document.getElementById('ca-cn').value.trim(),
  16597. organization: document.getElementById('ca-org').value.trim(),
  16598. country: document.getElementById('ca-country').value.trim(),
  16599. days: parseInt(document.getElementById('ca-days').value, 10) || 3650,
  16600. key_type: document.getElementById('ca-key-type').value
  16601. };
  16602. try {
  16603. const res = await fetch(`${API_BASE}/certificates/ca`, {
  16604. method: 'POST',
  16605. headers: { 'Content-Type': 'application/json' },
  16606. body: JSON.stringify(payload)
  16607. });
  16608. if (!res.ok) {
  16609. const errData = await res.json();
  16610. throw new Error(errData.message || 'Failed to create CA');
  16611. }
  16612. closeCreateCAModal();
  16613. showToast('CA Created', `Root CA ${payload.name} generated successfully`, 'success');
  16614. await loadCertificates();
  16615. } catch (err) {
  16616. showToast('Error', err.message, 'error');
  16617. }
  16618. }
  16619. // Create Cert
  16620. function openCreateCertModal() {
  16621. document.getElementById('form-create-cert').reset();
  16622. document.getElementById('cert-days').value = '730';
  16623. document.getElementById('cert-key-type').value = 'RSA-2048';
  16624. const caSelect = document.getElementById('cert-ca-select');
  16625. caSelect.innerHTML = '<option value="">[ Self-Signed Certificate ]</option>';
  16626. (state.certificates || []).filter(c => c.is_ca).forEach(ca => {
  16627. const opt = document.createElement('option');
  16628. opt.value = ca.name;
  16629. opt.textContent = `${ca.name} (${ca.common_name})`;
  16630. caSelect.appendChild(opt);
  16631. });
  16632. document.getElementById('modal-create-cert').classList.remove('hidden');
  16633. setTimeout(() => document.getElementById('cert-name').focus(), 50);
  16634. }
  16635. function closeCreateCertModal() {
  16636. document.getElementById('modal-create-cert').classList.add('hidden');
  16637. }
  16638. async function submitCreateCert(event) {
  16639. event.preventDefault();
  16640. const rawSans = document.getElementById('cert-sans').value;
  16641. const sansList = rawSans ? rawSans.split(',').map(s => s.trim()).filter(Boolean) : [];
  16642. const caName = document.getElementById('cert-ca-select').value;
  16643. const payload = {
  16644. name: document.getElementById('cert-name').value.trim(),
  16645. common_name: document.getElementById('cert-cn').value.trim(),
  16646. ca_name: caName,
  16647. sans: sansList,
  16648. days: parseInt(document.getElementById('cert-days').value, 10) || 730,
  16649. key_type: document.getElementById('cert-key-type').value,
  16650. is_server: true
  16651. };
  16652. try {
  16653. const res = await fetch(`${API_BASE}/certificates/generate`, {
  16654. method: 'POST',
  16655. headers: { 'Content-Type': 'application/json' },
  16656. body: JSON.stringify(payload)
  16657. });
  16658. if (!res.ok) {
  16659. const errData = await res.json();
  16660. throw new Error(errData.message || 'Failed to issue certificate');
  16661. }
  16662. closeCreateCertModal();
  16663. showToast('Certificate Issued', `Certificate ${payload.name} generated successfully`, 'success');
  16664. await loadCertificates();
  16665. } catch (err) {
  16666. showToast('Error', err.message, 'error');
  16667. }
  16668. }
  16669. // Let's Encrypt
  16670. function openLetsEncryptModal() {
  16671. document.getElementById('form-letsencrypt').reset();
  16672. document.getElementById('modal-letsencrypt').classList.remove('hidden');
  16673. setTimeout(() => document.getElementById('le-domain').focus(), 50);
  16674. }
  16675. function closeLetsEncryptModal() {
  16676. document.getElementById('modal-letsencrypt').classList.add('hidden');
  16677. }
  16678. async function submitLetsEncrypt(event) {
  16679. event.preventDefault();
  16680. const domain = document.getElementById('le-domain').value.trim();
  16681. const email = document.getElementById('le-email').value.trim();
  16682. let name = document.getElementById('le-name').value.trim();
  16683. if (!name) name = domain.replace(/[^a-zA-Z0-9_-]/g, '-');
  16684. const staging = document.getElementById('le-staging').checked;
  16685. const btn = document.getElementById('btn-submit-letsencrypt');
  16686. const origBtnHtml = btn.innerHTML;
  16687. btn.disabled = true;
  16688. 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>`;
  16689. try {
  16690. const res = await fetch(`${API_BASE}/certificates/letsencrypt`, {
  16691. method: 'POST',
  16692. headers: { 'Content-Type': 'application/json' },
  16693. body: JSON.stringify({
  16694. name: name,
  16695. domain: domain,
  16696. email: email,
  16697. staging: staging
  16698. })
  16699. });
  16700. if (!res.ok) {
  16701. const errData = await res.json();
  16702. throw new Error(errData.message || 'Let\'s Encrypt challenge failed');
  16703. }
  16704. closeLetsEncryptModal();
  16705. showToast('Let\'s Encrypt Issued', `Successfully issued trusted certificate for ${domain}`, 'success');
  16706. await loadCertificates();
  16707. } catch (err) {
  16708. showToast('Let\'s Encrypt Error', err.message, 'error');
  16709. } finally {
  16710. btn.disabled = false;
  16711. btn.innerHTML = origBtnHtml;
  16712. }
  16713. }
  16714. // Import Cert
  16715. function openImportCertModal() {
  16716. document.getElementById('form-import-cert').reset();
  16717. document.getElementById('modal-import-cert').classList.remove('hidden');
  16718. setTimeout(() => document.getElementById('import-cert-name').focus(), 50);
  16719. }
  16720. function closeImportCertModal() {
  16721. document.getElementById('modal-import-cert').classList.add('hidden');
  16722. }
  16723. async function submitImportCert(event) {
  16724. event.preventDefault();
  16725. const payload = {
  16726. name: document.getElementById('import-cert-name').value.trim(),
  16727. cert_pem: document.getElementById('import-cert-pem').value.trim(),
  16728. key_pem: document.getElementById('import-key-pem').value.trim()
  16729. };
  16730. try {
  16731. const res = await fetch(`${API_BASE}/certificates/import`, {
  16732. method: 'POST',
  16733. headers: { 'Content-Type': 'application/json' },
  16734. body: JSON.stringify(payload)
  16735. });
  16736. if (!res.ok) {
  16737. const errData = await res.json();
  16738. throw new Error(errData.message || 'Failed to import certificate');
  16739. }
  16740. closeImportCertModal();
  16741. showToast('Certificate Imported', `Imported ${payload.name} successfully`, 'success');
  16742. await loadCertificates();
  16743. } catch (err) {
  16744. showToast('Error', err.message, 'error');
  16745. }
  16746. }
  16747. // View / Export Modal
  16748. async function openViewCertModal(name) {
  16749. const c = (state.certificates || []).find(x => x.name === name);
  16750. if (!c) return;
  16751. document.getElementById('view-cert-modal-title').textContent = `Certificate: ${c.name}`;
  16752. document.getElementById('view-cert-cn').textContent = c.common_name || '-';
  16753. document.getElementById('view-cert-issuer').textContent = c.issuer || '-';
  16754. document.getElementById('view-cert-type').textContent = `${c.is_ca ? 'CA' : 'Server/Client'} (${c.key_type || 'Unknown'})`;
  16755. document.getElementById('view-cert-validto').textContent = c.valid_to ? new Date(c.valid_to).toLocaleString() : '-';
  16756. document.getElementById('view-cert-sans').textContent = (c.sans && c.sans.length > 0) ? c.sans.join(', ') : 'None';
  16757. document.getElementById('view-cert-fp').textContent = c.fingerprint || '-';
  16758. document.getElementById('view-cert-pem-text').value = 'Loading PEM...';
  16759. document.getElementById('view-key-pem-text').value = 'Loading Key...';
  16760. document.getElementById('modal-view-cert').classList.remove('hidden');
  16761. try {
  16762. const res = await fetch(`${API_BASE}/certificates/${encodeURIComponent(name)}/export`);
  16763. if (!res.ok) throw new Error('Failed to export certificate PEM');
  16764. const data = await res.json();
  16765. document.getElementById('view-cert-pem-text').value = data.cert_pem || '';
  16766. document.getElementById('view-key-pem-text').value = data.key_pem || '(Private key not available)';
  16767. } catch (err) {
  16768. document.getElementById('view-cert-pem-text').value = 'Error loading certificate PEM: ' + err.message;
  16769. document.getElementById('view-key-pem-text').value = '';
  16770. }
  16771. }
  16772. function closeViewCertModal() {
  16773. document.getElementById('modal-view-cert').classList.add('hidden');
  16774. }
  16775. function copyCertPEM() {
  16776. const text = document.getElementById('view-cert-pem-text').value;
  16777. if (!text) return;
  16778. navigator.clipboard.writeText(text).then(() => {
  16779. showToast('Copied', 'Certificate PEM copied to clipboard', 'info');
  16780. }).catch(() => {
  16781. showToast('Error', 'Failed to copy to clipboard', 'error');
  16782. });
  16783. }
  16784. function copyKeyPEM() {
  16785. const text = document.getElementById('view-key-pem-text').value;
  16786. if (!text) return;
  16787. navigator.clipboard.writeText(text).then(() => {
  16788. showToast('Copied', 'Private Key PEM copied to clipboard', 'info');
  16789. }).catch(() => {
  16790. showToast('Error', 'Failed to copy to clipboard', 'error');
  16791. });
  16792. }
  16793. async function deleteCertificate(name) {
  16794. if (!confirm(`Are you sure you want to delete certificate "${name}"? This action cannot be undone.`)) {
  16795. return;
  16796. }
  16797. try {
  16798. const res = await fetch(`${API_BASE}/certificates/${encodeURIComponent(name)}`, {
  16799. method: 'DELETE'
  16800. });
  16801. if (!res.ok) {
  16802. const errData = await res.json();
  16803. throw new Error(errData.message || 'Failed to delete certificate');
  16804. }
  16805. showToast('Certificate Deleted', `Certificate "${name}" removed`, 'success');
  16806. await loadCertificates();
  16807. } catch (err) {
  16808. showToast('Error', err.message, 'error');
  16809. }
  16810. }
  16811. // Refresh immediately when returning to a backgrounded controller tab.
  16812. document.addEventListener('visibilitychange', () => {
  16813. if (!state.currentUser) return;
  16814. if (document.hidden) {
  16815. if (trafficEventSource) trafficEventSource.close();
  16816. trafficEventSource = null;
  16817. if (trafficPollFallback) clearInterval(trafficPollFallback);
  16818. trafficPollFallback = null;
  16819. } else {
  16820. fetchData(false);
  16821. initLiveTrafficStream();
  16822. if (state.activeTab === 'bwtest') loadBwTestView();
  16823. }
  16824. });
  16825. async function loadUpdateStatus(populate = true) {
  16826. try {
  16827. const res = await fetch(`${API_BASE}/update/status`);
  16828. if (!res.ok) throw new Error(await responseError(res));
  16829. const data = await res.json();
  16830. if (populate && document.activeElement?.id !== 'update-repository') document.getElementById('update-repository').value = data.repository || '';
  16831. if (populate && document.activeElement?.id !== 'update-tls-pin') document.getElementById('update-tls-pin').value = data.tls_key_pin || '';
  16832. document.getElementById('update-installed').textContent = data.installed_version || 'unknown';
  16833. document.getElementById('update-state').textContent = data.state || 'idle';
  16834. document.getElementById('update-log').textContent = data.log || '';
  16835. } catch (err) { showToast('Update Status', err.message, 'error'); }
  16836. }
  16837. async function saveUpdateConfig() {
  16838. try {
  16839. const repository = document.getElementById('update-repository').value.trim();
  16840. const branch = 'master';
  16841. const tls_key_pin = document.getElementById('update-tls-pin').value.trim();
  16842. const res = await fetch(`${API_BASE}/update/config`, {method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({repository,branch,tls_key_pin})});
  16843. if (!res.ok) throw new Error(await responseError(res));
  16844. document.getElementById('update-install-button').disabled = true;
  16845. document.getElementById('update-available').textContent = '—';
  16846. showToast('Update Source Saved', 'Repository and branch saved', 'success');
  16847. await loadUpdateStatus(false);
  16848. } catch (err) { showToast('Update Source', err.message, 'error'); }
  16849. }
  16850. async function checkUpdate() {
  16851. try {
  16852. const res = await fetch(`${API_BASE}/update/check`, {method:'POST'});
  16853. if (!res.ok) throw new Error(await responseError(res));
  16854. const data = await res.json();
  16855. document.getElementById('update-available').textContent = data.available_version;
  16856. document.getElementById('update-install-button').disabled = !data.update_available;
  16857. showToast('Git Check', data.update_available ? 'An update is available' : 'No newer version available', 'info');
  16858. } catch (err) { showToast('Git Check Failed', err.message, 'error'); }
  16859. }
  16860. async function startUpdate(action) {
  16861. if (!confirm(action === 'rollback' ? 'Restore the previous version and restart DebTik?' : 'Install the newer release version and restart DebTik?')) return;
  16862. try {
  16863. const res = await fetch(`${API_BASE}/update/${action}`, {method:'POST'});
  16864. if (!res.ok) throw new Error(await responseError(res));
  16865. showToast('Update Started', 'The service will restart; reconnect after a few seconds', 'info');
  16866. await loadUpdateStatus(false);
  16867. } catch (err) { showToast('Update Failed', err.message, 'error'); }
  16868. }
  16869. async function resetCurrentRuleCounters() { return resetFirewallRuleCounter('filter', resetRuleCounterDisplay); }
  16870. async function resetCurrentNATRuleCounters() { return resetFirewallRuleCounter('nat', resetNATCounterDisplay); }
  16871. async function resetCurrentMangleRuleCounters() { return resetFirewallRuleCounter('mangle', resetMangleCounterDisplay); }
  16872. function safeFirewallRow(row) {
  16873. const result = {...row};
  16874. for (const [key,value] of Object.entries(result)) if (typeof value === 'string') result[key] = escapeHtml(value);
  16875. result.id = encodeURIComponent(String(row.id || '')).replace(/'/g, '%27').replace(/\(/g, '%28').replace(/\)/g, '%29');
  16876. return result;
  16877. }
  16878. function setFirewallDays(prefix, days) {
  16879. const selected = days ? days.toLowerCase().split(',') : ['sun','mon','tue','wed','thu','fri','sat'];
  16880. for (const d of ['sun','mon','tue','wed','thu','fri','sat']) { const el = document.getElementById(prefix+'-day-'+d); if (el) el.checked = selected.includes(d); }
  16881. }
  16882. function getFirewallDays(prefix) {
  16883. if (document.getElementById(prefix+'-field-days')?.classList.contains('hidden')) return '';
  16884. const selected = ['sun','mon','tue','wed','thu','fri','sat'].filter(d => document.getElementById(prefix+'-day-'+d)?.checked);
  16885. if (!selected.length) throw new Error('Select at least one weekday, or remove the Days condition.');
  16886. return selected.join(',');
  16887. }
  16888. async function resetFirewallRuleCounter(kind, resetDisplay) {
  16889. const id = document.getElementById(kind+'-modal-id')?.value;
  16890. if (!id) { resetDisplay(); return; }
  16891. try {
  16892. const response = await fetch(`${API_BASE}/firewall/${kind}/${encodeURIComponent(id)}/reset-counters`, {method:'POST'});
  16893. if (!response.ok) { const error = await response.json(); throw new Error(error.message || 'Counter reset failed'); }
  16894. resetDisplay(); await loadFirewall(false);
  16895. } catch(error) { showToast('Error', error.message, 'error'); }
  16896. }
  16897. function reviewLegacyFirewallSettings(kind, id) {
  16898. if (!id) return true;
  16899. const rows = kind === 'filter' ? state.filterRules : kind === 'nat' ? state.natRules : state.mangleRules;
  16900. const rule = (rows || []).find(r => r.id === id);
  16901. if (!rule) return true;
  16902. const unsupported = ['layer7_protocol','connection_bytes','connection_rate','pcc','in_bridge_port_list','out_bridge_port_list','tls_host','ingress_priority','priority','ipv4_options','dst_limit','psd','hotspot','route','sniff_target'];
  16903. const present = unsupported.filter(key => rule[key]);
  16904. if (!present.length) return true;
  16905. return confirm('This saved rule contains unsupported settings: '+present.join(', ')+'. Saving removes them. Review the remaining match conditions before continuing.');
  16906. }
  16907. function refreshFirewallRejectTypes() {
  16908. const select=document.getElementById('filter-modal-rejectwith'); if(!select) return;
  16909. const old=select.value;
  16910. const ipv6=document.getElementById('filter-modal-family')?.value==='6';
  16911. const types=ipv6 ? ['icmp6-port-unreachable','icmp6-no-route','icmp6-adm-prohibited','icmp6-addr-unreachable','tcp-reset'] : ['icmp-port-unreachable','icmp-net-unreachable','icmp-host-unreachable','icmp-proto-unreachable','icmp-net-prohibited','icmp-host-prohibited','icmp-admin-prohibited','tcp-reset'];
  16912. select.replaceChildren(...types.map(value=>{const option=document.createElement('option');option.value=value;option.textContent=value;return option}));
  16913. if(types.includes(old))select.value=old;
  16914. }
  16915. function setFirewallActionSelection(kind, value) {
  16916. const select=document.getElementById(kind+'-modal-action'); if(!select)return;
  16917. if(!Array.from(select.options).some(option=>option.value===value)) {
  16918. const option=document.createElement('option');option.value=value;option.textContent='Unsupported saved action: '+value;option.disabled=true;select.appendChild(option);
  16919. }
  16920. select.value=value;
  16921. }
  16922. // ==========================================
  16923. // REVERSE PROXY & APPLICATION GATEWAY
  16924. // ==========================================
  16925. state.proxyRules = [];
  16926. state.proxyConfig = null;
  16927. async function loadReverseProxy(manual = false) {
  16928. try {
  16929. const [cfgRes, rulesRes, certsRes] = await Promise.all([
  16930. fetch(`${API_BASE}/proxy/config`),
  16931. fetch(`${API_BASE}/proxy/rules`),
  16932. fetch(`${API_BASE}/certificates`).catch(() => null)
  16933. ]);
  16934. if (!cfgRes.ok) throw new Error('Failed to load proxy config');
  16935. if (!rulesRes.ok) throw new Error('Failed to load proxy rules');
  16936. state.proxyConfig = await cfgRes.json();
  16937. state.proxyRules = await rulesRes.json() || [];
  16938. if (certsRes && certsRes.ok) {
  16939. state.certificates = await certsRes.json() || [];
  16940. }
  16941. renderProxyRules(state.proxyRules);
  16942. updateProxyMetrics();
  16943. if (manual) showToast('Reverse Proxy', 'Proxy configuration and rules reloaded', 'success');
  16944. } catch (err) {
  16945. console.error('loadReverseProxy error:', err);
  16946. if (manual) showToast('Error', err.message, 'error');
  16947. }
  16948. }
  16949. function updateProxyMetrics() {
  16950. const badge = document.getElementById('badge-proxy-count');
  16951. if (badge) badge.textContent = (state.proxyRules || []).length;
  16952. const metricRules = document.getElementById('proxy-metric-rules');
  16953. if (metricRules) metricRules.textContent = (state.proxyRules || []).length;
  16954. const cfg = state.proxyConfig;
  16955. const statusEl = document.getElementById('proxy-metric-status');
  16956. const portsEl = document.getElementById('proxy-metric-ports');
  16957. if (cfg) {
  16958. if (statusEl) {
  16959. if (cfg.enabled) {
  16960. statusEl.innerHTML = '<span class="w-2.5 h-2.5 rounded-full bg-emerald-500 animate-pulse"></span><span class="text-white">Active</span>';
  16961. } else {
  16962. statusEl.innerHTML = '<span class="w-2.5 h-2.5 rounded-full bg-rose-500"></span><span class="text-rose-400">Disabled</span>';
  16963. }
  16964. }
  16965. if (portsEl) {
  16966. portsEl.textContent = `HTTP: ${cfg.http_port || 80} | HTTPS: ${cfg.https_port || 443}`;
  16967. }
  16968. }
  16969. let totalRequests = 0;
  16970. const certSet = new Set();
  16971. (state.proxyRules || []).forEach(r => {
  16972. totalRequests += (r.stats && r.stats.requests) || 0;
  16973. if (r.enabled && r.certificate) certSet.add(r.certificate.toLowerCase());
  16974. });
  16975. const metricRequests = document.getElementById('proxy-metric-requests');
  16976. if (metricRequests) metricRequests.textContent = totalRequests.toLocaleString();
  16977. const metricCerts = document.getElementById('proxy-metric-certs');
  16978. if (metricCerts) metricCerts.textContent = certSet.size;
  16979. }
  16980. function renderProxyRules(rules) {
  16981. const tbody = document.getElementById('proxy-rules-table-body');
  16982. if (!tbody) return;
  16983. if (!rules || rules.length === 0) {
  16984. tbody.innerHTML = '<tr><td colspan="9" class="py-8 text-center text-slate-500 text-xs font-sans">No reverse proxy rules configured yet. Click "Add Proxy Rule" to begin.</td></tr>';
  16985. return;
  16986. }
  16987. tbody.innerHTML = rules.map(r => {
  16988. const isEnabled = r.enabled !== false;
  16989. const domainsStr = (r.domains && r.domains.length > 0) ? r.domains.map(d => `<span class="px-1.5 py-0.5 rounded bg-slate-800 text-slate-200 border border-slate-700 font-mono text-[11px]">${escapeHtml(d)}</span>`).join(' ') : '<span class="px-1.5 py-0.5 rounded bg-violet-950/60 text-violet-300 border border-violet-800/40 font-mono text-[11px]">* (any)</span>';
  16990. const pathBadge = `<span class="px-2 py-0.5 rounded bg-cyan-950/60 text-cyan-300 border border-cyan-800/40 font-mono text-[11px] font-bold">${escapeHtml(r.path || '/')}</span>`;
  16991. let protoBadge = '<span class="px-1.5 py-0.5 rounded bg-slate-800 text-slate-300 text-[10px] font-mono">HTTP/S</span>';
  16992. if (r.protocol === 'https') protoBadge = '<span class="px-1.5 py-0.5 rounded bg-emerald-950 text-emerald-400 border border-emerald-800/40 text-[10px] font-mono font-bold">HTTPS</span>';
  16993. else if (r.protocol === 'http') protoBadge = '<span class="px-1.5 py-0.5 rounded bg-sky-950 text-sky-400 border border-sky-800/40 text-[10px] font-mono">HTTP</span>';
  16994. const certBadge = r.certificate ? `<span class="ml-1 text-[10px] bg-amber-950 text-amber-300 border border-amber-800/40 px-1 py-0.5 rounded font-mono truncate max-w-[120px] inline-block align-bottom" title="${escapeHtml(r.certificate)}">🔒 ${escapeHtml(r.certificate)}</span>` : '';
  16995. const stripBadge = r.strip_path ? '<span class="text-amber-400 text-[11px]">Yes</span>' : '<span class="text-slate-500 text-[11px]">No</span>';
  16996. const requests = (r.stats && r.stats.requests) ? r.stats.requests.toLocaleString() : '0';
  16997. return `
  16998. <tr class="hover:bg-slate-800/40 transition">
  16999. <td class="py-3 px-4">
  17000. <button onclick="toggleProxyRuleState('${escapeHtml(r.id)}', ${isEnabled})" class="relative inline-flex h-5 w-9 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none ${isEnabled ? 'bg-emerald-500' : 'bg-slate-700'}" title="${isEnabled ? 'Click to disable' : 'Click to enable'}">
  17001. <span class="inline-block h-4 w-4 transform rounded-full bg-white shadow transition duration-200 ease-in-out ${isEnabled ? 'translate-x-4' : 'translate-x-0'}"></span>
  17002. </button>
  17003. </td>
  17004. <td class="py-3 px-4">
  17005. <div class="font-bold text-white text-xs">${escapeHtml(r.name || 'Unnamed Rule')}</div>
  17006. ${r.comment ? `<div class="text-[10px] text-slate-400 font-sans truncate max-w-[200px]">${escapeHtml(r.comment)}</div>` : ''}
  17007. </td>
  17008. <td class="py-3 px-4 flex flex-wrap gap-1 items-center max-w-xs">
  17009. ${domainsStr}
  17010. </td>
  17011. <td class="py-3 px-4">
  17012. ${pathBadge}
  17013. </td>
  17014. <td class="py-3 px-4 font-mono text-slate-300 max-w-xs truncate" title="${escapeHtml(r.target_url || '')}">
  17015. <span class="text-emerald-400">→</span> ${escapeHtml(r.target_url || '')}
  17016. </td>
  17017. <td class="py-3 px-4 whitespace-nowrap">
  17018. ${protoBadge}${certBadge}
  17019. </td>
  17020. <td class="py-3 px-4 font-mono">
  17021. ${stripBadge}
  17022. </td>
  17023. <td class="py-3 px-4 font-mono text-slate-300">
  17024. ${requests}
  17025. </td>
  17026. <td class="py-3 px-4 text-right whitespace-nowrap">
  17027. <button onclick="openEditProxyRuleModal('${escapeHtml(r.id)}')" class="px-2.5 py-1 rounded-lg bg-slate-800 hover:bg-slate-700 text-slate-300 text-xs mr-1 transition font-sans">Edit</button>
  17028. <button onclick="deleteProxyRule('${escapeHtml(r.id)}')" class="px-2.5 py-1 rounded-lg bg-rose-950/40 hover:bg-rose-900/60 text-rose-300 border border-rose-800/40 text-xs transition font-sans">Delete</button>
  17029. </td>
  17030. </tr>
  17031. `;
  17032. }).join('');
  17033. }
  17034. function populateProxyCertDropdown(selectedVal = '') {
  17035. const select = document.getElementById('proxy-rule-cert');
  17036. if (!select) return;
  17037. const certs = state.certificates || [];
  17038. select.innerHTML = '<option value="">(None / Use Default Cert)</option>';
  17039. certs.filter(c => !c.is_ca).forEach(c => {
  17040. const opt = document.createElement('option');
  17041. opt.value = c.name;
  17042. const cn = c.common_name ? ` (${c.common_name})` : '';
  17043. opt.textContent = `${c.name}${cn}`;
  17044. if (selectedVal && selectedVal.toLowerCase() === c.name.toLowerCase()) {
  17045. opt.selected = true;
  17046. }
  17047. select.appendChild(opt);
  17048. });
  17049. }
  17050. function populateDefaultProxyCertDropdown(selectedVal = '') {
  17051. const select = document.getElementById('proxy-cfg-default-cert');
  17052. if (!select) return;
  17053. const certs = state.certificates || [];
  17054. select.innerHTML = '<option value="">(None / First Available Cert)</option>';
  17055. certs.filter(c => !c.is_ca).forEach(c => {
  17056. const opt = document.createElement('option');
  17057. opt.value = c.name;
  17058. const cn = c.common_name ? ` (${c.common_name})` : '';
  17059. opt.textContent = `${c.name}${cn}`;
  17060. if (selectedVal && selectedVal.toLowerCase() === c.name.toLowerCase()) {
  17061. opt.selected = true;
  17062. }
  17063. select.appendChild(opt);
  17064. });
  17065. }
  17066. function onProxyProtoChange() {
  17067. const proto = document.getElementById('proxy-rule-proto')?.value;
  17068. const certSelect = document.getElementById('proxy-rule-cert');
  17069. const redirectCheck = document.getElementById('proxy-rule-http-to-https');
  17070. if (proto === 'http') {
  17071. if (certSelect) certSelect.disabled = true;
  17072. if (redirectCheck) redirectCheck.disabled = true;
  17073. } else {
  17074. if (certSelect) certSelect.disabled = false;
  17075. if (redirectCheck) redirectCheck.disabled = false;
  17076. }
  17077. }
  17078. function openAddProxyRuleModal() {
  17079. const modal = document.getElementById('modal-proxy-rule');
  17080. if (!modal) return;
  17081. document.getElementById('proxy-rule-modal-title').innerHTML = `
  17082. <svg class="w-4 h-4 text-violet-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7h12m0 0l-4-4m4 4l-4 4m0 6H4m0 0l4 4m-4-4l4-4" /></svg>
  17083. <span>Add Reverse Proxy Rule</span>
  17084. `;
  17085. document.getElementById('proxy-rule-id').value = '';
  17086. document.getElementById('proxy-rule-name').value = '';
  17087. document.getElementById('proxy-rule-domains').value = '';
  17088. document.getElementById('proxy-rule-path').value = '/';
  17089. document.getElementById('proxy-rule-target').value = '';
  17090. document.getElementById('proxy-rule-proto').value = 'both';
  17091. document.getElementById('proxy-rule-strip-path').checked = false;
  17092. document.getElementById('proxy-rule-http-to-https').checked = false;
  17093. document.getElementById('proxy-rule-preserve-host').checked = false;
  17094. document.getElementById('proxy-rule-insecure-tls').checked = false;
  17095. document.getElementById('proxy-rule-enabled').checked = true;
  17096. document.getElementById('proxy-rule-comment').value = '';
  17097. populateProxyCertDropdown('');
  17098. onProxyProtoChange();
  17099. modal.classList.remove('hidden');
  17100. }
  17101. function openEditProxyRuleModal(id) {
  17102. const modal = document.getElementById('modal-proxy-rule');
  17103. if (!modal) return;
  17104. const rule = (state.proxyRules || []).find(r => r.id === id);
  17105. if (!rule) {
  17106. showToast('Error', 'Rule not found', 'error');
  17107. return;
  17108. }
  17109. document.getElementById('proxy-rule-modal-title').innerHTML = `
  17110. <svg class="w-4 h-4 text-violet-400" 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>
  17111. <span>Edit Reverse Proxy Rule</span>
  17112. `;
  17113. document.getElementById('proxy-rule-id').value = rule.id || '';
  17114. document.getElementById('proxy-rule-name').value = rule.name || '';
  17115. document.getElementById('proxy-rule-domains').value = (rule.domains || []).join(', ');
  17116. document.getElementById('proxy-rule-path').value = rule.path || '/';
  17117. document.getElementById('proxy-rule-target').value = rule.target_url || '';
  17118. document.getElementById('proxy-rule-proto').value = rule.protocol || 'both';
  17119. document.getElementById('proxy-rule-strip-path').checked = !!rule.strip_path;
  17120. document.getElementById('proxy-rule-http-to-https').checked = !!rule.http_to_https;
  17121. document.getElementById('proxy-rule-preserve-host').checked = !!rule.preserve_host;
  17122. document.getElementById('proxy-rule-insecure-tls').checked = !!rule.insecure_tls;
  17123. document.getElementById('proxy-rule-enabled').checked = rule.enabled !== false;
  17124. document.getElementById('proxy-rule-comment').value = rule.comment || '';
  17125. populateProxyCertDropdown(rule.certificate || '');
  17126. onProxyProtoChange();
  17127. modal.classList.remove('hidden');
  17128. }
  17129. function closeProxyRuleModal() {
  17130. const modal = document.getElementById('modal-proxy-rule');
  17131. if (modal) modal.classList.add('hidden');
  17132. }
  17133. async function saveProxyRule(event) {
  17134. event.preventDefault();
  17135. const id = document.getElementById('proxy-rule-id').value;
  17136. const name = document.getElementById('proxy-rule-name').value.trim();
  17137. const rawDomains = document.getElementById('proxy-rule-domains').value.trim();
  17138. const pathVal = document.getElementById('proxy-rule-path').value.trim() || '/';
  17139. const target = document.getElementById('proxy-rule-target').value.trim();
  17140. const proto = document.getElementById('proxy-rule-proto').value;
  17141. const cert = document.getElementById('proxy-rule-cert').value;
  17142. const stripPath = document.getElementById('proxy-rule-strip-path').checked;
  17143. const httpToHttps = document.getElementById('proxy-rule-http-to-https').checked;
  17144. const preserveHost = document.getElementById('proxy-rule-preserve-host').checked;
  17145. const insecureTLS = document.getElementById('proxy-rule-insecure-tls').checked;
  17146. const enabled = document.getElementById('proxy-rule-enabled').checked;
  17147. const comment = document.getElementById('proxy-rule-comment').value.trim();
  17148. let domains = [];
  17149. if (rawDomains && rawDomains !== '*') {
  17150. domains = rawDomains.split(',').map(d => d.trim()).filter(d => d.length > 0);
  17151. }
  17152. const payload = {
  17153. id: id || undefined,
  17154. name,
  17155. domains,
  17156. path: pathVal,
  17157. target_url: target,
  17158. protocol: proto,
  17159. certificate: cert,
  17160. strip_path: stripPath,
  17161. http_to_https: httpToHttps,
  17162. preserve_host: preserveHost,
  17163. insecure_tls: insecureTLS,
  17164. enabled,
  17165. comment
  17166. };
  17167. try {
  17168. const url = id ? `${API_BASE}/proxy/rules/${encodeURIComponent(id)}` : `${API_BASE}/proxy/rules`;
  17169. const method = id ? 'PUT' : 'POST';
  17170. const res = await fetch(url, {
  17171. method,
  17172. headers: { 'Content-Type': 'application/json' },
  17173. body: JSON.stringify(payload)
  17174. });
  17175. if (!res.ok) {
  17176. const errData = await res.json().catch(() => ({}));
  17177. throw new Error(errData.message || 'Failed to save proxy rule');
  17178. }
  17179. closeProxyRuleModal();
  17180. showToast('Success', `Proxy rule "${name}" saved successfully`, 'success');
  17181. await loadReverseProxy(false);
  17182. } catch (err) {
  17183. showToast('Error', err.message, 'error');
  17184. }
  17185. }
  17186. async function deleteProxyRule(id) {
  17187. const rule = (state.proxyRules || []).find(r => r.id === id);
  17188. const name = rule ? rule.name : id;
  17189. if (!confirm(`Are you sure you want to delete proxy rule "${name}"?`)) {
  17190. return;
  17191. }
  17192. try {
  17193. const res = await fetch(`${API_BASE}/proxy/rules/${encodeURIComponent(id)}`, {
  17194. method: 'DELETE'
  17195. });
  17196. if (!res.ok) {
  17197. const errData = await res.json().catch(() => ({}));
  17198. throw new Error(errData.message || 'Failed to delete rule');
  17199. }
  17200. showToast('Rule Deleted', `Proxy rule "${name}" removed`, 'success');
  17201. await loadReverseProxy(false);
  17202. } catch (err) {
  17203. showToast('Error', err.message, 'error');
  17204. }
  17205. }
  17206. async function toggleProxyRuleState(id, currentState) {
  17207. try {
  17208. const res = await fetch(`${API_BASE}/proxy/rules/${encodeURIComponent(id)}/state`, {
  17209. method: 'POST',
  17210. headers: { 'Content-Type': 'application/json' },
  17211. body: JSON.stringify({ enabled: !currentState })
  17212. });
  17213. if (!res.ok) {
  17214. const errData = await res.json().catch(() => ({}));
  17215. throw new Error(errData.message || 'Failed to toggle rule state');
  17216. }
  17217. await loadReverseProxy(false);
  17218. } catch (err) {
  17219. showToast('Error', err.message, 'error');
  17220. }
  17221. }
  17222. function openProxyConfigModal() {
  17223. const modal = document.getElementById('modal-proxy-config');
  17224. if (!modal) return;
  17225. const cfg = state.proxyConfig || { enabled: true, http_port: 80, https_port: 443, default_cert: '' };
  17226. document.getElementById('proxy-cfg-enabled').checked = cfg.enabled !== false;
  17227. document.getElementById('proxy-cfg-http-port').value = cfg.http_port || 80;
  17228. document.getElementById('proxy-cfg-https-port').value = cfg.https_port || 443;
  17229. populateDefaultProxyCertDropdown(cfg.default_cert || '');
  17230. modal.classList.remove('hidden');
  17231. }
  17232. function closeProxyConfigModal() {
  17233. const modal = document.getElementById('modal-proxy-config');
  17234. if (modal) modal.classList.add('hidden');
  17235. }
  17236. async function saveProxyConfig(event) {
  17237. event.preventDefault();
  17238. const enabled = document.getElementById('proxy-cfg-enabled').checked;
  17239. const httpPort = parseInt(document.getElementById('proxy-cfg-http-port').value, 10) || 80;
  17240. const httpsPort = parseInt(document.getElementById('proxy-cfg-https-port').value, 10) || 443;
  17241. const defaultCert = document.getElementById('proxy-cfg-default-cert').value;
  17242. const payload = {
  17243. enabled,
  17244. http_port: httpPort,
  17245. https_port: httpsPort,
  17246. default_cert: defaultCert
  17247. };
  17248. try {
  17249. const res = await fetch(`${API_BASE}/proxy/config`, {
  17250. method: 'POST',
  17251. headers: { 'Content-Type': 'application/json' },
  17252. body: JSON.stringify(payload)
  17253. });
  17254. if (!res.ok) {
  17255. const errData = await res.json().catch(() => ({}));
  17256. throw new Error(errData.message || 'Failed to update proxy settings');
  17257. }
  17258. closeProxyConfigModal();
  17259. showToast('Success', 'Reverse proxy settings updated', 'success');
  17260. await loadReverseProxy(false);
  17261. } catch (err) {
  17262. showToast('Error', err.message, 'error');
  17263. }
  17264. }
  17265. // ==================== SD-WAN Controller ====================
  17266. async function loadSDWAN(manual = false) {
  17267. try {
  17268. const [groupsRes, telemetryRes] = await Promise.all([
  17269. fetch(`${API_BASE}/sdwan/groups`),
  17270. fetch(`${API_BASE}/sdwan/telemetry`)
  17271. ]);
  17272. if (!groupsRes.ok) throw new Error('Failed to load SD-WAN groups');
  17273. state.sdwanGroups = await groupsRes.json() || [];
  17274. if (telemetryRes.ok) {
  17275. state.sdwanTelemetry = await telemetryRes.json() || {};
  17276. }
  17277. renderSDWANGroups(state.sdwanGroups);
  17278. renderSDWANMembers(state.sdwanGroups);
  17279. updateSDWANMetrics(state.sdwanTelemetry);
  17280. if (manual) showToast('SD-WAN', 'SD-WAN groups and live telemetry reloaded', 'success');
  17281. } catch (err) {
  17282. console.error('loadSDWAN error:', err);
  17283. if (manual) showToast('Error', err.message, 'error');
  17284. }
  17285. }
  17286. function updateSDWANMetrics(telemetry) {
  17287. const groups = state.sdwanGroups || [];
  17288. const t = telemetry || {};
  17289. const badge = document.getElementById('badge-sdwan-count');
  17290. if (badge) badge.textContent = groups.length;
  17291. const metricGroups = document.getElementById('sdwan-metric-groups');
  17292. if (metricGroups) metricGroups.textContent = `${t.active_groups || 0} / ${t.total_groups || groups.length}`;
  17293. const metricHealthy = document.getElementById('sdwan-metric-healthy');
  17294. if (metricHealthy) metricHealthy.textContent = t.healthy_members || 0;
  17295. const metricDegraded = document.getElementById('sdwan-metric-degraded');
  17296. if (metricDegraded) metricDegraded.textContent = t.degraded_members || 0;
  17297. const metricDown = document.getElementById('sdwan-metric-down');
  17298. if (metricDown) metricDown.textContent = t.down_members || 0;
  17299. }
  17300. function renderSDWANGroups(groups) {
  17301. const tbody = document.getElementById('sdwan-groups-table-body');
  17302. if (!tbody) return;
  17303. if (!groups || groups.length === 0) {
  17304. tbody.innerHTML = '<tr><td colspan="8" class="py-8 text-center text-slate-500 text-xs font-sans">No SD-WAN groups configured yet. Click "Create SD-WAN Group" to begin.</td></tr>';
  17305. return;
  17306. }
  17307. tbody.innerHTML = groups.map(g => {
  17308. const isEnabled = g.disabled !== true;
  17309. const members = g.members || [];
  17310. const totalWeight = members.filter(m => !m.disabled).reduce((sum, m) => sum + (m.weight || 50), 0) || 1;
  17311. // Build distribution progress bar
  17312. let distHtml = '';
  17313. if (members.length === 0) {
  17314. distHtml = '<span class="text-slate-500 text-[11px] font-sans">No links attached</span>';
  17315. } else if (g.mode === 'weighted' || g.mode === 'pcc') {
  17316. const colors = ['bg-amber-500', 'bg-cyan-500', 'bg-emerald-500', 'bg-purple-500', 'bg-rose-500'];
  17317. const segments = members.map((m, idx) => {
  17318. const pct = m.disabled ? 0 : Math.round(((m.weight || 50) / totalWeight) * 100);
  17319. const col = colors[idx % colors.length];
  17320. return `<div class="${col} h-2 transition-all relative group" style="width: ${pct}%" title="${escapeHtml(m.interface)}: ${pct}%"></div>`;
  17321. }).join('');
  17322. const labels = members.map((m, idx) => {
  17323. const pct = m.disabled ? '0%' : `${Math.round(((m.weight || 50) / totalWeight) * 100)}%`;
  17324. const textCol = ['text-amber-400', 'text-cyan-400', 'text-emerald-400', 'text-purple-400', 'text-rose-400'][idx % 5];
  17325. return `<span class="${textCol} text-[10px] font-mono mr-2">${escapeHtml(m.interface)}: ${pct}</span>`;
  17326. }).join('');
  17327. distHtml = `
  17328. <div class="w-48 bg-slate-800 rounded-full h-2 overflow-hidden flex mb-1 border border-slate-700/50">${segments}</div>
  17329. <div class="flex flex-wrap">${labels}</div>
  17330. `;
  17331. } else if (g.mode === 'lowest-latency') {
  17332. distHtml = '<span class="text-emerald-400 text-[11px] font-sans">⚡ Auto: lowest RTT probe</span>';
  17333. } else if (g.mode === 'lowest-loss') {
  17334. distHtml = '<span class="text-cyan-400 text-[11px] font-sans">🛡 Auto: minimum packet loss</span>';
  17335. } else if (g.mode === 'failover') {
  17336. distHtml = '<span class="text-amber-400 text-[11px] font-sans">🔄 Priority Failover (Active-Backup)</span>';
  17337. }
  17338. let modeBadge = '';
  17339. switch (g.mode) {
  17340. case 'weighted':
  17341. modeBadge = '<span class="px-2 py-0.5 rounded bg-amber-500/20 text-amber-300 border border-amber-500/30 text-[10px] font-bold">Weighted LB</span>';
  17342. break;
  17343. case 'pcc':
  17344. modeBadge = '<span class="px-2 py-0.5 rounded bg-purple-500/20 text-purple-300 border border-purple-500/30 text-[10px] font-bold">PCC Hashing</span>';
  17345. break;
  17346. case 'lowest-latency':
  17347. modeBadge = '<span class="px-2 py-0.5 rounded bg-emerald-500/20 text-emerald-300 border border-emerald-500/30 text-[10px] font-bold">Lowest Latency SLA</span>';
  17348. break;
  17349. case 'lowest-loss':
  17350. modeBadge = '<span class="px-2 py-0.5 rounded bg-cyan-500/20 text-cyan-300 border border-cyan-500/30 text-[10px] font-bold">Lowest Loss SLA</span>';
  17351. break;
  17352. case 'failover':
  17353. modeBadge = '<span class="px-2 py-0.5 rounded bg-rose-500/20 text-rose-300 border border-rose-500/30 text-[10px] font-bold">Failover</span>';
  17354. break;
  17355. default:
  17356. modeBadge = `<span class="px-2 py-0.5 rounded bg-slate-800 text-slate-300 text-[10px] font-bold">${escapeHtml(g.mode)}</span>`;
  17357. }
  17358. const autoNatBadge = g.auto_nat
  17359. ? '<span class="text-emerald-400 text-[11px]">Enabled</span>'
  17360. : '<span class="text-slate-500 text-[11px]">Disabled</span>';
  17361. return `
  17362. <tr class="hover:bg-slate-800/40 transition">
  17363. <td class="py-3 px-4">
  17364. <button onclick="toggleSDWANGroupState('${escapeHtml(g.id)}', ${isEnabled})" class="relative inline-flex h-5 w-9 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none ${isEnabled ? 'bg-amber-500' : 'bg-slate-700'}" title="${isEnabled ? 'Click to disable' : 'Click to enable'}">
  17365. <span class="inline-block h-4 w-4 transform rounded-full bg-white shadow transition duration-200 ease-in-out ${isEnabled ? 'translate-x-4' : 'translate-x-0'}"></span>
  17366. </button>
  17367. </td>
  17368. <td class="py-3 px-4">
  17369. <div class="font-bold text-white text-xs flex items-center gap-1.5">
  17370. <span class="px-2 py-0.5 rounded bg-amber-950/60 text-amber-300 border border-amber-800/40 font-mono text-[11px] font-bold">${escapeHtml(g.name)}</span>
  17371. ${g.comment ? `<span class="text-slate-400 text-[10px] font-sans truncate max-w-[150px]" title="${escapeHtml(g.comment)}">(${escapeHtml(g.comment)})</span>` : ''}
  17372. </div>
  17373. </td>
  17374. <td class="py-3 px-4">${modeBadge}</td>
  17375. <td class="py-3 px-4">${distHtml}</td>
  17376. <td class="py-3 px-4">
  17377. <span class="px-2 py-0.5 rounded bg-slate-800 text-slate-200 border border-slate-700 font-mono text-[11px]">${members.length} links</span>
  17378. </td>
  17379. <td class="py-3 px-4 text-slate-300 font-mono text-xs">${g.probe_interval || 3}s</td>
  17380. <td class="py-3 px-4">${autoNatBadge}</td>
  17381. <td class="py-3 px-4 text-right">
  17382. <div class="flex items-center justify-end gap-1.5">
  17383. <button onclick="openAddSDWANMemberModal('${escapeHtml(g.id)}')" class="p-1.5 rounded-lg bg-slate-800 hover:bg-slate-700 text-amber-300 transition" title="Add Member Link">
  17384. <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="M12 4v16m8-8H4"/></svg>
  17385. </button>
  17386. <button onclick="openEditSDWANGroupModal('${escapeHtml(g.id)}')" class="p-1.5 rounded-lg bg-slate-800 hover:bg-slate-700 text-slate-300 transition" title="Edit Group">
  17387. <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="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>
  17388. </button>
  17389. <button onclick="deleteSDWANGroup('${escapeHtml(g.id)}')" class="p-1.5 rounded-lg bg-rose-950/40 hover:bg-rose-900/60 text-rose-400 border border-rose-800/40 transition" title="Delete Group">
  17390. <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>
  17391. </button>
  17392. </div>
  17393. </td>
  17394. </tr>
  17395. `;
  17396. }).join('');
  17397. }
  17398. function renderSDWANMembers(groups) {
  17399. const tbody = document.getElementById('sdwan-members-table-body');
  17400. if (!tbody) return;
  17401. const allMembers = [];
  17402. (groups || []).forEach(g => {
  17403. (g.members || []).forEach(m => {
  17404. allMembers.push({ ...m, group_id: g.id, group_name: g.name });
  17405. });
  17406. });
  17407. if (allMembers.length === 0) {
  17408. tbody.innerHTML = '<tr><td colspan="11" class="py-8 text-center text-slate-500 text-xs font-sans">No member WAN links configured. Click "Add Member Link" above.</td></tr>';
  17409. return;
  17410. }
  17411. tbody.innerHTML = allMembers.map(m => {
  17412. const isEnabled = m.disabled !== true;
  17413. let statusBadge = '<span class="px-2 py-0.5 rounded bg-emerald-500/20 text-emerald-400 border border-emerald-500/30 text-[10px] font-bold">HEALTHY</span>';
  17414. if (!isEnabled) {
  17415. statusBadge = '<span class="px-2 py-0.5 rounded bg-slate-800 text-slate-400 border border-slate-700 text-[10px]">DISABLED</span>';
  17416. } else if (m.status === 'DEGRADED') {
  17417. statusBadge = '<span class="px-2 py-0.5 rounded bg-amber-500/20 text-amber-400 border border-amber-500/30 text-[10px] font-bold">DEGRADED</span>';
  17418. } else if (m.status === 'DOWN') {
  17419. statusBadge = '<span class="px-2 py-0.5 rounded bg-rose-500/20 text-rose-400 border border-rose-500/30 text-[10px] font-bold animate-pulse">DOWN</span>';
  17420. }
  17421. const latColor = m.live_latency > (m.max_latency || 250) ? 'text-amber-400' : 'text-emerald-400';
  17422. const lossColor = m.packet_loss > (m.max_loss || 20) ? 'text-rose-400' : 'text-slate-300';
  17423. return `
  17424. <tr class="hover:bg-slate-800/40 transition">
  17425. <td class="py-3 px-4">
  17426. <button onclick="toggleSDWANMemberState('${escapeHtml(m.group_id)}', '${escapeHtml(m.id)}', ${isEnabled})" class="relative inline-flex h-5 w-9 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none ${isEnabled ? 'bg-amber-500' : 'bg-slate-700'}" title="${isEnabled ? 'Click to disable link' : 'Click to enable link'}">
  17427. <span class="inline-block h-4 w-4 transform rounded-full bg-white shadow transition duration-200 ease-in-out ${isEnabled ? 'translate-x-4' : 'translate-x-0'}"></span>
  17428. </button>
  17429. </td>
  17430. <td class="py-3 px-4">
  17431. <span class="px-2 py-0.5 rounded bg-amber-950/60 text-amber-300 border border-amber-800/40 font-mono text-[11px] font-bold">${escapeHtml(m.group_name)}</span>
  17432. </td>
  17433. <td class="py-3 px-4">
  17434. <div class="font-bold text-white text-xs font-mono">${escapeHtml(m.interface)}</div>
  17435. ${m.comment ? `<div class="text-[10px] text-slate-500 font-sans">${escapeHtml(m.comment)}</div>` : ''}
  17436. </td>
  17437. <td class="py-3 px-4 text-slate-300 font-mono text-xs">${escapeHtml(m.gateway || '(auto)')}</td>
  17438. <td class="py-3 px-4">
  17439. <div class="text-xs font-mono text-white">W: ${m.weight || 50}</div>
  17440. <div class="text-[10px] text-slate-500">Prio: ${m.priority || 1}</div>
  17441. </td>
  17442. <td class="py-3 px-4">${statusBadge}</td>
  17443. <td class="py-3 px-4 text-cyan-400 font-mono text-xs">${escapeHtml(m.target_probe || '1.1.1.1')}</td>
  17444. <td class="py-3 px-4 font-mono text-xs ${latColor}">
  17445. ${m.live_latency ? `${m.live_latency.toFixed(1)} ms` : '<span class="text-slate-500">--</span>'}
  17446. </td>
  17447. <td class="py-3 px-4 font-mono text-xs ${lossColor}">
  17448. ${m.packet_loss !== undefined ? `${m.packet_loss.toFixed(1)}%` : '<span class="text-slate-500">--</span>'}
  17449. </td>
  17450. <td class="py-3 px-4 font-mono text-xs text-slate-400">
  17451. ${m.jitter ? `${m.jitter.toFixed(1)} ms` : '<span class="text-slate-500">--</span>'}
  17452. </td>
  17453. <td class="py-3 px-4 text-right">
  17454. <div class="flex items-center justify-end gap-1.5">
  17455. <button onclick="openEditSDWANMemberModal('${escapeHtml(m.group_id)}', '${escapeHtml(m.id)}')" class="p-1.5 rounded-lg bg-slate-800 hover:bg-slate-700 text-slate-300 transition" title="Edit Member">
  17456. <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="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>
  17457. </button>
  17458. <button onclick="deleteSDWANMember('${escapeHtml(m.group_id)}', '${escapeHtml(m.interface)}')" class="p-1.5 rounded-lg bg-rose-950/40 hover:bg-rose-900/60 text-rose-400 border border-rose-800/40 transition" title="Remove Link">
  17459. <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>
  17460. </button>
  17461. </div>
  17462. </td>
  17463. </tr>
  17464. `;
  17465. }).join('');
  17466. }
  17467. // Modal handling for SD-WAN Groups
  17468. function openAddSDWANGroupModal() {
  17469. const modal = document.getElementById('modal-sdwan-group');
  17470. if (!modal) return;
  17471. document.getElementById('sdwan-group-modal-title').querySelector('span').textContent = 'Create SD-WAN Group';
  17472. document.getElementById('sdwan-group-id').value = '';
  17473. document.getElementById('sdwan-group-name').value = `sdwan${(state.sdwanGroups || []).length}`;
  17474. document.getElementById('sdwan-group-name').disabled = false;
  17475. document.getElementById('sdwan-group-mode').value = 'weighted';
  17476. document.getElementById('sdwan-group-pcc-container').classList.add('hidden');
  17477. document.getElementById('sdwan-group-hash-fields').value = 'both-addresses-and-ports';
  17478. document.getElementById('sdwan-group-probe-interval').value = 3;
  17479. document.getElementById('sdwan-group-auto-nat').checked = true;
  17480. document.getElementById('sdwan-group-comment').value = '';
  17481. modal.classList.remove('hidden');
  17482. }
  17483. function openEditSDWANGroupModal(id) {
  17484. const group = (state.sdwanGroups || []).find(g => g.id === id);
  17485. if (!group) return;
  17486. const modal = document.getElementById('modal-sdwan-group');
  17487. if (!modal) return;
  17488. document.getElementById('sdwan-group-modal-title').querySelector('span').textContent = `Edit SD-WAN Group (${group.name})`;
  17489. document.getElementById('sdwan-group-id').value = group.id;
  17490. document.getElementById('sdwan-group-name').value = group.name;
  17491. document.getElementById('sdwan-group-name').disabled = true;
  17492. document.getElementById('sdwan-group-mode').value = group.mode || 'weighted';
  17493. if (group.mode === 'pcc') {
  17494. document.getElementById('sdwan-group-pcc-container').classList.remove('hidden');
  17495. } else {
  17496. document.getElementById('sdwan-group-pcc-container').classList.add('hidden');
  17497. }
  17498. document.getElementById('sdwan-group-hash-fields').value = group.hash_fields || 'both-addresses-and-ports';
  17499. document.getElementById('sdwan-group-probe-interval').value = group.probe_interval || 3;
  17500. document.getElementById('sdwan-group-auto-nat').checked = group.auto_nat !== false;
  17501. document.getElementById('sdwan-group-comment').value = group.comment || '';
  17502. modal.classList.remove('hidden');
  17503. }
  17504. function closeSDWANGroupModal() {
  17505. const modal = document.getElementById('modal-sdwan-group');
  17506. if (modal) modal.classList.add('hidden');
  17507. }
  17508. function onSDWANModeChange() {
  17509. const mode = document.getElementById('sdwan-group-mode').value;
  17510. const pccContainer = document.getElementById('sdwan-group-pcc-container');
  17511. if (pccContainer) {
  17512. if (mode === 'pcc') pccContainer.classList.remove('hidden');
  17513. else pccContainer.classList.add('hidden');
  17514. }
  17515. }
  17516. async function saveSDWANGroup(event) {
  17517. event.preventDefault();
  17518. const id = document.getElementById('sdwan-group-id').value;
  17519. const name = document.getElementById('sdwan-group-name').value.trim();
  17520. const mode = document.getElementById('sdwan-group-mode').value;
  17521. const hashFields = document.getElementById('sdwan-group-hash-fields').value;
  17522. const probeInterval = parseInt(document.getElementById('sdwan-group-probe-interval').value, 10) || 3;
  17523. const autoNAT = document.getElementById('sdwan-group-auto-nat').checked;
  17524. const comment = document.getElementById('sdwan-group-comment').value.trim();
  17525. const existing = (state.sdwanGroups || []).find(g => g.id === id);
  17526. const payload = {
  17527. id: id || undefined,
  17528. name,
  17529. mode,
  17530. hash_fields: mode === 'pcc' ? hashFields : undefined,
  17531. probe_interval: probeInterval,
  17532. auto_nat: autoNAT,
  17533. comment,
  17534. members: existing ? existing.members : undefined
  17535. };
  17536. try {
  17537. const res = await fetch(`${API_BASE}/sdwan/groups`, {
  17538. method: 'POST',
  17539. headers: { 'Content-Type': 'application/json' },
  17540. body: JSON.stringify(payload)
  17541. });
  17542. if (!res.ok) {
  17543. const err = await res.json().catch(() => ({}));
  17544. throw new Error(err.message || 'Failed to save SD-WAN group');
  17545. }
  17546. closeSDWANGroupModal();
  17547. showToast('Success', `SD-WAN group ${name} saved successfully`, 'success');
  17548. await loadSDWAN(false);
  17549. } catch (err) {
  17550. showToast('Error', err.message, 'error');
  17551. }
  17552. }
  17553. async function toggleSDWANGroupState(id, currentState) {
  17554. try {
  17555. const res = await fetch(`${API_BASE}/sdwan/groups/${id}/state`, {
  17556. method: 'POST',
  17557. headers: { 'Content-Type': 'application/json' },
  17558. body: JSON.stringify({ disabled: currentState })
  17559. });
  17560. if (!res.ok) throw new Error('Failed to update group state');
  17561. await loadSDWAN(false);
  17562. } catch (err) {
  17563. showToast('Error', err.message, 'error');
  17564. }
  17565. }
  17566. async function deleteSDWANGroup(id) {
  17567. const group = (state.sdwanGroups || []).find(g => g.id === id);
  17568. const name = group ? group.name : id;
  17569. if (!confirm(`Are you sure you want to delete SD-WAN group "${name}"? Member routing tables will be cleared.`)) return;
  17570. try {
  17571. const res = await fetch(`${API_BASE}/sdwan/groups/${id}`, {
  17572. method: 'DELETE'
  17573. });
  17574. if (!res.ok) {
  17575. const err = await res.json().catch(() => ({}));
  17576. throw new Error(err.message || 'Failed to delete SD-WAN group');
  17577. }
  17578. showToast('Deleted', `SD-WAN group ${name} removed`, 'success');
  17579. await loadSDWAN(false);
  17580. } catch (err) {
  17581. showToast('Error', err.message, 'error');
  17582. }
  17583. }
  17584. // Modal handling for SD-WAN Members
  17585. function populateSDWANGroupsSelect(selectedId = '') {
  17586. const sel = document.getElementById('sdwan-member-group-id');
  17587. if (!sel) return;
  17588. sel.innerHTML = '';
  17589. (state.sdwanGroups || []).forEach(g => {
  17590. const opt = document.createElement('option');
  17591. opt.value = g.id;
  17592. opt.textContent = `${g.name} (${g.mode})`;
  17593. if (g.id === selectedId) opt.selected = true;
  17594. sel.appendChild(opt);
  17595. });
  17596. }
  17597. function populateSDWANMemberInterfaceSelect(selectedVal = '') {
  17598. const sel = document.getElementById('sdwan-member-interface');
  17599. if (!sel) return;
  17600. sel.innerHTML = '';
  17601. (state.interfaces || []).forEach(i => {
  17602. const opt = document.createElement('option');
  17603. opt.value = i.name;
  17604. opt.textContent = `${i.name} (${i.role || i.type})`;
  17605. if (i.name === selectedVal) opt.selected = true;
  17606. sel.appendChild(opt);
  17607. });
  17608. }
  17609. function openAddSDWANMemberModal(defaultGroupId = null) {
  17610. const modal = document.getElementById('modal-sdwan-member');
  17611. if (!modal) return;
  17612. if (!state.sdwanGroups || state.sdwanGroups.length === 0) {
  17613. showToast('Notice', 'Please create an SD-WAN group first before adding member links', 'warning');
  17614. return;
  17615. }
  17616. document.getElementById('sdwan-member-modal-title').querySelector('span').textContent = 'Add Member Link';
  17617. document.getElementById('sdwan-member-id').value = '';
  17618. populateSDWANGroupsSelect(defaultGroupId || (state.sdwanGroups[0] && state.sdwanGroups[0].id));
  17619. populateSDWANMemberInterfaceSelect();
  17620. document.getElementById('sdwan-member-gateway').value = '';
  17621. document.getElementById('sdwan-member-weight').value = 50;
  17622. document.getElementById('sdwan-member-priority').value = 1;
  17623. document.getElementById('sdwan-member-probe').value = '1.1.1.1';
  17624. document.getElementById('sdwan-member-max-lat').value = 250;
  17625. document.getElementById('sdwan-member-max-loss').value = 20;
  17626. document.getElementById('sdwan-member-comment').value = '';
  17627. modal.classList.remove('hidden');
  17628. }
  17629. function openEditSDWANMemberModal(groupId, memberId) {
  17630. const group = (state.sdwanGroups || []).find(g => g.id === groupId);
  17631. if (!group) return;
  17632. const member = (group.members || []).find(m => m.id === memberId);
  17633. if (!member) return;
  17634. const modal = document.getElementById('modal-sdwan-member');
  17635. if (!modal) return;
  17636. document.getElementById('sdwan-member-modal-title').querySelector('span').textContent = `Edit Member Link (${member.interface})`;
  17637. document.getElementById('sdwan-member-id').value = member.id;
  17638. populateSDWANGroupsSelect(group.id);
  17639. document.getElementById('sdwan-member-group-id').disabled = true;
  17640. populateSDWANMemberInterfaceSelect(member.interface);
  17641. document.getElementById('sdwan-member-interface').disabled = true;
  17642. document.getElementById('sdwan-member-gateway').value = member.gateway || '';
  17643. document.getElementById('sdwan-member-weight').value = member.weight || 50;
  17644. document.getElementById('sdwan-member-priority').value = member.priority || 1;
  17645. document.getElementById('sdwan-member-probe').value = member.target_probe || '1.1.1.1';
  17646. document.getElementById('sdwan-member-max-lat').value = member.max_latency || 250;
  17647. document.getElementById('sdwan-member-max-loss').value = member.max_loss || 20;
  17648. document.getElementById('sdwan-member-comment').value = member.comment || '';
  17649. modal.classList.remove('hidden');
  17650. }
  17651. function closeSDWANMemberModal() {
  17652. const modal = document.getElementById('modal-sdwan-member');
  17653. if (modal) {
  17654. document.getElementById('sdwan-member-group-id').disabled = false;
  17655. document.getElementById('sdwan-member-interface').disabled = false;
  17656. modal.classList.add('hidden');
  17657. }
  17658. }
  17659. async function saveSDWANMember(event) {
  17660. event.preventDefault();
  17661. const id = document.getElementById('sdwan-member-id').value;
  17662. let groupId = document.getElementById('sdwan-member-group-id').value;
  17663. let iface = document.getElementById('sdwan-member-interface').value;
  17664. // In edit mode with disabled selects, fallback to existing member data if needed
  17665. if (id) {
  17666. const existingGroup = (state.sdwanGroups || []).find(g => (g.members || []).some(m => m.id === id));
  17667. if (existingGroup) {
  17668. if (!groupId) groupId = existingGroup.id;
  17669. const mem = (existingGroup.members || []).find(m => m.id === id);
  17670. if (mem && !iface) iface = mem.interface;
  17671. }
  17672. }
  17673. const gateway = document.getElementById('sdwan-member-gateway').value.trim();
  17674. const weight = parseInt(document.getElementById('sdwan-member-weight').value, 10) || 50;
  17675. const priority = parseInt(document.getElementById('sdwan-member-priority').value, 10) || 1;
  17676. const targetProbe = document.getElementById('sdwan-member-probe').value.trim() || '1.1.1.1';
  17677. const maxLatency = parseInt(document.getElementById('sdwan-member-max-lat').value, 10) || 250;
  17678. const maxLoss = parseInt(document.getElementById('sdwan-member-max-loss').value, 10) || 20;
  17679. const comment = document.getElementById('sdwan-member-comment').value.trim();
  17680. const payload = {
  17681. id: id || undefined,
  17682. interface: iface,
  17683. gateway,
  17684. weight,
  17685. priority,
  17686. target_probe: targetProbe,
  17687. max_latency: maxLatency,
  17688. max_loss: maxLoss,
  17689. comment
  17690. };
  17691. try {
  17692. const method = id ? 'PUT' : 'POST';
  17693. const res = await fetch(`${API_BASE}/sdwan/groups/${groupId}/members`, {
  17694. method,
  17695. headers: { 'Content-Type': 'application/json' },
  17696. body: JSON.stringify(payload)
  17697. });
  17698. if (!res.ok) {
  17699. const err = await res.json().catch(() => ({}));
  17700. throw new Error(err.message || 'Failed to save member link');
  17701. }
  17702. closeSDWANMemberModal();
  17703. showToast('Success', `Link ${iface} saved to SD-WAN group`, 'success');
  17704. await loadSDWAN(false);
  17705. } catch (err) {
  17706. showToast('Error', err.message, 'error');
  17707. }
  17708. }
  17709. async function toggleSDWANMemberState(groupId, memberId, currentState) {
  17710. const group = (state.sdwanGroups || []).find(g => g.id === groupId);
  17711. if (!group) return;
  17712. const member = (group.members || []).find(m => m.id === memberId);
  17713. if (!member) return;
  17714. const payload = {
  17715. ...member,
  17716. disabled: currentState
  17717. };
  17718. try {
  17719. const res = await fetch(`${API_BASE}/sdwan/groups/${groupId}/members`, {
  17720. method: 'PUT',
  17721. headers: { 'Content-Type': 'application/json' },
  17722. body: JSON.stringify(payload)
  17723. });
  17724. if (!res.ok) throw new Error('Failed to update member state');
  17725. await loadSDWAN(false);
  17726. } catch (err) {
  17727. showToast('Error', err.message, 'error');
  17728. }
  17729. }
  17730. async function deleteSDWANMember(groupId, iface) {
  17731. if (!confirm(`Are you sure you want to remove link "${iface}" from this SD-WAN group?`)) return;
  17732. try {
  17733. const res = await fetch(`${API_BASE}/sdwan/groups/${groupId}/members/${iface}`, {
  17734. method: 'DELETE'
  17735. });
  17736. if (!res.ok) {
  17737. const err = await res.json().catch(() => ({}));
  17738. throw new Error(err.message || 'Failed to remove member link');
  17739. }
  17740. showToast('Removed', `Link ${iface} removed from SD-WAN group`, 'success');
  17741. await loadSDWAN(false);
  17742. } catch (err) {
  17743. showToast('Error', err.message, 'error');
  17744. }
  17745. }
  17746. // ==============================================================================
  17747. async function routingMutation(url, options) {
  17748. try {
  17749. const response = await fetch(url, options);
  17750. if (!response.ok) throw new Error(await responseError(response));
  17751. return true;
  17752. } catch (error) {
  17753. showToast('Routing change failed', error.message || 'Request failed', 'error');
  17754. return false;
  17755. }
  17756. }
  17757. // DYNAMIC ROUTING: RIP MODULE
  17758. // ==============================================================================
  17759. state.ripInstances = [];
  17760. state.ripInterfaces = [];
  17761. state.ripNeighborsLive = [];
  17762. state.ripRoutes = [];
  17763. state.selectedRipRow = {};
  17764. state.activeRipTab = 'instances';
  17765. function switchRipTab(tab) {
  17766. state.activeRipTab = tab;
  17767. ['instances', 'interfaces', 'neighbors', 'routes'].forEach(t => {
  17768. const pane = document.getElementById(`rip-pane-${t}`);
  17769. const btn = document.getElementById(`rip-tab-btn-${t}`);
  17770. if (pane) {
  17771. if (t === tab) pane.classList.remove('hidden');
  17772. else pane.classList.add('hidden');
  17773. }
  17774. if (btn) {
  17775. if (t === tab) {
  17776. btn.className = 'px-3 py-2 text-xs font-semibold border-b-2 border-rose-500 text-white transition flex items-center gap-1.5 whitespace-nowrap';
  17777. } else {
  17778. 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';
  17779. }
  17780. }
  17781. });
  17782. }
  17783. function selectRipRow(tab, id) {
  17784. if (!state.selectedRipRow) state.selectedRipRow = {};
  17785. state.selectedRipRow[tab] = id;
  17786. if (tab === 'instances') {
  17787. renderRipInstances();
  17788. const btnEn = document.getElementById('btn-rip-inst-enable');
  17789. const btnDis = document.getElementById('btn-rip-inst-disable');
  17790. const btnRem = document.getElementById('btn-rip-inst-remove');
  17791. if (btnEn) btnEn.disabled = false;
  17792. if (btnDis) btnDis.disabled = false;
  17793. if (btnRem) btnRem.disabled = false;
  17794. } else if (tab === 'interfaces') {
  17795. renderRipInterfaces();
  17796. const btnEn = document.getElementById('btn-rip-iface-enable');
  17797. const btnDis = document.getElementById('btn-rip-iface-disable');
  17798. const btnRem = document.getElementById('btn-rip-iface-remove');
  17799. if (btnEn) btnEn.disabled = false;
  17800. if (btnDis) btnDis.disabled = false;
  17801. if (btnRem) btnRem.disabled = false;
  17802. }
  17803. }
  17804. function renderRipInstances() {
  17805. const tbody = document.getElementById('rip-instances-table-body');
  17806. if (!tbody) return;
  17807. const countEl = document.getElementById('rip-instances-footer-count');
  17808. const filter = (document.getElementById('filter-rip-instances')?.value || '').toLowerCase();
  17809. let list = state.ripInstances || [];
  17810. if (filter) {
  17811. list = list.filter(i => (i.name || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  17812. }
  17813. if (countEl) countEl.innerText = list.length;
  17814. const selId = state.selectedRipRow?.instances;
  17815. tbody.innerHTML = list.map((inst, idx) => {
  17816. const isSel = inst.id === selId;
  17817. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-rose-400' : 'hover:bg-[#1a2636] text-slate-300';
  17818. const flagD = inst.disabled
  17819. ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>'
  17820. : (inst.running
  17821. ? '<span class="text-emerald-400 font-bold" title="Running (R)">R</span>'
  17822. : '<span class="text-amber-400 font-bold" title="Inactive (I)">I</span>');
  17823. const redist = [];
  17824. if (inst.redistribute_connected) redist.push('conn');
  17825. if (inst.redistribute_static) redist.push('static');
  17826. if (inst.redistribute_bgp) redist.push('bgp');
  17827. if (inst.redistribute_ospf) redist.push('ospf');
  17828. if (inst.redistribute_default) redist.push('default');
  17829. const filterBadges = [];
  17830. if (inst.in_filter) filterBadges.push(`<span class="px-1.5 py-0.5 rounded text-[10px] bg-blue-950 text-blue-300 border border-blue-800/50" title="In Filter">IN: ${escapeHtml(inst.in_filter)}</span>`);
  17831. if (inst.out_filter) filterBadges.push(`<span class="px-1.5 py-0.5 rounded text-[10px] bg-purple-950 text-purple-300 border border-purple-800/50" title="Out Filter">OUT: ${escapeHtml(inst.out_filter)}</span>`);
  17832. return `
  17833. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectRipRow('instances', '${inst.id}')" ondblclick="openEditRipInstanceModal('${inst.id}')">
  17834. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  17835. <td class="py-1.5 px-3 w-12 text-center">${flagD}</td>
  17836. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(inst.comment || '')}</td>
  17837. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  17838. <span class="text-rose-400">↳</span> <span>${escapeHtml(inst.name || 'default')}</span>
  17839. ${filterBadges.join(' ')}
  17840. </td>
  17841. <td class="py-1.5 px-3 uppercase text-rose-300 font-bold">${inst.version == 1 || inst.version === 'ripng' ? 'RIPng' : 'RIPv2'}</td>
  17842. <td class="py-1.5 px-3 text-slate-400">${inst.update_time || 30}s</td>
  17843. <td class="py-1.5 px-3 text-slate-400">${inst.timeout_time || 180}s</td>
  17844. <td class="py-1.5 px-3 font-mono text-cyan-300">${redist.join(', ') || 'none'}</td>
  17845. <td class="py-1.5 px-3 font-mono text-slate-300">${inst.default_metric || 1}</td>
  17846. </tr>
  17847. `;
  17848. }).join('');
  17849. }
  17850. function renderRipInterfaces() {
  17851. const tbody = document.getElementById('rip-interfaces-table-body');
  17852. if (!tbody) return;
  17853. const countEl = document.getElementById('rip-interfaces-footer-count');
  17854. const filter = (document.getElementById('filter-rip-interfaces')?.value || '').toLowerCase();
  17855. let list = state.ripInterfaces || [];
  17856. if (filter) {
  17857. list = list.filter(i => (i.interface || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  17858. }
  17859. if (countEl) countEl.innerText = list.length;
  17860. const selId = state.selectedRipRow?.interfaces;
  17861. tbody.innerHTML = list.map((iface, idx) => {
  17862. const isSel = iface.id === selId;
  17863. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-rose-400' : 'hover:bg-[#1a2636] text-slate-300';
  17864. const flagD = iface.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '<span class="text-emerald-400">R</span>';
  17865. return `
  17866. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectRipRow('interfaces', '${iface.id}')" ondblclick="openEditRipInterfaceModal('${iface.id}')">
  17867. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  17868. <td class="py-1.5 px-3 w-12 text-center">${flagD}</td>
  17869. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(iface.comment || '')}</td>
  17870. <td class="py-1.5 px-3 font-mono font-semibold text-white">${escapeHtml(iface.interface || '*')}</td>
  17871. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(iface.mode || 'multicast')}</td>
  17872. <td class="py-1.5 px-3 font-mono text-slate-300">${iface.metric || 1}</td>
  17873. <td class="py-1.5 px-3 text-slate-400">${iface.passive ? 'yes' : 'no'}</td>
  17874. <td class="py-1.5 px-3">${iface.use_bfd ? '<span class="text-amber-400 font-bold">yes</span>' : '<span class="text-slate-500">no</span>'}</td>
  17875. </tr>
  17876. `;
  17877. }).join('');
  17878. }
  17879. function renderRipNeighbors() {
  17880. const tbody = document.getElementById('rip-neighbors-table-body');
  17881. if (!tbody) return;
  17882. const countEl = document.getElementById('rip-neighbors-footer-count');
  17883. const list = state.ripNeighborsLive || [];
  17884. if (countEl) countEl.innerText = list.length;
  17885. tbody.innerHTML = list.map((nbr, idx) => `
  17886. <tr class="hover:bg-[#1a2636] text-slate-300">
  17887. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  17888. <td class="py-1.5 px-3 font-mono font-semibold text-rose-300">${escapeHtml(nbr.address || '')}</td>
  17889. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(nbr.interface || '')}</td>
  17890. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(nbr.last_seen || '')}</td>
  17891. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(nbr.uptime || '')}</td>
  17892. </tr>
  17893. `).join('');
  17894. }
  17895. function renderRipRoutes() {
  17896. const tbody = document.getElementById('rip-routes-table-body');
  17897. if (!tbody) return;
  17898. const countEl = document.getElementById('rip-routes-footer-count');
  17899. const list = state.ripRoutes || [];
  17900. if (countEl) countEl.innerText = list.length;
  17901. tbody.innerHTML = list.map((r, idx) => `
  17902. <tr class="hover:bg-[#1a2636] text-slate-300">
  17903. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  17904. <td class="py-1.5 px-3 font-mono font-semibold text-white">${escapeHtml(r.prefix || '')}</td>
  17905. <td class="py-1.5 px-3 font-mono text-cyan-300">${escapeHtml(r.next_hop || '')}</td>
  17906. <td class="py-1.5 px-3 font-mono text-slate-300">${r.metric || 1}</td>
  17907. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(r.interface || '')}</td>
  17908. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(r.uptime || '')}</td>
  17909. </tr>
  17910. `).join('');
  17911. }
  17912. function openRipInstanceModal() {
  17913. document.getElementById('rip-instance-modal-title').innerText = 'New RIP Instance';
  17914. document.getElementById('modal-rip-instance-id').value = '';
  17915. document.getElementById('modal-rip-instance-name').value = 'rip1';
  17916. document.getElementById('modal-rip-instance-version').value = '2';
  17917. document.getElementById('modal-rip-instance-update').value = '30';
  17918. document.getElementById('modal-rip-instance-timeout').value = '180';
  17919. document.getElementById('modal-rip-instance-garbage').value = '120';
  17920. document.getElementById('modal-rip-instance-metric').value = '1';
  17921. document.getElementById('modal-rip-instance-comment').value = '';
  17922. document.getElementById('modal-rip-instance-in-filter').value = '';
  17923. document.getElementById('modal-rip-instance-out-filter').value = '';
  17924. document.getElementById('modal-rip-instance-enabled').checked = true;
  17925. document.getElementById('modal-rip-instance-redist-conn').checked = false;
  17926. document.getElementById('modal-rip-instance-redist-static').checked = false;
  17927. document.getElementById('modal-rip-instance-redist-bgp').checked = false;
  17928. document.getElementById('modal-rip-instance-redist-ospf').checked = false;
  17929. document.getElementById('modal-rip-instance-redist-default').checked = false;
  17930. document.getElementById('rip-instance-modal')?.classList.remove('hidden');
  17931. }
  17932. function openEditRipInstanceModal(id) {
  17933. const inst = (state.ripInstances || []).find(i => i.id === id);
  17934. if (!inst) return;
  17935. document.getElementById('rip-instance-modal-title').innerText = `Edit RIP Instance: ${inst.name}`;
  17936. document.getElementById('modal-rip-instance-id').value = inst.id;
  17937. document.getElementById('modal-rip-instance-name').value = inst.name || '';
  17938. document.getElementById('modal-rip-instance-version').value = (inst.version == 1 || inst.version === 'ripng') ? '1' : '2';
  17939. document.getElementById('modal-rip-instance-update').value = inst.update_time || 30;
  17940. document.getElementById('modal-rip-instance-timeout').value = inst.timeout_time || 180;
  17941. document.getElementById('modal-rip-instance-garbage').value = inst.garbage_time || 120;
  17942. document.getElementById('modal-rip-instance-metric').value = inst.default_metric || 1;
  17943. document.getElementById('modal-rip-instance-comment').value = inst.comment || '';
  17944. document.getElementById('modal-rip-instance-in-filter').value = inst.in_filter || '';
  17945. document.getElementById('modal-rip-instance-out-filter').value = inst.out_filter || '';
  17946. document.getElementById('modal-rip-instance-enabled').checked = !inst.disabled;
  17947. document.getElementById('modal-rip-instance-redist-conn').checked = !!inst.redistribute_connected;
  17948. document.getElementById('modal-rip-instance-redist-static').checked = !!inst.redistribute_static;
  17949. document.getElementById('modal-rip-instance-redist-bgp').checked = !!inst.redistribute_bgp;
  17950. document.getElementById('modal-rip-instance-redist-ospf').checked = !!inst.redistribute_ospf;
  17951. document.getElementById('modal-rip-instance-redist-default').checked = !!inst.redistribute_default;
  17952. document.getElementById('rip-instance-modal')?.classList.remove('hidden');
  17953. }
  17954. function closeRipInstanceModal() {
  17955. document.getElementById('rip-instance-modal')?.classList.add('hidden');
  17956. }
  17957. async function submitRipInstance(e) {
  17958. e.preventDefault();
  17959. const id = document.getElementById('modal-rip-instance-id').value;
  17960. const payload = {
  17961. id: id || undefined,
  17962. name: document.getElementById('modal-rip-instance-name').value.trim(),
  17963. version: parseInt(document.getElementById('modal-rip-instance-version').value, 10) || 2,
  17964. update_time: parseInt(document.getElementById('modal-rip-instance-update').value, 10) || 30,
  17965. timeout_time: parseInt(document.getElementById('modal-rip-instance-timeout').value, 10) || 180,
  17966. garbage_time: parseInt(document.getElementById('modal-rip-instance-garbage').value, 10) || 120,
  17967. default_metric: parseInt(document.getElementById('modal-rip-instance-metric').value, 10) || 1,
  17968. comment: document.getElementById('modal-rip-instance-comment').value.trim(),
  17969. in_filter: (document.getElementById('modal-rip-instance-in-filter')?.value || '').trim(),
  17970. out_filter: (document.getElementById('modal-rip-instance-out-filter')?.value || '').trim(),
  17971. disabled: !document.getElementById('modal-rip-instance-enabled').checked,
  17972. redistribute_connected: document.getElementById('modal-rip-instance-redist-conn').checked,
  17973. redistribute_static: document.getElementById('modal-rip-instance-redist-static').checked,
  17974. redistribute_bgp: document.getElementById('modal-rip-instance-redist-bgp').checked,
  17975. redistribute_ospf: document.getElementById('modal-rip-instance-redist-ospf').checked,
  17976. redistribute_default: document.getElementById('modal-rip-instance-redist-default').checked
  17977. };
  17978. try {
  17979. const res = await fetch(`${API_BASE}/routing/rip/instances`, {
  17980. method: 'POST',
  17981. headers: { 'Content-Type': 'application/json' },
  17982. body: JSON.stringify(payload)
  17983. });
  17984. if (!res.ok) throw new Error(await res.text());
  17985. closeRipInstanceModal();
  17986. showToast('Saved', `RIP instance ${payload.name} saved`, 'success');
  17987. await loadDynamicRouting(false);
  17988. } catch (err) {
  17989. showToast('Error', err.message, 'error');
  17990. }
  17991. }
  17992. async function enableSelectedRipInstance() {
  17993. const id = state.selectedRipRow?.instances;
  17994. if (!id) return;
  17995. if (!await routingMutation(`${API_BASE}/routing/rip/instances/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: false }) })) return;
  17996. await loadDynamicRouting(false);
  17997. }
  17998. async function disableSelectedRipInstance() {
  17999. const id = state.selectedRipRow?.instances;
  18000. if (!id) return;
  18001. if (!await routingMutation(`${API_BASE}/routing/rip/instances/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: true }) })) return;
  18002. await loadDynamicRouting(false);
  18003. }
  18004. async function removeSelectedRipInstance() {
  18005. const id = state.selectedRipRow?.instances;
  18006. if (!id || !confirm('Are you sure you want to delete this RIP instance?')) return;
  18007. if (!await routingMutation(`${API_BASE}/routing/rip/instances/${id}`, { method: 'DELETE' })) return;
  18008. state.selectedRipRow.instances = null;
  18009. await loadDynamicRouting(false);
  18010. }
  18011. function openRipInterfaceModal() {
  18012. document.getElementById('rip-interface-modal-title').innerText = 'New RIP Interface';
  18013. document.getElementById('modal-rip-iface-id').value = '';
  18014. const dl = document.getElementById('rip-iface-datalist');
  18015. if (dl) {
  18016. dl.innerHTML = '<option value="*">' + (state.interfaces || []).map(i => `<option value="${escapeHtml(i.name)}">`).join('');
  18017. }
  18018. const instSel = document.getElementById('modal-rip-iface-instance');
  18019. if (instSel && instSel.tagName === 'SELECT') {
  18020. instSel.innerHTML = (state.ripInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)}</option>`).join('');
  18021. if (instSel.innerHTML === '') instSel.innerHTML = '<option value="default">default</option>';
  18022. }
  18023. document.getElementById('modal-rip-iface-pattern').value = '*';
  18024. if (instSel) instSel.value = (state.ripInstances && state.ripInstances.length > 0) ? state.ripInstances[0].name : 'default';
  18025. document.getElementById('modal-rip-iface-mode').value = 'multicast';
  18026. document.getElementById('modal-rip-iface-metric').value = '1';
  18027. document.getElementById('modal-rip-iface-comment').value = '';
  18028. document.getElementById('modal-rip-iface-enabled').checked = true;
  18029. document.getElementById('modal-rip-iface-passive').checked = false;
  18030. document.getElementById('modal-rip-iface-bfd').checked = false;
  18031. document.getElementById('rip-interface-modal')?.classList.remove('hidden');
  18032. }
  18033. function openEditRipInterfaceModal(id) {
  18034. const iface = (state.ripInterfaces || []).find(i => i.id === id);
  18035. if (!iface) return;
  18036. document.getElementById('rip-interface-modal-title').innerText = `Edit RIP Interface: ${iface.interface}`;
  18037. document.getElementById('modal-rip-iface-id').value = iface.id;
  18038. const dl = document.getElementById('rip-iface-datalist');
  18039. if (dl) {
  18040. dl.innerHTML = '<option value="*">' + (state.interfaces || []).map(i => `<option value="${escapeHtml(i.name)}">`).join('');
  18041. }
  18042. const instSel = document.getElementById('modal-rip-iface-instance');
  18043. if (instSel && instSel.tagName === 'SELECT') {
  18044. instSel.innerHTML = (state.ripInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)}</option>`).join('');
  18045. if (instSel.innerHTML === '') instSel.innerHTML = '<option value="default">default</option>';
  18046. instSel.value = iface.instance || 'default';
  18047. } else if (instSel) {
  18048. instSel.value = iface.instance || '';
  18049. }
  18050. document.getElementById('modal-rip-iface-pattern').value = iface.interface || '*';
  18051. document.getElementById('modal-rip-iface-mode').value = iface.mode || 'multicast';
  18052. document.getElementById('modal-rip-iface-metric').value = iface.metric || 1;
  18053. document.getElementById('modal-rip-iface-comment').value = iface.comment || '';
  18054. document.getElementById('modal-rip-iface-enabled').checked = !iface.disabled;
  18055. document.getElementById('modal-rip-iface-passive').checked = !!iface.passive;
  18056. document.getElementById('modal-rip-iface-bfd').checked = !!iface.use_bfd;
  18057. document.getElementById('rip-interface-modal')?.classList.remove('hidden');
  18058. }
  18059. function closeRipInterfaceModal() {
  18060. document.getElementById('rip-interface-modal')?.classList.add('hidden');
  18061. }
  18062. async function submitRipInterface(e) {
  18063. e.preventDefault();
  18064. const id = document.getElementById('modal-rip-iface-id').value;
  18065. const payload = {
  18066. id: id || undefined,
  18067. interface: document.getElementById('modal-rip-iface-pattern').value.trim(),
  18068. instance: document.getElementById('modal-rip-iface-instance').value.trim(),
  18069. mode: document.getElementById('modal-rip-iface-mode').value,
  18070. metric: parseInt(document.getElementById('modal-rip-iface-metric').value, 10) || 1,
  18071. comment: document.getElementById('modal-rip-iface-comment').value.trim(),
  18072. disabled: !document.getElementById('modal-rip-iface-enabled').checked,
  18073. passive: document.getElementById('modal-rip-iface-passive').checked,
  18074. use_bfd: document.getElementById('modal-rip-iface-bfd').checked
  18075. };
  18076. try {
  18077. const res = await fetch(`${API_BASE}/routing/rip/interfaces`, {
  18078. method: 'POST',
  18079. headers: { 'Content-Type': 'application/json' },
  18080. body: JSON.stringify(payload)
  18081. });
  18082. if (!res.ok) throw new Error(await res.text());
  18083. closeRipInterfaceModal();
  18084. showToast('Saved', `RIP interface template saved`, 'success');
  18085. await loadDynamicRouting(false);
  18086. } catch (err) {
  18087. showToast('Error', err.message, 'error');
  18088. }
  18089. }
  18090. async function enableSelectedRipInterface() {
  18091. const id = state.selectedRipRow?.interfaces;
  18092. if (!id) return;
  18093. if (!await routingMutation(`${API_BASE}/routing/rip/interfaces/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: false }) })) return;
  18094. await loadDynamicRouting(false);
  18095. }
  18096. async function disableSelectedRipInterface() {
  18097. const id = state.selectedRipRow?.interfaces;
  18098. if (!id) return;
  18099. if (!await routingMutation(`${API_BASE}/routing/rip/interfaces/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: true }) })) return;
  18100. await loadDynamicRouting(false);
  18101. }
  18102. async function removeSelectedRipInterface() {
  18103. const id = state.selectedRipRow?.interfaces;
  18104. if (!id || !confirm('Are you sure you want to delete this RIP interface template?')) return;
  18105. if (!await routingMutation(`${API_BASE}/routing/rip/interfaces/${id}`, { method: 'DELETE' })) return;
  18106. state.selectedRipRow.interfaces = null;
  18107. await loadDynamicRouting(false);
  18108. }
  18109. // ==============================================================================
  18110. // DYNAMIC ROUTING: BFD MODULE
  18111. // ==============================================================================
  18112. state.bfdInstance = null;
  18113. state.bfdInterfaces = [];
  18114. state.bfdNeighbors = [];
  18115. state.bfdSessions = [];
  18116. state.selectedBfdRow = {};
  18117. state.activeBfdTab = 'config';
  18118. function switchBfdTab(tab) {
  18119. state.activeBfdTab = tab;
  18120. ['config', 'interfaces', 'peers', 'sessions'].forEach(t => {
  18121. const pane = document.getElementById(`bfd-pane-${t}`);
  18122. const btn = document.getElementById(`bfd-tab-btn-${t}`);
  18123. if (pane) {
  18124. if (t === tab) pane.classList.remove('hidden');
  18125. else pane.classList.add('hidden');
  18126. }
  18127. if (btn) {
  18128. if (t === tab) {
  18129. btn.className = 'px-3 py-2 text-xs font-semibold border-b-2 border-amber-500 text-white transition flex items-center gap-1.5 whitespace-nowrap';
  18130. } else {
  18131. 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';
  18132. }
  18133. }
  18134. });
  18135. }
  18136. function selectBfdRow(tab, id) {
  18137. if (!state.selectedBfdRow) state.selectedBfdRow = {};
  18138. state.selectedBfdRow[tab] = id;
  18139. if (tab === 'interfaces') {
  18140. renderBfdInterfaces();
  18141. const btnEn = document.getElementById('btn-bfd-iface-enable');
  18142. const btnDis = document.getElementById('btn-bfd-iface-disable');
  18143. const btnRem = document.getElementById('btn-bfd-iface-remove');
  18144. if (btnEn) btnEn.disabled = false;
  18145. if (btnDis) btnDis.disabled = false;
  18146. if (btnRem) btnRem.disabled = false;
  18147. } else if (tab === 'peers') {
  18148. renderBfdPeers();
  18149. const btnEn = document.getElementById('btn-bfd-peer-enable');
  18150. const btnDis = document.getElementById('btn-bfd-peer-disable');
  18151. const btnRem = document.getElementById('btn-bfd-peer-remove');
  18152. if (btnEn) btnEn.disabled = false;
  18153. if (btnDis) btnDis.disabled = false;
  18154. if (btnRem) btnRem.disabled = false;
  18155. }
  18156. }
  18157. function renderBfdConfig() {
  18158. const inst = state.bfdInstance;
  18159. const pill = document.getElementById('bfd-live-status-pill');
  18160. const toggleBtn = document.getElementById('bfd-global-toggle-btn');
  18161. const ifaceStat = document.getElementById('bfd-stat-interfaces');
  18162. const peerStat = document.getElementById('bfd-stat-peers');
  18163. const sessStat = document.getElementById('bfd-stat-sessions');
  18164. if (ifaceStat) ifaceStat.innerText = (state.bfdInterfaces || []).length;
  18165. if (peerStat) peerStat.innerText = (state.bfdNeighbors || []).length;
  18166. if (sessStat) sessStat.innerText = (state.bfdSessions || []).length;
  18167. const isEnabled = inst && (inst.enabled || inst.running || (!inst.disabled && (state.bfdInterfaces || []).length > 0));
  18168. if (!inst || inst.disabled || !isEnabled) {
  18169. if (pill) {
  18170. pill.className = 'text-[10px] px-2 py-0.5 rounded font-mono bg-slate-800 text-slate-400 border border-slate-700';
  18171. pill.innerText = 'DISABLED';
  18172. }
  18173. if (toggleBtn) {
  18174. toggleBtn.innerText = 'Enable BFD';
  18175. toggleBtn.className = 'px-4 py-2 rounded-lg text-xs font-semibold bg-amber-600 hover:bg-amber-500 text-white shadow-lg shadow-amber-500/20 transition';
  18176. }
  18177. } else {
  18178. if (pill) {
  18179. if (inst.running) {
  18180. pill.className = 'text-[10px] px-2 py-0.5 rounded font-mono bg-emerald-950 text-emerald-300 border border-emerald-800/60 font-semibold';
  18181. pill.innerText = 'RUNNING (ACTIVE)';
  18182. } else {
  18183. pill.className = 'text-[10px] px-2 py-0.5 rounded font-mono bg-amber-950 text-amber-300 border border-amber-800/60 font-semibold';
  18184. pill.innerText = 'CONFIGURED';
  18185. }
  18186. }
  18187. if (toggleBtn) {
  18188. toggleBtn.innerText = 'Disable BFD';
  18189. toggleBtn.className = 'px-4 py-2 rounded-lg text-xs font-semibold bg-rose-600/80 hover:bg-rose-600 text-white transition';
  18190. }
  18191. }
  18192. }
  18193. async function toggleBfdGlobalState() {
  18194. const current = state.bfdInstance;
  18195. const isCurrentlyEnabled = current && (current.enabled || current.running) && !current.disabled;
  18196. const newEnabled = !isCurrentlyEnabled;
  18197. const newDisabled = !newEnabled;
  18198. try {
  18199. const res = await fetch(`${API_BASE}/routing/bfd/instance`, {
  18200. method: 'POST',
  18201. headers: { 'Content-Type': 'application/json' },
  18202. body: JSON.stringify({ enabled: newEnabled, disabled: newDisabled })
  18203. });
  18204. if (!res.ok) throw new Error(await res.text());
  18205. showToast('Success', `BFD protocol ${newDisabled ? 'disabled' : 'enabled'}`, 'success');
  18206. await loadDynamicRouting(false);
  18207. } catch (err) {
  18208. showToast('Error', err.message, 'error');
  18209. }
  18210. }
  18211. function renderBfdInterfaces() {
  18212. const tbody = document.getElementById('bfd-interfaces-table-body');
  18213. if (!tbody) return;
  18214. const countEl = document.getElementById('bfd-interfaces-footer-count');
  18215. const filter = (document.getElementById('filter-bfd-interfaces')?.value || '').toLowerCase();
  18216. let list = state.bfdInterfaces || [];
  18217. if (filter) {
  18218. list = list.filter(i => (i.interface || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  18219. }
  18220. if (countEl) countEl.innerText = list.length;
  18221. const selId = state.selectedBfdRow?.interfaces;
  18222. tbody.innerHTML = list.map((iface, idx) => {
  18223. const isSel = iface.id === selId;
  18224. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-amber-400' : 'hover:bg-[#1a2636] text-slate-300';
  18225. const flagD = iface.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '<span class="text-emerald-400">B</span>';
  18226. return `
  18227. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectBfdRow('interfaces', '${iface.id}')" ondblclick="openEditBfdInterfaceModal('${iface.id}')">
  18228. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  18229. <td class="py-1.5 px-3 w-12 text-center">${flagD}</td>
  18230. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(iface.comment || '')}</td>
  18231. <td class="py-1.5 px-3 font-mono font-semibold text-white">${escapeHtml(iface.interface || '*')}</td>
  18232. <td class="py-1.5 px-3 font-mono text-slate-300">${iface.min_rx_interval || 100} ms</td>
  18233. <td class="py-1.5 px-3 font-mono text-slate-300">${iface.min_tx_interval || 100} ms</td>
  18234. <td class="py-1.5 px-3 font-mono text-slate-400">${iface.idle_tx_interval || 1000} ms</td>
  18235. <td class="py-1.5 px-3 font-mono text-slate-300">${iface.multiplier || 3}</td>
  18236. <td class="py-1.5 px-3 text-slate-400">${iface.passive ? 'yes' : 'no'}</td>
  18237. </tr>
  18238. `;
  18239. }).join('');
  18240. }
  18241. function renderBfdPeers() {
  18242. const tbody = document.getElementById('bfd-peers-table-body');
  18243. if (!tbody) return;
  18244. const countEl = document.getElementById('bfd-peers-footer-count');
  18245. const filter = (document.getElementById('filter-bfd-peers')?.value || '').toLowerCase();
  18246. let list = state.bfdNeighbors || [];
  18247. if (filter) {
  18248. list = list.filter(p => (p.address || '').toLowerCase().includes(filter) || (p.comment || '').toLowerCase().includes(filter));
  18249. }
  18250. if (countEl) countEl.innerText = list.length;
  18251. const selId = state.selectedBfdRow?.peers;
  18252. tbody.innerHTML = list.map((p, idx) => {
  18253. const isSel = p.id === selId;
  18254. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-amber-400' : 'hover:bg-[#1a2636] text-slate-300';
  18255. const flagD = p.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '<span class="text-emerald-400">B</span>';
  18256. return `
  18257. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectBfdRow('peers', '${p.id}')" ondblclick="openEditBfdPeerModal('${p.id}')">
  18258. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  18259. <td class="py-1.5 px-3 w-12 text-center">${flagD}</td>
  18260. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(p.comment || '')}</td>
  18261. <td class="py-1.5 px-3 font-mono font-semibold text-amber-300">${escapeHtml(p.address || '')}</td>
  18262. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(p.interface || 'auto')}</td>
  18263. <td class="py-1.5 px-3 font-mono text-cyan-300">${escapeHtml(p.local_address || 'auto')}</td>
  18264. <td class="py-1.5 px-3 text-slate-400">${p.multihop ? 'yes' : 'no'}</td>
  18265. </tr>
  18266. `;
  18267. }).join('');
  18268. }
  18269. function renderBfdSessions() {
  18270. const tbody = document.getElementById('bfd-sessions-table-body');
  18271. if (!tbody) return;
  18272. const countEl = document.getElementById('bfd-sessions-footer-count');
  18273. const list = state.bfdSessions || [];
  18274. if (countEl) countEl.innerText = list.length;
  18275. tbody.innerHTML = list.map((s, idx) => {
  18276. const isUp = (s.state || '').toLowerCase() === 'up';
  18277. const stateBadge = isUp
  18278. ? '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-emerald-500/20 text-emerald-300 border border-emerald-500/30">UP</span>'
  18279. : `<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-rose-500/20 text-rose-300 border border-rose-500/30">${escapeHtml(s.state || 'DOWN')}</span>`;
  18280. return `
  18281. <tr class="hover:bg-[#1a2636] text-slate-300">
  18282. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  18283. <td class="py-1.5 px-3 font-mono font-semibold text-white">${escapeHtml(s.ip || '')}</td>
  18284. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(s.interface || '')}</td>
  18285. <td class="py-1.5 px-3">${stateBadge}</td>
  18286. <td class="py-1.5 px-3 font-mono text-slate-400">${escapeHtml(s.interval || '')}</td>
  18287. <td class="py-1.5 px-3 font-mono text-slate-400">${escapeHtml(s.timeout || '')}</td>
  18288. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(s.since || '')}</td>
  18289. </tr>
  18290. `;
  18291. }).join('');
  18292. }
  18293. function openBfdInterfaceModal() {
  18294. document.getElementById('bfd-interface-modal-title').innerText = 'New BFD Interface Profile';
  18295. document.getElementById('modal-bfd-iface-id').value = '';
  18296. const dl = document.getElementById('bfd-iface-datalist');
  18297. if (dl) {
  18298. dl.innerHTML = '<option value="*">' + (state.interfaces || []).map(i => `<option value="${escapeHtml(i.name)}">`).join('');
  18299. }
  18300. document.getElementById('modal-bfd-iface-pattern').value = '*';
  18301. document.getElementById('modal-bfd-iface-min-rx').value = '100';
  18302. document.getElementById('modal-bfd-iface-min-tx').value = '100';
  18303. document.getElementById('modal-bfd-iface-idle-tx').value = '1000';
  18304. document.getElementById('modal-bfd-iface-multiplier').value = '3';
  18305. document.getElementById('modal-bfd-iface-comment').value = '';
  18306. document.getElementById('modal-bfd-iface-enabled').checked = true;
  18307. document.getElementById('modal-bfd-iface-passive').checked = false;
  18308. document.getElementById('bfd-interface-modal')?.classList.remove('hidden');
  18309. }
  18310. function openEditBfdInterfaceModal(id) {
  18311. const iface = (state.bfdInterfaces || []).find(i => i.id === id);
  18312. if (!iface) return;
  18313. document.getElementById('bfd-interface-modal-title').innerText = `Edit BFD Interface: ${iface.interface}`;
  18314. document.getElementById('modal-bfd-iface-id').value = iface.id;
  18315. const dl = document.getElementById('bfd-iface-datalist');
  18316. if (dl) {
  18317. dl.innerHTML = '<option value="*">' + (state.interfaces || []).map(i => `<option value="${escapeHtml(i.name)}">`).join('');
  18318. }
  18319. document.getElementById('modal-bfd-iface-pattern').value = iface.interface || '*';
  18320. document.getElementById('modal-bfd-iface-min-rx').value = iface.min_rx_interval || 100;
  18321. document.getElementById('modal-bfd-iface-min-tx').value = iface.min_tx_interval || 100;
  18322. document.getElementById('modal-bfd-iface-idle-tx').value = iface.idle_tx_interval || 1000;
  18323. document.getElementById('modal-bfd-iface-multiplier').value = iface.multiplier || 3;
  18324. document.getElementById('modal-bfd-iface-comment').value = iface.comment || '';
  18325. document.getElementById('modal-bfd-iface-enabled').checked = !iface.disabled;
  18326. document.getElementById('modal-bfd-iface-passive').checked = !!iface.passive;
  18327. document.getElementById('bfd-interface-modal')?.classList.remove('hidden');
  18328. }
  18329. function closeBfdInterfaceModal() {
  18330. document.getElementById('bfd-interface-modal')?.classList.add('hidden');
  18331. }
  18332. async function submitBfdInterface(e) {
  18333. e.preventDefault();
  18334. const id = document.getElementById('modal-bfd-iface-id').value;
  18335. const payload = {
  18336. id: id || undefined,
  18337. interface: document.getElementById('modal-bfd-iface-pattern').value.trim(),
  18338. min_rx_interval: parseInt(document.getElementById('modal-bfd-iface-min-rx').value, 10) || 100,
  18339. min_tx_interval: parseInt(document.getElementById('modal-bfd-iface-min-tx').value, 10) || 100,
  18340. idle_tx_interval: parseInt(document.getElementById('modal-bfd-iface-idle-tx').value, 10) || 1000,
  18341. multiplier: parseInt(document.getElementById('modal-bfd-iface-multiplier').value, 10) || 3,
  18342. comment: document.getElementById('modal-bfd-iface-comment').value.trim(),
  18343. disabled: !document.getElementById('modal-bfd-iface-enabled').checked,
  18344. passive: document.getElementById('modal-bfd-iface-passive').checked
  18345. };
  18346. try {
  18347. const res = await fetch(`${API_BASE}/routing/bfd/interfaces`, {
  18348. method: 'POST',
  18349. headers: { 'Content-Type': 'application/json' },
  18350. body: JSON.stringify(payload)
  18351. });
  18352. if (!res.ok) throw new Error(await res.text());
  18353. closeBfdInterfaceModal();
  18354. showToast('Saved', `BFD profile saved`, 'success');
  18355. await loadDynamicRouting(false);
  18356. } catch (err) {
  18357. showToast('Error', err.message, 'error');
  18358. }
  18359. }
  18360. async function enableSelectedBfdInterface() {
  18361. const id = state.selectedBfdRow?.interfaces;
  18362. if (!id) return;
  18363. if (!await routingMutation(`${API_BASE}/routing/bfd/interfaces/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: false }) })) return;
  18364. await loadDynamicRouting(false);
  18365. }
  18366. async function disableSelectedBfdInterface() {
  18367. const id = state.selectedBfdRow?.interfaces;
  18368. if (!id) return;
  18369. if (!await routingMutation(`${API_BASE}/routing/bfd/interfaces/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: true }) })) return;
  18370. await loadDynamicRouting(false);
  18371. }
  18372. async function removeSelectedBfdInterface() {
  18373. const id = state.selectedBfdRow?.interfaces;
  18374. if (!id || !confirm('Are you sure you want to remove this BFD interface template?')) return;
  18375. if (!await routingMutation(`${API_BASE}/routing/bfd/interfaces/${id}`, { method: 'DELETE' })) return;
  18376. state.selectedBfdRow.interfaces = null;
  18377. await loadDynamicRouting(false);
  18378. }
  18379. function openBfdPeerModal() {
  18380. document.getElementById('bfd-peer-modal-title').innerText = 'New Static BFD Peer';
  18381. document.getElementById('modal-bfd-peer-id').value = '';
  18382. const dlPeer = document.getElementById('bfd-peer-iface-datalist');
  18383. if (dlPeer) {
  18384. dlPeer.innerHTML = (state.interfaces || []).map(i => `<option value="${escapeHtml(i.name)}">`).join('');
  18385. }
  18386. document.getElementById('modal-bfd-peer-address').value = '';
  18387. document.getElementById('modal-bfd-peer-interface').value = '';
  18388. const localAddrEl = document.getElementById('modal-bfd-peer-local-address');
  18389. if (localAddrEl) localAddrEl.value = '';
  18390. document.getElementById('modal-bfd-peer-comment').value = '';
  18391. document.getElementById('modal-bfd-peer-enabled').checked = true;
  18392. document.getElementById('modal-bfd-peer-multihop').checked = false;
  18393. document.getElementById('bfd-peer-modal')?.classList.remove('hidden');
  18394. }
  18395. function openEditBfdPeerModal(id) {
  18396. const p = (state.bfdNeighbors || []).find(n => n.id === id);
  18397. if (!p) return;
  18398. document.getElementById('bfd-peer-modal-title').innerText = `Edit BFD Peer: ${p.address}`;
  18399. document.getElementById('modal-bfd-peer-id').value = p.id;
  18400. const dlPeer = document.getElementById('bfd-peer-iface-datalist');
  18401. if (dlPeer) {
  18402. dlPeer.innerHTML = (state.interfaces || []).map(i => `<option value="${escapeHtml(i.name)}">`).join('');
  18403. }
  18404. document.getElementById('modal-bfd-peer-address').value = p.address || '';
  18405. document.getElementById('modal-bfd-peer-interface').value = p.interface || '';
  18406. const localAddrEl = document.getElementById('modal-bfd-peer-local-address');
  18407. if (localAddrEl) localAddrEl.value = p.local_address || '';
  18408. document.getElementById('modal-bfd-peer-comment').value = p.comment || '';
  18409. document.getElementById('modal-bfd-peer-enabled').checked = !p.disabled;
  18410. document.getElementById('modal-bfd-peer-multihop').checked = !!p.multihop;
  18411. document.getElementById('bfd-peer-modal')?.classList.remove('hidden');
  18412. }
  18413. function closeBfdPeerModal() {
  18414. document.getElementById('bfd-peer-modal')?.classList.add('hidden');
  18415. }
  18416. async function submitBfdPeer(e) {
  18417. e.preventDefault();
  18418. const id = document.getElementById('modal-bfd-peer-id').value;
  18419. const localAddr = document.getElementById('modal-bfd-peer-local-address')?.value.trim() || '';
  18420. const payload = {
  18421. id: id || undefined,
  18422. address: document.getElementById('modal-bfd-peer-address').value.trim(),
  18423. interface: document.getElementById('modal-bfd-peer-interface').value.trim(),
  18424. local_address: localAddr,
  18425. comment: document.getElementById('modal-bfd-peer-comment').value.trim(),
  18426. disabled: !document.getElementById('modal-bfd-peer-enabled').checked,
  18427. multihop: document.getElementById('modal-bfd-peer-multihop').checked
  18428. };
  18429. try {
  18430. const res = await fetch(`${API_BASE}/routing/bfd/peers`, {
  18431. method: 'POST',
  18432. headers: { 'Content-Type': 'application/json' },
  18433. body: JSON.stringify(payload)
  18434. });
  18435. if (!res.ok) throw new Error(await res.text());
  18436. closeBfdPeerModal();
  18437. showToast('Saved', `BFD peer saved`, 'success');
  18438. await loadDynamicRouting(false);
  18439. } catch (err) {
  18440. showToast('Error', err.message, 'error');
  18441. }
  18442. }
  18443. async function enableSelectedBfdPeer() {
  18444. const id = state.selectedBfdRow?.peers;
  18445. if (!id) return;
  18446. const p = (state.bfdNeighbors || []).find(n => n.id === id);
  18447. if (!p) return;
  18448. if (!await routingMutation(`${API_BASE}/routing/bfd/peers`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ ...p, disabled: false }) })) return;
  18449. await loadDynamicRouting(false);
  18450. }
  18451. async function disableSelectedBfdPeer() {
  18452. const id = state.selectedBfdRow?.peers;
  18453. if (!id) return;
  18454. const p = (state.bfdNeighbors || []).find(n => n.id === id);
  18455. if (!p) return;
  18456. if (!await routingMutation(`${API_BASE}/routing/bfd/peers`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ ...p, disabled: true }) })) return;
  18457. await loadDynamicRouting(false);
  18458. }
  18459. async function removeSelectedBfdPeer() {
  18460. const id = state.selectedBfdRow?.peers;
  18461. if (!id || !confirm('Are you sure you want to remove this BFD peer?')) return;
  18462. if (!await routingMutation(`${API_BASE}/routing/bfd/peers/${id}`, { method: 'DELETE' })) return;
  18463. state.selectedBfdRow.peers = null;
  18464. await loadDynamicRouting(false);
  18465. }
  18466. // ==============================================================================
  18467. // DYNAMIC ROUTING: BABEL MODULE
  18468. // ==============================================================================
  18469. state.babelInstances = [];
  18470. state.babelInterfaces = [];
  18471. state.babelInterfacesLive = [];
  18472. state.babelNeighbors = [];
  18473. state.babelRoutes = [];
  18474. state.selectedBabelRow = {};
  18475. state.activeBabelTab = 'instances';
  18476. function switchBabelTab(tab) {
  18477. state.activeBabelTab = tab;
  18478. ['instances', 'interfaces', 'interfaces-live', 'neighbors', 'routes'].forEach(t => {
  18479. const pane = document.getElementById(`babel-pane-${t}`);
  18480. const btn = document.getElementById(`babel-tab-btn-${t}`);
  18481. if (pane) {
  18482. if (t === tab) pane.classList.remove('hidden');
  18483. else pane.classList.add('hidden');
  18484. }
  18485. if (btn) {
  18486. if (t === tab) {
  18487. btn.className = 'px-3 py-2 text-xs font-semibold border-b-2 border-teal-500 text-white transition flex items-center gap-1.5 whitespace-nowrap';
  18488. } else {
  18489. 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';
  18490. }
  18491. }
  18492. });
  18493. }
  18494. function selectBabelRow(tab, id) {
  18495. if (!state.selectedBabelRow) state.selectedBabelRow = {};
  18496. state.selectedBabelRow[tab] = id;
  18497. if (tab === 'instances') {
  18498. renderBabelInstances();
  18499. const btnEn = document.getElementById('btn-babel-inst-enable');
  18500. const btnDis = document.getElementById('btn-babel-inst-disable');
  18501. const btnRem = document.getElementById('btn-babel-inst-remove');
  18502. if (btnEn) btnEn.disabled = false;
  18503. if (btnDis) btnDis.disabled = false;
  18504. if (btnRem) btnRem.disabled = false;
  18505. } else if (tab === 'interfaces') {
  18506. renderBabelInterfaces();
  18507. const btnEn = document.getElementById('btn-babel-iface-enable');
  18508. const btnDis = document.getElementById('btn-babel-iface-disable');
  18509. const btnRem = document.getElementById('btn-babel-iface-remove');
  18510. if (btnEn) btnEn.disabled = false;
  18511. if (btnDis) btnDis.disabled = false;
  18512. if (btnRem) btnRem.disabled = false;
  18513. }
  18514. }
  18515. function renderBabelInstances() {
  18516. const tbody = document.getElementById('babel-instances-table-body');
  18517. if (!tbody) return;
  18518. const countEl = document.getElementById('babel-instances-footer-count');
  18519. const filter = (document.getElementById('filter-babel-instances')?.value || '').toLowerCase();
  18520. let list = state.babelInstances || [];
  18521. if (filter) {
  18522. list = list.filter(i => (i.name || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  18523. }
  18524. if (countEl) countEl.innerText = list.length;
  18525. const selId = state.selectedBabelRow?.instances;
  18526. tbody.innerHTML = list.map((inst, idx) => {
  18527. const isSel = inst.id === selId;
  18528. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-teal-400' : 'hover:bg-[#1a2636] text-slate-300';
  18529. const flagD = inst.disabled
  18530. ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>'
  18531. : (inst.running
  18532. ? '<span class="text-emerald-400 font-bold" title="Running">R</span>'
  18533. : '<span class="text-amber-400 font-bold" title="Inactive">I</span>');
  18534. const redist = [];
  18535. if (inst.redistribute_connected) redist.push('conn');
  18536. if (inst.redistribute_static) redist.push('static');
  18537. if (inst.redistribute_bgp) redist.push('bgp');
  18538. if (inst.redistribute_ospf) redist.push('ospf');
  18539. if (inst.redistribute_default) redist.push('default');
  18540. const filterBadges = [];
  18541. if (inst.in_filter) filterBadges.push(`<span class="px-1.5 py-0.5 rounded text-[10px] bg-blue-950 text-blue-300 border border-blue-800/50" title="In Filter">IN: ${escapeHtml(inst.in_filter)}</span>`);
  18542. if (inst.out_filter) filterBadges.push(`<span class="px-1.5 py-0.5 rounded text-[10px] bg-purple-950 text-purple-300 border border-purple-800/50" title="Out Filter">OUT: ${escapeHtml(inst.out_filter)}</span>`);
  18543. return `
  18544. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectBabelRow('instances', '${inst.id}')" ondblclick="openEditBabelInstanceModal('${inst.id}')">
  18545. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  18546. <td class="py-1.5 px-3 w-12 text-center">${flagD}</td>
  18547. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(inst.comment || '')}</td>
  18548. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  18549. <span class="text-teal-400">↳</span> <span>${escapeHtml(inst.name || 'default')}</span>
  18550. ${filterBadges.join(' ')}
  18551. </td>
  18552. <td class="py-1.5 px-3 font-mono text-cyan-300">${escapeHtml(inst.router_id || 'auto')}</td>
  18553. <td class="py-1.5 px-3 text-emerald-400 font-bold">IPv4 + IPv6</td>
  18554. <td class="py-1.5 px-3 font-mono text-cyan-300">${redist.join(', ') || 'none'}</td>
  18555. <td class="py-1.5 px-3 font-mono text-slate-300">${inst.default_metric || 10}</td>
  18556. </tr>
  18557. `;
  18558. }).join('');
  18559. }
  18560. function renderBabelInterfaces() {
  18561. const tbody = document.getElementById('babel-interfaces-table-body');
  18562. if (!tbody) return;
  18563. const countEl = document.getElementById('babel-interfaces-footer-count');
  18564. const filter = (document.getElementById('filter-babel-interfaces')?.value || '').toLowerCase();
  18565. let list = state.babelInterfaces || [];
  18566. if (filter) {
  18567. list = list.filter(i => (i.interface || '').toLowerCase().includes(filter) || (i.instance || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  18568. }
  18569. if (countEl) countEl.innerText = list.length;
  18570. const selId = state.selectedBabelRow?.interfaces;
  18571. tbody.innerHTML = list.map((iface, idx) => {
  18572. const isSel = iface.id === selId;
  18573. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-teal-400' : 'hover:bg-[#1a2636] text-slate-300';
  18574. const flagD = iface.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '<span class="text-emerald-400">B</span>';
  18575. return `
  18576. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectBabelRow('interfaces', '${iface.id}')" ondblclick="openEditBabelInterfaceModal('${iface.id}')">
  18577. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  18578. <td class="py-1.5 px-3 w-12 text-center">${flagD}</td>
  18579. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(iface.comment || '')}</td>
  18580. <td class="py-1.5 px-3 font-semibold text-teal-300 font-mono">${escapeHtml(iface.instance || 'all')}</td>
  18581. <td class="py-1.5 px-3 font-mono font-semibold text-white">${escapeHtml(iface.interface || '*')}</td>
  18582. <td class="py-1.5 px-3 uppercase text-teal-300 font-bold">${escapeHtml(iface.type || 'wired')}</td>
  18583. <td class="py-1.5 px-3 font-mono text-slate-300">${iface.rxcost || 10}</td>
  18584. <td class="py-1.5 px-3 text-slate-400">${iface.hello_interval || 4}s</td>
  18585. <td class="py-1.5 px-3 text-slate-400">${iface.update_interval || 16}s</td>
  18586. </tr>
  18587. `;
  18588. }).join('');
  18589. }
  18590. function renderBabelLiveInterfaces() {
  18591. const tbody = document.getElementById('babel-interfaces-live-table-body');
  18592. if (!tbody) return;
  18593. const countEl = document.getElementById('babel-interfaces-live-footer-count');
  18594. const filter = (document.getElementById('filter-babel-interfaces-live')?.value || '').toLowerCase();
  18595. let list = state.babelInterfacesLive || [];
  18596. if (filter) {
  18597. list = list.filter(i => (i.interface || '').toLowerCase().includes(filter) || (i.instance || '').toLowerCase().includes(filter));
  18598. }
  18599. if (countEl) countEl.innerText = list.length;
  18600. tbody.innerHTML = list.map((iface, idx) => {
  18601. const isUp = (iface.state || '').toLowerCase() === 'up';
  18602. const stateBadge = isUp
  18603. ? '<span class="px-1.5 py-0.5 rounded text-[10px] font-bold bg-emerald-500/20 text-emerald-400 border border-emerald-500/30">UP</span>'
  18604. : '<span class="px-1.5 py-0.5 rounded text-[10px] font-bold bg-rose-500/20 text-rose-400 border border-rose-500/30">DOWN</span>';
  18605. return `
  18606. <tr class="hover:bg-[#1a2636] text-slate-300 font-mono">
  18607. <td class="py-1.5 px-3 w-8 text-center text-slate-500 font-sans">${idx}</td>
  18608. <td class="py-1.5 px-3 w-12 text-center text-cyan-400 font-bold">D</td>
  18609. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(iface.interface || '')}</td>
  18610. <td class="py-1.5 px-3 font-semibold text-teal-300">${escapeHtml(iface.instance || 'default')}</td>
  18611. <td class="py-1.5 px-3">${stateBadge}</td>
  18612. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(iface.auth || 'No')}</td>
  18613. <td class="py-1.5 px-3 text-slate-300">${iface.rxcost || 96}</td>
  18614. <td class="py-1.5 px-3 text-slate-300">${iface.neighbors || 0}</td>
  18615. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(iface.timer || '')}</td>
  18616. <td class="py-1.5 px-3 text-cyan-300">${escapeHtml(iface.next_hop_v4 || '-')}</td>
  18617. <td class="py-1.5 px-3 text-slate-400 text-[11px]">${escapeHtml(iface.next_hop_v6 || '-')}</td>
  18618. </tr>
  18619. `;
  18620. }).join('');
  18621. }
  18622. function renderBabelNeighbors() {
  18623. const tbody = document.getElementById('babel-neighbors-table-body');
  18624. if (!tbody) return;
  18625. const countEl = document.getElementById('babel-neighbors-footer-count');
  18626. const list = state.babelNeighbors || [];
  18627. if (countEl) countEl.innerText = list.length;
  18628. tbody.innerHTML = list.map((nbr, idx) => `
  18629. <tr class="hover:bg-[#1a2636] text-slate-300">
  18630. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  18631. <td class="py-1.5 px-3 font-mono font-semibold text-teal-300">${escapeHtml(nbr.ip || '')}</td>
  18632. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(nbr.interface || '')}</td>
  18633. <td class="py-1.5 px-3 font-mono text-slate-400">${nbr.metric || 0}</td>
  18634. <td class="py-1.5 px-3 font-mono text-slate-400">${nbr.cost || nbr.routes || 0}</td>
  18635. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(nbr.uptime || nbr.expires || '')}</td>
  18636. </tr>
  18637. `).join('');
  18638. }
  18639. function renderBabelRoutes() {
  18640. const tbody = document.getElementById('babel-routes-table-body');
  18641. if (!tbody) return;
  18642. const countEl = document.getElementById('babel-routes-footer-count');
  18643. const list = state.babelRoutes || [];
  18644. if (countEl) countEl.innerText = list.length;
  18645. tbody.innerHTML = list.map((r, idx) => `
  18646. <tr class="hover:bg-[#1a2636] text-slate-300">
  18647. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  18648. <td class="py-1.5 px-3 font-mono font-semibold text-white">${escapeHtml(r.prefix || '')}</td>
  18649. <td class="py-1.5 px-3 font-mono text-cyan-300">${escapeHtml(r.next_hop || '')}</td>
  18650. <td class="py-1.5 px-3 font-mono text-slate-300">${r.metric || 10}</td>
  18651. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(r.interface || '')}</td>
  18652. </tr>
  18653. `).join('');
  18654. }
  18655. function openBabelInstanceModal() {
  18656. document.getElementById('babel-instance-modal-title').innerText = 'New Babel Instance';
  18657. document.getElementById('modal-babel-instance-id').value = '';
  18658. document.getElementById('modal-babel-instance-name').value = 'babel1';
  18659. document.getElementById('modal-babel-instance-routerid').value = '';
  18660. document.getElementById('modal-babel-instance-metric').value = '10';
  18661. document.getElementById('modal-babel-instance-comment').value = '';
  18662. document.getElementById('modal-babel-instance-in-filter').value = '';
  18663. document.getElementById('modal-babel-instance-out-filter').value = '';
  18664. document.getElementById('modal-babel-instance-enabled').checked = true;
  18665. document.getElementById('modal-babel-instance-redist-conn').checked = false;
  18666. document.getElementById('modal-babel-instance-redist-static').checked = false;
  18667. document.getElementById('modal-babel-instance-redist-bgp').checked = false;
  18668. document.getElementById('modal-babel-instance-redist-ospf').checked = false;
  18669. document.getElementById('modal-babel-instance-redist-default').checked = false;
  18670. document.getElementById('babel-instance-modal')?.classList.remove('hidden');
  18671. }
  18672. function openEditBabelInstanceModal(id) {
  18673. const inst = (state.babelInstances || []).find(i => i.id === id);
  18674. if (!inst) return;
  18675. document.getElementById('babel-instance-modal-title').innerText = `Edit Babel Instance: ${inst.name}`;
  18676. document.getElementById('modal-babel-instance-id').value = inst.id;
  18677. document.getElementById('modal-babel-instance-name').value = inst.name || '';
  18678. document.getElementById('modal-babel-instance-routerid').value = inst.router_id || '';
  18679. document.getElementById('modal-babel-instance-metric').value = inst.default_metric || 10;
  18680. document.getElementById('modal-babel-instance-comment').value = inst.comment || '';
  18681. document.getElementById('modal-babel-instance-in-filter').value = inst.in_filter || '';
  18682. document.getElementById('modal-babel-instance-out-filter').value = inst.out_filter || '';
  18683. document.getElementById('modal-babel-instance-enabled').checked = !inst.disabled;
  18684. document.getElementById('modal-babel-instance-redist-conn').checked = !!inst.redistribute_connected;
  18685. document.getElementById('modal-babel-instance-redist-static').checked = !!inst.redistribute_static;
  18686. document.getElementById('modal-babel-instance-redist-bgp').checked = !!inst.redistribute_bgp;
  18687. document.getElementById('modal-babel-instance-redist-ospf').checked = !!inst.redistribute_ospf;
  18688. document.getElementById('modal-babel-instance-redist-default').checked = !!inst.redistribute_default;
  18689. document.getElementById('babel-instance-modal')?.classList.remove('hidden');
  18690. }
  18691. function closeBabelInstanceModal() {
  18692. document.getElementById('babel-instance-modal')?.classList.add('hidden');
  18693. }
  18694. async function submitBabelInstance(e) {
  18695. e.preventDefault();
  18696. const id = document.getElementById('modal-babel-instance-id').value;
  18697. const isEnabled = document.getElementById('modal-babel-instance-enabled').checked;
  18698. const payload = {
  18699. id: id || undefined,
  18700. name: document.getElementById('modal-babel-instance-name').value.trim(),
  18701. router_id: document.getElementById('modal-babel-instance-routerid').value.trim(),
  18702. default_metric: parseInt(document.getElementById('modal-babel-instance-metric').value, 10) || 10,
  18703. comment: document.getElementById('modal-babel-instance-comment').value.trim(),
  18704. in_filter: (document.getElementById('modal-babel-instance-in-filter')?.value || '').trim(),
  18705. out_filter: (document.getElementById('modal-babel-instance-out-filter')?.value || '').trim(),
  18706. enabled: isEnabled,
  18707. disabled: !isEnabled,
  18708. redistribute_connected: document.getElementById('modal-babel-instance-redist-conn').checked,
  18709. redistribute_static: document.getElementById('modal-babel-instance-redist-static').checked,
  18710. redistribute_bgp: document.getElementById('modal-babel-instance-redist-bgp').checked,
  18711. redistribute_ospf: document.getElementById('modal-babel-instance-redist-ospf').checked,
  18712. redistribute_default: document.getElementById('modal-babel-instance-redist-default').checked
  18713. };
  18714. try {
  18715. const res = await fetch(`${API_BASE}/routing/babel/instances`, {
  18716. method: 'POST',
  18717. headers: { 'Content-Type': 'application/json' },
  18718. body: JSON.stringify(payload)
  18719. });
  18720. if (!res.ok) throw new Error(await res.text());
  18721. closeBabelInstanceModal();
  18722. showToast('Saved', `Babel instance saved`, 'success');
  18723. await loadDynamicRouting(false);
  18724. } catch (err) {
  18725. showToast('Error', err.message, 'error');
  18726. }
  18727. }
  18728. async function enableSelectedBabelInstance() {
  18729. const id = state.selectedBabelRow?.instances;
  18730. if (!id) return;
  18731. if (!await routingMutation(`${API_BASE}/routing/babel/instances/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: false }) })) return;
  18732. await loadDynamicRouting(false);
  18733. }
  18734. async function disableSelectedBabelInstance() {
  18735. const id = state.selectedBabelRow?.instances;
  18736. if (!id) return;
  18737. if (!await routingMutation(`${API_BASE}/routing/babel/instances/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: true }) })) return;
  18738. await loadDynamicRouting(false);
  18739. }
  18740. async function removeSelectedBabelInstance() {
  18741. const id = state.selectedBabelRow?.instances;
  18742. if (!id || !confirm('Are you sure you want to remove this Babel instance?')) return;
  18743. if (!await routingMutation(`${API_BASE}/routing/babel/instances/${id}`, { method: 'DELETE' })) return;
  18744. state.selectedBabelRow.instances = null;
  18745. await loadDynamicRouting(false);
  18746. }
  18747. function toggleBabelAuthKey() {
  18748. const authVal = document.getElementById('modal-babel-iface-auth')?.value;
  18749. const wrap = document.getElementById('modal-babel-iface-auth-key-wrap');
  18750. if (wrap) {
  18751. if (authVal === 'mac') wrap.classList.remove('hidden');
  18752. else wrap.classList.add('hidden');
  18753. }
  18754. }
  18755. function openBabelInterfaceModal() {
  18756. document.getElementById('babel-interface-modal-title').innerText = 'New Babel Interface Template';
  18757. document.getElementById('modal-babel-iface-id').value = '';
  18758. const instSel = document.getElementById('modal-babel-iface-instance');
  18759. if (instSel) {
  18760. instSel.innerHTML = '<option value="all">all (Any instance)</option>' +
  18761. (state.babelInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)}</option>`).join('');
  18762. if (state.babelInstances && state.babelInstances.length > 0) {
  18763. instSel.value = state.babelInstances[0].name;
  18764. }
  18765. }
  18766. const dl = document.getElementById('babel-iface-datalist');
  18767. if (dl) {
  18768. dl.innerHTML = '<option value="*">' + (state.interfaces || []).map(i => `<option value="${escapeHtml(i.name)}">`).join('');
  18769. }
  18770. document.getElementById('modal-babel-iface-pattern').value = '*';
  18771. document.getElementById('modal-babel-iface-type').value = 'wired';
  18772. document.getElementById('modal-babel-iface-auth').value = 'none';
  18773. document.getElementById('modal-babel-iface-auth-key').value = '';
  18774. toggleBabelAuthKey();
  18775. document.getElementById('modal-babel-iface-rxcost').value = '10';
  18776. document.getElementById('modal-babel-iface-hello').value = '4';
  18777. document.getElementById('modal-babel-iface-update').value = '16';
  18778. document.getElementById('modal-babel-iface-comment').value = '';
  18779. document.getElementById('modal-babel-iface-enabled').checked = true;
  18780. document.getElementById('babel-interface-modal')?.classList.remove('hidden');
  18781. }
  18782. function openEditBabelInterfaceModal(id) {
  18783. const iface = (state.babelInterfaces || []).find(i => i.id === id);
  18784. if (!iface) return;
  18785. document.getElementById('babel-interface-modal-title').innerText = `Edit Babel Interface: ${iface.interface}`;
  18786. document.getElementById('modal-babel-iface-id').value = iface.id;
  18787. const instSel = document.getElementById('modal-babel-iface-instance');
  18788. if (instSel) {
  18789. instSel.innerHTML = '<option value="all">all (Any instance)</option>' +
  18790. (state.babelInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)}</option>`).join('');
  18791. instSel.value = iface.instance || 'all';
  18792. }
  18793. const dl = document.getElementById('babel-iface-datalist');
  18794. if (dl) {
  18795. dl.innerHTML = '<option value="*">' + (state.interfaces || []).map(i => `<option value="${escapeHtml(i.name)}">`).join('');
  18796. }
  18797. document.getElementById('modal-babel-iface-pattern').value = iface.interface || '';
  18798. document.getElementById('modal-babel-iface-type').value = iface.type || 'wired';
  18799. document.getElementById('modal-babel-iface-auth').value = iface.auth || 'none';
  18800. document.getElementById('modal-babel-iface-auth-key').value = iface.auth_key || '';
  18801. toggleBabelAuthKey();
  18802. document.getElementById('modal-babel-iface-rxcost').value = iface.rxcost || 10;
  18803. document.getElementById('modal-babel-iface-hello').value = iface.hello_interval || 4;
  18804. document.getElementById('modal-babel-iface-update').value = iface.update_interval || 16;
  18805. document.getElementById('modal-babel-iface-comment').value = iface.comment || '';
  18806. document.getElementById('modal-babel-iface-enabled').checked = !iface.disabled;
  18807. document.getElementById('babel-interface-modal')?.classList.remove('hidden');
  18808. }
  18809. function closeBabelInterfaceModal() {
  18810. document.getElementById('babel-interface-modal')?.classList.add('hidden');
  18811. }
  18812. async function submitBabelInterface(e) {
  18813. e.preventDefault();
  18814. const id = document.getElementById('modal-babel-iface-id').value;
  18815. const isEnabled = document.getElementById('modal-babel-iface-enabled').checked;
  18816. const payload = {
  18817. id: id || undefined,
  18818. instance: document.getElementById('modal-babel-iface-instance').value.trim(),
  18819. interface: document.getElementById('modal-babel-iface-pattern').value.trim(),
  18820. type: document.getElementById('modal-babel-iface-type').value,
  18821. auth: document.getElementById('modal-babel-iface-auth').value,
  18822. auth_key: document.getElementById('modal-babel-iface-auth-key').value.trim(),
  18823. rxcost: parseInt(document.getElementById('modal-babel-iface-rxcost').value, 10) || 10,
  18824. hello_interval: parseInt(document.getElementById('modal-babel-iface-hello').value, 10) || 4,
  18825. update_interval: parseInt(document.getElementById('modal-babel-iface-update').value, 10) || 16,
  18826. comment: document.getElementById('modal-babel-iface-comment').value.trim(),
  18827. disabled: !isEnabled
  18828. };
  18829. try {
  18830. const res = await fetch(`${API_BASE}/routing/babel/interfaces`, {
  18831. method: 'POST',
  18832. headers: { 'Content-Type': 'application/json' },
  18833. body: JSON.stringify(payload)
  18834. });
  18835. if (!res.ok) throw new Error(await res.text());
  18836. closeBabelInterfaceModal();
  18837. showToast('Saved', `Babel interface template saved`, 'success');
  18838. await loadDynamicRouting(false);
  18839. } catch (err) {
  18840. showToast('Error', err.message, 'error');
  18841. }
  18842. }
  18843. async function enableSelectedBabelInterface() {
  18844. const id = state.selectedBabelRow?.interfaces;
  18845. if (!id) return;
  18846. if (!await routingMutation(`${API_BASE}/routing/babel/interfaces/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: false }) })) return;
  18847. await loadDynamicRouting(false);
  18848. }
  18849. async function disableSelectedBabelInterface() {
  18850. const id = state.selectedBabelRow?.interfaces;
  18851. if (!id) return;
  18852. if (!await routingMutation(`${API_BASE}/routing/babel/interfaces/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: true }) })) return;
  18853. await loadDynamicRouting(false);
  18854. }
  18855. async function removeSelectedBabelInterface() {
  18856. const id = state.selectedBabelRow?.interfaces;
  18857. if (!id || !confirm('Are you sure you want to remove this Babel interface template?')) return;
  18858. if (!await routingMutation(`${API_BASE}/routing/babel/interfaces/${id}`, { method: 'DELETE' })) return;
  18859. state.selectedBabelRow.interfaces = null;
  18860. await loadDynamicRouting(false);
  18861. }
  18862. // ==============================================================================
  18863. // DYNAMIC ROUTING: RADV MODULE (IPv6 Router Advertisements)
  18864. // ==============================================================================
  18865. state.radvInstances = [];
  18866. state.radvInterfaces = [];
  18867. state.selectedRadvRow = {};
  18868. state.activeRadvTab = 'instances';
  18869. function switchRadvTab(tab) {
  18870. state.activeRadvTab = tab;
  18871. ['instances', 'interfaces'].forEach(t => {
  18872. const pane = document.getElementById(`radv-pane-${t}`);
  18873. const btn = document.getElementById(`radv-tab-btn-${t}`);
  18874. if (pane) {
  18875. if (t === tab) pane.classList.remove('hidden');
  18876. else pane.classList.add('hidden');
  18877. }
  18878. if (btn) {
  18879. if (t === tab) {
  18880. btn.className = 'px-3 py-2 text-xs font-semibold border-b-2 border-blue-500 text-white transition flex items-center gap-1.5 whitespace-nowrap';
  18881. } else {
  18882. 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';
  18883. }
  18884. }
  18885. });
  18886. }
  18887. function selectRadvRow(tab, id) {
  18888. if (!state.selectedRadvRow) state.selectedRadvRow = {};
  18889. state.selectedRadvRow[tab] = id;
  18890. if (tab === 'instances') {
  18891. renderRAdvInstances();
  18892. const btnEn = document.getElementById('btn-radv-inst-enable');
  18893. const btnDis = document.getElementById('btn-radv-inst-disable');
  18894. const btnRem = document.getElementById('btn-radv-inst-remove');
  18895. if (btnEn) btnEn.disabled = false;
  18896. if (btnDis) btnDis.disabled = false;
  18897. if (btnRem) btnRem.disabled = false;
  18898. } else if (tab === 'interfaces') {
  18899. renderRAdvInterfaces();
  18900. const btnEn = document.getElementById('btn-radv-iface-enable');
  18901. const btnDis = document.getElementById('btn-radv-iface-disable');
  18902. const btnRem = document.getElementById('btn-radv-iface-remove');
  18903. if (btnEn) btnEn.disabled = false;
  18904. if (btnDis) btnDis.disabled = false;
  18905. if (btnRem) btnRem.disabled = false;
  18906. }
  18907. }
  18908. function renderRAdvInstances() {
  18909. const tbody = document.getElementById('radv-instances-table-body');
  18910. if (!tbody) return;
  18911. const countEl = document.getElementById('radv-instances-footer-count');
  18912. const filter = (document.getElementById('filter-radv-instances')?.value || '').toLowerCase();
  18913. let list = state.radvInstances || [];
  18914. if (filter) {
  18915. list = list.filter(i => (i.name || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  18916. }
  18917. if (countEl) countEl.innerText = list.length;
  18918. const selId = state.selectedRadvRow?.instances;
  18919. tbody.innerHTML = list.map((inst, idx) => {
  18920. const isSel = inst.id === selId;
  18921. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-blue-400' : 'hover:bg-[#1a2636] text-slate-300';
  18922. const flagD = inst.disabled
  18923. ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>'
  18924. : (inst.running
  18925. ? '<span class="text-emerald-400 font-bold" title="Running (R)">R</span>'
  18926. : '<span class="text-amber-400 font-bold" title="Inactive (I)">I</span>');
  18927. return `
  18928. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectRadvRow('instances', '${inst.id}')" ondblclick="openEditRAdvInstanceModal('${inst.id}')">
  18929. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  18930. <td class="py-1.5 px-3 w-12 text-center">${flagD}</td>
  18931. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(inst.comment || '')}</td>
  18932. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  18933. <span class="text-blue-400">↳</span> <span>${escapeHtml(inst.name || 'default')}</span>
  18934. </td>
  18935. <td class="py-1.5 px-3">${inst.running ? '<span class="text-emerald-400 font-bold">running</span>' : '<span class="text-slate-500">stopped</span>'}</td>
  18936. </tr>
  18937. `;
  18938. }).join('');
  18939. }
  18940. function renderRAdvInterfaces() {
  18941. const tbody = document.getElementById('radv-interfaces-table-body');
  18942. if (!tbody) return;
  18943. const countEl = document.getElementById('radv-interfaces-footer-count');
  18944. const filter = (document.getElementById('filter-radv-interfaces')?.value || '').toLowerCase();
  18945. let list = state.radvInterfaces || [];
  18946. if (filter) {
  18947. list = list.filter(i => (i.interface || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  18948. }
  18949. if (countEl) countEl.innerText = list.length;
  18950. const selId = state.selectedRadvRow?.interfaces;
  18951. tbody.innerHTML = list.map((iface, idx) => {
  18952. const isSel = iface.id === selId;
  18953. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-blue-400' : 'hover:bg-[#1a2636] text-slate-300';
  18954. const flagD = iface.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '<span class="text-emerald-400">R</span>';
  18955. const prefixes = (iface.prefixes || []).join(', ') || 'default';
  18956. const rdnss = (iface.rdnss || []).join(', ') || 'none';
  18957. return `
  18958. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectRadvRow('interfaces', '${iface.id}')" ondblclick="openEditRAdvInterfaceModal('${iface.id}')">
  18959. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  18960. <td class="py-1.5 px-3 w-12 text-center">${flagD}</td>
  18961. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(iface.comment || '')}</td>
  18962. <td class="py-1.5 px-3 font-mono font-semibold text-white">${escapeHtml(iface.interface || '')}</td>
  18963. <td class="py-1.5 px-3 text-slate-300">${iface.min_ra_interval || 200}s / ${iface.max_ra_interval || 600}s</td>
  18964. <td class="py-1.5 px-3 text-slate-400">${iface.default_lifetime || 1800}s</td>
  18965. <td class="py-1.5 px-3 font-mono text-cyan-300">${escapeHtml(prefixes)}</td>
  18966. <td class="py-1.5 px-3 font-mono text-purple-300">${escapeHtml(rdnss)}</td>
  18967. </tr>
  18968. `;
  18969. }).join('');
  18970. }
  18971. function openRAdvInstanceModal() {
  18972. document.getElementById('radv-instance-modal-title').innerText = 'New RAdv Instance';
  18973. document.getElementById('modal-radv-instance-id').value = '';
  18974. document.getElementById('modal-radv-instance-name').value = 'radv1';
  18975. document.getElementById('modal-radv-instance-comment').value = '';
  18976. document.getElementById('modal-radv-instance-enabled').checked = true;
  18977. document.getElementById('radv-instance-modal')?.classList.remove('hidden');
  18978. }
  18979. function openEditRAdvInstanceModal(id) {
  18980. const inst = (state.radvInstances || []).find(i => i.id === id);
  18981. if (!inst) return;
  18982. document.getElementById('radv-instance-modal-title').innerText = `Edit RAdv Instance: ${inst.name}`;
  18983. document.getElementById('modal-radv-instance-id').value = inst.id;
  18984. document.getElementById('modal-radv-instance-name').value = inst.name || '';
  18985. document.getElementById('modal-radv-instance-comment').value = inst.comment || '';
  18986. document.getElementById('modal-radv-instance-enabled').checked = !inst.disabled;
  18987. document.getElementById('radv-instance-modal')?.classList.remove('hidden');
  18988. }
  18989. function closeRAdvInstanceModal() {
  18990. document.getElementById('radv-instance-modal')?.classList.add('hidden');
  18991. }
  18992. async function submitRAdvInstance(e) {
  18993. e.preventDefault();
  18994. const id = document.getElementById('modal-radv-instance-id').value;
  18995. const payload = {
  18996. id: id || undefined,
  18997. name: document.getElementById('modal-radv-instance-name').value.trim(),
  18998. comment: document.getElementById('modal-radv-instance-comment').value.trim(),
  18999. disabled: !document.getElementById('modal-radv-instance-enabled').checked
  19000. };
  19001. try {
  19002. const res = await fetch(`${API_BASE}/routing/radv/instances`, {
  19003. method: 'POST',
  19004. headers: { 'Content-Type': 'application/json' },
  19005. body: JSON.stringify(payload)
  19006. });
  19007. if (!res.ok) throw new Error(await res.text());
  19008. closeRAdvInstanceModal();
  19009. showToast('Saved', `RAdv instance saved`, 'success');
  19010. await loadDynamicRouting(false);
  19011. } catch (err) {
  19012. showToast('Error', err.message, 'error');
  19013. }
  19014. }
  19015. async function enableSelectedRadvInstance() {
  19016. const id = state.selectedRadvRow?.instances;
  19017. if (!id) return;
  19018. if (!await routingMutation(`${API_BASE}/routing/radv/instances/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: false }) })) return;
  19019. await loadDynamicRouting(false);
  19020. }
  19021. async function disableSelectedRadvInstance() {
  19022. const id = state.selectedRadvRow?.instances;
  19023. if (!id) return;
  19024. if (!await routingMutation(`${API_BASE}/routing/radv/instances/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: true }) })) return;
  19025. await loadDynamicRouting(false);
  19026. }
  19027. async function removeSelectedRadvInstance() {
  19028. const id = state.selectedRadvRow?.instances;
  19029. if (!id || !confirm('Are you sure you want to remove this RAdv instance?')) return;
  19030. if (!await routingMutation(`${API_BASE}/routing/radv/instances/${id}`, { method: 'DELETE' })) return;
  19031. state.selectedRadvRow.instances = null;
  19032. await loadDynamicRouting(false);
  19033. }
  19034. function openRAdvInterfaceModal() {
  19035. document.getElementById('radv-interface-modal-title').innerText = 'New RAdv Interface';
  19036. document.getElementById('modal-radv-iface-id').value = '';
  19037. const dl = document.getElementById('radv-iface-datalist');
  19038. if (dl) {
  19039. dl.innerHTML = '<option value="*">' + (state.interfaces || []).map(i => `<option value="${escapeHtml(i.name)}">`).join('');
  19040. }
  19041. const instSel = document.getElementById('modal-radv-iface-instance');
  19042. if (instSel && instSel.tagName === 'SELECT') {
  19043. instSel.innerHTML = (state.radvInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)}</option>`).join('');
  19044. if (instSel.innerHTML === '') instSel.innerHTML = '<option value="default">default</option>';
  19045. instSel.value = (state.radvInstances && state.radvInstances.length > 0) ? state.radvInstances[0].name : 'default';
  19046. } else if (instSel) {
  19047. instSel.value = 'default';
  19048. }
  19049. document.getElementById('modal-radv-iface-interface').value = '*';
  19050. document.getElementById('modal-radv-iface-min-ra').value = '200';
  19051. document.getElementById('modal-radv-iface-max-ra').value = '600';
  19052. document.getElementById('modal-radv-iface-lifetime').value = '1800';
  19053. document.getElementById('modal-radv-iface-hoplimit').value = '64';
  19054. document.getElementById('modal-radv-iface-prefixes').value = '';
  19055. document.getElementById('modal-radv-iface-rdnss').value = '';
  19056. document.getElementById('modal-radv-iface-comment').value = '';
  19057. document.getElementById('modal-radv-iface-enabled').checked = true;
  19058. document.getElementById('radv-interface-modal')?.classList.remove('hidden');
  19059. }
  19060. function openEditRAdvInterfaceModal(id) {
  19061. const iface = (state.radvInterfaces || []).find(i => i.id === id);
  19062. if (!iface) return;
  19063. document.getElementById('radv-interface-modal-title').innerText = `Edit RAdv Interface: ${iface.interface}`;
  19064. document.getElementById('modal-radv-iface-id').value = iface.id;
  19065. const dl = document.getElementById('radv-iface-datalist');
  19066. if (dl) {
  19067. dl.innerHTML = '<option value="*">' + (state.interfaces || []).map(i => `<option value="${escapeHtml(i.name)}">`).join('');
  19068. }
  19069. const instSel = document.getElementById('modal-radv-iface-instance');
  19070. if (instSel && instSel.tagName === 'SELECT') {
  19071. instSel.innerHTML = (state.radvInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)}</option>`).join('');
  19072. if (instSel.innerHTML === '') instSel.innerHTML = '<option value="default">default</option>';
  19073. instSel.value = iface.instance || 'default';
  19074. } else if (instSel) {
  19075. instSel.value = iface.instance || '';
  19076. }
  19077. document.getElementById('modal-radv-iface-interface').value = iface.interface || '*';
  19078. document.getElementById('modal-radv-iface-min-ra').value = iface.min_ra_interval || 200;
  19079. document.getElementById('modal-radv-iface-max-ra').value = iface.max_ra_interval || 600;
  19080. document.getElementById('modal-radv-iface-lifetime').value = iface.default_lifetime || 1800;
  19081. document.getElementById('modal-radv-iface-hoplimit').value = iface.hop_limit || 64;
  19082. document.getElementById('modal-radv-iface-prefixes').value = (iface.prefixes || []).join(', ');
  19083. document.getElementById('modal-radv-iface-rdnss').value = (iface.rdnss || []).join(', ');
  19084. document.getElementById('modal-radv-iface-comment').value = iface.comment || '';
  19085. document.getElementById('modal-radv-iface-enabled').checked = !iface.disabled;
  19086. document.getElementById('radv-interface-modal')?.classList.remove('hidden');
  19087. }
  19088. function closeRAdvInterfaceModal() {
  19089. document.getElementById('radv-interface-modal')?.classList.add('hidden');
  19090. }
  19091. async function submitRAdvInterface(e) {
  19092. e.preventDefault();
  19093. const id = document.getElementById('modal-radv-iface-id').value;
  19094. const pRaw = document.getElementById('modal-radv-iface-prefixes').value;
  19095. const rRaw = document.getElementById('modal-radv-iface-rdnss').value;
  19096. const prefixes = pRaw ? pRaw.split(',').map(s => s.trim()).filter(Boolean) : [];
  19097. const rdnss = rRaw ? rRaw.split(',').map(s => s.trim()).filter(Boolean) : [];
  19098. const payload = {
  19099. id: id || undefined,
  19100. interface: document.getElementById('modal-radv-iface-interface').value.trim(),
  19101. instance: document.getElementById('modal-radv-iface-instance').value.trim(),
  19102. min_ra_interval: parseInt(document.getElementById('modal-radv-iface-min-ra').value, 10) || 200,
  19103. max_ra_interval: parseInt(document.getElementById('modal-radv-iface-max-ra').value, 10) || 600,
  19104. default_lifetime: parseInt(document.getElementById('modal-radv-iface-lifetime').value, 10) || 1800,
  19105. hop_limit: parseInt(document.getElementById('modal-radv-iface-hoplimit').value, 10) || 64,
  19106. prefixes: prefixes,
  19107. rdnss: rdnss,
  19108. comment: document.getElementById('modal-radv-iface-comment').value.trim(),
  19109. disabled: !document.getElementById('modal-radv-iface-enabled').checked
  19110. };
  19111. try {
  19112. const res = await fetch(`${API_BASE}/routing/radv/interfaces`, {
  19113. method: 'POST',
  19114. headers: { 'Content-Type': 'application/json' },
  19115. body: JSON.stringify(payload)
  19116. });
  19117. if (!res.ok) throw new Error(await res.text());
  19118. closeRAdvInterfaceModal();
  19119. showToast('Saved', `RAdv interface saved`, 'success');
  19120. await loadDynamicRouting(false);
  19121. } catch (err) {
  19122. showToast('Error', err.message, 'error');
  19123. }
  19124. }
  19125. async function enableSelectedRadvInterface() {
  19126. const id = state.selectedRadvRow?.interfaces;
  19127. if (!id) return;
  19128. if (!await routingMutation(`${API_BASE}/routing/radv/interfaces/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: false }) })) return;
  19129. await loadDynamicRouting(false);
  19130. }
  19131. async function disableSelectedRadvInterface() {
  19132. const id = state.selectedRadvRow?.interfaces;
  19133. if (!id) return;
  19134. if (!await routingMutation(`${API_BASE}/routing/radv/interfaces/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: true }) })) return;
  19135. await loadDynamicRouting(false);
  19136. }
  19137. async function removeSelectedRadvInterface() {
  19138. const id = state.selectedRadvRow?.interfaces;
  19139. if (!id || !confirm('Are you sure you want to remove this RAdv interface?')) return;
  19140. if (!await routingMutation(`${API_BASE}/routing/radv/interfaces/${id}`, { method: 'DELETE' })) return;
  19141. state.selectedRadvRow.interfaces = null;
  19142. await loadDynamicRouting(false);
  19143. }
  19144. // ================= EIGRP ROUTING CONTROLLER =================
  19145. state.selectedEigrpRow = { instances: null, networks: null, interfaces: null };
  19146. function switchEigrpTab(tab) {
  19147. state.activeEigrpTab = tab;
  19148. const tabs = ['instances', 'networks', 'interfaces', 'neighbors', 'topology'];
  19149. tabs.forEach(t => {
  19150. const btn = document.getElementById(`eigrp-tab-btn-${t}`);
  19151. const pane = document.getElementById(`eigrp-pane-${t}`);
  19152. if (btn) {
  19153. if (t === tab) {
  19154. btn.className = 'px-3 py-2 text-xs font-semibold border-b-2 border-purple-500 text-white transition flex items-center gap-1.5 whitespace-nowrap';
  19155. } else {
  19156. 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';
  19157. }
  19158. }
  19159. if (pane) {
  19160. if (t === tab) pane.classList.remove('hidden');
  19161. else pane.classList.add('hidden');
  19162. }
  19163. });
  19164. const dlIface = document.getElementById('eigrp-iface-datalist');
  19165. if (dlIface && state.interfaces) {
  19166. dlIface.innerHTML = '<option value="*">' + state.interfaces.map(i => `<option value="${escapeHtml(i.name)}">`).join('');
  19167. }
  19168. const dlNet = document.getElementById('eigrp-net-datalist');
  19169. if (dlNet && state.interfaces) {
  19170. const cidrs = [];
  19171. state.interfaces.forEach(i => {
  19172. (i.addrs || []).forEach(a => {
  19173. if (a.includes('.') && a.includes('/')) cidrs.push(a);
  19174. });
  19175. });
  19176. dlNet.innerHTML = '<option value="0.0.0.0/0">' + cidrs.map(c => `<option value="${escapeHtml(c)}">`).join('');
  19177. }
  19178. }
  19179. function selectEigrpRow(kind, id) {
  19180. if (!state.selectedEigrpRow) state.selectedEigrpRow = {};
  19181. if (state.selectedEigrpRow[kind] === id) {
  19182. state.selectedEigrpRow[kind] = null;
  19183. } else {
  19184. state.selectedEigrpRow[kind] = id;
  19185. }
  19186. if (kind === 'instances') {
  19187. renderEigrpInstances();
  19188. const isSel = !!state.selectedEigrpRow.instances;
  19189. const btnEn = document.getElementById('btn-eigrp-inst-enable');
  19190. const btnDis = document.getElementById('btn-eigrp-inst-disable');
  19191. const btnRem = document.getElementById('btn-eigrp-inst-remove');
  19192. if (btnEn) btnEn.disabled = !isSel;
  19193. if (btnDis) btnDis.disabled = !isSel;
  19194. if (btnRem) btnRem.disabled = !isSel;
  19195. } else if (kind === 'networks') {
  19196. renderEigrpNetworks();
  19197. const isSel = !!state.selectedEigrpRow.networks;
  19198. const btnRem = document.getElementById('btn-eigrp-net-remove');
  19199. if (btnRem) btnRem.disabled = !isSel;
  19200. } else if (kind === 'interfaces') {
  19201. renderEigrpInterfaces();
  19202. const isSel = !!state.selectedEigrpRow.interfaces;
  19203. const btnEn = document.getElementById('btn-eigrp-iface-enable');
  19204. const btnDis = document.getElementById('btn-eigrp-iface-disable');
  19205. const btnRem = document.getElementById('btn-eigrp-iface-remove');
  19206. if (btnEn) btnEn.disabled = !isSel;
  19207. if (btnDis) btnDis.disabled = !isSel;
  19208. if (btnRem) btnRem.disabled = !isSel;
  19209. }
  19210. }
  19211. // --- EIGRP INSTANCES ---
  19212. function renderEigrpInstances() {
  19213. const tbody = document.getElementById('eigrp-instances-table-body');
  19214. if (!tbody) return;
  19215. const countEl = document.getElementById('eigrp-instances-footer-count');
  19216. const filter = (document.getElementById('filter-eigrp-instances')?.value || '').toLowerCase();
  19217. let list = state.eigrpInstances || [];
  19218. if (filter) {
  19219. list = list.filter(i => (i.name || '').toLowerCase().includes(filter) || String(i.as || '').includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  19220. }
  19221. if (countEl) countEl.innerText = list.length;
  19222. const selId = state.selectedEigrpRow?.instances;
  19223. tbody.innerHTML = list.map((inst, idx) => {
  19224. const isSel = inst.id === selId;
  19225. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-purple-400' : 'hover:bg-[#1a2636] text-slate-300';
  19226. const flagD = inst.disabled
  19227. ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>'
  19228. : (inst.running
  19229. ? '<span class="text-emerald-400 font-bold" title="Running">R</span>'
  19230. : '<span class="text-amber-400 font-bold" title="Inactive">I</span>');
  19231. const redist = [];
  19232. if (inst.redistribute_connected) redist.push('conn');
  19233. if (inst.redistribute_static) redist.push('static');
  19234. if (inst.redistribute_ospf) redist.push('ospf');
  19235. if (inst.redistribute_bgp) redist.push('bgp');
  19236. const filterBadges = [];
  19237. if (inst.in_filter) filterBadges.push(`<span class="px-1.5 py-0.5 rounded text-[10px] bg-blue-950 text-blue-300 border border-blue-800/50" title="In Filter">IN: ${escapeHtml(inst.in_filter)}</span>`);
  19238. if (inst.out_filter) filterBadges.push(`<span class="px-1.5 py-0.5 rounded text-[10px] bg-purple-950 text-purple-300 border border-purple-800/50" title="Out Filter">OUT: ${escapeHtml(inst.out_filter)}</span>`);
  19239. return `
  19240. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectEigrpRow('instances', '${inst.id}')" ondblclick="openEditEigrpInstanceModal('${inst.id}')">
  19241. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  19242. <td class="py-1.5 px-3 w-12 text-center">${flagD}</td>
  19243. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(inst.comment || '')}</td>
  19244. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  19245. <span class="text-purple-400">⚡</span> <span>${escapeHtml(inst.name || 'default')}</span>
  19246. ${filterBadges.join(' ')}
  19247. </td>
  19248. <td class="py-1.5 px-3 font-mono text-purple-300 font-bold">${inst.as || 100}</td>
  19249. <td class="py-1.5 px-3 font-mono text-cyan-300">${escapeHtml(inst.router_id || 'auto')}</td>
  19250. <td class="py-1.5 px-3 font-mono text-cyan-300">${redist.join(', ') || 'none'}</td>
  19251. <td class="py-1.5 px-3 font-mono text-slate-300">${inst.variance || 1}</td>
  19252. <td class="py-1.5 px-3 font-mono text-slate-300">${inst.max_paths || 4}</td>
  19253. </tr>
  19254. `;
  19255. }).join('');
  19256. }
  19257. function openEigrpInstanceModal() {
  19258. document.getElementById('eigrp-instance-modal-title').innerText = 'Add EIGRP Instance';
  19259. document.getElementById('modal-eigrp-instance-id').value = '';
  19260. document.getElementById('modal-eigrp-instance-name').value = 'eigrp' + ((state.eigrpInstances || []).length + 1);
  19261. document.getElementById('modal-eigrp-instance-as').value = '100';
  19262. document.getElementById('modal-eigrp-instance-routerid').value = '';
  19263. document.getElementById('modal-eigrp-instance-comment').value = '';
  19264. document.getElementById('modal-eigrp-instance-in-filter').value = '';
  19265. document.getElementById('modal-eigrp-instance-out-filter').value = '';
  19266. document.getElementById('modal-eigrp-instance-variance').value = '1';
  19267. document.getElementById('modal-eigrp-instance-maxpaths').value = '4';
  19268. document.getElementById('modal-eigrp-instance-metric').value = '10000';
  19269. document.getElementById('modal-eigrp-instance-redist-conn').checked = false;
  19270. document.getElementById('modal-eigrp-instance-redist-static').checked = false;
  19271. document.getElementById('modal-eigrp-instance-redist-ospf').checked = false;
  19272. document.getElementById('modal-eigrp-instance-redist-bgp').checked = false;
  19273. document.getElementById('modal-eigrp-instance-enabled').checked = true;
  19274. document.getElementById('eigrp-instance-modal')?.classList.remove('hidden');
  19275. }
  19276. function openEditEigrpInstanceModal(id) {
  19277. const inst = (state.eigrpInstances || []).find(i => i.id === id);
  19278. if (!inst) return;
  19279. document.getElementById('eigrp-instance-modal-title').innerText = `Edit EIGRP Instance: ${inst.name}`;
  19280. document.getElementById('modal-eigrp-instance-id').value = inst.id;
  19281. document.getElementById('modal-eigrp-instance-name').value = inst.name || '';
  19282. document.getElementById('modal-eigrp-instance-as').value = inst.as || 100;
  19283. document.getElementById('modal-eigrp-instance-routerid').value = inst.router_id || '';
  19284. document.getElementById('modal-eigrp-instance-comment').value = inst.comment || '';
  19285. document.getElementById('modal-eigrp-instance-in-filter').value = inst.in_filter || '';
  19286. document.getElementById('modal-eigrp-instance-out-filter').value = inst.out_filter || '';
  19287. document.getElementById('modal-eigrp-instance-variance').value = inst.variance || 1;
  19288. document.getElementById('modal-eigrp-instance-maxpaths').value = inst.max_paths || 4;
  19289. document.getElementById('modal-eigrp-instance-metric').value = inst.default_metric || 10000;
  19290. document.getElementById('modal-eigrp-instance-redist-conn').checked = !!inst.redistribute_connected;
  19291. document.getElementById('modal-eigrp-instance-redist-static').checked = !!inst.redistribute_static;
  19292. document.getElementById('modal-eigrp-instance-redist-ospf').checked = !!inst.redistribute_ospf;
  19293. document.getElementById('modal-eigrp-instance-redist-bgp').checked = !!inst.redistribute_bgp;
  19294. document.getElementById('modal-eigrp-instance-enabled').checked = !inst.disabled;
  19295. document.getElementById('eigrp-instance-modal')?.classList.remove('hidden');
  19296. }
  19297. function closeEigrpInstanceModal() {
  19298. document.getElementById('eigrp-instance-modal')?.classList.add('hidden');
  19299. }
  19300. async function submitEigrpInstance(e) {
  19301. e.preventDefault();
  19302. const payload = {
  19303. id: document.getElementById('modal-eigrp-instance-id').value.trim() || undefined,
  19304. name: document.getElementById('modal-eigrp-instance-name').value.trim(),
  19305. as: parseInt(document.getElementById('modal-eigrp-instance-as').value, 10) || 100,
  19306. router_id: document.getElementById('modal-eigrp-instance-routerid').value.trim(),
  19307. comment: document.getElementById('modal-eigrp-instance-comment').value.trim(),
  19308. in_filter: (document.getElementById('modal-eigrp-instance-in-filter')?.value || '').trim(),
  19309. out_filter: (document.getElementById('modal-eigrp-instance-out-filter')?.value || '').trim(),
  19310. variance: parseInt(document.getElementById('modal-eigrp-instance-variance').value, 10) || 1,
  19311. max_paths: parseInt(document.getElementById('modal-eigrp-instance-maxpaths').value, 10) || 4,
  19312. default_metric: parseInt(document.getElementById('modal-eigrp-instance-metric').value, 10) || 10000,
  19313. redistribute_connected: document.getElementById('modal-eigrp-instance-redist-conn').checked,
  19314. redistribute_static: document.getElementById('modal-eigrp-instance-redist-static').checked,
  19315. redistribute_ospf: document.getElementById('modal-eigrp-instance-redist-ospf').checked,
  19316. redistribute_bgp: document.getElementById('modal-eigrp-instance-redist-bgp').checked,
  19317. disabled: !document.getElementById('modal-eigrp-instance-enabled').checked
  19318. };
  19319. try {
  19320. const res = await fetch(`${API_BASE}/routing/eigrp/instances`, {
  19321. method: 'POST',
  19322. headers: { 'Content-Type': 'application/json' },
  19323. body: JSON.stringify(payload)
  19324. });
  19325. if (!res.ok) throw new Error(await res.text());
  19326. closeEigrpInstanceModal();
  19327. showToast('Saved', `EIGRP instance saved`, 'success');
  19328. await loadDynamicRouting(false);
  19329. } catch (err) {
  19330. showToast('Error', err.message, 'error');
  19331. }
  19332. }
  19333. async function enableSelectedEigrpInstance() {
  19334. const id = state.selectedEigrpRow?.instances;
  19335. if (!id) return;
  19336. if (!await routingMutation(`${API_BASE}/routing/eigrp/instances/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: false }) })) return;
  19337. await loadDynamicRouting(false);
  19338. }
  19339. async function disableSelectedEigrpInstance() {
  19340. const id = state.selectedEigrpRow?.instances;
  19341. if (!id) return;
  19342. if (!await routingMutation(`${API_BASE}/routing/eigrp/instances/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: true }) })) return;
  19343. await loadDynamicRouting(false);
  19344. }
  19345. async function removeSelectedEigrpInstance() {
  19346. const id = state.selectedEigrpRow?.instances;
  19347. if (!id || !confirm('Are you sure you want to remove this EIGRP instance?')) return;
  19348. if (!await routingMutation(`${API_BASE}/routing/eigrp/instances/${id}`, { method: 'DELETE' })) return;
  19349. state.selectedEigrpRow.instances = null;
  19350. await loadDynamicRouting(false);
  19351. }
  19352. // --- EIGRP NETWORKS ---
  19353. function renderEigrpNetworks() {
  19354. const tbody = document.getElementById('eigrp-networks-table-body');
  19355. if (!tbody) return;
  19356. const countEl = document.getElementById('eigrp-networks-footer-count');
  19357. const filter = (document.getElementById('filter-eigrp-networks')?.value || '').toLowerCase();
  19358. let list = state.eigrpNetworks || [];
  19359. if (filter) {
  19360. list = list.filter(n => (n.network || '').toLowerCase().includes(filter) || (n.instance || '').toLowerCase().includes(filter) || (n.comment || '').toLowerCase().includes(filter));
  19361. }
  19362. if (countEl) countEl.innerText = list.length;
  19363. const selId = state.selectedEigrpRow?.networks;
  19364. tbody.innerHTML = list.map((net, idx) => {
  19365. const isSel = net.id === selId;
  19366. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-purple-400' : 'hover:bg-[#1a2636] text-slate-300';
  19367. return `
  19368. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectEigrpRow('networks', '${net.id}')">
  19369. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  19370. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(net.comment || '')}</td>
  19371. <td class="py-1.5 px-3 font-mono font-semibold text-white">${escapeHtml(net.network || '')}</td>
  19372. <td class="py-1.5 px-3 font-semibold text-purple-300 font-mono">${escapeHtml(net.instance || 'all')}</td>
  19373. </tr>
  19374. `;
  19375. }).join('');
  19376. }
  19377. function openEigrpNetworkModal() {
  19378. document.getElementById('modal-eigrp-network-id').value = '';
  19379. const instSel = document.getElementById('modal-eigrp-network-instance');
  19380. if (instSel) {
  19381. instSel.innerHTML = '<option value="all">all (Any instance)</option>' +
  19382. (state.eigrpInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)} (AS ${i.as})</option>`).join('');
  19383. }
  19384. document.getElementById('modal-eigrp-network-cidr').value = '0.0.0.0/0';
  19385. document.getElementById('modal-eigrp-network-comment').value = '';
  19386. document.getElementById('eigrp-network-modal')?.classList.remove('hidden');
  19387. }
  19388. function closeEigrpNetworkModal() {
  19389. document.getElementById('eigrp-network-modal')?.classList.add('hidden');
  19390. }
  19391. async function submitEigrpNetwork(e) {
  19392. e.preventDefault();
  19393. const payload = {
  19394. id: document.getElementById('modal-eigrp-network-id').value.trim() || undefined,
  19395. instance: document.getElementById('modal-eigrp-network-instance').value,
  19396. network: document.getElementById('modal-eigrp-network-cidr').value.trim(),
  19397. comment: document.getElementById('modal-eigrp-network-comment').value.trim()
  19398. };
  19399. try {
  19400. const res = await fetch(`${API_BASE}/routing/eigrp/networks`, {
  19401. method: 'POST',
  19402. headers: { 'Content-Type': 'application/json' },
  19403. body: JSON.stringify(payload)
  19404. });
  19405. if (!res.ok) throw new Error(await res.text());
  19406. closeEigrpNetworkModal();
  19407. showToast('Saved', `EIGRP network saved`, 'success');
  19408. await loadDynamicRouting(false);
  19409. } catch (err) {
  19410. showToast('Error', err.message, 'error');
  19411. }
  19412. }
  19413. async function removeSelectedEigrpNetwork() {
  19414. const id = state.selectedEigrpRow?.networks;
  19415. if (!id || !confirm('Are you sure you want to remove this EIGRP network?')) return;
  19416. if (!await routingMutation(`${API_BASE}/routing/eigrp/networks/${id}`, { method: 'DELETE' })) return;
  19417. state.selectedEigrpRow.networks = null;
  19418. await loadDynamicRouting(false);
  19419. }
  19420. // --- EIGRP INTERFACES ---
  19421. function renderEigrpInterfaces() {
  19422. const tbody = document.getElementById('eigrp-interfaces-table-body');
  19423. if (!tbody) return;
  19424. const countEl = document.getElementById('eigrp-interfaces-footer-count');
  19425. const filter = (document.getElementById('filter-eigrp-interfaces')?.value || '').toLowerCase();
  19426. let list = state.eigrpInterfaces || [];
  19427. if (filter) {
  19428. list = list.filter(i => (i.interface || '').toLowerCase().includes(filter) || (i.instance || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  19429. }
  19430. if (countEl) countEl.innerText = list.length;
  19431. const selId = state.selectedEigrpRow?.interfaces;
  19432. tbody.innerHTML = list.map((iface, idx) => {
  19433. const isSel = iface.id === selId;
  19434. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-purple-400' : 'hover:bg-[#1a2636] text-slate-300';
  19435. const flagD = iface.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '<span class="text-emerald-400 font-bold">E</span>';
  19436. return `
  19437. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectEigrpRow('interfaces', '${iface.id}')" ondblclick="openEditEigrpInterfaceModal('${iface.id}')">
  19438. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  19439. <td class="py-1.5 px-3 w-12 text-center">${flagD}</td>
  19440. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(iface.comment || '')}</td>
  19441. <td class="py-1.5 px-3 font-mono font-semibold text-white">${escapeHtml(iface.interface || '*')}</td>
  19442. <td class="py-1.5 px-3 font-semibold text-purple-300 font-mono">${escapeHtml(iface.instance || 'all')}</td>
  19443. <td class="py-1.5 px-3 text-slate-400">${iface.hello_interval || 5}s / ${iface.hold_time || 15}s</td>
  19444. <td class="py-1.5 px-3 font-mono ${iface.passive ? 'text-amber-400 font-bold' : 'text-slate-400'}">${iface.passive ? 'Yes' : 'No'}</td>
  19445. <td class="py-1.5 px-3 font-mono ${iface.split_horizon ? 'text-emerald-400' : 'text-slate-400'}">${iface.split_horizon ? 'Yes' : 'No'}</td>
  19446. <td class="py-1.5 px-3 text-slate-300 uppercase font-mono">${escapeHtml(iface.auth_mode || 'none')}</td>
  19447. </tr>
  19448. `;
  19449. }).join('');
  19450. }
  19451. function toggleEigrpAuthKey() {
  19452. const mode = document.getElementById('modal-eigrp-iface-auth-mode')?.value;
  19453. const wrap = document.getElementById('modal-eigrp-iface-auth-key-wrap');
  19454. if (wrap) {
  19455. if (mode === 'md5') wrap.classList.remove('hidden');
  19456. else wrap.classList.add('hidden');
  19457. }
  19458. }
  19459. function openEigrpInterfaceModal() {
  19460. document.getElementById('eigrp-interface-modal-title').innerText = 'Add EIGRP Interface Profile';
  19461. document.getElementById('modal-eigrp-iface-id').value = '';
  19462. const instSel = document.getElementById('modal-eigrp-iface-instance');
  19463. if (instSel) {
  19464. instSel.innerHTML = '<option value="all">all (Any instance)</option>' +
  19465. (state.eigrpInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)} (AS ${i.as})</option>`).join('');
  19466. }
  19467. const dl = document.getElementById('eigrp-iface-datalist');
  19468. if (dl && state.interfaces) {
  19469. dl.innerHTML = '<option value="*">' + state.interfaces.map(i => `<option value="${escapeHtml(i.name)}">`).join('');
  19470. }
  19471. document.getElementById('modal-eigrp-iface-interface').value = '*';
  19472. document.getElementById('modal-eigrp-iface-hello').value = '5';
  19473. document.getElementById('modal-eigrp-iface-hold').value = '15';
  19474. document.getElementById('modal-eigrp-iface-auth-mode').value = 'none';
  19475. document.getElementById('modal-eigrp-iface-auth-key').value = '';
  19476. toggleEigrpAuthKey();
  19477. document.getElementById('modal-eigrp-iface-passive').checked = false;
  19478. document.getElementById('modal-eigrp-iface-split-horizon').checked = true;
  19479. document.getElementById('modal-eigrp-iface-comment').value = '';
  19480. document.getElementById('modal-eigrp-iface-enabled').checked = true;
  19481. document.getElementById('eigrp-interface-modal')?.classList.remove('hidden');
  19482. }
  19483. function openEditEigrpInterfaceModal(id) {
  19484. const iface = (state.eigrpInterfaces || []).find(i => i.id === id);
  19485. if (!iface) return;
  19486. document.getElementById('eigrp-interface-modal-title').innerText = `Edit EIGRP Interface: ${iface.interface}`;
  19487. document.getElementById('modal-eigrp-iface-id').value = iface.id;
  19488. const instSel = document.getElementById('modal-eigrp-iface-instance');
  19489. if (instSel) {
  19490. instSel.innerHTML = '<option value="all">all (Any instance)</option>' +
  19491. (state.eigrpInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)} (AS ${i.as})</option>`).join('');
  19492. instSel.value = iface.instance || 'all';
  19493. }
  19494. const dl = document.getElementById('eigrp-iface-datalist');
  19495. if (dl && state.interfaces) {
  19496. dl.innerHTML = '<option value="*">' + state.interfaces.map(i => `<option value="${escapeHtml(i.name)}">`).join('');
  19497. }
  19498. document.getElementById('modal-eigrp-iface-interface').value = iface.interface || '*';
  19499. document.getElementById('modal-eigrp-iface-hello').value = iface.hello_interval || 5;
  19500. document.getElementById('modal-eigrp-iface-hold').value = iface.hold_time || 15;
  19501. document.getElementById('modal-eigrp-iface-auth-mode').value = iface.auth_mode || 'none';
  19502. document.getElementById('modal-eigrp-iface-auth-key').value = iface.auth_key || '';
  19503. toggleEigrpAuthKey();
  19504. document.getElementById('modal-eigrp-iface-passive').checked = !!iface.passive;
  19505. document.getElementById('modal-eigrp-iface-split-horizon').checked = iface.split_horizon !== false;
  19506. document.getElementById('modal-eigrp-iface-comment').value = iface.comment || '';
  19507. document.getElementById('modal-eigrp-iface-enabled').checked = !iface.disabled;
  19508. document.getElementById('eigrp-interface-modal')?.classList.remove('hidden');
  19509. }
  19510. function closeEigrpInterfaceModal() {
  19511. document.getElementById('eigrp-interface-modal')?.classList.add('hidden');
  19512. }
  19513. async function submitEigrpInterface(e) {
  19514. e.preventDefault();
  19515. const payload = {
  19516. id: document.getElementById('modal-eigrp-iface-id').value.trim() || undefined,
  19517. instance: document.getElementById('modal-eigrp-iface-instance').value,
  19518. interface: document.getElementById('modal-eigrp-iface-interface').value.trim(),
  19519. hello_interval: parseInt(document.getElementById('modal-eigrp-iface-hello').value, 10) || 5,
  19520. hold_time: parseInt(document.getElementById('modal-eigrp-iface-hold').value, 10) || 15,
  19521. passive: document.getElementById('modal-eigrp-iface-passive').checked,
  19522. split_horizon: document.getElementById('modal-eigrp-iface-split-horizon').checked,
  19523. auth_mode: document.getElementById('modal-eigrp-iface-auth-mode').value,
  19524. auth_key: document.getElementById('modal-eigrp-iface-auth-key').value.trim(),
  19525. comment: document.getElementById('modal-eigrp-iface-comment').value.trim(),
  19526. disabled: !document.getElementById('modal-eigrp-iface-enabled').checked
  19527. };
  19528. try {
  19529. const res = await fetch(`${API_BASE}/routing/eigrp/interfaces`, {
  19530. method: 'POST',
  19531. headers: { 'Content-Type': 'application/json' },
  19532. body: JSON.stringify(payload)
  19533. });
  19534. if (!res.ok) throw new Error(await res.text());
  19535. closeEigrpInterfaceModal();
  19536. showToast('Saved', `EIGRP interface saved`, 'success');
  19537. await loadDynamicRouting(false);
  19538. } catch (err) {
  19539. showToast('Error', err.message, 'error');
  19540. }
  19541. }
  19542. async function enableSelectedEigrpInterface() {
  19543. const id = state.selectedEigrpRow?.interfaces;
  19544. if (!id) return;
  19545. if (!await routingMutation(`${API_BASE}/routing/eigrp/interfaces/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: false }) })) return;
  19546. await loadDynamicRouting(false);
  19547. }
  19548. async function disableSelectedEigrpInterface() {
  19549. const id = state.selectedEigrpRow?.interfaces;
  19550. if (!id) return;
  19551. if (!await routingMutation(`${API_BASE}/routing/eigrp/interfaces/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: true }) })) return;
  19552. await loadDynamicRouting(false);
  19553. }
  19554. async function removeSelectedEigrpInterface() {
  19555. const id = state.selectedEigrpRow?.interfaces;
  19556. if (!id || !confirm('Are you sure you want to remove this EIGRP interface?')) return;
  19557. if (!await routingMutation(`${API_BASE}/routing/eigrp/interfaces/${id}`, { method: 'DELETE' })) return;
  19558. state.selectedEigrpRow.interfaces = null;
  19559. await loadDynamicRouting(false);
  19560. }
  19561. // --- EIGRP NEIGHBORS (LIVE) ---
  19562. function renderEigrpNeighbors() {
  19563. const tbody = document.getElementById('eigrp-neighbors-table-body');
  19564. if (!tbody) return;
  19565. const countEl = document.getElementById('eigrp-neighbors-footer-count');
  19566. const filter = (document.getElementById('filter-eigrp-neighbors')?.value || '').toLowerCase();
  19567. let list = state.eigrpNeighbors || [];
  19568. if (filter) {
  19569. list = list.filter(n => (n.address || '').toLowerCase().includes(filter) || (n.interface || '').toLowerCase().includes(filter) || String(n.as || '').includes(filter));
  19570. }
  19571. if (countEl) countEl.innerText = list.length;
  19572. tbody.innerHTML = list.map((nbr, idx) => `
  19573. <tr class="hover:bg-[#1a2636] text-slate-300">
  19574. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  19575. <td class="py-1.5 px-3 font-mono font-bold text-purple-400">${nbr.as || '-'}</td>
  19576. <td class="py-1.5 px-3 font-mono font-semibold text-purple-300">${escapeHtml(nbr.address || '')}</td>
  19577. <td class="py-1.5 px-3 font-mono text-white">${escapeHtml(nbr.interface || '')}</td>
  19578. <td class="py-1.5 px-3 font-mono text-slate-400">${nbr.hold_time || 0}s</td>
  19579. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(nbr.uptime || '-')}</td>
  19580. <td class="py-1.5 px-3 font-mono text-slate-300">${nbr.srtt || 0}</td>
  19581. <td class="py-1.5 px-3 font-mono text-slate-300">${nbr.rto || 0}</td>
  19582. <td class="py-1.5 px-3 font-mono text-slate-400">${nbr.q_cnt || 0}</td>
  19583. <td class="py-1.5 px-3 font-mono text-slate-400">${nbr.seq_num || 0}</td>
  19584. </tr>
  19585. `).join('');
  19586. }
  19587. // --- EIGRP TOPOLOGY (LIVE) ---
  19588. function renderEigrpTopology() {
  19589. const tbody = document.getElementById('eigrp-topology-table-body');
  19590. if (!tbody) return;
  19591. const countEl = document.getElementById('eigrp-topology-footer-count');
  19592. const filter = (document.getElementById('filter-eigrp-topology')?.value || '').toLowerCase();
  19593. let list = state.eigrpTopology || [];
  19594. if (filter) {
  19595. list = list.filter(t => (t.network || '').toLowerCase().includes(filter) || (t.next_hop || '').toLowerCase().includes(filter) || (t.interface || '').toLowerCase().includes(filter) || String(t.as || '').includes(filter));
  19596. }
  19597. if (countEl) countEl.innerText = list.length;
  19598. tbody.innerHTML = list.map((top, idx) => `
  19599. <tr class="hover:bg-[#1a2636] text-slate-300">
  19600. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  19601. <td class="py-1.5 px-3 font-mono font-bold text-purple-400">${top.as || '-'}</td>
  19602. <td class="py-1.5 px-3 font-mono font-semibold text-white">${escapeHtml(top.network || '')}</td>
  19603. <td class="py-1.5 px-3 font-mono text-slate-300">${top.successors || 1}</td>
  19604. <td class="py-1.5 px-3 font-mono text-purple-300">${escapeHtml(top.fd || '-')}</td>
  19605. <td class="py-1.5 px-3 font-mono text-cyan-300">${escapeHtml(top.next_hop || '-')}</td>
  19606. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(top.interface || '-')}</td>
  19607. </tr>
  19608. `).join('');
  19609. }