app.js 899 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966
  1. // DebTik - Debian Linux Router Frontend Application Logic
  2. // ================= Interceptor: Automatic Auth Bearer & 401 Handling =================
  3. const originalFetch = window.fetch.bind(window);
  4. const pendingAPIReads = new Map();
  5. const telemetryHealth = { lastSuccess: 0, failures: new Map() };
  6. let coreRefreshPromise = null;
  7. let lastSummaryRefresh = 0;
  8. function renderTelemetryHealth() {
  9. const el = document.getElementById('telemetry-health');
  10. if (!el) return;
  11. const failures = [...telemetryHealth.failures.entries()];
  12. const seconds = telemetryHealth.lastSuccess ? Math.floor((Date.now() - telemetryHealth.lastSuccess) / 1000) : null;
  13. const stale = seconds === null || seconds > 15;
  14. el.textContent = failures.length ? `Data unavailable / incomplete${seconds === null ? '' : ` · updated ${seconds}s ago`}` : stale ? 'Waiting for fresh data' : `Updated ${seconds}s ago`;
  15. el.className = `text-[10px] font-mono ${failures.length || stale ? 'text-amber-400' : 'text-emerald-400'}`;
  16. el.title = failures.length ? failures.map(([path, error]) => `${path}: ${error}`).join('\n') : telemetryHealth.lastSuccess ? `Last successful update: ${new Date(telemetryHealth.lastSuccess).toLocaleTimeString()}` : 'No successful update yet';
  17. }
  18. function stopSessionPolling() {
  19. if (window._telemetryInterval) clearInterval(window._telemetryInterval);
  20. window._telemetryInterval = null;
  21. if (trafficEventSource) trafficEventSource.close();
  22. trafficEventSource = null;
  23. if (trafficPollFallback) clearInterval(trafficPollFallback);
  24. trafficPollFallback = null;
  25. if (bwtestState.pollTimer) clearInterval(bwtestState.pollTimer);
  26. bwtestState.pollTimer = null;
  27. if (logsTimer) clearInterval(logsTimer);
  28. logsTimer = null;
  29. stopFwStatPolling();
  30. stopNATStatPolling();
  31. stopMangleStatPolling();
  32. telemetryHealth.failures.clear();
  33. telemetryHealth.lastSuccess = 0;
  34. lastSummaryRefresh = 0;
  35. }
  36. window.fetch = async function(resource, options = {}) {
  37. const url = new URL(resource instanceof Request ? resource.url : resource, window.location.href);
  38. const isAPI = url.origin === window.location.origin && url.pathname.startsWith('/api/');
  39. if (!isAPI) return originalFetch(resource, options);
  40. const config = { ...options, headers: new Headers(options.headers || (resource instanceof Request ? resource.headers : undefined)) };
  41. const token = localStorage.getItem('debtik_token');
  42. if (token && !config.headers.has('Authorization')) config.headers.set('Authorization', `Bearer ${token}`);
  43. const method = (config.method || (resource instanceof Request ? resource.method : 'GET')).toUpperCase();
  44. const isRead = method === 'GET' && !url.pathname.includes('/stream') && !url.pathname.startsWith('/api/auth/');
  45. const key = `${url.href}|${JSON.stringify([...config.headers])}`;
  46. if (isRead && pendingAPIReads.has(key)) return (await pendingAPIReads.get(key)).clone();
  47. const perform = async () => {
  48. let timeout;
  49. if (isRead && !config.signal) {
  50. const controller = new AbortController();
  51. config.signal = controller.signal;
  52. timeout = setTimeout(() => controller.abort(), 15000);
  53. }
  54. try {
  55. const response = await originalFetch(resource, config);
  56. if (isRead) {
  57. if (response.ok) {
  58. telemetryHealth.lastSuccess = Date.now();
  59. telemetryHealth.failures.delete(url.pathname);
  60. } else {
  61. telemetryHealth.failures.set(url.pathname, `HTTP ${response.status}; displayed values may be old`);
  62. }
  63. renderTelemetryHealth();
  64. }
  65. if (response.status === 401 && url.pathname !== '/api/auth/login' && state.currentUser && token === localStorage.getItem('debtik_token')) {
  66. stopSessionPolling();
  67. state.isPolling = false;
  68. state.currentUser = null;
  69. localStorage.removeItem('debtik_token');
  70. showLoginScreen(true);
  71. }
  72. return response;
  73. } catch (err) {
  74. if (isRead) {
  75. telemetryHealth.failures.set(url.pathname, err.name === 'AbortError' ? 'Request timed out' : 'Connection failed; displayed values may be old');
  76. renderTelemetryHealth();
  77. }
  78. throw err;
  79. } finally {
  80. if (timeout) clearTimeout(timeout);
  81. }
  82. };
  83. if (!isRead) return perform();
  84. const request = perform();
  85. pendingAPIReads.set(key, request);
  86. try { return (await request).clone(); }
  87. finally { if (pendingAPIReads.get(key) === request) pendingAPIReads.delete(key); }
  88. };
  89. let state = {
  90. currentUser: null,
  91. users: [],
  92. interfaces: [],
  93. vlans: [],
  94. systemStatus: null,
  95. vpnStatus: null,
  96. routes: [],
  97. activeTab: 'dashboard',
  98. fwSubTab: 'filter',
  99. bridgeSubTab: 'bridges',
  100. bridges: [],
  101. bridgePorts: [],
  102. bridgeVLANs: [],
  103. bridgeHosts: [],
  104. bridgeSummary: null,
  105. routesSubTab: 'routes',
  106. pppSubTab: 'secrets',
  107. eoipTunnels: [],
  108. vxlanTunnels: [],
  109. vxlanVteps: [],
  110. pppSecrets: [],
  111. pppProfiles: [],
  112. pppActiveSessions: [],
  113. pppoeServer: null,
  114. pptpServer: null,
  115. l2tpServer: null,
  116. ipsecServer: null,
  117. ifaceFilter: 'all',
  118. currentModalIface: null,
  119. isPolling: false,
  120. expandedParents: new Set(['eth0']),
  121. pppoeData: null,
  122. wgData: null,
  123. ipsecData: null,
  124. l2tpData: null,
  125. pptpData: null,
  126. fwSummary: null,
  127. filterRules: [],
  128. natRules: [],
  129. mangleRules: [],
  130. addressLists: [],
  131. connections: [],
  132. policyRules: [],
  133. routingTables: [],
  134. routingFilters: [],
  135. filterChainSelected: 'all',
  136. activeToolsSubTab: 'ping',
  137. dhcpClients: [],
  138. dhcpSummary: null,
  139. dhcpServerTab: 'servers',
  140. dhcpServers: [],
  141. dhcpNetworks: [],
  142. dhcpLeases: [],
  143. dhcpOptions: [],
  144. dhcpServerSummary: null,
  145. sdwanGroups: [],
  146. sdwanTelemetry: null
  147. };
  148. const API_BASE = '/api';
  149. function escapeHtml(str) {
  150. if (str === null || str === undefined) return '';
  151. return String(str)
  152. .replace(/&/g, '&')
  153. .replace(/</g, '&lt;')
  154. .replace(/>/g, '&gt;')
  155. .replace(/"/g, '&quot;')
  156. .replace(/'/g, '&#039;');
  157. }
  158. function formatBytes(bytes) {
  159. if (bytes === undefined || bytes === null || isNaN(bytes) || bytes === 0) return '0 B';
  160. const k = 1024;
  161. const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
  162. const i = Math.floor(Math.log(bytes) / Math.log(k));
  163. if (i < 0 || i >= sizes.length) return `${bytes} B`;
  164. return `${parseFloat((bytes / Math.pow(k, i)).toFixed(2))} ${sizes[i]}`;
  165. }
  166. // Initialize on page load
  167. document.addEventListener('DOMContentLoaded', async () => {
  168. initTableSorting();
  169. // Verify authentication before bootstrapping telemetry and views
  170. const isAuthenticated = await checkAuthStatus();
  171. if (isAuthenticated) {
  172. const hash = window.location.hash.replace('#', '') || 'dashboard';
  173. navigate(hash);
  174. // Full state telemetry polling every 5 seconds (smooth & flicker-free)
  175. if (!window._telemetryInterval) {
  176. window._telemetryInterval = setInterval(() => {
  177. if (state.isPolling && state.currentUser && !document.hidden) {
  178. fetchData(false);
  179. }
  180. }, 5000);
  181. }
  182. }
  183. });
  184. let trafficEventSource = null;
  185. let trafficPollFallback = null;
  186. function initLiveTrafficStream() {
  187. if (trafficEventSource) {
  188. try { trafficEventSource.close(); } catch(e) {}
  189. trafficEventSource = null;
  190. }
  191. if (trafficPollFallback) {
  192. clearInterval(trafficPollFallback);
  193. trafficPollFallback = null;
  194. }
  195. if (window.EventSource) {
  196. try {
  197. trafficEventSource = new EventSource(`${API_BASE}/interfaces/traffic/stream`);
  198. trafficEventSource.onmessage = (event) => {
  199. try {
  200. const data = JSON.parse(event.data);
  201. updateLiveInterfaceTraffic(data);
  202. } catch (e) {
  203. console.error('Error parsing live traffic event:', e);
  204. }
  205. };
  206. trafficEventSource.onerror = () => {
  207. // Fallback polling if SSE disconnects
  208. if (!trafficPollFallback) {
  209. trafficPollFallback = setInterval(pollLiveTrafficSnapshot, 1000);
  210. }
  211. };
  212. trafficEventSource.onopen = () => {
  213. if (trafficPollFallback) {
  214. clearInterval(trafficPollFallback);
  215. trafficPollFallback = null;
  216. }
  217. };
  218. return;
  219. } catch (e) {
  220. console.warn('EventSource failed, using 1s polling fallback:', e);
  221. }
  222. }
  223. // Fallback if EventSource is unavailable
  224. trafficPollFallback = setInterval(pollLiveTrafficSnapshot, 1000);
  225. }
  226. async function pollLiveTrafficSnapshot() {
  227. try {
  228. const res = await fetch(`${API_BASE}/interfaces/traffic/rates`);
  229. if (res.ok) {
  230. const data = await res.json();
  231. updateLiveInterfaceTraffic(data);
  232. }
  233. } catch (e) {}
  234. }
  235. function updateLiveInterfaceTraffic(data) {
  236. if (!data || !data.interfaces) return;
  237. state.latestTraffic = data;
  238. // 1. Update Top & Dashboard Total Bandwidth Indicators
  239. const rxHuman = data.total_rx_human || '0 B/s';
  240. const txHuman = data.total_tx_human || '0 B/s';
  241. const statRx = document.getElementById('stat-traffic-rx');
  242. if (statRx && statRx.innerText !== rxHuman) statRx.innerText = rxHuman;
  243. const statTx = document.getElementById('stat-traffic-tx');
  244. if (statTx && statTx.innerText !== txHuman) statTx.innerText = txHuman;
  245. // 2. Update state.interfaces rates in-memory
  246. if (Array.isArray(state.interfaces)) {
  247. state.interfaces.forEach(i => {
  248. const live = data.interfaces[i.name];
  249. if (live) {
  250. i.rate = {
  251. rx_bytes_sec: live.rx_bytes_sec,
  252. tx_bytes_sec: live.tx_bytes_sec,
  253. rx_human: live.rx_human,
  254. tx_human: live.tx_human
  255. };
  256. i.stats = {
  257. rx_bytes: live.rx_bytes,
  258. tx_bytes: live.tx_bytes,
  259. rx_packets: live.rx_packets,
  260. tx_packets: live.tx_packets,
  261. rx_errors: live.rx_errors,
  262. tx_errors: live.tx_errors,
  263. rx_dropped: live.rx_dropped,
  264. tx_dropped: live.tx_dropped
  265. };
  266. }
  267. });
  268. }
  269. // 3. Update all live UI rate spans in-place (ZERO flicker)
  270. Object.keys(data.interfaces).forEach(name => {
  271. const live = data.interfaces[name];
  272. // Dashboard Port Matrix Card
  273. const cardRate = document.getElementById(`port-card-rate-${name}`);
  274. if (cardRate && cardRate.innerText !== live.rx_human) {
  275. cardRate.innerText = live.rx_human;
  276. }
  277. // Dashboard Quick Interfaces Table
  278. const quickRx = document.getElementById(`quick-rx-${name}`);
  279. if (quickRx) quickRx.innerText = `↓ ${live.rx_human}`;
  280. const quickTx = document.getElementById(`quick-tx-${name}`);
  281. if (quickTx) quickTx.innerText = `↑ ${live.tx_human}`;
  282. // Main Interfaces Tree Table
  283. const ifaceRx = document.getElementById(`iface-rate-rx-${name}`);
  284. if (ifaceRx) ifaceRx.innerText = `↓ ${live.rx_human}`;
  285. const ifaceTx = document.getElementById(`iface-rate-tx-${name}`);
  286. if (ifaceTx) ifaceTx.innerText = `↑ ${live.tx_human}`;
  287. // VLAN Sub-interfaces Table
  288. const vlanRx = document.getElementById(`vlan-rate-rx-${name}`);
  289. if (vlanRx) vlanRx.innerText = `↓ ${live.rx_human}`;
  290. const vlanTx = document.getElementById(`vlan-rate-tx-${name}`);
  291. if (vlanTx) vlanTx.innerText = `↑ ${live.tx_human}`;
  292. // VLAN Page Table
  293. const vlanPageRx = document.getElementById(`vlan-page-rate-rx-${name}`);
  294. if (vlanPageRx) vlanPageRx.innerText = `↓ ${live.rx_human}`;
  295. const vlanPageTx = document.getElementById(`vlan-page-rate-tx-${name}`);
  296. if (vlanPageTx) vlanPageTx.innerText = `↑ ${live.tx_human}`;
  297. });
  298. }
  299. // Navigation Handler
  300. function navigate(tabName) {
  301. if (tabName === 'dynamic-routing' || tabName === 'routing') {
  302. navigate('bgp');
  303. return;
  304. }
  305. if (tabName === 'vlans') {
  306. navigate('interfaces');
  307. return;
  308. }
  309. if (tabName === 'persistence') {
  310. navigate('dashboard');
  311. return;
  312. }
  313. stopFwStatPolling();
  314. stopNATStatPolling();
  315. stopMangleStatPolling();
  316. state.activeTab = tabName;
  317. window.location.hash = tabName;
  318. // Update nav links styling
  319. document.querySelectorAll('.nav-link').forEach(link => {
  320. 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';
  321. });
  322. const activeNav = document.getElementById(`nav-${tabName}`);
  323. if (activeNav) {
  324. 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';
  325. }
  326. // Update page headers
  327. const titles = {
  328. dashboard: { title: 'Dashboard Overview', sub: 'Live router performance and network telemetry' },
  329. interfaces: { title: 'Network Interfaces', sub: 'Interface Table View' },
  330. 'dhcp-client': { title: 'DHCP Client', sub: 'DHCP Client List' },
  331. 'dhcp-server': { title: 'DHCP Server & Subnets', sub: 'DHCP Server instances, subnet networks (NTP, TFTP, DNS), dynamic leases & static reservations' },
  332. bridge: { title: 'Bridge Interfaces', sub: 'IEEE 802.1D / 802.1Q VLAN-aware Layer 2 switching, RSTP & hardware forwarding (FDB)' },
  333. vlans: { title: 'VLAN Virtual Networks', sub: 'IEEE 802.1Q sub-interface segmentation and routing' },
  334. firewall: { title: 'Network Firewall', sub: 'Stateful packet inspection, NAT, traffic mangle, address lists & connection tracking' },
  335. routes: { title: 'Routing & Policy', sub: 'Routing tables, static routes (DAS/DAC), and policy routing rules' },
  336. sdwan: { title: 'Software-Defined WAN (SD-WAN)', sub: 'Multi-link aggregation, traffic load balancing & quality SLA health monitoring' },
  337. bgp: { title: 'BGP Dynamic Routing', sub: 'BGP multi-instance peering sessions, advertised networks, and routing table (RIB)' },
  338. ospf: { title: 'OSPF Dynamic Routing', sub: 'OSPFv2 link-state routing, dynamic neighbor adjacencies, and multi-area topology' },
  339. rip: { title: 'RIP Dynamic Routing', sub: 'Routing Information Protocol (RIPv2 IPv4 & RIPng IPv6) hop-count distance-vector routing' },
  340. bfd: { title: 'BFD Fast Session Detection', sub: 'Bidirectional Forwarding Detection (BFD) sub-second link failure detection for BGP and OSPF' },
  341. babel: { title: 'Babel Dynamic Routing', sub: 'Babel loop-avoiding distance-vector routing for wired and wireless mesh networks (RFC 8966)' },
  342. radv: { title: 'IPv6 Router Advertisements (RAdv)', sub: 'BIRD 2 ICMPv6 Router Advertisement daemon for IPv6 SLAAC autoconfiguration and RDNSS' },
  343. 'routing-filters': { title: 'Routing Policy Filters', sub: 'Route filter chains, prefix matching, BGP community maps & policy-based path control' },
  344. 'dynamic-routing': { title: 'BGP Dynamic Routing', sub: 'Dynamic routing engine and peering sessions' },
  345. ppp: { title: 'PPP Servers & Secrets', sub: 'Subscriber authentication, dynamic IP pools and VPN access concentrators' },
  346. eoip: { title: 'EoIP Tunnels', sub: 'Ethernet over IP (EoIP / GRETAP) Layer 2 encapsulation & transparent network bridging' },
  347. vxlan: { title: 'VXLAN Tunnels', sub: 'Virtual Extensible LAN (RFC 7348) Layer 2 overlay networks and static VTEPs' },
  348. aerotun: { title: 'AeroTUN High-Speed VPN', sub: 'Layer 3 encrypted tunnel with XChaCha20-Poly1305 and adaptive LZ4 compression' },
  349. pppoe: { title: 'PPPoE Client WAN', sub: 'Point-to-Point Protocol over Ethernet WAN access' },
  350. wireguard: { title: 'WireGuard VPN', sub: 'High-performance cryptographic Layer 3 tunnels with ChaCha20-Poly1305 key exchange' },
  351. ipsec: { title: 'IPSec (IKEv2) strongSwan', sub: 'Enterprise Site-to-Site & Roadwarrior IPSec controller' },
  352. l2tp: { title: 'L2TP VPN Client', sub: 'Layer 2 Tunneling Protocol via xl2tpd' },
  353. pptp: { title: 'PPTP VPN Client', sub: 'Point-to-Point Tunneling Protocol with MPPE-128 encryption' },
  354. vrrp: { title: 'VRRP High Availability', sub: 'Virtual Router Redundancy Protocol, active-backup gateway failover & Virtual IP (VIP) routing' },
  355. bwtest: { title: 'Bandwidth Test Benchmark', sub: 'High-speed line-rate throughput benchmark, token-bucket rate limiting, loss & jitter telemetry' },
  356. tools: { title: 'Diagnostic & Troubleshooting Tools', sub: 'Network latency analysis, ICMP/MTR telemetry, path tracing, DNS resolution and TCP probing' },
  357. settings: { title: 'Router Settings & DNS', sub: 'System DNS forwarder, upstream resolvers, static host mappings, and appliance identity' },
  358. users: { title: 'Local User Manager', sub: 'Manage local system administrator credentials and access permissions' },
  359. certificates: { title: 'Certificates & SSL/TLS', sub: 'Root Certificate Authorities (CA), Server/Client certificates and automated Let\'s Encrypt' },
  360. reverse_proxy: { title: 'Reverse Proxy & Gateway', sub: 'HTTP/HTTPS Path Routing, Domain Forwarding & SSL Termination' },
  361. services: { title: 'Management Services', sub: 'Enable or disable Web, SSH, and Telnet management listeners and listening ports' },
  362. updates: { title: 'Git Updates', sub: 'Check, install and restore appliance software' },
  363. logs: { title: 'System Activity Logs', sub: 'Real-time circular buffer log viewer and topic-based event monitoring' }
  364. };
  365. const header = titles[tabName] || titles.dashboard;
  366. const pTitle = document.getElementById('page-title');
  367. if (pTitle) pTitle.innerText = header.title;
  368. const pSub = document.getElementById('page-subtitle');
  369. if (pSub) pSub.innerText = header.sub;
  370. // Toggle sections dynamically for all section elements
  371. document.querySelectorAll('main section[id^="section-"]').forEach(el => {
  372. if (el.id === `section-${tabName}`) {
  373. el.classList.remove('hidden');
  374. } else {
  375. el.classList.add('hidden');
  376. }
  377. });
  378. if (tabName === 'interfaces') {
  379. loadRoles();
  380. if (state.activeIfaceSubTab === 'roles') switchIfaceSubTab('roles');
  381. else switchIfaceSubTab('tree');
  382. }
  383. if (tabName === 'bridge') loadBridge();
  384. if (tabName === 'firewall') loadFirewall();
  385. if (tabName === 'routes') loadRoutes();
  386. if (tabName === 'sdwan') loadSDWAN();
  387. if (tabName === 'bgp') {
  388. loadDynamicRouting();
  389. switchBgpSubTab(state.activeBgpSubTab || 'bgp-peers');
  390. }
  391. if (tabName === 'ospf') {
  392. loadDynamicRouting();
  393. switchOspfTab(state.activeOspfTab || 'instances');
  394. }
  395. if (tabName === 'rip') {
  396. loadDynamicRouting();
  397. switchRipTab(state.activeRipTab || 'instances');
  398. }
  399. if (tabName === 'bfd') {
  400. loadDynamicRouting();
  401. switchBfdTab(state.activeBfdTab || 'config');
  402. }
  403. if (tabName === 'babel') {
  404. loadDynamicRouting();
  405. switchBabelTab(state.activeBabelTab || 'instances');
  406. }
  407. if (tabName === 'radv') {
  408. loadDynamicRouting();
  409. switchRadvTab(state.activeRadvTab || 'instances');
  410. }
  411. if (tabName === 'routing-filters') loadDynamicRouting();
  412. if (tabName === 'dynamic-routing') loadDynamicRouting();
  413. if (tabName === 'ppp') loadPPP();
  414. if (tabName === 'eoip') loadEoIP();
  415. if (tabName === 'vxlan') loadVXLAN();
  416. if (tabName === 'aerotun') loadAeroTUN();
  417. if (tabName === 'pppoe') loadPPPoE();
  418. if (tabName === 'wireguard') loadWireGuard();
  419. if (tabName === 'ipsec') loadIPSec();
  420. if (tabName === 'l2tp') loadL2TP();
  421. if (tabName === 'pptp') loadPPTP();
  422. if (tabName === 'tools') loadToolsView();
  423. if (tabName === 'dhcp-client') loadDHCPClients();
  424. if (tabName === 'dhcp-server') loadDHCPServer();
  425. if (tabName === 'vrrp') loadVRRP();
  426. if (tabName === 'bwtest') loadBwTestView();
  427. if (tabName === 'settings') loadSettingsData();
  428. if (tabName === 'users') loadUsers();
  429. if (tabName === 'certificates') loadCertificates();
  430. if (tabName === 'reverse_proxy') loadReverseProxy();
  431. if (tabName === 'services') loadServices();
  432. if (tabName === 'updates') loadUpdateStatus();
  433. if (tabName === 'logs') loadLogs();
  434. setTimeout(initTableSorting, 50);
  435. }
  436. // Fetch all core system, network and VPN telemetry
  437. function fetchData(isManual = false) {
  438. if (coreRefreshPromise) return coreRefreshPromise;
  439. coreRefreshPromise = refreshCoreData(isManual).finally(() => { coreRefreshPromise = null; });
  440. return coreRefreshPromise;
  441. }
  442. async function refreshCoreData(isManual = false) {
  443. const spinner = document.getElementById('refresh-spinner');
  444. if (isManual && spinner) spinner.classList.add('animate-spin');
  445. try {
  446. const refreshSummaries = isManual || Date.now() - lastSummaryRefresh > 30000;
  447. const summaryFetch = path => (refreshSummaries || (state.activeTab === 'interfaces' && ['/vlans', '/roles'].includes(path))) ? fetch(`${API_BASE}${path}`).catch(() => ({ ok: false })) : Promise.resolve({ ok: false });
  448. const [statusRes, ifacesRes, vlansRes, vpnRes, fwRes, dynRes, brSummaryRes, dhcpSumRes, dhcpClientsRes, vrrpSumRes, rolesRes] = await Promise.all([
  449. fetch(`${API_BASE}/system/status`).catch(() => ({ ok: false })),
  450. fetch(`${API_BASE}/interfaces`).catch(() => ({ ok: false })),
  451. summaryFetch('/vlans'),
  452. summaryFetch('/vpn/status'),
  453. summaryFetch('/firewall/summary'),
  454. summaryFetch('/routing/dynamic/summary'),
  455. summaryFetch('/bridge/summary'),
  456. summaryFetch('/dhcp/clients/summary'),
  457. summaryFetch('/dhcp/clients'),
  458. summaryFetch('/vrrp/summary').catch(() => null),
  459. summaryFetch('/roles').catch(() => null)
  460. ]);
  461. if (refreshSummaries && [vlansRes, vpnRes, fwRes, dynRes, brSummaryRes, dhcpSumRes, dhcpClientsRes, vrrpSumRes, rolesRes].every(r => r && r.ok)) lastSummaryRefresh = Date.now();
  462. if (rolesRes && rolesRes.ok) {
  463. state.roles = await rolesRes.json();
  464. const countEl = document.getElementById('badge-roles-count');
  465. if (countEl) countEl.innerText = (state.roles || []).length;
  466. }
  467. if (vrrpSumRes && vrrpSumRes.ok) {
  468. state.vrrpSummary = await vrrpSumRes.json();
  469. renderVRRPSummary();
  470. }
  471. if (dhcpSumRes && dhcpSumRes.ok) {
  472. state.dhcpSummary = await dhcpSumRes.json();
  473. const bDhcp = document.getElementById('badge-dhcp-client-count');
  474. if (bDhcp) bDhcp.innerText = state.dhcpSummary?.total_clients || 0;
  475. }
  476. if (dhcpClientsRes && dhcpClientsRes.ok) {
  477. state.dhcpClients = await dhcpClientsRes.json();
  478. }
  479. if (brSummaryRes.ok) {
  480. state.bridgeSummary = await brSummaryRes.json();
  481. const bBridge = document.getElementById('badge-bridge-count');
  482. if (bBridge) bBridge.innerText = state.bridgeSummary?.bridges_count || 0;
  483. const sBr = document.getElementById('bridge-stat-bridges');
  484. if (sBr) sBr.innerText = state.bridgeSummary?.bridges_count || 0;
  485. const sPorts = document.getElementById('bridge-stat-ports');
  486. if (sPorts) sPorts.innerText = state.bridgeSummary?.ports_count || 0;
  487. const sHosts = document.getElementById('bridge-stat-hosts');
  488. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  489. }
  490. if (statusRes.ok) state.systemStatus = await statusRes.json();
  491. if (ifacesRes.ok) {
  492. const ifacesData = await ifacesRes.json();
  493. const rawIfaces = Array.isArray(ifacesData) ? ifacesData : [];
  494. state.interfaces = rawIfaces.filter(i => {
  495. if (!i.name) return false;
  496. if (i.name.startsWith('ep_')) return false;
  497. return !['gre0', 'gretap0', 'erspan0', 'sit0', 'tunl0', 'ip6tnl0', 'ip6gre0', 'ip6erspan0'].includes(i.name);
  498. });
  499. try { populateToolsInterfaces(); } catch (e) {}
  500. }
  501. if (vlansRes.ok) {
  502. const vlansData = await vlansRes.json();
  503. state.vlans = Array.isArray(vlansData) ? vlansData : [];
  504. }
  505. if (vpnRes.ok) state.vpnStatus = await vpnRes.json();
  506. if (fwRes && fwRes.ok) state.fwSummary = await fwRes.json();
  507. if (dynRes && dynRes.ok) state.dynSummary = await dynRes.json();
  508. updateSystemMetrics();
  509. updateBadges();
  510. if (state.activeTab === 'dashboard') renderDashboard();
  511. if (state.activeTab === 'interfaces') {
  512. if (state.activeIfaceSubTab === 'roles') renderRolesTable();
  513. else renderInterfacesList();
  514. }
  515. if (state.activeTab === 'vlans') renderVlansList();
  516. if (state.activeTab === 'firewall') await loadFirewall(false);
  517. if (state.activeTab === 'routes') await loadRoutes(false);
  518. if (state.activeTab === 'dynamic-routing' || state.activeTab === 'bgp' || state.activeTab === 'ospf' || state.activeTab === 'rip' || state.activeTab === 'bfd' || state.activeTab === 'babel' || state.activeTab === 'radv') await loadDynamicRouting(false);
  519. if (state.activeTab === 'ppp') await loadPPP(false);
  520. if (state.activeTab === 'eoip') await loadEoIP(false);
  521. if (state.activeTab === 'vxlan') await loadVXLAN(false);
  522. if (state.activeTab === 'aerotun') await loadAeroTUN(false);
  523. if (state.activeTab === 'pppoe') await loadPPPoE(false);
  524. if (state.activeTab === 'wireguard') await loadWireGuard(false);
  525. if (state.activeTab === 'ipsec') await loadIPSec(false);
  526. if (state.activeTab === 'l2tp') await loadL2TP(false);
  527. if (state.activeTab === 'pptp') await loadPPTP(false);
  528. if (state.activeTab === 'dhcp-client') await loadDHCPClients(false);
  529. if (state.activeTab === 'dhcp-server') await loadDHCPServer(false);
  530. if (state.activeTab === 'vrrp') await loadVRRP(false);
  531. if (state.activeTab === 'settings') await loadSettingsData(false);
  532. if (state.activeTab === 'users') await loadUsers(false);
  533. if (state.activeTab === 'certificates') await loadCertificates(false);
  534. if (state.activeTab === 'reverse_proxy') await loadReverseProxy(false);
  535. if (state.activeTab === 'sdwan') await loadSDWAN(false);
  536. if (state.activeTab === 'services') await loadServices(false);
  537. if (state.activeTab === 'updates') await loadUpdateStatus(false);
  538. if (state.activeTab === 'bwtest') await fetchBwTestServerStatus();
  539. } catch (err) {
  540. console.error('Failed to fetch router state:', err);
  541. } finally {
  542. if (isManual && spinner) {
  543. setTimeout(() => spinner.classList.remove('animate-spin'), 300);
  544. }
  545. }
  546. }
  547. // Update Top KPI and Sidebar Telemetry
  548. function updateSystemMetrics() {
  549. const s = state.systemStatus;
  550. const v = state.vpnStatus;
  551. if (!s) return;
  552. // Sidebar Host & Uptime
  553. const sideHost = document.getElementById('side-hostname');
  554. if (sideHost) sideHost.innerText = s.hostname || 'debian-lxc';
  555. const sideUp = document.getElementById('side-uptime');
  556. if (sideUp) sideUp.innerText = s.uptime_human || '0m';
  557. const sideGw = document.getElementById('side-gateway-ip');
  558. if (sideGw) sideGw.innerText = s.default_gateway ? `GW: ${s.default_gateway}` : 'GW: Isolated';
  559. // Compute CPU Metrics
  560. let cpuPct = 0;
  561. if (s.cpu_pct !== undefined) {
  562. cpuPct = s.cpu_pct;
  563. } else if (s.cpu_load && s.cpu_load.length > 0) {
  564. const cores = s.cpu_cores || 1;
  565. cpuPct = Math.min(100, Math.round((parseFloat(s.cpu_load[0]) / cores) * 100));
  566. }
  567. const cpuPctStr = `${cpuPct.toFixed(1)}%`;
  568. const cpuWidth = `${Math.max(3, Math.min(100, cpuPct))}%`;
  569. const loadStr = s.cpu_load ? s.cpu_load.join(', ') : '-';
  570. // Sidebar CPU
  571. const sideCpuVal = document.getElementById('side-cpu-val');
  572. if (sideCpuVal) sideCpuVal.innerText = cpuPctStr;
  573. const sideCpuBar = document.getElementById('side-cpu-bar');
  574. if (sideCpuBar) {
  575. sideCpuBar.style.width = cpuWidth;
  576. sideCpuBar.title = `Container: ${cpuPctStr} | Host Loadavg: ${loadStr} (${s.cpu_cores || 1} cores)`;
  577. }
  578. // Dashboard CPU Card
  579. const dashCpuVal = document.getElementById('dash-cpu-val');
  580. if (dashCpuVal) dashCpuVal.innerText = cpuPctStr;
  581. const dashCpuBar = document.getElementById('dash-cpu-bar');
  582. if (dashCpuBar) {
  583. dashCpuBar.style.width = cpuWidth;
  584. if (cpuPct > 85) {
  585. dashCpuBar.className = 'h-full rounded-full bg-rose-500 transition-all duration-500';
  586. } else if (cpuPct > 65) {
  587. dashCpuBar.className = 'h-full rounded-full bg-amber-500 transition-all duration-500';
  588. } else {
  589. dashCpuBar.className = 'h-full rounded-full bg-emerald-500 transition-all duration-500';
  590. }
  591. }
  592. const dashCpuCores = document.getElementById('dash-cpu-cores');
  593. if (dashCpuCores) dashCpuCores.innerText = `${s.cpu_cores || 1} Cores`;
  594. const dashCpuLoad = document.getElementById('dash-cpu-load');
  595. if (dashCpuLoad) dashCpuLoad.innerText = loadStr;
  596. const dashCpuStatus = document.getElementById('dash-cpu-status');
  597. if (dashCpuStatus) {
  598. if (cpuPct > 85) {
  599. dashCpuStatus.innerText = 'High';
  600. dashCpuStatus.className = 'text-[11px] font-semibold text-rose-400 uppercase px-2 py-0.5 rounded bg-rose-500/10';
  601. } else if (cpuPct > 65) {
  602. dashCpuStatus.innerText = 'Heavy';
  603. dashCpuStatus.className = 'text-[11px] font-semibold text-amber-400 uppercase px-2 py-0.5 rounded bg-amber-500/10';
  604. } else {
  605. dashCpuStatus.innerText = 'Normal';
  606. dashCpuStatus.className = 'text-[11px] font-semibold text-emerald-400 uppercase px-2 py-0.5 rounded bg-emerald-500/10';
  607. }
  608. }
  609. // Compute RAM Metrics
  610. const memPct = Math.round(s.mem_usage_pct || 0);
  611. const memPctStr = `${memPct}%`;
  612. const memWidth = `${Math.max(3, Math.min(100, memPct))}%`;
  613. const usedMB = s.mem_used_mb || 0;
  614. const totalMB = s.mem_total_mb || 0;
  615. const freeMB = totalMB > usedMB ? totalMB - usedMB : 0;
  616. function fmtMemMB(mb) {
  617. if (mb >= 1024) {
  618. return `${(mb / 1024).toFixed(1)} GB`;
  619. }
  620. return `${mb} MB`;
  621. }
  622. // Sidebar RAM
  623. const sideRamVal = document.getElementById('side-ram-val');
  624. if (sideRamVal) sideRamVal.innerText = memPctStr;
  625. const sideRamBar = document.getElementById('side-ram-bar');
  626. if (sideRamBar) sideRamBar.style.width = memWidth;
  627. // Dashboard RAM Card
  628. const dashRamVal = document.getElementById('dash-ram-val');
  629. if (dashRamVal) dashRamVal.innerText = memPctStr;
  630. const dashRamBar = document.getElementById('dash-ram-bar');
  631. if (dashRamBar) {
  632. dashRamBar.style.width = memWidth;
  633. if (memPct > 85) {
  634. dashRamBar.className = 'h-full rounded-full bg-rose-500 transition-all duration-500';
  635. } else if (memPct > 70) {
  636. dashRamBar.className = 'h-full rounded-full bg-amber-500 transition-all duration-500';
  637. } else {
  638. dashRamBar.className = 'h-full rounded-full bg-indigo-500 transition-all duration-500';
  639. }
  640. }
  641. const dashRamUsedTotal = document.getElementById('dash-ram-used-total');
  642. if (dashRamUsedTotal) {
  643. dashRamUsedTotal.innerText = `${fmtMemMB(usedMB)} / ${fmtMemMB(totalMB)}`;
  644. }
  645. const dashRamFree = document.getElementById('dash-ram-free');
  646. if (dashRamFree) {
  647. dashRamFree.innerText = fmtMemMB(freeMB);
  648. }
  649. const dashRamStatus = document.getElementById('dash-ram-status');
  650. if (dashRamStatus) {
  651. if (memPct > 85) {
  652. dashRamStatus.innerText = 'High';
  653. dashRamStatus.className = 'text-[11px] font-semibold text-rose-400 uppercase px-2 py-0.5 rounded bg-rose-500/10';
  654. } else {
  655. dashRamStatus.innerText = 'Active';
  656. dashRamStatus.className = 'text-[11px] font-semibold text-indigo-400 uppercase px-2 py-0.5 rounded bg-indigo-500/10';
  657. }
  658. }
  659. // Legacy Dashboard Stats (Safe checks)
  660. const elIfacesUp = document.getElementById('stat-ifaces-up');
  661. if (elIfacesUp) elIfacesUp.innerText = s.up_ifaces || 0;
  662. const elIfacesTot = document.getElementById('stat-ifaces-total');
  663. if (elIfacesTot) elIfacesTot.innerText = `${s.total_ifaces || 0} Total`;
  664. const elIfacesDown = document.getElementById('stat-ifaces-down');
  665. if (elIfacesDown) elIfacesDown.innerText = `${s.down_ifaces || 0} DOWN`;
  666. const elVlans = document.getElementById('stat-vlans-count');
  667. if (elVlans) elVlans.innerText = s.vlan_ifaces || 0;
  668. // VPN Status Indicators
  669. if (v) {
  670. const totalActive = v.total_active_tunnels || 0;
  671. const statVpnActive = document.getElementById('stat-vpn-active');
  672. if (statVpnActive) statVpnActive.innerText = totalActive;
  673. const tunnelsDot = document.getElementById('tunnels-dot');
  674. const tunnelsLabel = document.getElementById('tunnels-label');
  675. if (tunnelsDot && tunnelsLabel) {
  676. if (totalActive > 0) {
  677. tunnelsDot.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  678. tunnelsLabel.innerText = `${totalActive} Active VPN Tunnel${totalActive > 1 ? 's' : ''}`;
  679. } else {
  680. tunnelsDot.className = 'w-2 h-2 rounded-full bg-slate-500';
  681. tunnelsLabel.innerText = '0 Active VPN Tunnels';
  682. }
  683. }
  684. setDotBadge('badge-pppoe-status', (v.active_pppoe || 0) > 0 || v.pppoe_connected);
  685. setDotBadge('badge-wg-status', (v.active_wireguard || 0) > 0 || v.wireguard_active);
  686. setDotBadge('badge-ipsec-status', (v.active_ipsec || 0) > 0 || v.ipsec_active);
  687. setDotBadge('badge-l2tp-status', (v.active_l2tp || 0) > 0 || v.l2tp_connected);
  688. setDotBadge('badge-pptp-status', (v.active_pptp || 0) > 0 || v.pptp_connected);
  689. }
  690. // Total Live Bandwidth Rate
  691. let totalRx = 0;
  692. let totalTx = 0;
  693. (state.interfaces || []).forEach(i => {
  694. if (i.rate) {
  695. totalRx += i.rate.rx_bytes_sec || 0;
  696. totalTx += i.rate.tx_bytes_sec || 0;
  697. }
  698. });
  699. document.getElementById('stat-traffic-rx').innerText = formatTraffic(totalRx);
  700. document.getElementById('stat-traffic-tx').innerText = formatTraffic(totalTx);
  701. }
  702. function setDotBadge(id, active) {
  703. const el = document.getElementById(id);
  704. if (!el) return;
  705. if (active) {
  706. el.className = 'w-2 h-2 rounded-full bg-emerald-400 shadow-sm shadow-emerald-400/80';
  707. } else {
  708. el.className = 'w-2 h-2 rounded-full bg-slate-600';
  709. }
  710. }
  711. function updateBadges() {
  712. const bIfaces = document.getElementById('badge-ifaces-count');
  713. if (bIfaces) bIfaces.innerText = (state.interfaces || []).length;
  714. const bVlans = document.getElementById('badge-vlans-count');
  715. if (bVlans) bVlans.innerText = (state.vlans || []).length;
  716. if (state.fwSummary) {
  717. const totalFwRules = (state.fwSummary.filter_rules_count || 0) + (state.fwSummary.nat_rules_count || 0) + (state.fwSummary.mangle_rules_count || 0);
  718. const badgeFw = document.getElementById('badge-firewall-count');
  719. if (badgeFw) badgeFw.innerText = totalFwRules;
  720. }
  721. if (state.vpnStatus) {
  722. const v = state.vpnStatus;
  723. const bEoIP = document.getElementById('badge-eoip-count');
  724. if (bEoIP) bEoIP.innerText = v.total_eoip || 0;
  725. const bVXLAN = document.getElementById('badge-vxlan-count');
  726. if (bVXLAN) bVXLAN.innerText = v.total_vxlan || 0;
  727. const bAero = document.getElementById('badge-aerotun-count');
  728. if (bAero) bAero.innerText = v.total_aerotun || 0;
  729. const bPPPSess = document.getElementById('badge-ppp-sessions');
  730. if (bPPPSess) bPPPSess.innerText = v.total_ppp_sessions || 0;
  731. setDotBadge('badge-pppoe-status', v.active_pppoe > 0 || v.pppoe_server_running);
  732. setDotBadge('badge-wg-status', v.active_wireguard > 0);
  733. setDotBadge('badge-ipsec-status', v.active_ipsec > 0 || v.ipsec_server_running);
  734. setDotBadge('badge-l2tp-status', v.active_l2tp > 0 || v.l2tp_server_running);
  735. setDotBadge('badge-pptp-status', v.active_pptp > 0 || v.pptp_server_running);
  736. }
  737. if (state.dynSummary) {
  738. const d = state.dynSummary;
  739. setDotBadge('badge-bgp-dot', d.bgp_running);
  740. setDotBadge('badge-ospf-dot', d.ospf_running);
  741. setDotBadge('badge-rip-dot', d.rip_running);
  742. setDotBadge('badge-bfd-dot', d.bfd_running);
  743. setDotBadge('badge-babel-dot', d.babel_running);
  744. setDotBadge('badge-radv-dot', d.radv_running);
  745. const bBgp = document.getElementById('badge-bgp-count');
  746. if (bBgp) bBgp.innerText = (state.bgpPeers || []).length;
  747. const bOspf = document.getElementById('badge-ospf-count');
  748. if (bOspf) bOspf.innerText = (state.ospfInterfaces || []).length;
  749. const bRip = document.getElementById('badge-rip-count');
  750. if (bRip) bRip.innerText = (state.ripInterfaces || []).length;
  751. const bBfd = document.getElementById('badge-bfd-count');
  752. if (bBfd) bBfd.innerText = (state.bfdInterfaces || []).length;
  753. const bBabel = document.getElementById('badge-babel-count');
  754. if (bBabel) bBabel.innerText = (state.babelInterfaces || []).length;
  755. const bRadv = document.getElementById('badge-radv-count');
  756. if (bRadv) bRadv.innerText = (state.radvInterfaces || []).length;
  757. const bFilters = document.getElementById('badge-filters-count');
  758. if (bFilters) bFilters.innerText = (state.routingFilters || []).length;
  759. }
  760. const bDhcpServer = document.getElementById('badge-dhcp-server-count');
  761. if (bDhcpServer) {
  762. bDhcpServer.innerText = state.dhcpServerSummary ? (state.dhcpServerSummary.active_leases || state.dhcpServerSummary.total_servers || 0) : (state.dhcpServers || []).length;
  763. }
  764. }
  765. // Render Dashboard View
  766. function renderDashboard() {
  767. const matrix = document.getElementById('port-matrix');
  768. if (!matrix) return;
  769. const ifaces = state.interfaces || [];
  770. const sig = ifaces.map(i => `${i.name}:${i.state}:${(i.ipv4 || []).join(',')}:${i.type}:${i.is_vlan}`).join(';');
  771. if (matrix.dataset.sig === sig) {
  772. return; // Structure & link states haven't changed! Do not rebuild or flicker!
  773. }
  774. matrix.dataset.sig = sig;
  775. matrix.innerHTML = '';
  776. (state.interfaces || []).forEach(iface => {
  777. const isUp = iface.state === 'UP';
  778. const isVlan = iface.is_vlan;
  779. const portCard = document.createElement('div');
  780. portCard.className = `p-3 rounded-xl border transition-all cursor-pointer select-none group ${
  781. isUp
  782. ? (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')
  783. : 'bg-slate-900/40 border-slate-800/60 opacity-60 hover:opacity-100 hover:border-slate-700'
  784. }`;
  785. portCard.onclick = () => openIfaceModal(iface.name);
  786. let statusPillClass = isUp ? 'bg-emerald-500 shadow-sm shadow-emerald-500/50' : 'bg-rose-500';
  787. if (isVlan) statusPillClass = isUp ? 'bg-cyan-400 shadow-sm shadow-cyan-400/50' : 'bg-rose-500';
  788. portCard.innerHTML = `
  789. <div class="flex items-center justify-between mb-2">
  790. <span class="font-bold text-xs font-mono text-white group-hover:text-brand-400 transition truncate">${iface.name}</span>
  791. <span class="w-2 h-2 rounded-full ${statusPillClass}"></span>
  792. </div>
  793. <div class="text-[11px] font-mono text-slate-300 truncate">${iface.ipv4 && iface.ipv4.length > 0 ? iface.ipv4[0] : (iface.mac || 'No IP')}</div>
  794. <div class="mt-2 flex items-center justify-between text-[10px] text-slate-400">
  795. <span class="uppercase tracking-wider font-semibold">${isVlan ? `VLAN ${iface.vlan_id}` : iface.type}</span>
  796. <span id="port-card-rate-${iface.name}">${iface.rate?.rx_human || '0 B/s'}</span>
  797. </div>
  798. `;
  799. matrix.appendChild(portCard);
  800. });
  801. const ifaceTbody = document.getElementById('quick-interfaces-table');
  802. if (ifaceTbody) {
  803. ifaceTbody.innerHTML = '';
  804. (state.interfaces || []).forEach(i => {
  805. const isUp = i.state === 'UP';
  806. const tr = document.createElement('tr');
  807. tr.className = 'hover:bg-slate-800/40 transition cursor-pointer';
  808. tr.onclick = () => openIfaceModal(i.name);
  809. const rxStr = i.rate?.rx_human || '0 B/s';
  810. const txStr = i.rate?.tx_human || '0 B/s';
  811. tr.innerHTML = `
  812. <td class="py-2.5 font-bold text-white flex items-center gap-2">
  813. <span class="w-2 h-2 rounded-full ${isUp ? 'bg-emerald-400 shadow-sm shadow-emerald-400/50' : 'bg-rose-400'}"></span>
  814. <span>${i.name}</span>
  815. </td>
  816. <td class="py-2.5 text-slate-300 font-sans">
  817. ${getRoleBadge(i.role || 'LAN')}
  818. </td>
  819. <td class="py-2.5 text-slate-400 text-[11px] font-mono">${i.mac || '-'}</td>
  820. <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>
  821. <td class="py-2.5 text-slate-300 text-[11px] font-mono">
  822. <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>
  823. </td>
  824. <td class="py-2.5 text-right font-sans font-semibold">
  825. <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>
  826. </td>
  827. `;
  828. ifaceTbody.appendChild(tr);
  829. });
  830. }
  831. const vlanTbody = document.getElementById('quick-vlans-table');
  832. if (vlanTbody) {
  833. vlanTbody.innerHTML = '';
  834. }
  835. }
  836. // Expand / Collapse Handlers
  837. function toggleExpand(parentName) {
  838. if (state.expandedParents.has(parentName)) {
  839. state.expandedParents.delete(parentName);
  840. } else {
  841. state.expandedParents.add(parentName);
  842. }
  843. renderInterfacesList();
  844. }
  845. // VLAN Support Checker: 802.1Q sub-interfaces are only supported on physical ethernet, veth, bridge, bond
  846. function supportsVLAN(iface) {
  847. if (!iface) return false;
  848. if (iface.is_vlan) return false;
  849. const name = (iface.name || '').toLowerCase();
  850. const type = (iface.type || '').toLowerCase();
  851. const role = (iface.role || '').toLowerCase();
  852. // Exclude loopback
  853. if (name === 'lo' || type === 'loopback' || role === 'loopback') return false;
  854. // Exclude WireGuard (Layer 3 tunnel, no 802.1Q support)
  855. if (type === 'wireguard' || name.startsWith('wg')) return false;
  856. // Exclude PPP / PPPoE
  857. if (type === 'ppp' || name.startsWith('ppp')) return false;
  858. // Exclude other Layer 3 tunnels and dummy devices
  859. if (type === 'dummy' || type === 'gre' || type === 'sit' || type === 'tun' || type === 'tap' ||
  860. name.startsWith('gre') || name.startsWith('sit') || name.startsWith('ipsec') || name.startsWith('xfrm') || name.startsWith('dummy')) {
  861. return false;
  862. }
  863. // If name already contains a dot, it's already a sub-interface
  864. if (name.includes('.')) return false;
  865. return true;
  866. }
  867. // DHCP Client Support Checker: Only broadcast-capable layer-2 interfaces (Ethernet, veth, VLAN, bridge, bond)
  868. function supportsDHCPClient(iface) {
  869. if (!iface) return false;
  870. const name = (iface.name || '').toLowerCase();
  871. const type = (iface.type || '').toLowerCase();
  872. const role = (iface.role || '').toLowerCase();
  873. // Exclude loopback
  874. if (name === 'lo' || type === 'loopback' || role === 'loopback') return false;
  875. // Exclude WireGuard (Layer 3 point-to-point tunnel, no broadcast/DHCP)
  876. if (type === 'wireguard' || name.startsWith('wg')) return false;
  877. // Exclude PPP / PPPoE / L2TP / PPTP tunnels
  878. if (type === 'ppp' || name.startsWith('ppp') || name.startsWith('l2tp') || name.startsWith('pptp')) return false;
  879. // Exclude other Layer 3 tunnels and dummy devices
  880. if (type === 'dummy' || type === 'gre' || type === 'sit' || type === 'tun' || type === 'tap' ||
  881. name.startsWith('gre') || name.startsWith('sit') || name.startsWith('ipsec') || name.startsWith('xfrm') || name.startsWith('dummy')) {
  882. return false;
  883. }
  884. // Exclude bridge member/slave ports (bridge itself handles IP / DHCP)
  885. const isBridgePort = (state.bridgePorts || []).some(bp => bp.interface === iface.name);
  886. if (isBridgePort) return false;
  887. return true;
  888. }
  889. // Expand / Collapse Handlers
  890. function toggleExpand(parentName) {
  891. const childVlans = (state.vlans || []).filter(v => v.parent_name === parentName || v.name.startsWith(parentName + '.'));
  892. if (childVlans.length === 0) {
  893. // Cannot expand an interface with no VLANs
  894. state.expandedParents.delete(parentName);
  895. return;
  896. }
  897. if (state.expandedParents.has(parentName)) {
  898. state.expandedParents.delete(parentName);
  899. } else {
  900. state.expandedParents.add(parentName);
  901. }
  902. renderInterfacesList();
  903. }
  904. function expandAllIfaces(expand) {
  905. if (expand) {
  906. (state.interfaces || []).forEach(i => {
  907. const hasVlans = (state.vlans || []).some(v => v.parent_name === i.name || v.name.startsWith(i.name + '.'));
  908. if (!i.is_vlan && hasVlans) state.expandedParents.add(i.name);
  909. });
  910. } else {
  911. state.expandedParents.clear();
  912. }
  913. renderInterfacesList();
  914. }
  915. // =========================================================================
  916. // INTERFACE ROLE TAGS MANAGEMENT
  917. // =========================================================================
  918. const ROLE_COLORS = {
  919. amber: { bg: 'bg-amber-500/20', text: 'text-amber-300', border: 'border-amber-500/30' },
  920. blue: { bg: 'bg-blue-500/20', text: 'text-blue-300', border: 'border-blue-500/30' },
  921. cyan: { bg: 'bg-cyan-500/20', text: 'text-cyan-300', border: 'border-cyan-500/30' },
  922. emerald: { bg: 'bg-emerald-500/20', text: 'text-emerald-300', border: 'border-emerald-500/30' },
  923. purple: { bg: 'bg-purple-500/20', text: 'text-purple-300', border: 'border-purple-500/30' },
  924. rose: { bg: 'bg-rose-500/20', text: 'text-rose-300', border: 'border-rose-500/30' },
  925. indigo: { bg: 'bg-indigo-500/20', text: 'text-indigo-300', border: 'border-indigo-500/30' },
  926. sky: { bg: 'bg-sky-500/20', text: 'text-sky-300', border: 'border-sky-500/30' },
  927. slate: { bg: 'bg-slate-800', text: 'text-slate-300', border: 'border-slate-700' }
  928. };
  929. function getRoleBadge(roleName) {
  930. const name = roleName || 'LAN';
  931. const role = (state.roles || []).find(r => r.name.toLowerCase() === name.toLowerCase() || r.id.toLowerCase() === name.toLowerCase());
  932. const colorKey = (role?.color || 'blue').toLowerCase();
  933. const theme = ROLE_COLORS[colorKey] || ROLE_COLORS.blue;
  934. 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>`;
  935. }
  936. function switchIfaceSubTab(subTab) {
  937. state.activeIfaceSubTab = subTab;
  938. const treeTab = document.getElementById('ifaces-subtab-tree');
  939. const rolesTab = document.getElementById('ifaces-subtab-roles');
  940. const btnTree = document.getElementById('ifaces-subtab-btn-tree');
  941. const btnRoles = document.getElementById('ifaces-subtab-btn-roles');
  942. if (subTab === 'roles') {
  943. treeTab?.classList.add('hidden');
  944. rolesTab?.classList.remove('hidden');
  945. if (btnRoles) {
  946. 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';
  947. }
  948. if (btnTree) {
  949. 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';
  950. }
  951. loadRoles();
  952. } else {
  953. rolesTab?.classList.add('hidden');
  954. treeTab?.classList.remove('hidden');
  955. if (btnTree) {
  956. 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';
  957. }
  958. if (btnRoles) {
  959. 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';
  960. }
  961. renderInterfacesList();
  962. }
  963. }
  964. async function loadRoles() {
  965. try {
  966. const res = await fetch(`${API_BASE}/roles`);
  967. if (res.ok) {
  968. state.roles = await res.json();
  969. const countEl = document.getElementById('badge-roles-count');
  970. if (countEl) countEl.innerText = (state.roles || []).length;
  971. renderRolesTable();
  972. populateRoleSelects();
  973. }
  974. } catch (err) {
  975. console.error('Failed to load role tags:', err);
  976. }
  977. }
  978. function renderRolesTable() {
  979. const tbody = document.getElementById('roles-table-body');
  980. const empty = document.getElementById('roles-empty-state');
  981. if (!tbody) return;
  982. const roles = state.roles || [];
  983. if (roles.length === 0) {
  984. tbody.innerHTML = '';
  985. empty?.classList.remove('hidden');
  986. return;
  987. }
  988. empty?.classList.add('hidden');
  989. const sig = roles.map(r => `${r.id}:${r.name}:${r.color}:${r.description}:${(r.interfaces||[]).join(',')}`).join(';');
  990. if (tbody.dataset.sig === sig) return;
  991. tbody.dataset.sig = sig;
  992. tbody.innerHTML = roles.map(r => {
  993. const colorKey = (r.color || 'blue').toLowerCase();
  994. const theme = ROLE_COLORS[colorKey] || ROLE_COLORS.blue;
  995. const ifaces = Array.isArray(r.interfaces) ? r.interfaces : [];
  996. const ifacesChips = ifaces.length > 0
  997. ? 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('')
  998. : '<span class="text-slate-600 font-sans text-xs italic">Unassigned (0)</span>';
  999. return `
  1000. <tr class="hover:bg-slate-800/40 transition">
  1001. <td class="py-3 px-4">
  1002. <span class="px-2.5 py-1 rounded text-xs font-semibold ${theme.bg} ${theme.text} border ${theme.border}">
  1003. ${escapeHtml(r.name)}
  1004. </span>
  1005. </td>
  1006. <td class="py-3 px-4 font-bold text-white font-mono flex items-center gap-2">
  1007. <span>${escapeHtml(r.name)}</span>
  1008. ${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>' : ''}
  1009. </td>
  1010. <td class="py-3 px-4 font-sans capitalize text-slate-300">
  1011. <span class="inline-flex items-center gap-1.5">
  1012. <span class="w-2 h-2 rounded-full ${theme.bg.replace('/20', '')}"></span>
  1013. <span>${escapeHtml(r.color || 'blue')}</span>
  1014. </span>
  1015. </td>
  1016. <td class="py-3 px-4 font-sans text-slate-400 text-xs">${escapeHtml(r.description || '-')}</td>
  1017. <td class="py-3 px-4 font-sans">
  1018. <div class="flex flex-wrap items-center">
  1019. ${ifacesChips}
  1020. </div>
  1021. </td>
  1022. <td class="py-3 px-4 text-right space-x-2 font-sans whitespace-nowrap">
  1023. <button onclick="openRoleModal('${escapeHtml(r.id)}')"
  1024. class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold px-2 py-1 rounded hover:bg-slate-800 transition">
  1025. Edit
  1026. </button>
  1027. <button onclick="deleteRoleTag('${escapeHtml(r.id)}', '${escapeHtml(r.name)}')"
  1028. class="text-xs text-rose-400 hover:text-rose-300 font-semibold px-2 py-1 rounded hover:bg-slate-800 transition">
  1029. Delete
  1030. </button>
  1031. </td>
  1032. </tr>
  1033. `;
  1034. }).join('');
  1035. }
  1036. function openRoleModal(id = null) {
  1037. const modal = document.getElementById('role-modal');
  1038. if (!modal) return;
  1039. const idInput = document.getElementById('role-modal-id');
  1040. const nameInput = document.getElementById('role-modal-name');
  1041. const colorSelect = document.getElementById('role-modal-color');
  1042. const descInput = document.getElementById('role-modal-desc');
  1043. const title = document.getElementById('role-modal-title');
  1044. if (id) {
  1045. const role = (state.roles || []).find(r => r.id === id);
  1046. if (role) {
  1047. if (title) title.innerText = `Edit Role Tag: ${role.name}`;
  1048. if (idInput) idInput.value = role.id;
  1049. if (nameInput) nameInput.value = role.name;
  1050. if (colorSelect) colorSelect.value = role.color || 'blue';
  1051. if (descInput) descInput.value = role.description || '';
  1052. }
  1053. } else {
  1054. if (title) title.innerText = 'Add Role Tag';
  1055. if (idInput) idInput.value = '';
  1056. if (nameInput) nameInput.value = '';
  1057. if (colorSelect) colorSelect.value = 'blue';
  1058. if (descInput) descInput.value = '';
  1059. }
  1060. updateRoleModalPreview();
  1061. modal.classList.remove('hidden');
  1062. }
  1063. function closeRoleModal() {
  1064. const modal = document.getElementById('role-modal');
  1065. if (modal) modal.classList.add('hidden');
  1066. }
  1067. function updateRoleModalPreview() {
  1068. const name = document.getElementById('role-modal-name')?.value.trim() || 'Preview';
  1069. const colorKey = (document.getElementById('role-modal-color')?.value || 'blue').toLowerCase();
  1070. const theme = ROLE_COLORS[colorKey] || ROLE_COLORS.blue;
  1071. const preview = document.getElementById('role-modal-preview');
  1072. if (preview) {
  1073. preview.innerText = name;
  1074. preview.className = `px-2.5 py-1 rounded text-xs font-semibold ${theme.bg} ${theme.text} border ${theme.border}`;
  1075. }
  1076. }
  1077. async function submitSaveRole(e) {
  1078. e.preventDefault();
  1079. const id = document.getElementById('role-modal-id')?.value;
  1080. const name = document.getElementById('role-modal-name')?.value.trim();
  1081. const color = document.getElementById('role-modal-color')?.value;
  1082. const desc = document.getElementById('role-modal-desc')?.value.trim();
  1083. if (!name) return;
  1084. try {
  1085. const payload = { id, name, color, description: desc };
  1086. const method = id ? 'PUT' : 'POST';
  1087. const url = id ? `${API_BASE}/roles/${encodeURIComponent(id)}` : `${API_BASE}/roles`;
  1088. const res = await fetch(url, {
  1089. method,
  1090. headers: { 'Content-Type': 'application/json' },
  1091. body: JSON.stringify(payload)
  1092. });
  1093. if (res.ok) {
  1094. showToast('Role Tag Saved', `Role tag "${name}" saved successfully`, 'success');
  1095. closeRoleModal();
  1096. await loadRoles();
  1097. fetchData(false);
  1098. } else {
  1099. const err = await res.json();
  1100. showToast('Error', err.error || err.message || 'Failed to save role tag', 'error');
  1101. }
  1102. } catch (err) {
  1103. showToast('Error', err.message, 'error');
  1104. }
  1105. }
  1106. async function deleteRoleTag(id, name) {
  1107. if (!confirm(`Are you sure you want to delete role tag "${name}"?\nInterfaces assigned to this role will default to LAN.`)) return;
  1108. try {
  1109. const res = await fetch(`${API_BASE}/roles/${encodeURIComponent(id)}`, {
  1110. method: 'DELETE'
  1111. });
  1112. if (res.ok) {
  1113. showToast('Role Tag Deleted', `Role tag "${name}" removed`, 'success');
  1114. await loadRoles();
  1115. fetchData(false);
  1116. } else {
  1117. const err = await res.json();
  1118. showToast('Error', err.error || err.message || 'Failed to delete role tag', 'error');
  1119. }
  1120. } catch (err) {
  1121. showToast('Error', err.message, 'error');
  1122. }
  1123. }
  1124. function populateRoleSelects(selectedRole = '') {
  1125. const ifaceSelect = document.getElementById('modal-iface-role');
  1126. const vlanSelect = document.getElementById('vlan-role');
  1127. const roles = state.roles || [];
  1128. const optionsHtml = roles.map(r => `<option value="${escapeHtml(r.name)}">${escapeHtml(r.name)}${r.description ? ` (${escapeHtml(r.description)})` : ''}</option>`).join('');
  1129. if (ifaceSelect) {
  1130. const currentVal = selectedRole || ifaceSelect.value || 'LAN';
  1131. if (ifaceSelect.dataset.optionsSig !== optionsHtml) {
  1132. ifaceSelect.innerHTML = optionsHtml;
  1133. ifaceSelect.dataset.optionsSig = optionsHtml;
  1134. }
  1135. if (currentVal) ifaceSelect.value = currentVal;
  1136. }
  1137. if (vlanSelect) {
  1138. const currentVal = selectedRole || vlanSelect.value || 'LAN';
  1139. if (vlanSelect.dataset.optionsSig !== optionsHtml) {
  1140. vlanSelect.innerHTML = optionsHtml;
  1141. vlanSelect.dataset.optionsSig = optionsHtml;
  1142. }
  1143. if (currentVal) vlanSelect.value = currentVal;
  1144. }
  1145. }
  1146. // Filter and Render Hierarchical Interfaces List
  1147. function filterIfaces(filter) {
  1148. state.ifaceFilter = filter || 'all';
  1149. renderInterfacesList();
  1150. }
  1151. function renderInterfacesList() {
  1152. const tbody = document.getElementById('interfaces-tree-tbody');
  1153. const emptyState = document.getElementById('interfaces-empty-state');
  1154. const summary = document.getElementById('ifaces-list-summary');
  1155. const query = (document.getElementById('iface-search')?.value || '').trim().toLowerCase();
  1156. const allIfaces = state.interfaces || [];
  1157. const allVlans = state.vlans || [];
  1158. const parentIfaces = allIfaces.filter(i => !i.is_vlan);
  1159. const filteredParents = parentIfaces.filter(parent => {
  1160. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  1161. if (query) {
  1162. const matchName = parent.name.toLowerCase().includes(query);
  1163. const matchIp = (parent.ipv4 || []).some(ip => ip.toLowerCase().includes(query));
  1164. const matchRole = (parent.role || '').toLowerCase().includes(query);
  1165. const matchType = (parent.type || '').toLowerCase().includes(query);
  1166. const matchVlan = childVlans.some(v =>
  1167. v.name.toLowerCase().includes(query) ||
  1168. String(v.vlan_id).includes(query) ||
  1169. (v.ipv4 || []).some(ip => ip.toLowerCase().includes(query)) ||
  1170. (v.description || '').toLowerCase().includes(query)
  1171. );
  1172. if (!matchName && !matchIp && !matchRole && !matchType && !matchVlan) return false;
  1173. }
  1174. if (state.ifaceFilter === 'has_vlans') return childVlans.length > 0;
  1175. if (state.ifaceFilter === 'physical') return parent.type !== 'loopback';
  1176. if (state.ifaceFilter === 'up') return parent.state === 'UP';
  1177. return true;
  1178. });
  1179. if (summary) {
  1180. summary.innerText = `${parentIfaces.length} Interfaces • ${allVlans.length} Active VLANs`;
  1181. }
  1182. if (filteredParents.length === 0) {
  1183. emptyState?.classList.remove('hidden');
  1184. tbody.innerHTML = '';
  1185. return;
  1186. }
  1187. emptyState?.classList.add('hidden');
  1188. const sig = `${state.ifaceFilter}|${query}|` + filteredParents.map(p => {
  1189. const cVlans = allVlans.filter(v => v.parent_name === p.name || v.name.startsWith(p.name + '.'));
  1190. const dhcp = (state.dhcpClients || []).find(dc => dc.interface === p.name);
  1191. return `${p.name}:${p.state}:${p.role||'LAN'}:${(p.ipv4||[]).join(',')}:${p.mtu}:${cVlans.length}:${state.expandedParents.has(p.name)}:${dhcp?.status || ''}`;
  1192. }).join(';');
  1193. if (tbody.dataset.sig === sig) {
  1194. return; // ZERO changes to structure, links, IPs or VLANs! Do not rebuild DOM!
  1195. }
  1196. tbody.dataset.sig = sig;
  1197. tbody.innerHTML = '';
  1198. filteredParents.forEach(parent => {
  1199. const isUp = parent.state === 'UP';
  1200. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  1201. const hasVlans = childVlans.length > 0;
  1202. const isExpanded = hasVlans && state.expandedParents.has(parent.name);
  1203. const canHaveVlan = supportsVLAN(parent);
  1204. const parentRow = document.createElement('tr');
  1205. parentRow.className = `hover:bg-slate-800/50 transition border-b border-slate-800/80 ${isExpanded ? 'bg-slate-900/80' : ''}`;
  1206. parentRow.innerHTML = `
  1207. <td class="py-3 px-3 text-center">
  1208. ${hasVlans ? `
  1209. <button onclick="toggleExpand('${parent.name}')" title="${isExpanded ? 'Collapse VLANs' : 'Expand VLANs'}"
  1210. class="w-6 h-6 rounded flex items-center justify-center hover:bg-slate-800 text-slate-400 hover:text-white transition">
  1211. <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">
  1212. <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M9 5l7 7-7 7" />
  1213. </svg>
  1214. </button>
  1215. ` : `
  1216. <div class="w-6 h-6 flex items-center justify-center text-slate-700 select-none">
  1217. <span class="w-1.5 h-1.5 rounded-full bg-slate-800"></span>
  1218. </div>
  1219. `}
  1220. </td>
  1221. <td class="py-3 px-4">
  1222. <div class="flex items-center space-x-2.5">
  1223. <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">
  1224. ${parent.type === 'loopback' ? 'LO' : (parent.type === 'wireguard' ? 'WG' : (parent.type === 'bridge' ? 'BR' : 'NIC'))}
  1225. </div>
  1226. <div>
  1227. <div class="flex items-center gap-2">
  1228. <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'}">
  1229. <span>${parent.name}</span>
  1230. <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>
  1231. </span>
  1232. ${hasVlans ? `
  1233. <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>
  1234. ` : `
  1235. <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>
  1236. `}
  1237. </div>
  1238. <div class="text-[10px] text-slate-500 font-sans mt-0.5">${parent.type}</div>
  1239. </div>
  1240. </div>
  1241. </td>
  1242. <td class="py-3 px-4 font-sans">
  1243. <div class="flex items-center gap-1.5">
  1244. ${getRoleBadge(parent.role || 'LAN')}
  1245. <span class="text-xs text-slate-400 truncate max-w-[120px]">${parent.description || '-'}</span>
  1246. </div>
  1247. </td>
  1248. <td class="py-3 px-4">
  1249. ${parent.ipv4 && parent.ipv4.length > 0
  1250. ? `<div class="text-white font-medium">${parent.ipv4[0]}</div>`
  1251. : '<span class="text-slate-600 font-sans">Unassigned</span>'
  1252. }
  1253. ${(() => {
  1254. const c = (state.dhcpClients || []).find(dc => dc.interface === parent.name);
  1255. if (!c) return '';
  1256. 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');
  1257. 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>`;
  1258. })()}
  1259. </td>
  1260. <td class="py-3 px-4 text-slate-400 text-[11px]">
  1261. <div>${parent.mac || 'N/A'}</div>
  1262. <div class="text-[10px] text-slate-500">MTU ${parent.mtu}</div>
  1263. </td>
  1264. <td class="py-3 px-4 text-[11px]">
  1265. <div class="flex items-center space-x-2">
  1266. <span id="iface-rate-rx-${parent.name}" class="text-emerald-400">↓ ${parent.rate?.rx_human || '0 B/s'}</span>
  1267. <span id="iface-rate-tx-${parent.name}" class="text-cyan-400">↑ ${parent.rate?.tx_human || '0 B/s'}</span>
  1268. </div>
  1269. </td>
  1270. <td class="py-3 px-4 font-sans">
  1271. <button onclick="toggleInterfaceState('${parent.name}', '${isUp ? 'down' : 'up'}')"
  1272. class="flex items-center gap-1.5 text-xs font-semibold px-2.5 py-1 rounded-full transition ${
  1273. 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'
  1274. }" title="Click to toggle link status">
  1275. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  1276. <span>${parent.state}</span>
  1277. </button>
  1278. </td>
  1279. <td class="py-3 px-4 text-right space-x-2 font-sans">
  1280. ${(() => {
  1281. const c = (state.dhcpClients || []).find(dc => dc.interface === parent.name);
  1282. if (c) {
  1283. 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>`;
  1284. }
  1285. if (!supportsDHCPClient(parent)) {
  1286. return '';
  1287. }
  1288. 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>`;
  1289. })()}
  1290. ${canHaveVlan ? `
  1291. <button onclick="openVlanModal('${parent.name}')"
  1292. 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">
  1293. + Add VLAN
  1294. </button>
  1295. ` : ''}
  1296. <button onclick="openIfaceModal('${parent.name}')"
  1297. 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">
  1298. Edit
  1299. </button>
  1300. </td>
  1301. `;
  1302. tbody.appendChild(parentRow);
  1303. if (isExpanded) {
  1304. const drawerRow = document.createElement('tr');
  1305. drawerRow.className = 'bg-slate-950/80 border-b border-slate-800/90';
  1306. const drawerCell = document.createElement('td');
  1307. drawerCell.colSpan = 8;
  1308. drawerCell.className = 'p-0';
  1309. drawerCell.innerHTML = `
  1310. <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">
  1311. <div class="flex items-center justify-between mb-3">
  1312. <div class="flex items-center space-x-3">
  1313. <span class="font-bold text-xs text-white uppercase tracking-wider flex items-center gap-1.5 font-sans">
  1314. <span>VLAN Sub-interfaces on <code class="text-cyan-300 lowercase">${parent.name}</code></span>
  1315. </span>
  1316. <span class="text-[11px] bg-cyan-950 text-cyan-400 px-2 py-0.5 rounded-full border border-cyan-800/60 font-mono">
  1317. ${childVlans.length} Attached
  1318. </span>
  1319. </div>
  1320. <button onclick="openVlanModal('${parent.name}')"
  1321. 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">
  1322. <span>+ Create VLAN on ${parent.name}</span>
  1323. </button>
  1324. </div>
  1325. ${childVlans.length === 0 ? `
  1326. <div class="p-6 text-center border border-dashed border-slate-800 rounded-xl bg-slate-900/40 font-sans">
  1327. <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>
  1328. <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">
  1329. <span>+ Create Your First VLAN on ${parent.name}</span>
  1330. </button>
  1331. </div>
  1332. ` : `
  1333. <div class="overflow-x-auto rounded-lg border border-slate-800 bg-slate-900/90 shadow-inner">
  1334. <table class="w-full text-left text-xs font-mono">
  1335. <thead class="text-slate-400 bg-slate-950/70 border-b border-slate-800 uppercase tracking-wider text-[10px] font-sans">
  1336. <tr>
  1337. <th class="py-2.5 px-4">VLAN ID</th>
  1338. <th class="py-2.5 px-4">Interface Device</th>
  1339. <th class="py-2.5 px-4">Subnet Gateway</th>
  1340. <th class="py-2.5 px-4">Role / Alias</th>
  1341. <th class="py-2.5 px-4">MTU</th>
  1342. <th class="py-2.5 px-4">Throughput</th>
  1343. <th class="py-2.5 px-4">Status</th>
  1344. <th class="py-2.5 px-4 text-right">Actions</th>
  1345. </tr>
  1346. </thead>
  1347. <tbody class="divide-y divide-slate-800/70">
  1348. ${childVlans.map(v => {
  1349. const isVlanUp = v.state === 'UP';
  1350. return `
  1351. <tr class="hover:bg-slate-800/40 transition">
  1352. <td class="py-2.5 px-4">
  1353. <span class="px-2 py-0.5 rounded text-xs font-bold bg-cyan-950 text-cyan-300 border border-cyan-800 shadow-sm">
  1354. VLAN ${v.vlan_id}
  1355. </span>
  1356. </td>
  1357. <td class="py-2.5 px-4 font-bold text-white flex items-center gap-1.5">
  1358. <span class="text-cyan-500">└─</span>
  1359. <span class="cursor-pointer hover:text-cyan-400 flex items-center gap-1" onclick="openIfaceModal('${v.name}')" title="Configure / Rename ${v.name}">
  1360. <span>${v.name}</span>
  1361. <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>
  1362. </span>
  1363. </td>
  1364. <td class="py-2.5 px-4 text-emerald-400 font-medium">
  1365. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  1366. ${(() => {
  1367. const c = (state.dhcpClients || []).find(dc => dc.interface === v.name);
  1368. if (!c) return '';
  1369. 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';
  1370. 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>`;
  1371. })()}
  1372. </td>
  1373. <td class="py-2.5 px-4 font-sans text-slate-300">
  1374. <div class="flex items-center gap-1.5">
  1375. ${getRoleBadge(v.role || 'LAN')}
  1376. <span class="text-slate-400 text-xs">${v.description || '-'}</span>
  1377. </div>
  1378. </td>
  1379. <td class="py-2.5 px-4 text-slate-400">${v.mtu}</td>
  1380. <td class="py-2.5 px-4 text-[11px]">
  1381. <span id="vlan-rate-rx-${v.name}" class="text-emerald-400">↓ ${v.rate?.rx_human || '0 B/s'}</span>
  1382. <span id="vlan-rate-tx-${v.name}" class="text-cyan-400 ml-1.5">↑ ${v.rate?.tx_human || '0 B/s'}</span>
  1383. </td>
  1384. <td class="py-2.5 px-4 font-sans">
  1385. <button onclick="toggleInterfaceState('${v.name}', '${isVlanUp ? 'down' : 'up'}')"
  1386. class="flex items-center gap-1 text-[11px] font-semibold px-2 py-0.5 rounded-full ${
  1387. 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'
  1388. }">
  1389. <span class="w-1.5 h-1.5 rounded-full ${isVlanUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  1390. <span>${v.state}</span>
  1391. </button>
  1392. </td>
  1393. <td class="py-2.5 px-4 text-right space-x-1.5 font-sans">
  1394. ${(() => {
  1395. const c = (state.dhcpClients || []).find(dc => dc.interface === v.name);
  1396. if (c) {
  1397. 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>`;
  1398. }
  1399. if (!supportsDHCPClient(v)) {
  1400. return '';
  1401. }
  1402. 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>`;
  1403. })()}
  1404. <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>
  1405. <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>
  1406. </td>
  1407. </tr>
  1408. `;
  1409. }).join('')}
  1410. </tbody>
  1411. </table>
  1412. </div>
  1413. `}
  1414. </div>
  1415. `;
  1416. drawerRow.appendChild(drawerCell);
  1417. tbody.appendChild(drawerRow);
  1418. }
  1419. });
  1420. }
  1421. // Render VLANs Dedicated View
  1422. function renderVlansList() {
  1423. const tbody = document.getElementById('vlans-table-body');
  1424. if (!tbody) return;
  1425. const emptyState = document.getElementById('vlans-empty-state');
  1426. const countBadge = document.getElementById('vlans-table-count');
  1427. const query = (document.getElementById('vlan-search')?.value || '').toLowerCase();
  1428. const allVlans = state.vlans || [];
  1429. if (countBadge) countBadge.innerText = allVlans.length;
  1430. const filtered = allVlans.filter(v => {
  1431. if (!query) return true;
  1432. return v.name.toLowerCase().includes(query) ||
  1433. String(v.vlan_id).includes(query) ||
  1434. (v.description || '').toLowerCase().includes(query) ||
  1435. (v.ipv4 && v.ipv4.some(ip => ip.includes(query)));
  1436. });
  1437. if (allVlans.length === 0) {
  1438. emptyState.classList.remove('hidden');
  1439. tbody.innerHTML = '';
  1440. return;
  1441. }
  1442. emptyState.classList.add('hidden');
  1443. const sig = `${query}|` + filtered.map(v => `${v.name}:${v.state}:${(v.ipv4||[]).join(',')}:${v.vlan_id}:${v.mtu}`).join(';');
  1444. if (tbody.dataset.sig === sig) return;
  1445. tbody.dataset.sig = sig;
  1446. tbody.innerHTML = '';
  1447. filtered.forEach(v => {
  1448. const isUp = v.state === 'UP';
  1449. const tr = document.createElement('tr');
  1450. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  1451. tr.innerHTML = `
  1452. <td class="py-3 px-4">
  1453. <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">
  1454. VLAN ${v.vlan_id}
  1455. </span>
  1456. </td>
  1457. <td class="py-3 px-4 font-bold text-white">
  1458. <span class="cursor-pointer hover:text-cyan-400 flex items-center gap-1.5" onclick="openIfaceModal('${v.name}')" title="Configure / Rename ${v.name}">
  1459. <span>${v.name}</span>
  1460. <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>
  1461. </span>
  1462. </td>
  1463. <td class="py-3 px-4 text-slate-300">
  1464. <span class="bg-slate-800 text-slate-200 px-2 py-0.5 rounded text-[11px]">${v.parent_name || 'eth0'}</span>
  1465. </td>
  1466. <td class="py-3 px-4 text-emerald-400 font-medium">
  1467. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  1468. </td>
  1469. <td class="py-3 px-4 text-slate-300 font-sans">
  1470. <span class="text-slate-400 text-xs">${v.description || v.role || '-'}</span>
  1471. </td>
  1472. <td class="py-3 px-4 text-slate-400">${v.mtu}</td>
  1473. <td class="py-3 px-4 font-sans">
  1474. <button onclick="toggleInterfaceState('${v.name}', '${isUp ? 'down' : 'up'}')"
  1475. class="flex items-center gap-1.5 text-xs font-semibold px-2 py-0.5 rounded-full ${
  1476. 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'
  1477. }">
  1478. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  1479. <span>${v.state}</span>
  1480. </button>
  1481. </td>
  1482. <td class="py-3 px-4 text-right space-x-2 font-sans">
  1483. <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>
  1484. <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>
  1485. </td>
  1486. `;
  1487. tbody.appendChild(tr);
  1488. });
  1489. }
  1490. // Toggle interface UP / DOWN
  1491. async function toggleInterfaceState(name, newState) {
  1492. try {
  1493. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(name)}/state`, {
  1494. method: 'POST',
  1495. headers: { 'Content-Type': 'application/json' },
  1496. body: JSON.stringify({ state: newState })
  1497. });
  1498. const data = await res.json();
  1499. if (res.ok) {
  1500. showToast('Interface Updated', `Interface ${name} is now ${newState.toUpperCase()}`, 'success');
  1501. fetchData(false);
  1502. } else {
  1503. showToast('Error', data.message || 'Failed to toggle interface state', 'error');
  1504. }
  1505. } catch (err) {
  1506. showToast('Error', err.message, 'error');
  1507. }
  1508. }
  1509. // ---------------- MikroTik Flag & Utilities ----------------
  1510. function renderMikroTikFlag(running, disabled) {
  1511. if (running) {
  1512. 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>`;
  1513. }
  1514. if (disabled) {
  1515. 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>`;
  1516. }
  1517. 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>`;
  1518. }
  1519. function copyToClipboard(text, label = 'Text') {
  1520. navigator.clipboard.writeText(text).then(() => {
  1521. showToast('Copied', `${label} copied to clipboard`, 'success');
  1522. }).catch(() => {
  1523. prompt('Copy value:', text);
  1524. });
  1525. }
  1526. // ======================== PPP Profiles Shared Helper ========================
  1527. async function fetchPPPProfilesList() {
  1528. try {
  1529. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`);
  1530. if (res.ok) {
  1531. state.pppProfiles = await res.json();
  1532. }
  1533. } catch (err) {
  1534. console.error('Failed to load PPP profiles:', err);
  1535. }
  1536. }
  1537. function populateProfileSelect(selectId, selectedVal, defaultVal = 'default') {
  1538. const sel = document.getElementById(selectId);
  1539. if (!sel) return;
  1540. const profiles = (state.pppProfiles && state.pppProfiles.length > 0) ? state.pppProfiles : [
  1541. { name: 'default', use_encryption: 'no' },
  1542. { name: 'default-encryption', use_encryption: 'required' }
  1543. ];
  1544. sel.innerHTML = '';
  1545. profiles.forEach(p => {
  1546. const opt = document.createElement('option');
  1547. opt.value = p.name;
  1548. const encBadge = p.use_encryption === 'required' ? ' (MPPE-128)' : (p.use_encryption === 'yes' ? ' (MPPE)' : '');
  1549. opt.innerText = `${p.name}${encBadge}`;
  1550. sel.appendChild(opt);
  1551. });
  1552. if (selectedVal) {
  1553. sel.value = selectedVal;
  1554. } else {
  1555. sel.value = defaultVal;
  1556. }
  1557. if (!sel.value && sel.options.length > 0) {
  1558. sel.selectedIndex = 0;
  1559. }
  1560. }
  1561. // ======================== PPPoE Multi-Instance ========================
  1562. async function loadPPPoE(populateInputs = true) {
  1563. try {
  1564. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  1565. await fetchPPPProfilesList();
  1566. }
  1567. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`);
  1568. const list = await res.json();
  1569. state.pppoeList = Array.isArray(list) ? list : [];
  1570. const badge = document.getElementById('pppoe-count-badge');
  1571. if (badge) badge.innerText = `${state.pppoeList.length} Interface${state.pppoeList.length !== 1 ? 's' : ''}`;
  1572. const tbody = document.getElementById('pppoe-table-body');
  1573. const empty = document.getElementById('pppoe-empty');
  1574. if (!tbody) return;
  1575. tbody.innerHTML = '';
  1576. if (state.pppoeList.length === 0) {
  1577. if (empty) empty.classList.remove('hidden');
  1578. } else {
  1579. if (empty) empty.classList.add('hidden');
  1580. state.pppoeList.forEach(inst => {
  1581. const tr = document.createElement('tr');
  1582. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1583. tr.innerHTML = `
  1584. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  1585. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  1586. <td class="py-2.5 px-3 text-cyan-400 font-mono">${escapeHtml(inst.interface)}</td>
  1587. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  1588. <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>
  1589. <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>
  1590. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  1591. <td class="py-2.5 px-3 text-center">
  1592. <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'}">
  1593. ${inst.default_route ? 'Yes' : 'No'}
  1594. </span>
  1595. </td>
  1596. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  1597. ${inst.running ? `
  1598. <button onclick="disconnectPPPoEInstance('${inst.name}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  1599. ` : `
  1600. <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>
  1601. `}
  1602. <button onclick="togglePPPoEState('${inst.name}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  1603. ${inst.disabled ? 'Enable' : 'Disable'}
  1604. </button>
  1605. <button onclick="openEditPPPoEModal('${inst.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  1606. <button onclick="deletePPPoEInstance('${inst.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  1607. </td>
  1608. `;
  1609. tbody.appendChild(tr);
  1610. });
  1611. }
  1612. } catch (err) {
  1613. console.error('Failed to load PPPoE:', err);
  1614. }
  1615. }
  1616. function openAddPPPoEModal() {
  1617. document.getElementById('pppoe-modal-title').innerText = 'Add PPPoE Client Interface';
  1618. document.getElementById('pppoe-modal-edit-orig').value = '';
  1619. document.getElementById('pppoe-modal-name').value = `pppoe-out${(state.pppoeList || []).length + 1}`;
  1620. document.getElementById('pppoe-modal-name').readOnly = false;
  1621. document.getElementById('pppoe-modal-user').value = '';
  1622. document.getElementById('pppoe-modal-pass').value = '';
  1623. document.getElementById('pppoe-modal-service').value = '';
  1624. document.getElementById('pppoe-modal-mtu').value = '1492';
  1625. document.getElementById('pppoe-modal-defroute').checked = true;
  1626. document.getElementById('pppoe-modal-reconnect').checked = true;
  1627. document.getElementById('pppoe-modal-disabled').checked = false;
  1628. // Populate profiles
  1629. populateProfileSelect('pppoe-modal-profile', 'default', 'default');
  1630. // Populate interfaces
  1631. const sel = document.getElementById('pppoe-modal-iface');
  1632. sel.innerHTML = '';
  1633. (state.interfaces || []).forEach(i => {
  1634. if (i.name === 'lo') return;
  1635. const opt = document.createElement('option');
  1636. opt.value = i.name;
  1637. opt.innerText = `${i.name} (${i.role || i.type})`;
  1638. sel.appendChild(opt);
  1639. });
  1640. document.getElementById('pppoe-modal').classList.remove('hidden');
  1641. }
  1642. function openEditPPPoEModal(name) {
  1643. const inst = (state.pppoeList || []).find(i => i.name === name);
  1644. if (!inst) return;
  1645. document.getElementById('pppoe-modal-title').innerText = `Edit PPPoE Client: ${name}`;
  1646. document.getElementById('pppoe-modal-edit-orig').value = name;
  1647. document.getElementById('pppoe-modal-name').value = inst.name;
  1648. document.getElementById('pppoe-modal-name').readOnly = true;
  1649. document.getElementById('pppoe-modal-user').value = inst.username || '';
  1650. document.getElementById('pppoe-modal-pass').value = inst.password || '';
  1651. document.getElementById('pppoe-modal-service').value = inst.service_name || '';
  1652. document.getElementById('pppoe-modal-mtu').value = inst.mtu || 1492;
  1653. document.getElementById('pppoe-modal-defroute').checked = inst.default_route ?? true;
  1654. document.getElementById('pppoe-modal-reconnect').checked = inst.auto_reconnect ?? true;
  1655. document.getElementById('pppoe-modal-disabled').checked = !!inst.disabled;
  1656. // Populate profiles
  1657. populateProfileSelect('pppoe-modal-profile', inst.profile || 'default', 'default');
  1658. const sel = document.getElementById('pppoe-modal-iface');
  1659. sel.innerHTML = '';
  1660. (state.interfaces || []).forEach(i => {
  1661. if (i.name === 'lo') return;
  1662. const opt = document.createElement('option');
  1663. opt.value = i.name;
  1664. opt.innerText = `${i.name} (${i.role || i.type})`;
  1665. if (i.name === inst.interface) opt.selected = true;
  1666. sel.appendChild(opt);
  1667. });
  1668. document.getElementById('pppoe-modal').classList.remove('hidden');
  1669. }
  1670. function closePPPoEModal() {
  1671. document.getElementById('pppoe-modal').classList.add('hidden');
  1672. }
  1673. async function submitSavePPPoE(e) {
  1674. e.preventDefault();
  1675. const name = document.getElementById('pppoe-modal-name').value.trim();
  1676. const iface = document.getElementById('pppoe-modal-iface').value;
  1677. const user = document.getElementById('pppoe-modal-user').value.trim();
  1678. const pass = document.getElementById('pppoe-modal-pass').value;
  1679. const profile = document.getElementById('pppoe-modal-profile')?.value || 'default';
  1680. const service = document.getElementById('pppoe-modal-service').value.trim();
  1681. const mtu = parseInt(document.getElementById('pppoe-modal-mtu').value, 10) || 1492;
  1682. const defRoute = document.getElementById('pppoe-modal-defroute').checked;
  1683. const reconnect = document.getElementById('pppoe-modal-reconnect').checked;
  1684. const disabled = document.getElementById('pppoe-modal-disabled').checked;
  1685. try {
  1686. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`, {
  1687. method: 'POST',
  1688. headers: { 'Content-Type': 'application/json' },
  1689. body: JSON.stringify({
  1690. name,
  1691. interface: iface,
  1692. username: user,
  1693. password: pass,
  1694. profile: profile,
  1695. service_name: service,
  1696. mtu,
  1697. default_route: defRoute,
  1698. auto_reconnect: reconnect,
  1699. disabled
  1700. })
  1701. });
  1702. if (res.ok) {
  1703. showToast('PPPoE Saved', `Configuration for ${name} saved`, 'success');
  1704. closePPPoEModal();
  1705. loadPPPoE(false);
  1706. fetchData(false);
  1707. } else {
  1708. const err = await res.json();
  1709. showToast('Error', err.message || 'Failed to save PPPoE', 'error');
  1710. }
  1711. } catch (err) {
  1712. showToast('Error', err.message, 'error');
  1713. }
  1714. }
  1715. async function connectPPPoEInstance(name) {
  1716. try {
  1717. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  1718. if (res.ok) {
  1719. showToast('Connecting', `Dialing ${name}...`, 'info');
  1720. setTimeout(() => loadPPPoE(false), 2000);
  1721. }
  1722. } catch (err) {
  1723. showToast('Error', err.message, 'error');
  1724. }
  1725. }
  1726. async function disconnectPPPoEInstance(name) {
  1727. try {
  1728. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  1729. if (res.ok) {
  1730. showToast('Disconnected', `${name} session terminated`, 'info');
  1731. setTimeout(() => loadPPPoE(false), 1000);
  1732. }
  1733. } catch (err) {
  1734. showToast('Error', err.message, 'error');
  1735. }
  1736. }
  1737. async function togglePPPoEState(name, enable) {
  1738. try {
  1739. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/state`, {
  1740. method: 'POST',
  1741. headers: { 'Content-Type': 'application/json' },
  1742. body: JSON.stringify({ enabled: enable })
  1743. });
  1744. if (res.ok) {
  1745. showToast(enable ? 'Enabled' : 'Disabled', `${name} is now ${enable ? 'enabled' : 'disabled'}`, 'info');
  1746. loadPPPoE(false);
  1747. }
  1748. } catch (err) {
  1749. showToast('Error', err.message, 'error');
  1750. }
  1751. }
  1752. async function deletePPPoEInstance(name) {
  1753. if (!confirm(`Are you sure you want to delete PPPoE client ${name}?`)) return;
  1754. try {
  1755. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1756. if (res.ok) {
  1757. showToast('Deleted', `PPPoE client ${name} removed`, 'success');
  1758. loadPPPoE(false);
  1759. fetchData(false);
  1760. }
  1761. } catch (err) {
  1762. showToast('Error', err.message, 'error');
  1763. }
  1764. }
  1765. // ======================== WireGuard Multi-Interface & Multi-Peer ========================
  1766. state.wgSubTab = 'ifaces';
  1767. function switchWGSubTab(tab) {
  1768. state.wgSubTab = tab;
  1769. const ifacesPanel = document.getElementById('wg-subtab-ifaces');
  1770. const peersPanel = document.getElementById('wg-subtab-peers');
  1771. const ifacesBtn = document.getElementById('wg-subtab-btn-ifaces');
  1772. const peersBtn = document.getElementById('wg-subtab-btn-peers');
  1773. if (tab === 'ifaces') {
  1774. ifacesPanel?.classList.remove('hidden');
  1775. peersPanel?.classList.add('hidden');
  1776. 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';
  1777. 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';
  1778. } else {
  1779. ifacesPanel?.classList.add('hidden');
  1780. peersPanel?.classList.remove('hidden');
  1781. 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';
  1782. 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';
  1783. renderWGPeers();
  1784. }
  1785. }
  1786. async function loadWireGuard(populateInputs = true) {
  1787. try {
  1788. const [ifacesRes, peersRes] = await Promise.all([
  1789. fetch(`${API_BASE}/vpn/wireguard/interfaces`),
  1790. fetch(`${API_BASE}/vpn/wireguard/peers`)
  1791. ]);
  1792. const ifaces = ifacesRes.ok ? await ifacesRes.json() : [];
  1793. const peers = peersRes.ok ? await peersRes.json() : [];
  1794. state.wgInterfaces = Array.isArray(ifaces) ? ifaces : [];
  1795. state.wgPeers = Array.isArray(peers) ? peers : [];
  1796. // Badges
  1797. const ifacesCountBadge = document.getElementById('wg-ifaces-count');
  1798. if (ifacesCountBadge) ifacesCountBadge.innerText = `${state.wgInterfaces.length} Interfaces`;
  1799. const peersCountBadge = document.getElementById('wg-peers-count');
  1800. if (peersCountBadge) peersCountBadge.innerText = `${state.wgPeers.length} Peers`;
  1801. const subTabIfaces = document.getElementById('wg-subtab-badge-ifaces');
  1802. if (subTabIfaces) subTabIfaces.innerText = state.wgInterfaces.length;
  1803. const subTabPeers = document.getElementById('wg-subtab-badge-peers');
  1804. if (subTabPeers) subTabPeers.innerText = state.wgPeers.length;
  1805. // Render Interfaces
  1806. const ifacesTbody = document.getElementById('wg-ifaces-table-body');
  1807. const ifacesEmpty = document.getElementById('wg-ifaces-empty');
  1808. if (ifacesTbody) {
  1809. ifacesTbody.innerHTML = '';
  1810. if (state.wgInterfaces.length === 0) {
  1811. if (ifacesEmpty) ifacesEmpty.classList.remove('hidden');
  1812. } else {
  1813. if (ifacesEmpty) ifacesEmpty.classList.add('hidden');
  1814. state.wgInterfaces.forEach(iface => {
  1815. const peersOnIface = state.wgPeers.filter(p => p.interface === iface.name).length;
  1816. const tr = document.createElement('tr');
  1817. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1818. tr.innerHTML = `
  1819. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(iface.running, iface.disabled)}</td>
  1820. <td class="py-2.5 px-3">
  1821. <div class="flex items-center gap-1.5">
  1822. <span class="font-bold text-white">${escapeHtml(iface.name)}</span>
  1823. ${iface.comment ? `<span class="text-[10px] text-slate-400 font-sans italic">(${escapeHtml(iface.comment)})</span>` : ''}
  1824. </div>
  1825. </td>
  1826. <td class="py-2.5 px-3 text-amber-400 font-mono">${iface.listen_port}</td>
  1827. <td class="py-2.5 px-3 text-emerald-400 font-mono">${iface.address || '<span class="text-slate-600 font-sans">--</span>'}</td>
  1828. <td class="py-2.5 px-3 text-slate-300 font-mono">
  1829. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${iface.public_key}', 'Public Key')" title="Click to copy: ${iface.public_key}">
  1830. ${(iface.public_key || '').substring(0, 10)}... 📋
  1831. </span>
  1832. </td>
  1833. <td class="py-2.5 px-3 text-slate-400 font-mono">${iface.mtu || 1420}</td>
  1834. <td class="py-2.5 px-3 text-center">
  1835. <span class="px-2 py-0.5 rounded text-[10px] font-sans bg-slate-800 text-slate-300">${peersOnIface} peer${peersOnIface !== 1 ? 's' : ''}</span>
  1836. </td>
  1837. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  1838. ${iface.running ? `
  1839. <button onclick="stopWGInterface('${iface.name}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Stop</button>
  1840. ` : `
  1841. <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>
  1842. `}
  1843. <button onclick="toggleWGInterfaceState('${iface.name}', ${iface.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white font-medium">
  1844. ${iface.disabled ? 'Enable' : 'Disable'}
  1845. </button>
  1846. <button onclick="openEditWGInterfaceModal('${iface.name}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Edit</button>
  1847. <button onclick="deleteWGInterface('${iface.name}')" class="text-xs text-slate-500 hover:text-rose-400 font-medium">Delete</button>
  1848. </td>
  1849. `;
  1850. ifacesTbody.appendChild(tr);
  1851. });
  1852. }
  1853. }
  1854. // Populate filter dropdown in peers tab
  1855. const filterSel = document.getElementById('wg-peers-filter-iface');
  1856. if (filterSel) {
  1857. const currentVal = filterSel.value;
  1858. filterSel.innerHTML = '<option value="">All Interfaces</option>';
  1859. state.wgInterfaces.forEach(i => {
  1860. const opt = document.createElement('option');
  1861. opt.value = i.name;
  1862. opt.innerText = i.name;
  1863. if (i.name === currentVal) opt.selected = true;
  1864. filterSel.appendChild(opt);
  1865. });
  1866. }
  1867. renderWGPeers();
  1868. } catch (err) {
  1869. console.error('Failed to load WireGuard:', err);
  1870. }
  1871. }
  1872. function formatWGPeerEndpoint(address, port) {
  1873. if (!address || address === '(none)') return '--';
  1874. let addr = address.trim();
  1875. let p = port || 0;
  1876. while (addr.includes(':') && !addr.startsWith('[')) {
  1877. const lastColon = addr.lastIndexOf(':');
  1878. const maybePort = addr.substring(lastColon + 1);
  1879. if (!isNaN(parseInt(maybePort, 10)) && parseInt(maybePort, 10) > 0) {
  1880. if (!p) p = parseInt(maybePort, 10);
  1881. addr = addr.substring(0, lastColon);
  1882. } else {
  1883. break;
  1884. }
  1885. }
  1886. return p ? `${addr}:${p}` : addr;
  1887. }
  1888. function renderWGPeers() {
  1889. const filterSel = document.getElementById('wg-peers-filter-iface');
  1890. const selectedIface = filterSel ? filterSel.value : '';
  1891. const tbody = document.getElementById('wg-peers-table-body');
  1892. const empty = document.getElementById('wg-peers-empty');
  1893. if (!tbody) return;
  1894. tbody.innerHTML = '';
  1895. const filtered = selectedIface ? state.wgPeers.filter(p => p.interface === selectedIface) : state.wgPeers;
  1896. if (filtered.length === 0) {
  1897. if (empty) empty.classList.remove('hidden');
  1898. } else {
  1899. if (empty) empty.classList.add('hidden');
  1900. filtered.forEach(p => {
  1901. const isOnline = p.latest_handshake && !p.latest_handshake.includes('Never');
  1902. const tr = document.createElement('tr');
  1903. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1904. tr.innerHTML = `
  1905. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(isOnline, p.disabled)}</td>
  1906. <td class="py-2.5 px-3 font-mono font-bold text-rose-400">${escapeHtml(p.interface)}</td>
  1907. <td class="py-2.5 px-3 font-bold text-white font-sans">${escapeHtml(p.name || 'Unnamed')}</td>
  1908. <td class="py-2.5 px-3 text-slate-300 font-mono">
  1909. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${p.public_key}', 'Peer Public Key')" title="${p.public_key}">
  1910. ${(p.public_key || '').substring(0, 10)}... 📋
  1911. </span>
  1912. </td>
  1913. <td class="py-2.5 px-3 text-emerald-400 font-mono font-semibold">${(p.allowed_ips || []).join(', ')}</td>
  1914. <td class="py-2.5 px-3 text-slate-400 font-mono">${formatWGPeerEndpoint(p.endpoint_address, p.endpoint_port)}</td>
  1915. <td class="py-2.5 px-3 text-slate-300 font-sans">${p.latest_handshake || 'Never'}</td>
  1916. <td class="py-2.5 px-3 font-mono text-[11px]">
  1917. <span class="text-emerald-400">↓ ${p.transfer_rx_human || '0 B'}</span>
  1918. <span class="text-cyan-400 ml-1">↑ ${p.transfer_tx_human || '0 B'}</span>
  1919. </td>
  1920. <td class="py-2.5 px-3 text-right font-sans space-x-2 whitespace-nowrap">
  1921. <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">
  1922. ${p.disabled ? 'Enable' : 'Disable'}
  1923. </button>
  1924. <button onclick="openEditWGPeerModal('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Edit</button>
  1925. <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>
  1926. <button onclick="deleteWGPeer('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Delete</button>
  1927. </td>
  1928. `;
  1929. tbody.appendChild(tr);
  1930. });
  1931. }
  1932. }
  1933. function openAddWGInterfaceModal() {
  1934. document.getElementById('wg-iface-modal-title').innerText = 'Add WireGuard Interface';
  1935. document.getElementById('wg-iface-modal-edit-orig').value = '';
  1936. const nameEl = document.getElementById('wg-iface-modal-name');
  1937. nameEl.value = `wg${(state.wgInterfaces || []).length}`;
  1938. nameEl.readOnly = false;
  1939. document.getElementById('wg-iface-modal-port').value = 51820 + (state.wgInterfaces || []).length;
  1940. document.getElementById('wg-iface-modal-addr').value = `10.${10 + (state.wgInterfaces || []).length}.0.1/24`;
  1941. document.getElementById('wg-iface-modal-mtu').value = '1420';
  1942. document.getElementById('wg-iface-modal-comment').value = '';
  1943. document.getElementById('wg-iface-modal-pubkey').value = '';
  1944. document.getElementById('wg-iface-modal-privkey').value = '';
  1945. document.getElementById('wg-iface-modal-disabled').checked = false;
  1946. generateWGInterfaceKeys();
  1947. document.getElementById('wg-iface-modal').classList.remove('hidden');
  1948. }
  1949. function openEditWGInterfaceModal(name) {
  1950. const iface = (state.wgInterfaces || []).find(i => i.name === name);
  1951. if (!iface) return;
  1952. document.getElementById('wg-iface-modal-title').innerText = `Edit WireGuard Interface: ${name}`;
  1953. document.getElementById('wg-iface-modal-edit-orig').value = name;
  1954. const nameEl = document.getElementById('wg-iface-modal-name');
  1955. nameEl.value = iface.name;
  1956. nameEl.readOnly = false; // ALLOW RENAMING
  1957. document.getElementById('wg-iface-modal-port').value = iface.listen_port || 51820;
  1958. document.getElementById('wg-iface-modal-addr').value = iface.address || '';
  1959. document.getElementById('wg-iface-modal-mtu').value = iface.mtu || 1420;
  1960. document.getElementById('wg-iface-modal-comment').value = iface.comment || '';
  1961. document.getElementById('wg-iface-modal-pubkey').value = iface.public_key || '';
  1962. document.getElementById('wg-iface-modal-privkey').value = iface.private_key || '';
  1963. document.getElementById('wg-iface-modal-disabled').checked = !!iface.disabled;
  1964. document.getElementById('wg-iface-modal').classList.remove('hidden');
  1965. }
  1966. function closeAddWGInterfaceModal() {
  1967. document.getElementById('wg-iface-modal').classList.add('hidden');
  1968. }
  1969. async function generateWGInterfaceKeys() {
  1970. try {
  1971. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  1972. const keys = await res.json();
  1973. if (res.ok) {
  1974. document.getElementById('wg-iface-modal-privkey').value = keys.private_key;
  1975. document.getElementById('wg-iface-modal-pubkey').value = keys.public_key;
  1976. }
  1977. } catch (err) {
  1978. showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
  1979. }
  1980. }
  1981. async function onWGInterfacePrivKeyInput() {
  1982. const privKey = document.getElementById('wg-iface-modal-privkey').value.trim();
  1983. if (!privKey) return;
  1984. try {
  1985. const res = await fetch(`${API_BASE}/vpn/wireguard/calc-pubkey`, {
  1986. method: 'POST',
  1987. headers: { 'Content-Type': 'application/json' },
  1988. body: JSON.stringify({ private_key: privKey })
  1989. });
  1990. if (res.ok) {
  1991. const data = await res.json();
  1992. if (data.public_key) {
  1993. document.getElementById('wg-iface-modal-pubkey').value = data.public_key;
  1994. }
  1995. }
  1996. } catch (err) {
  1997. // Ignore while typing
  1998. }
  1999. }
  2000. function toggleWGPrivKeyVisibility() {
  2001. const el = document.getElementById('wg-iface-modal-privkey');
  2002. const btn = document.getElementById('btn-toggle-wg-privkey');
  2003. if (el.type === 'password') {
  2004. el.type = 'text';
  2005. btn.innerText = '🙈 Hide';
  2006. } else {
  2007. el.type = 'password';
  2008. btn.innerText = '👁️ Show';
  2009. }
  2010. }
  2011. function copyWGInterfacePubKey() {
  2012. const pub = document.getElementById('wg-iface-modal-pubkey').value;
  2013. if (pub) copyToClipboard(pub, 'Interface Public Key');
  2014. }
  2015. async function submitSaveWGInterface(e) {
  2016. e.preventDefault();
  2017. const origName = document.getElementById('wg-iface-modal-edit-orig').value.trim();
  2018. const name = document.getElementById('wg-iface-modal-name').value.trim();
  2019. const port = parseInt(document.getElementById('wg-iface-modal-port').value, 10) || 51820;
  2020. const addr = document.getElementById('wg-iface-modal-addr').value.trim();
  2021. const mtu = parseInt(document.getElementById('wg-iface-modal-mtu').value, 10) || 1420;
  2022. const comment = document.getElementById('wg-iface-modal-comment').value.trim();
  2023. const pub = document.getElementById('wg-iface-modal-pubkey').value.trim();
  2024. const priv = document.getElementById('wg-iface-modal-privkey').value.trim();
  2025. const disabled = document.getElementById('wg-iface-modal-disabled').checked;
  2026. try {
  2027. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces`, {
  2028. method: 'POST',
  2029. headers: { 'Content-Type': 'application/json' },
  2030. body: JSON.stringify({
  2031. orig_name: origName,
  2032. name,
  2033. listen_port: port,
  2034. address: addr,
  2035. mtu,
  2036. comment,
  2037. public_key: pub,
  2038. private_key: priv,
  2039. disabled
  2040. })
  2041. });
  2042. const data = await res.json();
  2043. if (res.ok) {
  2044. showToast('WireGuard Saved', `Interface ${name} configured successfully`, 'success');
  2045. closeAddWGInterfaceModal();
  2046. loadWireGuard(false);
  2047. fetchData(false);
  2048. } else {
  2049. showToast('Error', data.error || 'Failed to save interface', 'error');
  2050. }
  2051. } catch (err) {
  2052. showToast('Error', err.message, 'error');
  2053. }
  2054. }
  2055. async function startWGInterface(name) {
  2056. try {
  2057. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/start`, { method: 'POST' });
  2058. if (res.ok) {
  2059. showToast('Interface UP', `Started WireGuard interface ${name}`, 'success');
  2060. loadWireGuard(false);
  2061. fetchData(false);
  2062. }
  2063. } catch (err) {
  2064. showToast('Error', err.message, 'error');
  2065. }
  2066. }
  2067. async function stopWGInterface(name) {
  2068. try {
  2069. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  2070. if (res.ok) {
  2071. showToast('Interface DOWN', `Stopped WireGuard interface ${name}`, 'info');
  2072. loadWireGuard(false);
  2073. fetchData(false);
  2074. }
  2075. } catch (err) {
  2076. showToast('Error', err.message, 'error');
  2077. }
  2078. }
  2079. async function toggleWGInterfaceState(name, enable) {
  2080. try {
  2081. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/state`, {
  2082. method: 'POST',
  2083. headers: { 'Content-Type': 'application/json' },
  2084. body: JSON.stringify({ enabled: enable })
  2085. });
  2086. if (res.ok) {
  2087. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  2088. loadWireGuard(false);
  2089. fetchData(false);
  2090. }
  2091. } catch (err) {
  2092. showToast('Error', err.message, 'error');
  2093. }
  2094. }
  2095. async function deleteWGInterface(name) {
  2096. if (!confirm(`Are you sure you want to delete WireGuard interface ${name}? All associated peers will also be removed.`)) return;
  2097. try {
  2098. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2099. if (res.ok) {
  2100. showToast('Deleted', `Interface ${name} removed`, 'success');
  2101. loadWireGuard(false);
  2102. fetchData(false);
  2103. }
  2104. } catch (err) {
  2105. showToast('Error', err.message, 'error');
  2106. }
  2107. }
  2108. function populateWGPeerIfaceSelect(selectedIface = '') {
  2109. const sel = document.getElementById('wg-peer-modal-iface');
  2110. if (!sel) return;
  2111. sel.innerHTML = '';
  2112. (state.wgInterfaces || []).forEach(i => {
  2113. const opt = document.createElement('option');
  2114. opt.value = i.name;
  2115. opt.innerText = `${i.name} (${i.address || 'No IP'})`;
  2116. if (i.name === selectedIface) opt.selected = true;
  2117. sel.appendChild(opt);
  2118. });
  2119. }
  2120. function openAddWGPeerModal() {
  2121. if ((state.wgInterfaces || []).length === 0) {
  2122. showToast('No Interfaces', 'Please add a WireGuard interface first before adding peers', 'warning');
  2123. openAddWGInterfaceModal();
  2124. return;
  2125. }
  2126. document.getElementById('wg-peer-modal-title').innerText = 'Add WireGuard Peer';
  2127. document.getElementById('wg-peer-modal-edit-orig-iface').value = '';
  2128. document.getElementById('wg-peer-modal-edit-orig-pubkey').value = '';
  2129. populateWGPeerIfaceSelect();
  2130. document.getElementById('wg-peer-modal-name').value = '';
  2131. document.getElementById('wg-peer-modal-pubkey').value = '';
  2132. document.getElementById('wg-peer-modal-allowedips').value = '10.10.0.2/32';
  2133. document.getElementById('wg-peer-modal-endpoint').value = '';
  2134. document.getElementById('wg-peer-modal-port').value = '';
  2135. document.getElementById('wg-peer-modal-keepalive').value = '25';
  2136. document.getElementById('wg-peer-modal-preshared').value = '';
  2137. document.getElementById('wg-peer-modal-disabled').checked = false;
  2138. document.getElementById('wg-peer-key-warning').classList.add('hidden');
  2139. document.getElementById('wg-peer-gen-key-box').classList.add('hidden');
  2140. document.getElementById('wg-peer-modal').classList.remove('hidden');
  2141. }
  2142. function openEditWGPeerModal(ifaceName, pubKey) {
  2143. const peer = (state.wgPeers || []).find(p => p.interface === ifaceName && p.public_key === pubKey);
  2144. if (!peer) {
  2145. showToast('Not Found', 'Peer not found', 'warning');
  2146. return;
  2147. }
  2148. document.getElementById('wg-peer-modal-title').innerText = `Edit WireGuard Peer (${peer.name || ifaceName})`;
  2149. document.getElementById('wg-peer-modal-edit-orig-iface').value = peer.interface;
  2150. document.getElementById('wg-peer-modal-edit-orig-pubkey').value = peer.public_key;
  2151. populateWGPeerIfaceSelect(peer.interface);
  2152. document.getElementById('wg-peer-modal-name').value = peer.name || '';
  2153. document.getElementById('wg-peer-modal-pubkey').value = peer.public_key || '';
  2154. document.getElementById('wg-peer-modal-allowedips').value = (peer.allowed_ips || []).join(', ');
  2155. let epHost = (peer.endpoint_address || '').trim();
  2156. let epPort = peer.endpoint_port || '';
  2157. while (epHost.includes(':') && !epHost.startsWith('[')) {
  2158. const lastColon = epHost.lastIndexOf(':');
  2159. const maybePort = epHost.substring(lastColon + 1);
  2160. if (!isNaN(parseInt(maybePort, 10)) && parseInt(maybePort, 10) > 0) {
  2161. if (!epPort) epPort = parseInt(maybePort, 10);
  2162. epHost = epHost.substring(0, lastColon);
  2163. } else {
  2164. break;
  2165. }
  2166. }
  2167. document.getElementById('wg-peer-modal-endpoint').value = epHost;
  2168. document.getElementById('wg-peer-modal-port').value = epPort;
  2169. document.getElementById('wg-peer-modal-keepalive').value = peer.persistent_keepalive ?? 25;
  2170. document.getElementById('wg-peer-modal-preshared').value = peer.preshared_key || '';
  2171. document.getElementById('wg-peer-modal-disabled').checked = !!peer.disabled;
  2172. document.getElementById('wg-peer-key-warning').classList.add('hidden');
  2173. document.getElementById('wg-peer-gen-key-box').classList.add('hidden');
  2174. document.getElementById('wg-peer-modal').classList.remove('hidden');
  2175. }
  2176. function closeAddWGPeerModal() {
  2177. document.getElementById('wg-peer-modal').classList.add('hidden');
  2178. }
  2179. async function generatePeerKeypairHelper() {
  2180. try {
  2181. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  2182. const keys = await res.json();
  2183. if (res.ok) {
  2184. document.getElementById('wg-peer-modal-pubkey').value = keys.public_key;
  2185. document.getElementById('wg-peer-gen-privkey').value = keys.private_key;
  2186. document.getElementById('wg-peer-gen-key-box').classList.remove('hidden');
  2187. checkWGPeerKeyValidity();
  2188. showToast('Keypair Generated', 'Public key inserted and client private key ready to copy', 'info');
  2189. }
  2190. } catch (err) {
  2191. showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
  2192. }
  2193. }
  2194. function copyGeneratedPeerPrivKey() {
  2195. const priv = document.getElementById('wg-peer-gen-privkey').value;
  2196. if (priv) copyToClipboard(priv, 'Client Private Key');
  2197. }
  2198. async function generatePeerPSK() {
  2199. try {
  2200. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  2201. const keys = await res.json();
  2202. if (res.ok && keys.private_key) {
  2203. document.getElementById('wg-peer-modal-preshared').value = keys.private_key;
  2204. showToast('PSK Generated', 'Generated 256-bit preshared key', 'info');
  2205. }
  2206. } catch (err) {
  2207. showToast('Error', err.message, 'error');
  2208. }
  2209. }
  2210. function checkWGPeerKeyValidity() {
  2211. const ifaceName = document.getElementById('wg-peer-modal-iface').value;
  2212. const peerPubKey = document.getElementById('wg-peer-modal-pubkey').value.trim();
  2213. const warningEl = document.getElementById('wg-peer-key-warning');
  2214. if (!warningEl) return;
  2215. const targetIface = (state.wgInterfaces || []).find(i => i.name === ifaceName);
  2216. if (targetIface && targetIface.public_key && peerPubKey && targetIface.public_key === peerPubKey) {
  2217. warningEl.classList.remove('hidden');
  2218. } else {
  2219. warningEl.classList.add('hidden');
  2220. }
  2221. }
  2222. async function submitSaveWGPeer(e) {
  2223. e.preventDefault();
  2224. const origIface = document.getElementById('wg-peer-modal-edit-orig-iface').value.trim();
  2225. const origPubKey = document.getElementById('wg-peer-modal-edit-orig-pubkey').value.trim();
  2226. const iface = document.getElementById('wg-peer-modal-iface').value;
  2227. const name = document.getElementById('wg-peer-modal-name').value.trim();
  2228. const pub = document.getElementById('wg-peer-modal-pubkey').value.trim();
  2229. const allowed = document.getElementById('wg-peer-modal-allowedips').value
  2230. .split(',')
  2231. .map(s => s.trim())
  2232. .filter(s => s.length > 0);
  2233. let epHost = document.getElementById('wg-peer-modal-endpoint').value.trim();
  2234. let epPort = parseInt(document.getElementById('wg-peer-modal-port').value, 10) || 0;
  2235. while (epHost.includes(':') && !epHost.startsWith('[')) {
  2236. const lastColon = epHost.lastIndexOf(':');
  2237. const maybePort = epHost.substring(lastColon + 1);
  2238. if (!isNaN(parseInt(maybePort, 10)) && parseInt(maybePort, 10) > 0) {
  2239. if (!epPort) epPort = parseInt(maybePort, 10);
  2240. epHost = epHost.substring(0, lastColon);
  2241. } else {
  2242. break;
  2243. }
  2244. }
  2245. const keepalive = parseInt(document.getElementById('wg-peer-modal-keepalive').value, 10) || 0;
  2246. const psk = document.getElementById('wg-peer-modal-preshared').value.trim();
  2247. const disabled = document.getElementById('wg-peer-modal-disabled').checked;
  2248. // Validation
  2249. const targetIface = (state.wgInterfaces || []).find(i => i.name === iface);
  2250. if (targetIface && targetIface.public_key === pub) {
  2251. showToast('Invalid Peer Key', 'Peer public key cannot be the same as the interface public key!', 'error');
  2252. return;
  2253. }
  2254. try {
  2255. const res = await fetch(`${API_BASE}/vpn/wireguard/peers`, {
  2256. method: 'POST',
  2257. headers: { 'Content-Type': 'application/json' },
  2258. body: JSON.stringify({
  2259. orig_interface: origIface,
  2260. orig_public_key: origPubKey,
  2261. interface: iface,
  2262. name,
  2263. public_key: pub,
  2264. allowed_ips: allowed,
  2265. endpoint_address: epHost,
  2266. endpoint_port: epPort,
  2267. persistent_keepalive: keepalive,
  2268. preshared_key: psk,
  2269. disabled
  2270. })
  2271. });
  2272. const data = await res.json();
  2273. if (res.ok) {
  2274. showToast('Peer Saved', `Peer ${name} saved on ${iface}`, 'success');
  2275. closeAddWGPeerModal();
  2276. loadWireGuard(false);
  2277. } else {
  2278. showToast('Error', data.error || 'Failed to save peer', 'error');
  2279. }
  2280. } catch (err) {
  2281. showToast('Error', err.message, 'error');
  2282. }
  2283. }
  2284. async function toggleWGPeerState(iface, pubkey, enable) {
  2285. try {
  2286. const res = await fetch(`${API_BASE}/vpn/wireguard/peers/state`, {
  2287. method: 'POST',
  2288. headers: { 'Content-Type': 'application/json' },
  2289. body: JSON.stringify({ interface: iface, public_key: pubkey, enabled: enable })
  2290. });
  2291. const data = await res.json();
  2292. if (res.ok) {
  2293. showToast(enable ? 'Peer Enabled' : 'Peer Disabled', `Peer state updated on ${iface}`, 'info');
  2294. loadWireGuard(false);
  2295. } else {
  2296. showToast('Error', data.error || 'Failed to update peer state', 'error');
  2297. }
  2298. } catch (err) {
  2299. showToast('Error', err.message, 'error');
  2300. }
  2301. }
  2302. async function deleteWGPeer(iface, pubkey) {
  2303. if (!confirm(`Are you sure you want to remove peer from ${iface}?`)) return;
  2304. try {
  2305. const res = await fetch(`${API_BASE}/vpn/wireguard/peers/delete`, {
  2306. method: 'POST',
  2307. headers: { 'Content-Type': 'application/json' },
  2308. body: JSON.stringify({ interface: iface, public_key: pubkey })
  2309. });
  2310. const data = await res.json();
  2311. if (res.ok) {
  2312. showToast('Peer Deleted', 'WireGuard peer removed', 'success');
  2313. loadWireGuard(false);
  2314. } else {
  2315. showToast('Error', data.error || 'Failed to remove peer', 'error');
  2316. }
  2317. } catch (err) {
  2318. showToast('Error', err.message, 'error');
  2319. }
  2320. }
  2321. // ======================== IPSec FortiGate Phase 1 & 2 Multi-Tunnel Engine ========================
  2322. function switchIpsecModalTab(tab) {
  2323. const p1Tab = document.getElementById('tab-btn-ipsec-p1');
  2324. const p2Tab = document.getElementById('tab-btn-ipsec-p2');
  2325. const p1Content = document.getElementById('ipsec-tab-content-p1');
  2326. const p2Content = document.getElementById('ipsec-tab-content-p2');
  2327. const stepBtn = document.getElementById('btn-ipsec-switch-step');
  2328. if (tab === 'p1') {
  2329. if (p1Tab) {
  2330. 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';
  2331. }
  2332. if (p2Tab) {
  2333. 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';
  2334. }
  2335. if (p1Content) p1Content.classList.remove('hidden');
  2336. if (p2Content) p2Content.classList.add('hidden');
  2337. if (stepBtn) stepBtn.innerHTML = 'Next: Phase 2 Selectors &rarr;';
  2338. } else {
  2339. if (p1Tab) {
  2340. 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';
  2341. }
  2342. if (p2Tab) {
  2343. 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';
  2344. }
  2345. if (p1Content) p1Content.classList.add('hidden');
  2346. if (p2Content) p2Content.classList.remove('hidden');
  2347. if (stepBtn) stepBtn.innerHTML = '&larr; Back: Phase 1 (IKE)';
  2348. }
  2349. }
  2350. function toggleIpsecPhaseStep() {
  2351. const p1Content = document.getElementById('ipsec-tab-content-p1');
  2352. if (p1Content && !p1Content.classList.contains('hidden')) {
  2353. switchIpsecModalTab('p2');
  2354. } else {
  2355. switchIpsecModalTab('p1');
  2356. }
  2357. }
  2358. function toggleIpsecPskVisibility() {
  2359. const pskInput = document.getElementById('ipsec-modal-psk');
  2360. if (!pskInput) return;
  2361. pskInput.type = pskInput.type === 'password' ? 'text' : 'password';
  2362. }
  2363. function addIpsecLocalSubnet(val = '') {
  2364. const container = document.getElementById('ipsec-modal-local-subnets-container');
  2365. if (!container) return;
  2366. const row = document.createElement('div');
  2367. row.className = 'flex items-center gap-2 ipsec-subnet-row';
  2368. row.innerHTML = `
  2369. <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">
  2370. <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>
  2371. `;
  2372. container.appendChild(row);
  2373. }
  2374. function addIpsecRemoteSubnet(val = '') {
  2375. const container = document.getElementById('ipsec-modal-remote-subnets-container');
  2376. if (!container) return;
  2377. const row = document.createElement('div');
  2378. row.className = 'flex items-center gap-2 ipsec-subnet-row';
  2379. row.innerHTML = `
  2380. <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">
  2381. <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>
  2382. `;
  2383. container.appendChild(row);
  2384. }
  2385. function updateIpsecEspProposalFromPFS(val) {
  2386. const prop = document.getElementById('ipsec-modal-espprop');
  2387. if (!prop) return;
  2388. if (val === 'none') {
  2389. prop.value = 'aes256-sha256,aes128-sha256,default';
  2390. } else {
  2391. prop.value = `aes256-sha256-${val},aes128-sha256-${val},default`;
  2392. }
  2393. }
  2394. function updateIpsecIkeProposalFromDH(dh) {
  2395. const el = document.getElementById('ipsec-modal-ikeprop');
  2396. if (el) {
  2397. el.value = `aes256-sha256-${dh},aes128-sha256-${dh},default`;
  2398. }
  2399. }
  2400. function safeSetVal(id, val) {
  2401. const el = document.getElementById(id);
  2402. if (el) el.value = val;
  2403. }
  2404. function safeSetChecked(id, val) {
  2405. const el = document.getElementById(id);
  2406. if (el) el.checked = !!val;
  2407. }
  2408. function safeGetVal(id, def = '') {
  2409. const el = document.getElementById(id);
  2410. return el ? el.value : def;
  2411. }
  2412. async function loadIPSec(populateInputs = true) {
  2413. try {
  2414. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`);
  2415. const list = await res.json();
  2416. state.ipsecTunnels = Array.isArray(list) ? list : [];
  2417. const activeCount = state.ipsecTunnels.filter(t => t.running || t.status === 'ESTABLISHED').length;
  2418. const badge = document.getElementById('ipsec-sas-badge');
  2419. if (badge) badge.innerText = `${activeCount} Active SAs`;
  2420. const tbody = document.getElementById('ipsec-table-body');
  2421. const empty = document.getElementById('ipsec-empty');
  2422. if (!tbody) return;
  2423. tbody.innerHTML = '';
  2424. if (state.ipsecTunnels.length === 0) {
  2425. if (empty) empty.classList.remove('hidden');
  2426. } else {
  2427. if (empty) empty.classList.add('hidden');
  2428. state.ipsecTunnels.forEach(c => {
  2429. const isEstablished = c.running || c.status === 'ESTABLISHED';
  2430. const tr = document.createElement('tr');
  2431. tr.className = 'hover:bg-slate-800/40 transition text-xs select-none';
  2432. // Local subnets tags
  2433. const localList = (c.local_subnets && c.local_subnets.length > 0) ? c.local_subnets : (c.local_subnet ? [c.local_subnet] : ['0.0.0.0/0']);
  2434. 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('');
  2435. // Remote subnets tags
  2436. const remoteList = (c.remote_subnets && c.remote_subnets.length > 0) ? c.remote_subnets : (c.remote_subnet ? [c.remote_subnet] : ['0.0.0.0/0']);
  2437. 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('');
  2438. const ikeVersionBadge = (c.ike_version || 'ikev2').toUpperCase();
  2439. const p2Name = c.phase2_name || `${c.name}_p2`;
  2440. tr.innerHTML = `
  2441. <td class="py-2.5 px-3 text-center">
  2442. ${isEstablished ? `
  2443. <span class="inline-flex items-center gap-1.5 text-emerald-400 font-mono font-bold text-[11px]" title="Active SA Established">
  2444. <span class="w-2.5 h-2.5 rounded-full bg-emerald-400 animate-pulse"></span>
  2445. <span>UP</span>
  2446. </span>
  2447. ` : (c.disabled ? `
  2448. <span class="inline-flex items-center gap-1.5 text-slate-500 font-mono text-[11px]" title="Tunnel Disabled">
  2449. <span class="w-2 h-2 rounded-full bg-rose-500"></span>
  2450. <span>DOWN</span>
  2451. </span>
  2452. ` : `
  2453. <span class="inline-flex items-center gap-1.5 text-amber-400 font-mono text-[11px]" title="Disconnected / Idle">
  2454. <span class="w-2 h-2 rounded-full bg-amber-400"></span>
  2455. <span>IDLE</span>
  2456. </span>
  2457. `)}
  2458. </td>
  2459. <td class="py-2.5 px-4 font-bold text-white">
  2460. <div class="flex items-center gap-2">
  2461. <span class="text-amber-400">🛡</span>
  2462. <div>
  2463. <div>${escapeHtml(c.name)}</div>
  2464. <div class="text-[10px] text-slate-500 font-normal">P2: ${escapeHtml(p2Name)}</div>
  2465. </div>
  2466. </div>
  2467. </td>
  2468. <td class="py-2.5 px-4 text-slate-300 font-mono font-medium">${escapeHtml(c.remote_addrs || '%any')}</td>
  2469. <td class="py-2.5 px-4 font-sans">
  2470. <div class="flex items-center gap-1.5">
  2471. <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>
  2472. <span class="text-[10px] text-slate-400">${c.auth_method || 'PSK'}</span>
  2473. </div>
  2474. </td>
  2475. <td class="py-2.5 px-4">
  2476. <div class="space-y-1">
  2477. <div class="flex items-center flex-wrap gap-1">
  2478. <span class="text-[9px] text-cyan-400 uppercase font-bold mr-1">Local:</span>
  2479. ${localBadges}
  2480. </div>
  2481. <div class="flex items-center flex-wrap gap-1">
  2482. <span class="text-[9px] text-purple-400 uppercase font-bold mr-1">Remote:</span>
  2483. ${remoteBadges}
  2484. </div>
  2485. </div>
  2486. </td>
  2487. <td class="py-2.5 px-4 font-mono text-[11px] text-slate-400">
  2488. <div class="truncate max-w-[140px]" title="${escapeHtml(c.esp_proposals || '')}">
  2489. ${escapeHtml(c.esp_proposals || 'aes256-sha256')}
  2490. </div>
  2491. <div class="text-[10px] text-slate-500">PFS: ${escapeHtml(c.pfs_group || 'modp2048')}</div>
  2492. </td>
  2493. <td class="py-2.5 px-4 text-right space-x-2 font-sans">
  2494. ${isEstablished ? `
  2495. <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>
  2496. ` : `
  2497. <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>
  2498. `}
  2499. <button onclick="toggleIPSecState('${c.name}', ${c.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  2500. ${c.disabled ? 'Enable' : 'Disable'}
  2501. </button>
  2502. <button onclick="openEditIPSecModal('${c.name}')" class="text-xs text-amber-400 hover:text-amber-300">Edit</button>
  2503. <button onclick="deleteIPSecConn('${c.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2504. </td>
  2505. `;
  2506. tbody.appendChild(tr);
  2507. });
  2508. }
  2509. } catch (err) {
  2510. console.error('Failed to load IPSec:', err);
  2511. }
  2512. }
  2513. function openAddIPSecModal() {
  2514. const modal = document.getElementById('ipsec-modal');
  2515. if (!modal) return;
  2516. const title = document.getElementById('ipsec-modal-title');
  2517. if (title) title.innerText = 'Configure IPSec Site-to-Site Tunnel';
  2518. // Phase 1 Fields
  2519. safeSetVal('ipsec-modal-name', `tunnel-${(state.ipsecTunnels || []).length + 1}`);
  2520. const nameEl = document.getElementById('ipsec-modal-name');
  2521. if (nameEl) nameEl.readOnly = false;
  2522. safeSetVal('ipsec-modal-ikeversion', 'ikev2');
  2523. safeSetVal('ipsec-modal-ikever', 'ikev2');
  2524. safeSetVal('ipsec-modal-remotegw', '');
  2525. safeSetVal('ipsec-modal-localaddrs', '');
  2526. safeSetVal('ipsec-modal-comments', '');
  2527. safeSetVal('ipsec-modal-psk', '');
  2528. safeSetVal('ipsec-modal-ikeprop', 'aes256-sha256-modp2048,aes128-sha256-modp2048,default');
  2529. safeSetVal('ipsec-modal-dhgroup', 'modp2048');
  2530. safeSetVal('ipsec-modal-ikekeylife', '86400');
  2531. safeSetVal('ipsec-modal-localid', '');
  2532. safeSetVal('ipsec-modal-remoteid', '');
  2533. safeSetVal('ipsec-modal-dpd', 'on-demand');
  2534. // Phase 2 Fields
  2535. safeSetVal('ipsec-modal-p2name', `tunnel-${(state.ipsecTunnels || []).length + 1}_p2`);
  2536. safeSetVal('ipsec-modal-espkeylife', '28800');
  2537. safeSetVal('ipsec-modal-espprop', 'aes256-sha256-modp2048,aes128-sha256-modp2048,default');
  2538. safeSetVal('ipsec-modal-pfsgroup', 'modp2048');
  2539. safeSetChecked('ipsec-modal-autostart', true);
  2540. safeSetChecked('ipsec-modal-disabled', false);
  2541. // Clear & Populate default dynamic subnets
  2542. const localContainer = document.getElementById('ipsec-modal-local-subnets-container');
  2543. const remoteContainer = document.getElementById('ipsec-modal-remote-subnets-container');
  2544. if (localContainer) {
  2545. localContainer.innerHTML = '';
  2546. addIpsecLocalSubnet('192.168.10.0/24');
  2547. }
  2548. if (remoteContainer) {
  2549. remoteContainer.innerHTML = '';
  2550. addIpsecRemoteSubnet('192.168.20.0/24');
  2551. }
  2552. switchIpsecModalTab('p1');
  2553. modal.classList.remove('hidden');
  2554. }
  2555. function openEditIPSecModal(name) {
  2556. const modal = document.getElementById('ipsec-modal');
  2557. if (!modal) return;
  2558. const conn = (state.ipsecTunnels || []).find(c => c.name === name);
  2559. if (!conn) return;
  2560. const title = document.getElementById('ipsec-modal-title');
  2561. if (title) title.innerText = `Edit IPSec Tunnel: ${name}`;
  2562. // Phase 1 Fields
  2563. safeSetVal('ipsec-modal-name', conn.name);
  2564. const nameEl = document.getElementById('ipsec-modal-name');
  2565. if (nameEl) nameEl.readOnly = true;
  2566. safeSetVal('ipsec-modal-ikeversion', conn.ike_version || 'ikev2');
  2567. safeSetVal('ipsec-modal-ikever', conn.ike_version || 'ikev2');
  2568. safeSetVal('ipsec-modal-remotegw', conn.remote_addrs || '');
  2569. safeSetVal('ipsec-modal-localaddrs', conn.local_addrs || '');
  2570. safeSetVal('ipsec-modal-comments', conn.comment || '');
  2571. safeSetVal('ipsec-modal-psk', conn.preshared_key || '');
  2572. safeSetVal('ipsec-modal-ikeprop', conn.ike_proposals || 'aes256-sha256-modp2048,default');
  2573. safeSetVal('ipsec-modal-ikekeylife', conn.ike_keylife || 86400);
  2574. safeSetVal('ipsec-modal-localid', conn.local_id || '');
  2575. safeSetVal('ipsec-modal-remoteid', conn.remote_id || '');
  2576. safeSetVal('ipsec-modal-dpd', conn.dpd || 'on-demand');
  2577. // Phase 2 Fields
  2578. safeSetVal('ipsec-modal-p2name', conn.phase2_name || `${conn.name}_p2`);
  2579. safeSetVal('ipsec-modal-espkeylife', conn.esp_keylife || 28800);
  2580. safeSetVal('ipsec-modal-espprop', conn.esp_proposals || 'aes256-sha256-modp2048,default');
  2581. safeSetVal('ipsec-modal-pfsgroup', conn.pfs_group || 'modp2048');
  2582. safeSetChecked('ipsec-modal-autostart', conn.auto_start ?? true);
  2583. safeSetChecked('ipsec-modal-disabled', !!conn.disabled);
  2584. // Populate dynamic subnets
  2585. const localContainer = document.getElementById('ipsec-modal-local-subnets-container');
  2586. const remoteContainer = document.getElementById('ipsec-modal-remote-subnets-container');
  2587. if (localContainer) {
  2588. localContainer.innerHTML = '';
  2589. const locals = (conn.local_subnets && conn.local_subnets.length > 0) ? conn.local_subnets : (conn.local_subnet ? [conn.local_subnet] : ['192.168.10.0/24']);
  2590. locals.forEach(s => addIpsecLocalSubnet(s));
  2591. }
  2592. if (remoteContainer) {
  2593. remoteContainer.innerHTML = '';
  2594. const remotes = (conn.remote_subnets && conn.remote_subnets.length > 0) ? conn.remote_subnets : (conn.remote_subnet ? [conn.remote_subnet] : ['192.168.20.0/24']);
  2595. remotes.forEach(s => addIpsecRemoteSubnet(s));
  2596. }
  2597. switchIpsecModalTab('p1');
  2598. modal.classList.remove('hidden');
  2599. }
  2600. function closeAddIPSecModal() {
  2601. const modal = document.getElementById('ipsec-modal');
  2602. if (modal) modal.classList.add('hidden');
  2603. }
  2604. async function submitSaveIPSec(e) {
  2605. if (e) e.preventDefault();
  2606. const name = safeGetVal('ipsec-modal-name').trim();
  2607. if (!name) {
  2608. showToast('Error', 'Tunnel name is required', 'error');
  2609. return;
  2610. }
  2611. const ikeVersion = safeGetVal('ipsec-modal-ikeversion') || safeGetVal('ipsec-modal-ikever', 'ikev2');
  2612. const remotegw = safeGetVal('ipsec-modal-remotegw').trim();
  2613. const localAddrs = safeGetVal('ipsec-modal-localaddrs').trim() || '%any';
  2614. const comments = safeGetVal('ipsec-modal-comments').trim();
  2615. const psk = safeGetVal('ipsec-modal-psk');
  2616. const ikeProposals = safeGetVal('ipsec-modal-ikeprop', 'aes256-sha256-modp2048,default').trim();
  2617. const ikeKeylife = parseInt(safeGetVal('ipsec-modal-ikekeylife', '86400'), 10) || 86400;
  2618. const localId = safeGetVal('ipsec-modal-localid').trim();
  2619. const remoteId = safeGetVal('ipsec-modal-remoteid').trim();
  2620. const dpd = safeGetVal('ipsec-modal-dpd', 'on-demand');
  2621. const phase2Name = safeGetVal('ipsec-modal-p2name').trim() || `${name}_p2`;
  2622. const espProposals = safeGetVal('ipsec-modal-espprop', 'aes256-sha256-modp2048,default').trim();
  2623. const espKeylife = parseInt(safeGetVal('ipsec-modal-espkeylife', '28800'), 10) || 28800;
  2624. const pfsGroup = safeGetVal('ipsec-modal-pfsgroup', 'modp2048');
  2625. const autostart = document.getElementById('ipsec-modal-autostart')?.checked ?? true;
  2626. const disabled = document.getElementById('ipsec-modal-disabled')?.checked ?? false;
  2627. // Scrape dynamic local and remote subnets
  2628. const localInputs = document.querySelectorAll('#ipsec-modal-local-subnets-container input');
  2629. const localSubnets = [];
  2630. localInputs.forEach(inp => {
  2631. const v = inp.value.trim();
  2632. if (v) localSubnets.push(v);
  2633. });
  2634. const remoteInputs = document.querySelectorAll('#ipsec-modal-remote-subnets-container input');
  2635. const remoteSubnets = [];
  2636. remoteInputs.forEach(inp => {
  2637. const v = inp.value.trim();
  2638. if (v) remoteSubnets.push(v);
  2639. });
  2640. try {
  2641. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`, {
  2642. method: 'POST',
  2643. headers: { 'Content-Type': 'application/json' },
  2644. body: JSON.stringify({
  2645. name,
  2646. comment: comments,
  2647. ike_version: ikeVersion,
  2648. local_addrs: localAddrs,
  2649. remote_addrs: remotegw,
  2650. preshared_key: psk,
  2651. ike_proposals: ikeProposals,
  2652. ike_keylife: ikeKeylife,
  2653. local_id: localId,
  2654. remote_id: remoteId,
  2655. dpd: dpd,
  2656. phase2_name: phase2Name,
  2657. esp_proposals: espProposals,
  2658. esp_keylife: espKeylife,
  2659. pfs_group: pfsGroup,
  2660. pfs: pfsGroup !== 'none',
  2661. local_subnets: localSubnets,
  2662. remote_subnets: remoteSubnets,
  2663. local_subnet: localSubnets[0] || '0.0.0.0/0',
  2664. remote_subnet: remoteSubnets[0] || '0.0.0.0/0',
  2665. auto_start: autostart,
  2666. disabled
  2667. })
  2668. });
  2669. if (res.ok) {
  2670. showToast('IPSec Saved', `FortiGate Tunnel ${name} configured`, 'success');
  2671. closeAddIPSecModal();
  2672. loadIPSec(false);
  2673. } else {
  2674. const err = await res.json();
  2675. showToast('Error', err.error || 'Failed to save IPSec tunnel', 'error');
  2676. }
  2677. } catch (err) {
  2678. showToast('Error', err.message, 'error');
  2679. }
  2680. }
  2681. async function startIPSecTunnel(name) {
  2682. try {
  2683. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/start`, { method: 'POST' });
  2684. if (res.ok) {
  2685. showToast('Initiating Tunnel', `Attempting SA handshake for ${name}...`, 'info');
  2686. setTimeout(() => loadIPSec(false), 2000);
  2687. }
  2688. } catch (err) {
  2689. showToast('Error', err.message, 'error');
  2690. }
  2691. }
  2692. async function stopIPSecTunnel(name) {
  2693. try {
  2694. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  2695. if (res.ok) {
  2696. showToast('Terminated', `IPSec SA for ${name} closed`, 'info');
  2697. loadIPSec(false);
  2698. }
  2699. } catch (err) {
  2700. showToast('Error', err.message, 'error');
  2701. }
  2702. }
  2703. async function toggleIPSecState(name, enable) {
  2704. try {
  2705. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/state`, {
  2706. method: 'POST',
  2707. headers: { 'Content-Type': 'application/json' },
  2708. body: JSON.stringify({ enabled: enable })
  2709. });
  2710. if (res.ok) {
  2711. showToast(enable ? 'Enabled' : 'Disabled', `IPSec tunnel ${name} updated`, 'info');
  2712. loadIPSec(false);
  2713. }
  2714. } catch (err) {
  2715. showToast('Error', err.message, 'error');
  2716. }
  2717. }
  2718. async function deleteIPSecConn(name) {
  2719. if (!confirm(`Are you sure you want to delete IPSec tunnel ${name}?`)) return;
  2720. try {
  2721. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2722. if (res.ok) {
  2723. showToast('Deleted', `IPSec connection ${name} removed`, 'success');
  2724. loadIPSec(false);
  2725. fetchData(false);
  2726. }
  2727. } catch (err) {
  2728. showToast('Error', err.message, 'error');
  2729. }
  2730. }
  2731. // ======================== L2TP Multi-Instance ========================
  2732. async function loadL2TP(populateInputs = true) {
  2733. try {
  2734. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2735. await fetchPPPProfilesList();
  2736. }
  2737. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`);
  2738. const list = await res.json();
  2739. state.l2tpList = Array.isArray(list) ? list : [];
  2740. const badge = document.getElementById('l2tp-count-badge');
  2741. if (badge) badge.innerText = `${state.l2tpList.length} Client${state.l2tpList.length !== 1 ? 's' : ''}`;
  2742. const tbody = document.getElementById('l2tp-table-body');
  2743. const empty = document.getElementById('l2tp-empty');
  2744. if (!tbody) return;
  2745. tbody.innerHTML = '';
  2746. if (state.l2tpList.length === 0) {
  2747. if (empty) empty.classList.remove('hidden');
  2748. } else {
  2749. if (empty) empty.classList.add('hidden');
  2750. state.l2tpList.forEach(inst => {
  2751. const tr = document.createElement('tr');
  2752. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  2753. tr.innerHTML = `
  2754. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  2755. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  2756. <td class="py-2.5 px-3 text-cyan-400 font-mono">${escapeHtml(inst.connect_to)}</td>
  2757. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  2758. <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>
  2759. <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>
  2760. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  2761. <td class="py-2.5 px-3 text-center">
  2762. <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'}">
  2763. ${inst.default_route ? 'Yes' : 'No'}
  2764. </span>
  2765. </td>
  2766. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  2767. ${inst.running ? `
  2768. <button onclick="disconnectL2TPInstance('${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  2769. ` : `
  2770. <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>
  2771. `}
  2772. <button onclick="toggleL2TPState('${escapeHtml(inst.name)}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  2773. ${inst.disabled ? 'Enable' : 'Disable'}
  2774. </button>
  2775. <button onclick="openEditL2TPModal('${escapeHtml(inst.name)}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2776. <button onclick="deleteL2TPInstance('${escapeHtml(inst.name)}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2777. </td>
  2778. `;
  2779. tbody.appendChild(tr);
  2780. });
  2781. }
  2782. } catch (err) {
  2783. console.error('Failed to load L2TP:', err);
  2784. }
  2785. }
  2786. async function openAddL2TPModal() {
  2787. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2788. await fetchPPPProfilesList();
  2789. }
  2790. document.getElementById('l2tp-modal-title').innerText = 'Add L2TP Client Interface';
  2791. document.getElementById('l2tp-modal-name').value = `l2tp-out${(state.l2tpList || []).length + 1}`;
  2792. document.getElementById('l2tp-modal-name').readOnly = false;
  2793. document.getElementById('l2tp-modal-server').value = '';
  2794. document.getElementById('l2tp-modal-user').value = '';
  2795. document.getElementById('l2tp-modal-pass').value = '';
  2796. document.getElementById('l2tp-modal-ipsec').value = '';
  2797. document.getElementById('l2tp-modal-defroute').checked = true;
  2798. document.getElementById('l2tp-modal-disabled').checked = false;
  2799. populateProfileSelect('l2tp-modal-profile', 'default-encryption', 'default-encryption');
  2800. document.getElementById('l2tp-modal').classList.remove('hidden');
  2801. }
  2802. async function openEditL2TPModal(name) {
  2803. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2804. await fetchPPPProfilesList();
  2805. }
  2806. const inst = (state.l2tpList || []).find(i => i.name === name);
  2807. if (!inst) return;
  2808. document.getElementById('l2tp-modal-title').innerText = `Edit L2TP Client: ${name}`;
  2809. document.getElementById('l2tp-modal-name').value = inst.name;
  2810. document.getElementById('l2tp-modal-name').readOnly = true;
  2811. document.getElementById('l2tp-modal-server').value = inst.connect_to || '';
  2812. document.getElementById('l2tp-modal-user').value = inst.username || '';
  2813. document.getElementById('l2tp-modal-pass').value = inst.password || '';
  2814. document.getElementById('l2tp-modal-ipsec').value = inst.ipsec_secret || '';
  2815. document.getElementById('l2tp-modal-defroute').checked = inst.default_route ?? true;
  2816. document.getElementById('l2tp-modal-disabled').checked = !!inst.disabled;
  2817. populateProfileSelect('l2tp-modal-profile', inst.profile || 'default-encryption', 'default-encryption');
  2818. document.getElementById('l2tp-modal').classList.remove('hidden');
  2819. }
  2820. function closeL2TPModal() {
  2821. document.getElementById('l2tp-modal').classList.add('hidden');
  2822. }
  2823. async function submitSaveL2TP(e) {
  2824. e.preventDefault();
  2825. const name = document.getElementById('l2tp-modal-name').value.trim();
  2826. const server = document.getElementById('l2tp-modal-server').value.trim();
  2827. const user = document.getElementById('l2tp-modal-user').value.trim();
  2828. const pass = document.getElementById('l2tp-modal-pass').value;
  2829. const profile = document.getElementById('l2tp-modal-profile')?.value || 'default-encryption';
  2830. const ipsec = document.getElementById('l2tp-modal-ipsec').value;
  2831. const defRoute = document.getElementById('l2tp-modal-defroute').checked;
  2832. const disabled = document.getElementById('l2tp-modal-disabled').checked;
  2833. try {
  2834. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`, {
  2835. method: 'POST',
  2836. headers: { 'Content-Type': 'application/json' },
  2837. body: JSON.stringify({
  2838. name,
  2839. connect_to: server,
  2840. username: user,
  2841. password: pass,
  2842. profile: profile,
  2843. ipsec_secret: ipsec,
  2844. default_route: defRoute,
  2845. disabled
  2846. })
  2847. });
  2848. if (res.ok) {
  2849. showToast('L2TP Saved', `Client ${name} configuration saved`, 'success');
  2850. closeL2TPModal();
  2851. loadL2TP(false);
  2852. fetchData(false);
  2853. }
  2854. } catch (err) {
  2855. showToast('Error', err.message, 'error');
  2856. }
  2857. }
  2858. async function connectL2TPInstance(name) {
  2859. try {
  2860. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  2861. if (res.ok) {
  2862. showToast('Connecting', `Dialing L2TP ${name}...`, 'info');
  2863. setTimeout(() => loadL2TP(false), 2000);
  2864. }
  2865. } catch (err) {
  2866. showToast('Error', err.message, 'error');
  2867. }
  2868. }
  2869. async function disconnectL2TPInstance(name) {
  2870. try {
  2871. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  2872. if (res.ok) {
  2873. showToast('Disconnected', `L2TP tunnel ${name} terminated`, 'info');
  2874. loadL2TP(false);
  2875. }
  2876. } catch (err) {
  2877. showToast('Error', err.message, 'error');
  2878. }
  2879. }
  2880. async function toggleL2TPState(name, enable) {
  2881. try {
  2882. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/state`, {
  2883. method: 'POST',
  2884. headers: { 'Content-Type': 'application/json' },
  2885. body: JSON.stringify({ enabled: enable })
  2886. });
  2887. if (res.ok) {
  2888. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  2889. loadL2TP(false);
  2890. }
  2891. } catch (err) {
  2892. showToast('Error', err.message, 'error');
  2893. }
  2894. }
  2895. async function deleteL2TPInstance(name) {
  2896. if (!confirm(`Are you sure you want to delete L2TP client ${name}?`)) return;
  2897. try {
  2898. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2899. if (res.ok) {
  2900. showToast('Deleted', `L2TP client ${name} removed`, 'success');
  2901. loadL2TP(false);
  2902. fetchData(false);
  2903. }
  2904. } catch (err) {
  2905. showToast('Error', err.message, 'error');
  2906. }
  2907. }
  2908. // ======================== PPTP Multi-Instance ========================
  2909. async function loadPPTP(populateInputs = true) {
  2910. try {
  2911. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2912. await fetchPPPProfilesList();
  2913. }
  2914. const res = await fetch(`${API_BASE}/vpn/pptp/clients`);
  2915. const list = await res.json();
  2916. state.pptpList = Array.isArray(list) ? list : [];
  2917. const badge = document.getElementById('pptp-count-badge');
  2918. if (badge) badge.innerText = `${state.pptpList.length} Client${state.pptpList.length !== 1 ? 's' : ''}`;
  2919. const tbody = document.getElementById('pptp-table-body');
  2920. const empty = document.getElementById('pptp-empty');
  2921. if (!tbody) return;
  2922. tbody.innerHTML = '';
  2923. if (state.pptpList.length === 0) {
  2924. if (empty) empty.classList.remove('hidden');
  2925. } else {
  2926. if (empty) empty.classList.add('hidden');
  2927. state.pptpList.forEach(inst => {
  2928. const tr = document.createElement('tr');
  2929. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  2930. tr.innerHTML = `
  2931. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  2932. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  2933. <td class="py-2.5 px-3 text-purple-400 font-mono">${escapeHtml(inst.connect_to)}</td>
  2934. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  2935. <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>
  2936. <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>
  2937. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  2938. <td class="py-2.5 px-3 text-center">
  2939. <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'}">
  2940. ${inst.require_mppe ? 'MPPE-128' : 'None'}
  2941. </span>
  2942. </td>
  2943. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  2944. ${inst.running ? `
  2945. <button onclick="disconnectPPTPInstance('${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  2946. ` : `
  2947. <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>
  2948. `}
  2949. <button onclick="togglePPTPState('${escapeHtml(inst.name)}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  2950. ${inst.disabled ? 'Enable' : 'Disable'}
  2951. </button>
  2952. <button onclick="openEditPPTPModal('${escapeHtml(inst.name)}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2953. <button onclick="deletePPTPInstance('${escapeHtml(inst.name)}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2954. </td>
  2955. `;
  2956. tbody.appendChild(tr);
  2957. });
  2958. }
  2959. } catch (err) {
  2960. console.error('Failed to load PPTP:', err);
  2961. }
  2962. }
  2963. async function openAddPPTPModal() {
  2964. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2965. await fetchPPPProfilesList();
  2966. }
  2967. document.getElementById('pptp-modal-title').innerText = 'Add PPTP Client Interface';
  2968. document.getElementById('pptp-modal-name').value = `pptp-out${(state.pptpList || []).length + 1}`;
  2969. document.getElementById('pptp-modal-name').readOnly = false;
  2970. document.getElementById('pptp-modal-server').value = '';
  2971. document.getElementById('pptp-modal-user').value = '';
  2972. document.getElementById('pptp-modal-pass').value = '';
  2973. document.getElementById('pptp-modal-mppe').checked = true;
  2974. document.getElementById('pptp-modal-defroute').checked = true;
  2975. document.getElementById('pptp-modal-disabled').checked = false;
  2976. populateProfileSelect('pptp-modal-profile', 'default-encryption', 'default-encryption');
  2977. document.getElementById('pptp-modal').classList.remove('hidden');
  2978. }
  2979. async function openEditPPTPModal(name) {
  2980. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2981. await fetchPPPProfilesList();
  2982. }
  2983. const inst = (state.pptpList || []).find(i => i.name === name);
  2984. if (!inst) return;
  2985. document.getElementById('pptp-modal-title').innerText = `Edit PPTP Client: ${name}`;
  2986. document.getElementById('pptp-modal-name').value = inst.name;
  2987. document.getElementById('pptp-modal-name').readOnly = true;
  2988. document.getElementById('pptp-modal-server').value = inst.connect_to || '';
  2989. document.getElementById('pptp-modal-user').value = inst.username || '';
  2990. document.getElementById('pptp-modal-pass').value = inst.password || '';
  2991. document.getElementById('pptp-modal-mppe').checked = inst.require_mppe ?? true;
  2992. document.getElementById('pptp-modal-defroute').checked = inst.default_route ?? true;
  2993. document.getElementById('pptp-modal-disabled').checked = !!inst.disabled;
  2994. populateProfileSelect('pptp-modal-profile', inst.profile || 'default-encryption', 'default-encryption');
  2995. document.getElementById('pptp-modal').classList.remove('hidden');
  2996. }
  2997. function closePPTPModal() {
  2998. document.getElementById('pptp-modal').classList.add('hidden');
  2999. }
  3000. async function submitSavePPTP(e) {
  3001. e.preventDefault();
  3002. const name = document.getElementById('pptp-modal-name').value.trim();
  3003. const server = document.getElementById('pptp-modal-server').value.trim();
  3004. const user = document.getElementById('pptp-modal-user').value.trim();
  3005. const pass = document.getElementById('pptp-modal-pass').value;
  3006. const profile = document.getElementById('pptp-modal-profile')?.value || 'default-encryption';
  3007. const mppe = document.getElementById('pptp-modal-mppe').checked;
  3008. const defRoute = document.getElementById('pptp-modal-defroute').checked;
  3009. const disabled = document.getElementById('pptp-modal-disabled').checked;
  3010. try {
  3011. const res = await fetch(`${API_BASE}/vpn/pptp/clients`, {
  3012. method: 'POST',
  3013. headers: { 'Content-Type': 'application/json' },
  3014. body: JSON.stringify({
  3015. name,
  3016. connect_to: server,
  3017. username: user,
  3018. password: pass,
  3019. profile: profile,
  3020. require_mppe: mppe,
  3021. default_route: defRoute,
  3022. auto_reconnect: true,
  3023. disabled
  3024. })
  3025. });
  3026. if (res.ok) {
  3027. showToast('PPTP Saved', `Client ${name} configuration saved`, 'success');
  3028. closePPTPModal();
  3029. loadPPTP(false);
  3030. fetchData(false);
  3031. }
  3032. } catch (err) {
  3033. showToast('Error', err.message, 'error');
  3034. }
  3035. }
  3036. async function connectPPTPInstance(name) {
  3037. try {
  3038. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  3039. if (res.ok) {
  3040. showToast('Connecting', `Dialing PPTP ${name}...`, 'info');
  3041. setTimeout(() => loadPPTP(false), 2000);
  3042. }
  3043. } catch (err) {
  3044. showToast('Error', err.message, 'error');
  3045. }
  3046. }
  3047. async function disconnectPPTPInstance(name) {
  3048. try {
  3049. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  3050. if (res.ok) {
  3051. showToast('Disconnected', `PPTP tunnel ${name} terminated`, 'info');
  3052. loadPPTP(false);
  3053. }
  3054. } catch (err) {
  3055. showToast('Error', err.message, 'error');
  3056. }
  3057. }
  3058. async function togglePPTPState(name, enable) {
  3059. try {
  3060. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/state`, {
  3061. method: 'POST',
  3062. headers: { 'Content-Type': 'application/json' },
  3063. body: JSON.stringify({ enabled: enable })
  3064. });
  3065. if (res.ok) {
  3066. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  3067. loadPPTP(false);
  3068. }
  3069. } catch (err) {
  3070. showToast('Error', err.message, 'error');
  3071. }
  3072. }
  3073. async function deletePPTPInstance(name) {
  3074. if (!confirm(`Are you sure you want to delete PPTP client ${name}?`)) return;
  3075. try {
  3076. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  3077. if (res.ok) {
  3078. showToast('Deleted', `PPTP client ${name} removed`, 'success');
  3079. loadPPTP(false);
  3080. fetchData(false);
  3081. }
  3082. } catch (err) {
  3083. showToast('Error', err.message, 'error');
  3084. }
  3085. }
  3086. // ---------------- Modal & Helper Functions ----------------
  3087. function openVlanModal(defaultParent = '') {
  3088. const select = document.getElementById('vlan-parent');
  3089. select.innerHTML = '';
  3090. const allIfaces = state.interfaces || [];
  3091. const eligible = allIfaces.filter(i => supportsVLAN(i));
  3092. if (eligible.length === 0) {
  3093. const opt = document.createElement('option');
  3094. opt.value = '';
  3095. opt.innerText = 'No VLAN-capable interfaces available';
  3096. select.appendChild(opt);
  3097. } else {
  3098. eligible.forEach(i => {
  3099. const opt = document.createElement('option');
  3100. opt.value = i.name;
  3101. opt.innerText = `${i.name} (${i.role || i.type || 'Ethernet'} - ${i.state})`;
  3102. if (i.name === defaultParent) opt.selected = true;
  3103. select.appendChild(opt);
  3104. });
  3105. }
  3106. document.getElementById('vlan-id').value = '';
  3107. document.getElementById('vlan-name').value = '';
  3108. document.getElementById('vlan-ip').value = '';
  3109. document.getElementById('vlan-desc').value = '';
  3110. populateRoleSelects('LAN');
  3111. autoSuggestVlanName();
  3112. document.getElementById('vlan-modal').classList.remove('hidden');
  3113. }
  3114. function closeVlanModal() {
  3115. document.getElementById('vlan-modal').classList.add('hidden');
  3116. }
  3117. function autoSuggestVlanName() {
  3118. const parent = document.getElementById('vlan-parent').value;
  3119. if (!parent) return;
  3120. const id = document.getElementById('vlan-id').value;
  3121. const nameInput = document.getElementById('vlan-name');
  3122. if (parent && id) nameInput.placeholder = `${parent}.${id}`;
  3123. }
  3124. function setSubnetPreset(cidr) {
  3125. const ipInput = document.getElementById('vlan-ip');
  3126. const id = document.getElementById('vlan-id').value || '10';
  3127. ipInput.value = `192.168.${id}.1${cidr}`;
  3128. }
  3129. async function submitCreateVlan(e) {
  3130. e.preventDefault();
  3131. const btn = document.getElementById('vlan-submit-btn');
  3132. btn.disabled = true;
  3133. btn.innerText = 'Creating...';
  3134. const parent = document.getElementById('vlan-parent').value;
  3135. if (!parent) {
  3136. showToast('Error', 'Please select a valid VLAN-capable parent interface', 'error');
  3137. btn.disabled = false;
  3138. btn.innerText = 'Create VLAN';
  3139. return;
  3140. }
  3141. const id = parseInt(document.getElementById('vlan-id').value, 10);
  3142. const name = document.getElementById('vlan-name').value.trim();
  3143. const ip = document.getElementById('vlan-ip').value.trim();
  3144. const role = document.getElementById('vlan-role').value;
  3145. const desc = document.getElementById('vlan-desc').value.trim();
  3146. try {
  3147. const res = await fetch(`${API_BASE}/vlans`, {
  3148. method: 'POST',
  3149. headers: { 'Content-Type': 'application/json' },
  3150. body: JSON.stringify({
  3151. parent_name: parent,
  3152. vlan_id: id,
  3153. name: name,
  3154. ip_address: ip,
  3155. role: role,
  3156. description: desc,
  3157. mtu: 1500,
  3158. auto_up: true
  3159. })
  3160. });
  3161. const data = await res.json();
  3162. if (res.ok) {
  3163. showToast('VLAN Created', `Created ${data.name} (VLAN ${data.vlan_id})`, 'success');
  3164. state.expandedParents.add(parent);
  3165. closeVlanModal();
  3166. await fetchData(true);
  3167. if (state.activeTab !== 'interfaces') navigate('interfaces');
  3168. } else {
  3169. showToast('Creation Failed', data.message || 'Failed to create VLAN', 'error');
  3170. }
  3171. } catch (err) {
  3172. showToast('Error', err.message, 'error');
  3173. } finally {
  3174. btn.disabled = false;
  3175. btn.innerText = 'Create VLAN';
  3176. }
  3177. }
  3178. async function confirmDeleteVlan(name) {
  3179. if (!confirm(`Delete VLAN interface ${name}?`)) return;
  3180. try {
  3181. const res = await fetch(`${API_BASE}/vlans/${encodeURIComponent(name)}`, { method: 'DELETE' });
  3182. if (res.ok) {
  3183. showToast('VLAN Deleted', `Interface ${name} removed`, 'success');
  3184. closeIfaceModal();
  3185. fetchData(true);
  3186. }
  3187. } catch (err) {
  3188. showToast('Error', err.message, 'error');
  3189. }
  3190. }
  3191. function openIfaceModal(name) {
  3192. const iface = (state.interfaces || []).find(i => i.name === name);
  3193. if (!iface) return;
  3194. state.currentModalIface = iface.name;
  3195. document.getElementById('modal-iface-name').innerText = iface.name;
  3196. document.getElementById('modal-iface-badge').innerText = iface.is_vlan ? `VLAN ${iface.vlan_id}` : iface.type;
  3197. document.getElementById('modal-iface-mtu').value = iface.mtu;
  3198. populateRoleSelects(iface.role || 'LAN');
  3199. document.getElementById('modal-iface-desc').value = iface.description || '';
  3200. const nameInput = document.getElementById('modal-iface-new-name');
  3201. const renameBtn = document.getElementById('modal-btn-rename');
  3202. const renameHelp = document.getElementById('modal-iface-rename-help');
  3203. if (nameInput) {
  3204. nameInput.value = iface.name;
  3205. if (iface.name === 'lo' || iface.type === 'loopback') {
  3206. nameInput.disabled = true;
  3207. if (renameBtn) renameBtn.disabled = true;
  3208. if (renameHelp) renameHelp.innerText = 'Loopback interface cannot be renamed.';
  3209. } else {
  3210. nameInput.disabled = false;
  3211. if (renameBtn) renameBtn.disabled = false;
  3212. if (renameHelp) renameHelp.innerText = 'Device name in Linux (max 15 characters). Automatically preserves operational link state and metadata.';
  3213. }
  3214. }
  3215. const delBtn = document.getElementById('modal-delete-vlan-btn');
  3216. if (iface.is_vlan) {
  3217. delBtn.classList.remove('hidden');
  3218. } else {
  3219. delBtn.classList.add('hidden');
  3220. }
  3221. renderModalIPs(iface);
  3222. document.getElementById('iface-modal').classList.remove('hidden');
  3223. }
  3224. function renderModalIPs(iface) {
  3225. const container = document.getElementById('modal-ip-list');
  3226. container.innerHTML = '';
  3227. const addrs = [...(iface.ipv4 || []), ...(iface.ipv6 || [])];
  3228. if (addrs.length === 0) {
  3229. container.innerHTML = `<span class="text-slate-500 text-xs font-sans">No IP addresses currently bound</span>`;
  3230. return;
  3231. }
  3232. addrs.forEach(addr => {
  3233. const row = document.createElement('div');
  3234. row.className = 'flex items-center justify-between p-2 rounded bg-slate-900 border border-slate-800';
  3235. row.innerHTML = `
  3236. <span class="text-white">${addr}</span>
  3237. <button onclick="removeInterfaceIP('${addr}')" class="text-[11px] text-rose-400 hover:text-rose-300 font-sans">Remove</button>
  3238. `;
  3239. container.appendChild(row);
  3240. });
  3241. }
  3242. function closeIfaceModal() {
  3243. document.getElementById('iface-modal').classList.add('hidden');
  3244. state.currentModalIface = null;
  3245. }
  3246. async function setIfaceState(name, newState) {
  3247. const target = name || state.currentModalIface;
  3248. if (!target) return;
  3249. await toggleInterfaceState(target, newState);
  3250. const updated = (state.interfaces || []).find(i => i.name === target);
  3251. if (updated) openIfaceModal(target);
  3252. }
  3253. async function applyMTU() {
  3254. const mtu = parseInt(document.getElementById('modal-iface-mtu').value, 10);
  3255. try {
  3256. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/mtu`, {
  3257. method: 'POST',
  3258. headers: { 'Content-Type': 'application/json' },
  3259. body: JSON.stringify({ mtu })
  3260. });
  3261. if (res.ok) {
  3262. showToast('MTU Applied', `Set MTU to ${mtu} on ${state.currentModalIface}`, 'success');
  3263. fetchData(false);
  3264. }
  3265. } catch (err) {
  3266. showToast('Error', err.message, 'error');
  3267. }
  3268. }
  3269. async function addInterfaceIP() {
  3270. const ip = document.getElementById('modal-new-ip').value.trim();
  3271. if (!ip) return;
  3272. try {
  3273. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  3274. method: 'POST',
  3275. headers: { 'Content-Type': 'application/json' },
  3276. body: JSON.stringify({ ip })
  3277. });
  3278. if (res.ok) {
  3279. showToast('IP Added', `Bound ${ip} to ${state.currentModalIface}`, 'success');
  3280. document.getElementById('modal-new-ip').value = '';
  3281. await fetchData(false);
  3282. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  3283. if (iface) renderModalIPs(iface);
  3284. } else {
  3285. const err = await res.json();
  3286. showToast('Error', err.error || err.message || 'Failed to add IP address', 'error');
  3287. }
  3288. } catch (err) {
  3289. showToast('Error', err.message, 'error');
  3290. }
  3291. }
  3292. async function removeInterfaceIP(ip) {
  3293. if (!confirm(`Remove IP ${ip}?`)) return;
  3294. try {
  3295. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  3296. method: 'DELETE',
  3297. headers: { 'Content-Type': 'application/json' },
  3298. body: JSON.stringify({ ip })
  3299. });
  3300. if (res.ok) {
  3301. showToast('IP Removed', `Removed ${ip}`, 'success');
  3302. await fetchData(false);
  3303. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  3304. if (iface) renderModalIPs(iface);
  3305. }
  3306. } catch (err) {
  3307. showToast('Error', err.message, 'error');
  3308. }
  3309. }
  3310. async function renameInterface() {
  3311. const oldName = state.currentModalIface;
  3312. const newNameInput = document.getElementById('modal-iface-new-name');
  3313. const newName = (newNameInput?.value || '').trim();
  3314. if (!oldName) return;
  3315. if (!newName) {
  3316. showToast('Warning', 'Interface name cannot be empty', 'warning');
  3317. return;
  3318. }
  3319. if (newName === oldName) {
  3320. showToast('Info', `Interface name is already "${oldName}"`, 'info');
  3321. return;
  3322. }
  3323. if (newName.length > 15) {
  3324. showToast('Validation Error', 'Interface name cannot exceed 15 characters (Linux IFNAMSIZ)', 'error');
  3325. return;
  3326. }
  3327. if (!/^[a-zA-Z0-9_][a-zA-Z0-9_.-]*$/.test(newName)) {
  3328. showToast('Validation Error', 'Name must contain only alphanumeric characters, underscores, hyphens or dots', 'error');
  3329. return;
  3330. }
  3331. const renameBtn = document.getElementById('modal-btn-rename');
  3332. if (renameBtn) {
  3333. renameBtn.disabled = true;
  3334. renameBtn.innerHTML = `<span class="animate-spin inline-block mr-1">⟳</span> Renaming...`;
  3335. }
  3336. try {
  3337. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(oldName)}/rename`, {
  3338. method: 'POST',
  3339. headers: { 'Content-Type': 'application/json' },
  3340. body: JSON.stringify({ new_name: newName })
  3341. });
  3342. const data = await res.json();
  3343. if (!res.ok) {
  3344. showToast('Rename Failed', data.error || data.message || 'Failed to rename interface', 'error');
  3345. return;
  3346. }
  3347. showToast('Interface Renamed', `Successfully renamed ${oldName} → ${newName}`, 'success');
  3348. state.currentModalIface = newName;
  3349. document.getElementById('modal-iface-name').innerText = newName;
  3350. // Refresh application state
  3351. await fetchData(false);
  3352. const updated = (state.interfaces || []).find(i => i.name === newName);
  3353. if (updated) {
  3354. openIfaceModal(newName);
  3355. } else {
  3356. closeIfaceModal();
  3357. }
  3358. } catch (err) {
  3359. showToast('Error', err.message, 'error');
  3360. } finally {
  3361. if (renameBtn) {
  3362. renameBtn.disabled = false;
  3363. renameBtn.innerHTML = `
  3364. <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>
  3365. <span>Rename</span>
  3366. `;
  3367. }
  3368. }
  3369. }
  3370. async function saveInterfaceMetadata() {
  3371. const oldName = state.currentModalIface;
  3372. const newName = (document.getElementById('modal-iface-new-name')?.value || '').trim();
  3373. const role = document.getElementById('modal-iface-role').value;
  3374. const desc = document.getElementById('modal-iface-desc').value.trim();
  3375. let targetName = oldName;
  3376. // If user changed the name before clicking Save Changes, execute rename first
  3377. if (newName && newName !== oldName && oldName !== 'lo') {
  3378. try {
  3379. const renameRes = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(oldName)}/rename`, {
  3380. method: 'POST',
  3381. headers: { 'Content-Type': 'application/json' },
  3382. body: JSON.stringify({ new_name: newName })
  3383. });
  3384. const data = await renameRes.json();
  3385. if (!renameRes.ok) {
  3386. showToast('Rename Failed', data.error || data.message || 'Could not rename interface', 'error');
  3387. return;
  3388. }
  3389. targetName = newName;
  3390. state.currentModalIface = newName;
  3391. showToast('Renamed', `Interface renamed from ${oldName} to ${newName}`, 'success');
  3392. } catch (err) {
  3393. showToast('Error', err.message, 'error');
  3394. return;
  3395. }
  3396. }
  3397. try {
  3398. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(targetName)}/metadata`, {
  3399. method: 'POST',
  3400. headers: { 'Content-Type': 'application/json' },
  3401. body: JSON.stringify({ role, description: desc })
  3402. });
  3403. if (res.ok) {
  3404. showToast('Saved', 'Interface configuration updated', 'success');
  3405. closeIfaceModal();
  3406. fetchData(false);
  3407. } else {
  3408. const err = await res.json();
  3409. showToast('Error', err.error || err.message || 'Failed to save metadata', 'error');
  3410. }
  3411. } catch (err) {
  3412. showToast('Error', err.message, 'error');
  3413. }
  3414. }
  3415. // ======================== IPTABLES FIREWALL ========================
  3416. state.fwSubTab = 'filter';
  3417. state.routesSubTab = 'routes';
  3418. function nativeNATChain(chain) {
  3419. const value = (chain || '').toLowerCase();
  3420. if (value === 'dstnat') return 'prerouting';
  3421. if (value === 'srcnat') return 'postrouting';
  3422. return ['prerouting', 'input', 'output', 'postrouting'].includes(value) ? value : (chain || '');
  3423. }
  3424. function nativeFirewallTarget(action) {
  3425. const name = (action || '').toLowerCase();
  3426. 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();
  3427. }
  3428. function renderRuleFlag(disabled, hasComment) {
  3429. let flags = '';
  3430. if (disabled) flags += '<span class="text-rose-400 font-bold" title="Disabled">X</span>';
  3431. if (hasComment) flags += '<span class="text-amber-400 font-bold ml-1" title="Has Comment">C</span>';
  3432. return flags || '<span class="text-slate-600">-</span>';
  3433. }
  3434. function renderActionBadge(action) {
  3435. const act = (action || '').toLowerCase();
  3436. let color = 'bg-slate-800 text-slate-300';
  3437. if (act === 'accept') color = 'bg-emerald-500/20 text-emerald-300 border border-emerald-500/30';
  3438. else if (act === 'drop' || act === 'reject') color = 'bg-rose-500/20 text-rose-300 border border-rose-500/30';
  3439. else if (act === 'masquerade' || act === 'src-nat' || act === 'dst-nat') color = 'bg-amber-500/20 text-amber-300 border border-amber-500/30';
  3440. else if (act.startsWith('mark-')) color = 'bg-purple-500/20 text-purple-300 border border-purple-500/30';
  3441. else if (act === 'log') color = 'bg-cyan-500/20 text-cyan-300 border border-cyan-500/30';
  3442. return `<span class="px-2 py-0.5 rounded text-[10px] font-mono font-semibold ${color}">${escapeHtml(nativeFirewallTarget(action))}</span>`;
  3443. }
  3444. function switchFWSubTab(tab) {
  3445. state.fwSubTab = tab;
  3446. const tabs = ['filter', 'nat', 'mangle', 'addrlist', 'geo', 'connections'];
  3447. tabs.forEach(t => {
  3448. const panel = document.getElementById(`fw-subtab-${t}`);
  3449. const btn = document.getElementById(`fw-subtab-btn-${t}`);
  3450. if (panel) {
  3451. if (t === tab) panel.classList.remove('hidden');
  3452. else panel.classList.add('hidden');
  3453. }
  3454. if (btn) {
  3455. if (t === tab) {
  3456. 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';
  3457. } else {
  3458. 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';
  3459. }
  3460. }
  3461. });
  3462. const addBtn = document.getElementById('fw-primary-add-btn');
  3463. if (addBtn) {
  3464. if (tab === 'filter') addBtn.innerHTML = '<span>+ Add Filter Rule</span>';
  3465. else if (tab === 'nat') addBtn.innerHTML = '<span>+ Add NAT Rule</span>';
  3466. else if (tab === 'mangle') addBtn.innerHTML = '<span>+ Add Mangle Rule</span>';
  3467. else if (tab === 'addrlist') addBtn.innerHTML = '<span>+ Add Address List</span>';
  3468. else if (tab === 'geo') addBtn.innerHTML = '<span>⚙️ Schedule Settings</span>';
  3469. else if (tab === 'connections') addBtn.innerHTML = '<span>Refresh Flows</span>';
  3470. }
  3471. if (tab === 'filter') renderFilterRules();
  3472. else if (tab === 'nat') renderNATRules();
  3473. else if (tab === 'mangle') renderMangleRules();
  3474. else if (tab === 'addrlist') renderAddressLists();
  3475. else if (tab === 'geo') loadGeoIP();
  3476. else if (tab === 'connections') loadConnections();
  3477. setTimeout(initTableSorting, 50);
  3478. }
  3479. function openCurrentFWModal() {
  3480. if (state.fwSubTab === 'filter') openAddFilterModal();
  3481. else if (state.fwSubTab === 'nat') openAddNATModal();
  3482. else if (state.fwSubTab === 'mangle') openAddMangleModal();
  3483. else if (state.fwSubTab === 'addrlist') openAddAddrListModal();
  3484. else if (state.fwSubTab === 'geo') openGeoIntervalModal();
  3485. else if (state.fwSubTab === 'connections') loadConnections();
  3486. }
  3487. async function loadFirewall(populateDropdowns = true) {
  3488. try {
  3489. const [summaryRes, filterRes, natRes, mangleRes, addrlistRes, geoStatusRes, geoCountriesRes] = await Promise.all([
  3490. fetch(`${API_BASE}/firewall/summary`),
  3491. fetch(`${API_BASE}/firewall/filter`),
  3492. fetch(`${API_BASE}/firewall/nat`),
  3493. fetch(`${API_BASE}/firewall/mangle`),
  3494. fetch(`${API_BASE}/firewall/address-lists`),
  3495. fetch(`${API_BASE}/firewall/geoip/status`),
  3496. fetch(`${API_BASE}/firewall/geoip/countries`)
  3497. ]);
  3498. if (summaryRes.ok) state.fwSummary = await summaryRes.json();
  3499. const applyError = document.getElementById('fw-apply-error');
  3500. if (applyError) {
  3501. applyError.textContent = state.fwSummary?.last_error ? 'Firewall configuration was not applied: ' + state.fwSummary.last_error : '';
  3502. applyError.classList.toggle('hidden', !state.fwSummary?.last_error);
  3503. }
  3504. if (filterRes.ok) state.filterRules = await filterRes.json();
  3505. if (natRes.ok) state.natRules = await natRes.json();
  3506. if (mangleRes.ok) state.mangleRules = await mangleRes.json();
  3507. if (addrlistRes.ok) state.addressLists = await addrlistRes.json();
  3508. if (geoStatusRes.ok) state.geoStatus = await geoStatusRes.json();
  3509. if (geoCountriesRes.ok) state.geoCountries = await geoCountriesRes.json();
  3510. 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); }
  3511. // Badges
  3512. const bFilter = document.getElementById('fw-badge-filter');
  3513. if (bFilter) bFilter.innerText = (state.filterRules || []).length;
  3514. const bNat = document.getElementById('fw-badge-nat');
  3515. if (bNat) bNat.innerText = (state.natRules || []).length;
  3516. const bMangle = document.getElementById('fw-badge-mangle');
  3517. if (bMangle) bMangle.innerText = (state.mangleRules || []).length;
  3518. const bAddr = document.getElementById('fw-badge-addrlist');
  3519. if (bAddr) bAddr.innerText = (state.addressLists || []).length;
  3520. const bGeo = document.getElementById('fw-badge-geo');
  3521. if (bGeo) bGeo.innerText = state.geoStatus?.enabled_count || 0;
  3522. const sigFilter = (state.filterRules || []).map(r => JSON.stringify({...r, packets: 0, bytes: 0})).join(';');
  3523. const sigNat = (state.natRules || []).map(r => JSON.stringify({...r, packets: 0, bytes: 0})).join(';');
  3524. const sigMangle = (state.mangleRules || []).map(r => JSON.stringify({...r, packets: 0, bytes: 0})).join(';');
  3525. const sigAddr = (state.addressLists || []).map(a => JSON.stringify(a)).join(';');
  3526. const tbodyFilter = document.getElementById('filter-table-body');
  3527. if (tbodyFilter) {
  3528. if (populateDropdowns || tbodyFilter.dataset.sig !== sigFilter) {
  3529. tbodyFilter.dataset.sig = sigFilter;
  3530. renderFilterRules();
  3531. } else {
  3532. // In-place live stats update (ZERO flicker)
  3533. (state.filterRules || []).forEach(r => {
  3534. const p = document.getElementById(`filter-pkts-${r.id}`);
  3535. if (p) p.innerText = `${(r.packets || 0).toLocaleString()}p`;
  3536. const b = document.getElementById(`filter-bytes-${r.id}`);
  3537. if (b) b.innerText = formatTraffic(r.bytes || 0).replace('/s', '');
  3538. });
  3539. }
  3540. }
  3541. const tbodyNat = document.getElementById('nat-table-body');
  3542. if (tbodyNat) {
  3543. if (populateDropdowns || tbodyNat.dataset.sig !== sigNat) {
  3544. tbodyNat.dataset.sig = sigNat;
  3545. renderNATRules();
  3546. } else {
  3547. (state.natRules || []).forEach(r => {
  3548. const p = document.getElementById(`nat-pkts-${r.id}`);
  3549. if (p) p.innerText = `${(r.packets || 0).toLocaleString()}p`;
  3550. const b = document.getElementById(`nat-bytes-${r.id}`);
  3551. if (b) b.innerText = formatTraffic(r.bytes || 0).replace('/s', '');
  3552. });
  3553. }
  3554. }
  3555. const tbodyMangle = document.getElementById('mangle-table-body');
  3556. if (tbodyMangle) {
  3557. if (populateDropdowns || tbodyMangle.dataset.sig !== sigMangle) {
  3558. tbodyMangle.dataset.sig = sigMangle;
  3559. renderMangleRules();
  3560. } else {
  3561. (state.mangleRules || []).forEach(r => {
  3562. const p = document.getElementById(`mangle-pkts-${r.id}`);
  3563. if (p) p.innerText = `${(r.packets || 0).toLocaleString()}p`;
  3564. const b = document.getElementById(`mangle-bytes-${r.id}`);
  3565. if (b) b.innerText = formatTraffic(r.bytes || 0).replace('/s', '');
  3566. });
  3567. }
  3568. }
  3569. const tbodyAddr = document.getElementById('addrlist-table-body');
  3570. if (tbodyAddr && (populateDropdowns || tbodyAddr.dataset.sig !== sigAddr)) {
  3571. tbodyAddr.dataset.sig = sigAddr;
  3572. renderAddressLists();
  3573. }
  3574. renderGeoCountries();
  3575. if (state.fwSubTab === 'connections') {
  3576. loadConnections();
  3577. }
  3578. } catch (err) {
  3579. console.error('Failed to load firewall:', err);
  3580. }
  3581. }
  3582. // ----------------- Filter Rules -----------------
  3583. function renderFilterRules() {
  3584. const chainFilter = document.getElementById('filter-filter-chain')?.value || '';
  3585. const tbody = document.getElementById('filter-table-body');
  3586. const empty = document.getElementById('filter-empty');
  3587. if (!tbody) return;
  3588. tbody.innerHTML = '';
  3589. const rules = (state.filterRules || []).filter(r => !chainFilter || (r.chain || '').toLowerCase() === chainFilter);
  3590. document.getElementById('filter-count-badge').innerText = `${rules.length} Rules`;
  3591. if (rules.length === 0) {
  3592. empty?.classList.remove('hidden');
  3593. return;
  3594. }
  3595. empty?.classList.add('hidden');
  3596. rules.forEach((raw, idx) => {
  3597. const r = safeFirewallRow(raw);
  3598. const tr = document.createElement('tr');
  3599. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  3600. const ports = [r.src_port ? 's:' + r.src_port : '', r.dst_port ? 'd:' + r.dst_port : ''].filter(Boolean).join(' ');
  3601. const ifaces = [r.in_interface ? 'in:' + r.in_interface : '', r.out_interface ? 'out:' + r.out_interface : ''].filter(Boolean).join(' ');
  3602. let actionExtra = '';
  3603. if (r.action === 'reject') {
  3604. actionExtra = `<span class="block text-[10px] text-rose-300 font-mono mt-0.5">(${r.reject_with || 'icmp-net-unreach'})</span>`;
  3605. } else if (r.action === 'jump') {
  3606. actionExtra = `<span class="block text-[10px] text-yellow-300 font-mono mt-0.5">&rarr; ${r.jump_target || '-'}</span>`;
  3607. } else if (r.action.includes('address-list') || r.action.includes('address list')) {
  3608. actionExtra = `<span class="block text-[10px] text-emerald-300 font-mono mt-0.5">&rarr; ${r.address_list || '-'}</span>`;
  3609. } else if (r.action === 'log' && r.log_prefix) {
  3610. actionExtra = `<span class="block text-[10px] text-slate-400 font-mono mt-0.5">${r.log_prefix}</span>`;
  3611. }
  3612. tr.innerHTML = `
  3613. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  3614. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  3615. <td class="py-2.5 px-3 font-bold text-white">${(r.chain || '').toUpperCase()}</td>
  3616. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  3617. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  3618. <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>
  3619. <td class="py-2.5 px-3 text-amber-400">${ports || '-'}</td>
  3620. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  3621. <td class="py-2.5 px-3">${renderActionBadge(r.action)}${actionExtra}</td>
  3622. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  3623. <span class="text-slate-300" id="filter-pkts-${r.id}">${(r.packets || 0).toLocaleString()}p</span> /
  3624. <span class="text-slate-500" id="filter-bytes-${r.id}">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  3625. </td>
  3626. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  3627. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  3628. <button onclick="moveFilterRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  3629. <button onclick="moveFilterRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  3630. <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>
  3631. <button onclick="openEditFilterModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  3632. <button onclick="deleteFilterRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  3633. </td>
  3634. `;
  3635. tbody.appendChild(tr);
  3636. });
  3637. }
  3638. function formatTarget(addr, list, geo) {
  3639. const parts = [];
  3640. if (addr) parts.push(`<span>${addr}</span>`);
  3641. if (list) {
  3642. const inv = list.startsWith('!') ? '!' : '';
  3643. const clean = list.replace(/^!/, '');
  3644. 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>`);
  3645. }
  3646. if (geo) {
  3647. const inv = geo.startsWith('!') ? '!' : '';
  3648. const clean = geo.replace(/^!/, '').replace(/^geo:/, '');
  3649. 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>`);
  3650. }
  3651. if (parts.length === 0) return '<span class="text-slate-600">0.0.0.0/0</span>';
  3652. return parts.join(' ');
  3653. }
  3654. function populateInterfaceSelect(selectId, currentVal = '') {
  3655. const sel = document.getElementById(selectId);
  3656. if (!sel) return;
  3657. sel.innerHTML = '<option value="">(Any Interface)</option>';
  3658. (state.interfaces || []).forEach(i => {
  3659. const opt = document.createElement('option');
  3660. opt.value = i.name;
  3661. opt.innerText = `${i.name} (${i.role || i.type})`;
  3662. if (i.name === currentVal) opt.selected = true;
  3663. sel.appendChild(opt);
  3664. });
  3665. if (state.sdwanGroups && state.sdwanGroups.length > 0) {
  3666. const optgroup = document.createElement('optgroup');
  3667. optgroup.label = 'SD-WAN Groups';
  3668. state.sdwanGroups.forEach(g => {
  3669. const opt = document.createElement('option');
  3670. opt.value = g.name;
  3671. opt.innerText = `${g.name} [SD-WAN: ${g.mode}]`;
  3672. if (g.name === currentVal) opt.selected = true;
  3673. optgroup.appendChild(opt);
  3674. });
  3675. sel.appendChild(optgroup);
  3676. }
  3677. }
  3678. function populateAddressListSelect(selectId, currentVal = '') {
  3679. const sel = document.getElementById(selectId);
  3680. if (!sel) return;
  3681. sel.innerHTML = '<option value="">(None)</option>';
  3682. const cleanVal = (currentVal || '').replace(/^!/, '');
  3683. 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_'));
  3684. const customNames = Array.from(new Set([...(state.addressLists || []).map(a => a.name), ...ruleLists])).sort();
  3685. customNames.forEach(name => {
  3686. const count = (state.addressLists || []).filter(a => a.name === name).length;
  3687. const opt = document.createElement('option');
  3688. opt.value = name;
  3689. opt.innerText = `${name} (${count} entries)`;
  3690. if (name === cleanVal) opt.selected = true;
  3691. sel.appendChild(opt);
  3692. });
  3693. if (cleanVal && !Array.from(sel.options).some(option => option.value === cleanVal)) {
  3694. const opt = document.createElement('option');
  3695. opt.value = cleanVal;
  3696. opt.innerText = cleanVal;
  3697. opt.selected = true;
  3698. sel.appendChild(opt);
  3699. }
  3700. populateCommonAddrListDatalist();
  3701. }
  3702. function populateCommonAddrListDatalist() {
  3703. const dl = document.getElementById('fw-addrlist-datalist');
  3704. if (!dl) return;
  3705. dl.innerHTML = '';
  3706. const names = Array.from(new Set((state.addressLists || []).map(a => a.name).filter(Boolean))).sort();
  3707. names.forEach(name => {
  3708. const opt = document.createElement('option');
  3709. opt.value = name;
  3710. dl.appendChild(opt);
  3711. });
  3712. }
  3713. function populateGeoIPSelect(selectId, currentVal = '') {
  3714. const sel = document.getElementById(selectId);
  3715. if (!sel) return;
  3716. sel.innerHTML = '<option value="">(None)</option>';
  3717. const cleanVal = (currentVal || '').replace(/^!/, '').replace(/^geo:/, '').toUpperCase();
  3718. // Presets optgroup
  3719. const grpPresets = document.createElement('optgroup');
  3720. grpPresets.label = '⚡ Regional Presets';
  3721. const presets = [
  3722. { code: 'EU', label: '🇪🇺 European Union (EU - 27 countries)' },
  3723. { code: 'BALKANS', label: '🏛️ Balkans (GR, CY, BG, RO, AL, etc.)' },
  3724. { code: 'BLOCKLIST', label: '🛡️ High-Risk Blocklist (CN, RU, IR, KP, BY)' }
  3725. ];
  3726. presets.forEach(p => {
  3727. const opt = document.createElement('option');
  3728. opt.value = p.code;
  3729. opt.innerText = p.label;
  3730. if (p.code === cleanVal) opt.selected = true;
  3731. grpPresets.appendChild(opt);
  3732. });
  3733. sel.appendChild(grpPresets);
  3734. // All Countries optgroup
  3735. const grpCountries = document.createElement('optgroup');
  3736. grpCountries.label = '🌍 All Countries';
  3737. const countries = (state.geoCountries || []).slice().sort((a, b) => a.name.localeCompare(b.name));
  3738. countries.forEach(c => {
  3739. const opt = document.createElement('option');
  3740. opt.value = c.code;
  3741. const subnetsInfo = c.subnet_count ? ` [${c.subnet_count.toLocaleString()} subnets]` : '';
  3742. opt.innerText = `${c.name} (${c.code})${subnetsInfo}`;
  3743. if (c.code === cleanVal) opt.selected = true;
  3744. grpCountries.appendChild(opt);
  3745. });
  3746. sel.appendChild(grpCountries);
  3747. }
  3748. // ==================== FIREWALL FILTER MODAL (DEBTIK WEBFIG / WINBOX V4) ====================
  3749. function switchFwRuleTab(tab) {
  3750. state.activeFwRuleTab = tab;
  3751. document.querySelectorAll('.fw-rule-tab-btn').forEach(btn => {
  3752. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  3753. btn.classList.add('text-slate-400', 'border-transparent');
  3754. });
  3755. const activeBtn = document.getElementById(`fw-tab-btn-${tab}`);
  3756. if (activeBtn) {
  3757. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  3758. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  3759. }
  3760. document.querySelectorAll('.fw-rule-pane').forEach(p => p.classList.add('hidden'));
  3761. const activePane = document.getElementById(`fw-pane-${tab}`);
  3762. if (activePane) activePane.classList.remove('hidden');
  3763. if (tab === 'statistics') {
  3764. startFwStatPolling();
  3765. } else {
  3766. stopFwStatPolling();
  3767. }
  3768. }
  3769. function toggleFwField(fieldKey, expand) {
  3770. const plusBtn = document.getElementById(`fw-plus-${fieldKey}`);
  3771. const fieldBox = document.getElementById(`fw-field-${fieldKey}`);
  3772. if (!plusBtn || !fieldBox) return;
  3773. if (expand) {
  3774. plusBtn.classList.add('hidden');
  3775. fieldBox.classList.remove('hidden');
  3776. const valInput = document.getElementById(`fw-val-${fieldKey}`);
  3777. if (valInput) valInput.focus();
  3778. } else {
  3779. fieldBox.classList.add('hidden');
  3780. plusBtn.classList.remove('hidden');
  3781. const valInput = document.getElementById(`fw-val-${fieldKey}`);
  3782. if (valInput) {
  3783. if (valInput.tagName === 'SELECT') {
  3784. valInput.selectedIndex = 0;
  3785. } else {
  3786. valInput.value = '';
  3787. }
  3788. }
  3789. const invInput = document.getElementById(`fw-inv-${fieldKey}`);
  3790. if (invInput) invInput.checked = false;
  3791. if (fieldKey === 'cs') {
  3792. ['filter-modal-cs-established', 'filter-modal-cs-related', 'filter-modal-cs-new', 'filter-modal-cs-invalid', 'filter-modal-cs-untracked'].forEach(id => {
  3793. const el = document.getElementById(id);
  3794. if (el) el.checked = false;
  3795. });
  3796. }
  3797. if (fieldKey === 'natstate') {
  3798. ['filter-modal-nat-srcnat', 'filter-modal-nat-dstnat'].forEach(id => {
  3799. const el = document.getElementById(id);
  3800. if (el) el.checked = false;
  3801. });
  3802. }
  3803. if (fieldKey === 'days') {
  3804. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3805. const el = document.getElementById(`fw-day-${d}`);
  3806. if (el) el.checked = true;
  3807. });
  3808. }
  3809. }
  3810. }
  3811. function setFwFieldVal(fieldKey, value, hasInvert = false) {
  3812. if (fieldKey === 'ipsec' && typeof value === 'string') value = value.replace(':', ',');
  3813. if (value !== undefined && value !== null && value !== '' && !(fieldKey === 'proto' && value === 'all')) {
  3814. toggleFwField(fieldKey, true);
  3815. let strVal = String(value);
  3816. if (hasInvert) {
  3817. const inv = strVal.startsWith('!');
  3818. if (inv) strVal = strVal.slice(1);
  3819. const invEl = document.getElementById(`fw-inv-${fieldKey}`);
  3820. if (invEl) invEl.checked = inv;
  3821. else if (inv) strVal = '!'+strVal;
  3822. }
  3823. const valEl = document.getElementById(`fw-val-${fieldKey}`);
  3824. 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; }
  3825. } else {
  3826. toggleFwField(fieldKey, false);
  3827. }
  3828. }
  3829. function getFwFieldVal(fieldKey, hasInvert = false) {
  3830. const fieldBox = document.getElementById(`fw-field-${fieldKey}`);
  3831. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  3832. const valEl = document.getElementById(`fw-val-${fieldKey}`);
  3833. let v = valEl ? valEl.value.trim() : '';
  3834. if (!v) return '';
  3835. if (hasInvert) {
  3836. const invEl = document.getElementById(`fw-inv-${fieldKey}`);
  3837. if (invEl && invEl.checked) {
  3838. v = '!' + v.replace(/^!/, '');
  3839. }
  3840. }
  3841. return v;
  3842. }
  3843. function toggleMaximizeFilterModal() {
  3844. const win = document.getElementById('filter-modal-window');
  3845. if (!win) return;
  3846. if (win.classList.contains('max-w-[720px]')) {
  3847. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  3848. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  3849. } else {
  3850. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  3851. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  3852. }
  3853. }
  3854. const FW_NATIVE_CHAINS = {
  3855. filter: [
  3856. { id: 'forward', label: 'FORWARD (routed through router)' },
  3857. { id: 'input', label: 'INPUT (destined to this router)' },
  3858. { id: 'output', label: 'OUTPUT (generated by this router)' }
  3859. ],
  3860. nat: [
  3861. { id: 'postrouting', label: 'POSTROUTING (outgoing after routing — SNAT / MASQUERADE)' },
  3862. { id: 'prerouting', label: 'PREROUTING (incoming before routing — DNAT / REDIRECT)' },
  3863. { id: 'output', label: 'OUTPUT (locally generated — DNAT / REDIRECT)' },
  3864. { id: 'input', label: 'INPUT (destined to this machine — SNAT)' }
  3865. ],
  3866. mangle: [
  3867. { id: 'prerouting', label: 'PREROUTING (incoming before routing)' },
  3868. { id: 'input', label: 'INPUT (destined to this machine)' },
  3869. { id: 'forward', label: 'FORWARD (routed through router)' },
  3870. { id: 'output', label: 'OUTPUT (generated by this machine)' },
  3871. { id: 'postrouting', label: 'POSTROUTING (outgoing after routing)' }
  3872. ]
  3873. };
  3874. function populateChainDropdown(table, currentChain) {
  3875. const sel = document.getElementById(`${table}-modal-chain-select`);
  3876. if (!sel) return;
  3877. const cur = (currentChain || '').trim();
  3878. const lower = cur.toLowerCase();
  3879. const rulesKey = table === 'filter' ? 'filterRules' : table === 'nat' ? 'natRules' : 'mangleRules';
  3880. const rules = state[rulesKey] || [];
  3881. const nativeIds = FW_NATIVE_CHAINS[table].map(c => c.id);
  3882. const customChains = new Set();
  3883. rules.forEach(r => {
  3884. if (r.chain) {
  3885. const c = r.chain.trim();
  3886. const l = c.toLowerCase();
  3887. if (!nativeIds.includes(l) && l !== 'srcnat' && l !== 'dstnat' && !['forward', 'input', 'output', 'prerouting', 'postrouting'].includes(l)) {
  3888. customChains.add(c);
  3889. }
  3890. }
  3891. });
  3892. const isCurrentCustom = cur && !nativeIds.includes(lower) && lower !== 'srcnat' && lower !== 'dstnat' && !['forward', 'input', 'output', 'prerouting', 'postrouting'].includes(lower);
  3893. if (isCurrentCustom) {
  3894. customChains.add(cur);
  3895. }
  3896. let html = '';
  3897. FW_NATIVE_CHAINS[table].forEach(c => {
  3898. html += `<option value="${c.id}">${escapeHtml(c.label)}</option>`;
  3899. });
  3900. if (customChains.size > 0) {
  3901. html += `<optgroup label="Custom Chains">`;
  3902. customChains.forEach(c => {
  3903. html += `<option value="${escapeHtml(c)}">Chain: ${escapeHtml(c)} (custom)</option>`;
  3904. });
  3905. html += `</optgroup>`;
  3906. }
  3907. html += `<option value="__custom__">+ Custom Chain...</option>`;
  3908. sel.innerHTML = html;
  3909. if (isCurrentCustom) {
  3910. sel.value = cur;
  3911. } else if (nativeIds.includes(lower)) {
  3912. sel.value = lower;
  3913. } else if (table === 'nat' && (lower === 'srcnat' || lower === 'dstnat')) {
  3914. sel.value = lower === 'dstnat' ? 'prerouting' : 'postrouting';
  3915. } else {
  3916. sel.value = nativeIds[0];
  3917. }
  3918. const customWrap = document.getElementById(`${table}-modal-custom-wrap`);
  3919. const customInput = document.getElementById(`${table}-modal-custom-input`);
  3920. if (isCurrentCustom || sel.value === '__custom__') {
  3921. if (customWrap) customWrap.classList.remove('hidden');
  3922. if (customInput) customInput.value = cur;
  3923. } else {
  3924. if (customWrap) customWrap.classList.add('hidden');
  3925. if (customInput) customInput.value = '';
  3926. }
  3927. const chainInput = document.getElementById(`${table}-modal-chain`);
  3928. if (chainInput) chainInput.value = cur || sel.value;
  3929. }
  3930. function syncFilterChainFromSelect() {
  3931. const sel = document.getElementById('filter-modal-chain-select');
  3932. const customWrap = document.getElementById('filter-modal-custom-wrap');
  3933. const customInput = document.getElementById('filter-modal-custom-input');
  3934. const chainInput = document.getElementById('filter-modal-chain');
  3935. if (!sel || !chainInput) return;
  3936. if (sel.value === '__custom__') {
  3937. if (customWrap) customWrap.classList.remove('hidden');
  3938. if (customInput) {
  3939. customInput.value = '';
  3940. customInput.focus();
  3941. }
  3942. chainInput.value = '';
  3943. } else {
  3944. if (customWrap) customWrap.classList.add('hidden');
  3945. chainInput.value = sel.value;
  3946. }
  3947. handleFilterChainChange();
  3948. }
  3949. function syncFilterCustomChainInput() {
  3950. const customInput = document.getElementById('filter-modal-custom-input');
  3951. const chainInput = document.getElementById('filter-modal-chain');
  3952. if (customInput && chainInput) {
  3953. chainInput.value = customInput.value.trim();
  3954. }
  3955. handleFilterChainChange();
  3956. }
  3957. function handleFilterChainChange() {
  3958. const chainInput = document.getElementById('filter-modal-chain');
  3959. const chain = (chainInput?.value || 'forward').trim().toLowerCase();
  3960. const sel = document.getElementById('filter-modal-chain-select');
  3961. if (sel && sel.value !== chain && sel.value !== '__custom__') {
  3962. if (['forward', 'input', 'output'].includes(chain)) {
  3963. sel.value = chain;
  3964. }
  3965. }
  3966. const hintEl = document.getElementById('filter-chain-hint');
  3967. if (hintEl) {
  3968. if (chain === 'forward') {
  3969. hintEl.textContent = 'FORWARD: packets routed through this router (accepts both In and Out interfaces).';
  3970. } else if (chain === 'input') {
  3971. hintEl.textContent = 'INPUT: packets destined to this router (In-Interface only; Out-Interface is invalid in iptables).';
  3972. } else if (chain === 'output') {
  3973. hintEl.textContent = 'OUTPUT: packets generated by this router (Out-Interface only; In-Interface is invalid in iptables).';
  3974. } else {
  3975. hintEl.textContent = `Custom chain "${chain}": reached via an explicit JUMP from a built-in chain.`;
  3976. }
  3977. }
  3978. const rowIn = document.getElementById('fw-row-iniface');
  3979. const rowInList = document.getElementById('fw-row-inifacelist');
  3980. const rowOut = document.getElementById('fw-row-outiface');
  3981. const rowOutList = document.getElementById('fw-row-outifacelist');
  3982. const rowInBridge = document.getElementById('fw-row-inbridgeport');
  3983. const rowOutBridge = document.getElementById('fw-row-outbridgeport');
  3984. const rowSrcMac = document.getElementById('fw-row-srcmac');
  3985. if (chain === 'input') {
  3986. if (rowIn) rowIn.classList.remove('hidden');
  3987. if (rowInList) rowInList.classList.remove('hidden');
  3988. if (rowOut) rowOut.classList.add('hidden');
  3989. if (rowOutList) rowOutList.classList.add('hidden');
  3990. if (rowInBridge) rowInBridge.classList.remove('hidden');
  3991. if (rowOutBridge) rowOutBridge.classList.add('hidden');
  3992. if (rowSrcMac) rowSrcMac.classList.remove('hidden');
  3993. } else if (chain === 'output') {
  3994. if (rowIn) rowIn.classList.add('hidden');
  3995. if (rowInList) rowInList.classList.add('hidden');
  3996. if (rowOut) rowOut.classList.remove('hidden');
  3997. if (rowOutList) rowOutList.classList.remove('hidden');
  3998. if (rowInBridge) rowInBridge.classList.add('hidden');
  3999. if (rowOutBridge) rowOutBridge.classList.remove('hidden');
  4000. if (rowSrcMac) rowSrcMac.classList.add('hidden');
  4001. } else {
  4002. if (rowIn) rowIn.classList.remove('hidden');
  4003. if (rowInList) rowInList.classList.remove('hidden');
  4004. if (rowOut) rowOut.classList.remove('hidden');
  4005. if (rowOutList) rowOutList.classList.remove('hidden');
  4006. if (rowInBridge) rowInBridge.classList.remove('hidden');
  4007. if (rowOutBridge) rowOutBridge.classList.remove('hidden');
  4008. if (rowSrcMac) rowSrcMac.classList.remove('hidden');
  4009. }
  4010. checkFilterActionChainCompatibility();
  4011. }
  4012. function checkFilterActionChainCompatibility() {
  4013. const chain = (document.getElementById('filter-modal-chain')?.value || 'forward').trim().toLowerCase();
  4014. const warnBox = document.getElementById('filter-action-incompatible-warn');
  4015. const warnMsg = document.getElementById('filter-action-incompatible-msg');
  4016. if (!warnBox || !warnMsg) return;
  4017. if (chain === 'prerouting' || chain === 'postrouting') {
  4018. warnMsg.textContent = `Chain "${chain.toUpperCase()}" is not available in the Filter table. Filter only supports INPUT, FORWARD, OUTPUT or custom chains.`;
  4019. warnBox.classList.remove('hidden');
  4020. } else {
  4021. warnBox.classList.add('hidden');
  4022. }
  4023. }
  4024. function openAddFilterModal() {
  4025. const tos = document.getElementById('fw-val-tos'); if (tos) tos.value = '';
  4026. switchFwRuleTab('general');
  4027. setFirewallDays('fw', '');
  4028. const badge = document.getElementById('fw-modal-badge');
  4029. if (badge) badge.innerText = 'New...';
  4030. document.getElementById('filter-modal-id').value = '';
  4031. document.getElementById('filter-modal-family').value = '4';
  4032. document.getElementById('filter-modal-enabled').checked = true;
  4033. document.getElementById('filter-modal-comment').value = '';
  4034. document.getElementById('filter-modal-chain').value = 'forward';
  4035. populateChainDropdown('filter', 'forward');
  4036. handleFilterChainChange();
  4037. document.getElementById('filter-modal-action').value = 'accept';
  4038. document.getElementById('filter-modal-log').checked = false;
  4039. populateInterfaceSelect('fw-val-iniface');
  4040. populateInterfaceSelect('fw-val-outiface');
  4041. populateAddressListSelect('fw-val-srclist');
  4042. populateAddressListSelect('fw-val-dstlist');
  4043. populateGeoIPSelect('fw-val-srcgeo');
  4044. populateGeoIPSelect('fw-val-dstgeo');
  4045. const allFieldKeys = [
  4046. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  4047. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  4048. 'routingmark', 'conntype', 'cs', 'natstate',
  4049. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  4050. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  4051. 'ipsec', 'tlshost', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  4052. 'pktsize', 'random', 'tcpflags', 'icmpoptions', 'ipv4options', 'ttl',
  4053. 'time', 'days', 'limit', 'dstlimit', 'psd', 'logprefix'
  4054. ];
  4055. allFieldKeys.forEach(k => toggleFwField(k, false));
  4056. resetRuleCounterDisplay();
  4057. toggleFilterActionFields();
  4058. refreshFirewallRejectTypes();
  4059. document.getElementById('filter-modal').classList.remove('hidden');
  4060. }
  4061. function openEditFilterModal(id) {
  4062. id = decodeURIComponent(id);
  4063. const r = (state.filterRules || []).find(rule => rule.id === id);
  4064. if (!r) return;
  4065. switchFwRuleTab('general');
  4066. const badge = document.getElementById('fw-modal-badge');
  4067. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  4068. document.getElementById('filter-modal-id').value = r.id;
  4069. document.getElementById('filter-modal-family').value = String(r.ip_version || 4);
  4070. document.getElementById('filter-modal-enabled').checked = !r.disabled;
  4071. document.getElementById('filter-modal-comment').value = r.comment || '';
  4072. const filterChain = r.chain || 'forward';
  4073. document.getElementById('filter-modal-chain').value = filterChain;
  4074. populateChainDropdown('filter', filterChain);
  4075. handleFilterChainChange();
  4076. setFirewallActionSelection('filter', r.action || 'accept');
  4077. document.getElementById('filter-modal-log').checked = !!r.log;
  4078. populateInterfaceSelect('fw-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  4079. populateInterfaceSelect('fw-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  4080. populateAddressListSelect('fw-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  4081. populateAddressListSelect('fw-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  4082. populateGeoIPSelect('fw-val-srcgeo', r.src_geoip || '');
  4083. populateGeoIPSelect('fw-val-dstgeo', r.dst_geoip || '');
  4084. setFwFieldVal('src', r.src_address, true);
  4085. setFwFieldVal('dst', r.dst_address, true);
  4086. setFwFieldVal('srclist', r.src_address_list, true);
  4087. setFwFieldVal('dstlist', r.dst_address_list, true);
  4088. setFwFieldVal('srcgeo', r.src_geoip, true);
  4089. setFwFieldVal('dstgeo', r.dst_geoip, true);
  4090. if (r.protocol && r.protocol !== 'all') {
  4091. setFwFieldVal('proto', r.protocol, true);
  4092. } else {
  4093. toggleFwField('proto', false);
  4094. }
  4095. setFwFieldVal('sport', r.src_port, true);
  4096. setFwFieldVal('dport', r.dst_port, true);
  4097. setFwFieldVal('anyport', r.any_port, true);
  4098. setFwFieldVal('iniface', r.in_interface, true);
  4099. setFwFieldVal('outiface', r.out_interface, true);
  4100. setFwFieldVal('inifacelist', r.in_interface_list, true);
  4101. setFwFieldVal('outifacelist', r.out_interface_list, true);
  4102. setFwFieldVal('pktmark', r.packet_mark, true);
  4103. setFwFieldVal('connmark', r.connection_mark, true);
  4104. setFwFieldVal('routingmark', r.routing_mark, true);
  4105. setFwFieldVal('conntype', r.connection_type, false);
  4106. const states = r.connection_state || [];
  4107. if (states.length > 0) {
  4108. toggleFwField('cs', true);
  4109. document.getElementById('filter-modal-cs-established').checked = states.includes('established');
  4110. document.getElementById('filter-modal-cs-related').checked = states.includes('related');
  4111. document.getElementById('filter-modal-cs-new').checked = states.includes('new');
  4112. document.getElementById('filter-modal-cs-invalid').checked = states.includes('invalid');
  4113. document.getElementById('filter-modal-cs-untracked').checked = states.includes('untracked');
  4114. } else {
  4115. toggleFwField('cs', false);
  4116. }
  4117. const natStates = r.connection_nat_state || [];
  4118. if (natStates.length > 0) {
  4119. toggleFwField('natstate', true);
  4120. document.getElementById('filter-modal-nat-srcnat').checked = natStates.includes('srcnat');
  4121. document.getElementById('filter-modal-nat-dstnat').checked = natStates.includes('dstnat');
  4122. } else {
  4123. toggleFwField('natstate', false);
  4124. }
  4125. // Advanced tab fields
  4126. setFwFieldVal('layer7', r.layer7_protocol, false);
  4127. setFwFieldVal('content', r.content, false);
  4128. setFwFieldVal('connbytes', r.connection_bytes, false);
  4129. setFwFieldVal('connrate', r.connection_rate, false);
  4130. setFwFieldVal('pcc', r.pcc, false);
  4131. setFwFieldVal('srcmac', r.src_mac_address, true);
  4132. setFwFieldVal('outbridgeport', r.out_bridge_port, false);
  4133. setFwFieldVal('inbridgeport', r.in_bridge_port, false);
  4134. setFwFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  4135. setFwFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  4136. setFwFieldVal('ipsec', r.ipsec_policy, false);
  4137. setFwFieldVal('tlshost', r.tls_host, false);
  4138. setFwFieldVal('ingresspriority', r.ingress_priority, false);
  4139. setFwFieldVal('priority', r.priority, false);
  4140. setFwFieldVal('dscp', r.dscp, false);
  4141. setFwFieldVal('tcpmss', r.tcp_mss, false);
  4142. { const tosEl = document.getElementById('fw-val-tos'); if (tosEl) tosEl.value = r.tos || ''; }
  4143. setFwFieldVal('pktsize', r.packet_size, false);
  4144. setFwFieldVal('random', r.random, false);
  4145. setFwFieldVal('tcpflags', r.tcp_flags, false);
  4146. setFwFieldVal('icmpoptions', r.icmp_options, false);
  4147. setFwFieldVal('ipv4options', r.ipv4_options, false);
  4148. setFwFieldVal('ttl', r.ttl, false);
  4149. // Extra tab fields
  4150. setFwFieldVal('time', r.time, false);
  4151. if (r.days) {
  4152. toggleFwField('days', true);
  4153. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  4154. const chk = document.getElementById(`fw-day-${d}`);
  4155. if (chk) chk.checked = r.days.toLowerCase().includes(d);
  4156. });
  4157. } else {
  4158. toggleFwField('days', false);
  4159. }
  4160. setFwFieldVal('limit', r.limit, false);
  4161. setFwFieldVal('dstlimit', r.dst_limit, false);
  4162. setFwFieldVal('psd', r.psd, false);
  4163. // Action fields
  4164. if (r.reject_with) {
  4165. const rwEl = document.getElementById('filter-modal-rejectwith');
  4166. if (rwEl) rwEl.value = r.reject_with;
  4167. }
  4168. if (r.jump_target) {
  4169. const jtEl = document.getElementById('filter-modal-jumptarget');
  4170. if (jtEl) jtEl.value = r.jump_target;
  4171. }
  4172. if (r.address_list) {
  4173. const alEl = document.getElementById('filter-modal-action-addrlist');
  4174. if (alEl) alEl.value = r.address_list;
  4175. }
  4176. if (r.address_list_timeout) {
  4177. const toEl = document.getElementById('filter-modal-action-timeout');
  4178. if (toEl) toEl.value = r.address_list_timeout;
  4179. }
  4180. setFwFieldVal('logprefix', r.log_prefix, false);
  4181. // Statistics
  4182. const bEl = document.getElementById('fw-stat-bytes');
  4183. const pEl = document.getElementById('fw-stat-packets');
  4184. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  4185. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  4186. state.fwLastBytes = r.bytes || 0;
  4187. state.fwLastPackets = r.packets || 0;
  4188. state.fwLastTimestamp = Date.now();
  4189. state.fwStatRateHistory = new Array(30).fill(0);
  4190. state.fwStatPktHistory = new Array(30).fill(0);
  4191. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  4192. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  4193. toggleFilterActionFields();
  4194. refreshFirewallRejectTypes();
  4195. document.getElementById('filter-modal').classList.remove('hidden');
  4196. }
  4197. function closeFilterModal() {
  4198. stopFwStatPolling();
  4199. document.getElementById('filter-modal').classList.add('hidden');
  4200. }
  4201. function toggleFilterActionFields() {
  4202. const act = document.getElementById('filter-modal-action')?.value || 'accept';
  4203. const rejectBox = document.getElementById('filter-action-reject-box');
  4204. const jumpBox = document.getElementById('filter-action-jump-box');
  4205. const addrBox = document.getElementById('filter-action-addrlist-box');
  4206. if (rejectBox) {
  4207. if (act === 'reject') rejectBox.classList.remove('hidden');
  4208. else rejectBox.classList.add('hidden');
  4209. }
  4210. if (jumpBox) {
  4211. if (act === 'jump') jumpBox.classList.remove('hidden');
  4212. else jumpBox.classList.add('hidden');
  4213. }
  4214. if (addrBox) {
  4215. if (act === 'add-dst-to-address-list' || act === 'add-src-to-address-list' || act.includes('address-list') || act.includes('address list')) {
  4216. addrBox.classList.remove('hidden');
  4217. } else {
  4218. addrBox.classList.add('hidden');
  4219. }
  4220. }
  4221. if (act === 'log') {
  4222. const logEl = document.getElementById('filter-modal-log');
  4223. if (logEl) logEl.checked = true;
  4224. toggleFwField('logprefix', true);
  4225. }
  4226. }
  4227. function toggleFwLogPrefix() {
  4228. const isLog = document.getElementById('filter-modal-log')?.checked;
  4229. toggleFwField('logprefix', !!isLog);
  4230. }
  4231. function copyFilterRule() {
  4232. document.getElementById('filter-modal-id').value = '';
  4233. const badge = document.getElementById('fw-modal-badge');
  4234. if (badge) badge.innerText = 'New...';
  4235. showToast('Rule Cloned', 'Ready to save as a new rule copy', 'info');
  4236. }
  4237. function resetRuleCounterDisplay() {
  4238. state.fwStatRateHistory = new Array(30).fill(0);
  4239. state.fwStatPktHistory = new Array(30).fill(0);
  4240. state.fwLastBytes = 0;
  4241. state.fwLastPackets = 0;
  4242. state.fwLastTimestamp = Date.now();
  4243. const bEl = document.getElementById('fw-stat-bytes');
  4244. const pEl = document.getElementById('fw-stat-packets');
  4245. const rEl = document.getElementById('fw-stat-rate');
  4246. const prEl = document.getElementById('fw-stat-pktrate');
  4247. if (bEl) bEl.value = '0 B';
  4248. if (pEl) pEl.value = '0';
  4249. if (rEl) rEl.value = '0 bps';
  4250. if (prEl) prEl.value = '0 p/s';
  4251. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  4252. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  4253. showToast('Counters Reset', 'Rule counter display reset to 0', 'info');
  4254. }
  4255. async function resetAllFwCounters() {
  4256. try {
  4257. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  4258. if (res.ok) {
  4259. resetRuleCounterDisplay();
  4260. showToast('All Counters Reset', 'All firewall counters zeroed', 'success');
  4261. loadFirewall(false);
  4262. }
  4263. } catch (err) {
  4264. showToast('Error', err.message, 'error');
  4265. }
  4266. }
  4267. async function applyFilterRule(closeAfter = false) {
  4268. const id = document.getElementById('filter-modal-id').value;
  4269. if (!reviewLegacyFirewallSettings('filter', id)) return;
  4270. let selectedDays; try { selectedDays = getFirewallDays('fw'); } catch(error) { showToast('Error', error.message, 'error'); return; }
  4271. const chain = (document.getElementById('filter-modal-chain').value || '').trim();
  4272. const chainLower = chain.toLowerCase();
  4273. if (!chain) { switchFwRuleTab('general'); showToast('Filter Rule', 'A valid chain is required.', 'error'); document.getElementById('filter-modal-chain').focus(); return; }
  4274. if (chainLower === 'prerouting' || chainLower === 'postrouting') {
  4275. switchFwRuleTab('general');
  4276. showToast('Invalid Chain', `Chain "${chain.toUpperCase()}" is not available in the Filter table in iptables.`, 'error');
  4277. return;
  4278. }
  4279. const action = document.getElementById('filter-modal-action').value;
  4280. const comment = document.getElementById('filter-modal-comment').value.trim();
  4281. const enabled = document.getElementById('filter-modal-enabled').checked;
  4282. const src = getFwFieldVal('src', true);
  4283. const dst = getFwFieldVal('dst', true);
  4284. const srclist = getFwFieldVal('srclist', true);
  4285. const dstlist = getFwFieldVal('dstlist', true);
  4286. const srcgeo = getFwFieldVal('srcgeo', true);
  4287. const dstgeo = getFwFieldVal('dstgeo', true);
  4288. const proto = getFwFieldVal('proto', true);
  4289. const sport = getFwFieldVal('sport', true);
  4290. const dport = getFwFieldVal('dport', true);
  4291. const anyport = getFwFieldVal('anyport', true);
  4292. if ((sport || dport || anyport) && !['tcp', 'udp'].includes(proto)) {
  4293. switchFwRuleTab('general'); toggleFwField('proto', true);
  4294. showToast('Select protocol', 'Port matches require TCP or UDP without protocol inversion.', 'error'); document.getElementById('fw-val-proto').focus(); return;
  4295. }
  4296. let iniface = getFwFieldVal('iniface', true);
  4297. let outiface = getFwFieldVal('outiface', true);
  4298. let inifacelist = getFwFieldVal('inifacelist', true);
  4299. let outifacelist = getFwFieldVal('outifacelist', true);
  4300. if (chainLower === 'input') {
  4301. outiface = '';
  4302. outifacelist = '';
  4303. } else if (chainLower === 'output') {
  4304. iniface = '';
  4305. inifacelist = '';
  4306. }
  4307. const pktmark = getFwFieldVal('pktmark', true);
  4308. const connmark = getFwFieldVal('connmark', true);
  4309. const routingmark = getFwFieldVal('routingmark', true);
  4310. const conntype = getFwFieldVal('conntype', false);
  4311. const states = [];
  4312. const csBox = document.getElementById('fw-field-cs');
  4313. if (csBox && !csBox.classList.contains('hidden')) {
  4314. if (document.getElementById('filter-modal-cs-established')?.checked) states.push('established');
  4315. if (document.getElementById('filter-modal-cs-related')?.checked) states.push('related');
  4316. if (document.getElementById('filter-modal-cs-new')?.checked) states.push('new');
  4317. if (document.getElementById('filter-modal-cs-invalid')?.checked) states.push('invalid');
  4318. if (document.getElementById('filter-modal-cs-untracked')?.checked) states.push('untracked');
  4319. }
  4320. const natStates = [];
  4321. const natBox = document.getElementById('fw-field-natstate');
  4322. if (natBox && !natBox.classList.contains('hidden')) {
  4323. if (document.getElementById('filter-modal-nat-srcnat')?.checked) natStates.push('srcnat');
  4324. if (document.getElementById('filter-modal-nat-dstnat')?.checked) natStates.push('dstnat');
  4325. }
  4326. const payload = {
  4327. ip_version: Number(document.getElementById('filter-modal-family').value),
  4328. id,
  4329. chain,
  4330. action,
  4331. protocol: proto || 'all',
  4332. src_address: src,
  4333. dst_address: dst,
  4334. src_port: sport,
  4335. dst_port: dport,
  4336. any_port: anyport,
  4337. in_interface: iniface,
  4338. out_interface: outiface,
  4339. in_interface_list: inifacelist,
  4340. out_interface_list: outifacelist,
  4341. packet_mark: pktmark,
  4342. connection_mark: connmark,
  4343. routing_mark: routingmark,
  4344. connection_type: conntype,
  4345. connection_state: states,
  4346. connection_nat_state: natStates,
  4347. src_address_list: srclist,
  4348. dst_address_list: dstlist,
  4349. src_geoip: srcgeo,
  4350. dst_geoip: dstgeo,
  4351. comment,
  4352. disabled: !enabled,
  4353. // Advanced tab
  4354. content: getFwFieldVal('content', false),
  4355. src_mac_address: chainLower === 'output' ? '' : getFwFieldVal('srcmac', true),
  4356. out_bridge_port: chainLower === 'input' ? '' : getFwFieldVal('outbridgeport', false),
  4357. in_bridge_port: chainLower === 'output' ? '' : getFwFieldVal('inbridgeport', false),
  4358. ipsec_policy: getFwFieldVal('ipsec', false),
  4359. dscp: getFwFieldVal('dscp', false),
  4360. tcp_mss: getFwFieldVal('tcpmss', false),
  4361. tos: document.getElementById('fw-val-tos')?.value || '',
  4362. packet_size: getFwFieldVal('pktsize', false),
  4363. random: getFwFieldVal('random', false),
  4364. tcp_flags: getFwFieldVal('tcpflags', false),
  4365. icmp_options: getFwFieldVal('icmpoptions', false),
  4366. ttl: getFwFieldVal('ttl', false),
  4367. days: selectedDays,
  4368. // Extra tab
  4369. time: getFwFieldVal('time', false),
  4370. limit: getFwFieldVal('limit', false),
  4371. // Action tab
  4372. reject_with: action === 'reject' ? (document.getElementById('filter-modal-rejectwith')?.value || '') : '',
  4373. jump_target: action === 'jump' ? (document.getElementById('filter-modal-jumptarget')?.value || '') : '',
  4374. address_list: action.startsWith('add-') ? (document.getElementById('filter-modal-action-addrlist')?.value || '') : '',
  4375. address_list_timeout: action.startsWith('add-') ? (document.getElementById('filter-modal-action-timeout')?.value || '') : '',
  4376. log: document.getElementById('filter-modal-log')?.checked || false,
  4377. log_prefix: getFwFieldVal('logprefix', false)
  4378. };
  4379. try {
  4380. const res = await fetch(`${API_BASE}/firewall/filter`, {
  4381. method: 'POST',
  4382. headers: { 'Content-Type': 'application/json' },
  4383. body: JSON.stringify(payload)
  4384. });
  4385. if (res.ok) {
  4386. const data = await res.json();
  4387. showToast('Filter Rule Saved', 'Rule applied successfully to firewall', 'success');
  4388. loadFirewall(false);
  4389. if (closeAfter) {
  4390. closeFilterModal();
  4391. } else {
  4392. if (data.id) {
  4393. document.getElementById('filter-modal-id').value = data.id;
  4394. const badge = document.getElementById('fw-modal-badge');
  4395. if (badge) badge.innerText = `#${data.id}`;
  4396. }
  4397. }
  4398. } else {
  4399. const err = await res.json();
  4400. showToast('Error', err.message || 'Failed to save rule', 'error');
  4401. }
  4402. } catch (err) {
  4403. showToast('Error', err.message, 'error');
  4404. }
  4405. }
  4406. function submitSaveFilterRule(e) {
  4407. if (e && e.preventDefault) e.preventDefault();
  4408. return applyFilterRule(true);
  4409. }
  4410. function startFwStatPolling() {
  4411. stopFwStatPolling();
  4412. pollRuleStats();
  4413. state.fwStatInterval = setInterval(pollRuleStats, 1000);
  4414. }
  4415. function stopFwStatPolling() {
  4416. if (state.fwStatInterval) {
  4417. clearInterval(state.fwStatInterval);
  4418. state.fwStatInterval = null;
  4419. }
  4420. }
  4421. async function pollRuleStats() {
  4422. const id = document.getElementById('filter-modal-id')?.value;
  4423. if (!id) {
  4424. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory || new Array(30).fill(0), 'bps', 'fw-stat-legend-rate');
  4425. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory || new Array(30).fill(0), 'p/s', 'fw-stat-legend-pktrate');
  4426. return;
  4427. }
  4428. try {
  4429. const res = await fetch(`${API_BASE}/firewall/filter`);
  4430. if (!res.ok) return;
  4431. const rules = await res.json();
  4432. const r = rules.find(x => x.id === id);
  4433. if (!r) return;
  4434. const now = Date.now();
  4435. const dt = Math.max(0.2, (now - (state.fwLastTimestamp || now)) / 1000);
  4436. state.fwLastTimestamp = now;
  4437. const curBytes = r.bytes || 0;
  4438. const curPackets = r.packets || 0;
  4439. const deltaBytes = Math.max(0, curBytes - (state.fwLastBytes ?? curBytes));
  4440. const deltaPkts = Math.max(0, curPackets - (state.fwLastPackets ?? curPackets));
  4441. state.fwLastBytes = curBytes;
  4442. state.fwLastPackets = curPackets;
  4443. const rateBps = Math.round((deltaBytes * 8) / dt);
  4444. const ratePkt = Math.round(deltaPkts / dt);
  4445. if (!state.fwStatRateHistory) state.fwStatRateHistory = new Array(30).fill(0);
  4446. if (!state.fwStatPktHistory) state.fwStatPktHistory = new Array(30).fill(0);
  4447. state.fwStatRateHistory.push(rateBps);
  4448. if (state.fwStatRateHistory.length > 30) state.fwStatRateHistory.shift();
  4449. state.fwStatPktHistory.push(ratePkt);
  4450. if (state.fwStatPktHistory.length > 30) state.fwStatPktHistory.shift();
  4451. const bEl = document.getElementById('fw-stat-bytes');
  4452. const pEl = document.getElementById('fw-stat-packets');
  4453. const rEl = document.getElementById('fw-stat-rate');
  4454. const prEl = document.getElementById('fw-stat-pktrate');
  4455. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  4456. if (pEl) pEl.value = curPackets.toLocaleString();
  4457. if (rEl) rEl.value = formatBps(rateBps);
  4458. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  4459. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  4460. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  4461. } catch (e) {
  4462. console.error('Error polling rule stats', e);
  4463. }
  4464. }
  4465. function formatBps(bps) {
  4466. if (bps >= 1000000000) return (bps / 1000000000).toFixed(1) + ' Gbps';
  4467. if (bps >= 1000000) return (bps / 1000000).toFixed(1) + ' Mbps';
  4468. if (bps >= 1000) return (bps / 1000).toFixed(1) + ' kbps';
  4469. return bps + ' bps';
  4470. }
  4471. function renderFwSparkline(svgId, dataArray, unit, legendId) {
  4472. const svg = document.getElementById(svgId);
  4473. if (!svg) return;
  4474. const w = 500;
  4475. const h = 100;
  4476. const paddingRight = 45;
  4477. const graphWidth = w - paddingRight;
  4478. const maxVal = Math.max(5, ...dataArray);
  4479. const currentVal = dataArray[dataArray.length - 1] || 0;
  4480. const leg = document.getElementById(legendId);
  4481. if (leg) {
  4482. leg.innerText = unit === 'bps' ? formatBps(currentVal) : `${currentVal.toLocaleString()} p/s`;
  4483. }
  4484. let gridLines = '';
  4485. for (let i = 0; i <= 5; i++) {
  4486. const y = 8 + (i * (h - 18) / 5);
  4487. const valAtLevel = Math.round(maxVal * (5 - i) / 5);
  4488. const label = unit === 'bps' ? formatBps(valAtLevel) : `${valAtLevel} p/s`;
  4489. gridLines += `
  4490. <line x1="0" y1="${y.toFixed(1)}" x2="${graphWidth}" y2="${y.toFixed(1)}" stroke="#1e2c3e" stroke-width="1" />
  4491. <text x="${w - 2}" y="${(y + 3).toFixed(1)}" fill="#64748b" font-size="9" font-family="monospace" text-anchor="end">${label}</text>
  4492. `;
  4493. }
  4494. const step = graphWidth / (dataArray.length - 1);
  4495. const points = dataArray.map((val, idx) => {
  4496. const x = idx * step;
  4497. const y = (h - 10) - (val / maxVal) * (h - 20);
  4498. return `${x.toFixed(1)},${y.toFixed(1)}`;
  4499. });
  4500. const polylineStr = points.join(' ');
  4501. const areaPath = `M 0,${h - 10} L ${polylineStr} L ${graphWidth},${h - 10} Z`;
  4502. svg.innerHTML = `
  4503. ${gridLines}
  4504. <path d="${areaPath}" fill="rgba(14, 165, 233, 0.12)" />
  4505. <polyline fill="none" stroke="#38bdf8" stroke-width="1.8" stroke-linejoin="round" points="${polylineStr}" />
  4506. <circle cx="${graphWidth}" cy="${points[points.length - 1].split(',')[1]}" r="3" fill="#38bdf8" />
  4507. `;
  4508. }
  4509. async function moveFilterRule(id, dir) {
  4510. id = decodeURIComponent(id);
  4511. try {
  4512. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/move`, {
  4513. method: 'POST',
  4514. headers: { 'Content-Type': 'application/json' },
  4515. body: JSON.stringify({ direction: dir })
  4516. });
  4517. if (!res.ok) throw new Error(await responseError(res));
  4518. await loadFirewall(false);
  4519. } catch (err) {
  4520. showToast('Error', err.message, 'error');
  4521. }
  4522. }
  4523. async function toggleFilterRuleState(id, disabled) {
  4524. id = decodeURIComponent(id);
  4525. try {
  4526. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/state`, {
  4527. method: 'POST',
  4528. headers: { 'Content-Type': 'application/json' },
  4529. body: JSON.stringify({ disabled })
  4530. });
  4531. if (!res.ok) throw new Error(await responseError(res));
  4532. await loadFirewall(false);
  4533. } catch (err) {
  4534. showToast('Error', err.message, 'error');
  4535. }
  4536. }
  4537. async function deleteFilterRule(id) {
  4538. id = decodeURIComponent(id);
  4539. if (!confirm('Are you sure you want to delete this filter rule?')) return;
  4540. try {
  4541. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4542. if (!res.ok) throw new Error(await responseError(res));
  4543. {
  4544. showToast('Deleted', 'Filter rule removed', 'success');
  4545. loadFirewall(false);
  4546. }
  4547. } catch (err) {
  4548. showToast('Error', err.message, 'error');
  4549. }
  4550. }
  4551. // ----------------- NAT Rules -----------------
  4552. function renderNATRules() {
  4553. const chainFilter = document.getElementById('nat-filter-chain')?.value || '';
  4554. const tbody = document.getElementById('nat-table-body');
  4555. const empty = document.getElementById('nat-empty');
  4556. if (!tbody) return;
  4557. tbody.innerHTML = '';
  4558. const rules = (state.natRules || []).filter(r => !chainFilter || nativeNATChain(r.chain) === chainFilter);
  4559. document.getElementById('nat-count-badge').innerText = `${rules.length} Rules`;
  4560. if (rules.length === 0) {
  4561. empty?.classList.remove('hidden');
  4562. return;
  4563. }
  4564. empty?.classList.add('hidden');
  4565. rules.forEach((raw, idx) => {
  4566. const r = safeFirewallRow(raw);
  4567. const tr = document.createElement('tr');
  4568. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  4569. let toTarget = '-';
  4570. if (r.action === 'jump') {
  4571. toTarget = `<span class="text-yellow-300 font-mono font-bold">&rarr; ${r.jump_target || '-'}</span>`;
  4572. } else if (r.action.includes('address-list') || r.action.includes('address list')) {
  4573. toTarget = `<span class="text-emerald-300 font-mono font-bold">&rarr; ${r.address_list || '-'}</span>`;
  4574. } else if (r.action === 'redirect') {
  4575. toTarget = `<span class="text-amber-300 font-mono font-bold">ports:${r.to_ports || 'all'}</span>`;
  4576. } else if (r.action === 'masquerade') {
  4577. 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>`;
  4578. } else if (r.action === 'log') {
  4579. toTarget = `<span class="text-slate-400 font-mono font-bold">${r.log_prefix || 'log'}</span>`;
  4580. } else {
  4581. const parts = [r.to_addresses, r.to_ports].filter(Boolean);
  4582. toTarget = parts.length ? `<span class="text-amber-300 font-mono font-bold">${parts.join(':')}</span>` : '-';
  4583. }
  4584. 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(' ');
  4585. tr.innerHTML = `
  4586. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  4587. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  4588. <td class="py-2.5 px-3 font-bold text-amber-400">${escapeHtml(nativeNATChain(raw.chain).toUpperCase())}</td>
  4589. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  4590. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  4591. <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>
  4592. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  4593. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  4594. <td class="py-2.5 px-3 font-mono text-xs">${toTarget}</td>
  4595. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  4596. <span class="text-slate-300" id="nat-pkts-${r.id}">${(r.packets || 0).toLocaleString()}p</span> /
  4597. <span class="text-slate-500" id="nat-bytes-${r.id}">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  4598. </td>
  4599. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  4600. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  4601. <button onclick="moveNATRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  4602. <button onclick="moveNATRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  4603. <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>
  4604. <button onclick="openEditNATModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  4605. <button onclick="deleteNATRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  4606. </td>
  4607. `;
  4608. tbody.appendChild(tr);
  4609. });
  4610. }
  4611. // ==================== FIREWALL NAT MODAL (DEBTIK WEBFIG / WINBOX V4) ====================
  4612. function switchNATRuleTab(tab) {
  4613. if (!document.getElementById(`nat-pane-${tab}`)) tab = 'general';
  4614. state.activeNATRuleTab = tab;
  4615. document.querySelectorAll('.nat-rule-tab-btn').forEach(btn => {
  4616. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  4617. btn.classList.add('text-slate-400', 'border-transparent');
  4618. });
  4619. const activeBtn = document.getElementById(`nat-tab-btn-${tab}`);
  4620. if (activeBtn) {
  4621. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  4622. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  4623. }
  4624. document.querySelectorAll('.nat-rule-pane').forEach(p => p.classList.add('hidden'));
  4625. const activePane = document.getElementById(`nat-pane-${tab}`);
  4626. if (activePane) activePane.classList.remove('hidden');
  4627. if (tab === 'statistics') {
  4628. startNATStatPolling();
  4629. } else {
  4630. stopNATStatPolling();
  4631. }
  4632. }
  4633. function toggleNATField(fieldKey, expand) {
  4634. const plusBtn = document.getElementById(`nat-plus-${fieldKey}`);
  4635. const fieldBox = document.getElementById(`nat-field-${fieldKey}`);
  4636. if (!plusBtn || !fieldBox) return;
  4637. if (expand) {
  4638. plusBtn.classList.add('hidden');
  4639. fieldBox.classList.remove('hidden');
  4640. const valInput = document.getElementById(`nat-val-${fieldKey}`);
  4641. if (valInput) valInput.focus();
  4642. } else {
  4643. fieldBox.classList.add('hidden');
  4644. plusBtn.classList.remove('hidden');
  4645. const valInput = document.getElementById(`nat-val-${fieldKey}`);
  4646. if (valInput) {
  4647. if (valInput.tagName === 'SELECT') {
  4648. valInput.selectedIndex = 0;
  4649. } else {
  4650. valInput.value = '';
  4651. }
  4652. }
  4653. const invInput = document.getElementById(`nat-inv-${fieldKey}`);
  4654. if (invInput) invInput.checked = false;
  4655. if (fieldKey === 'days') {
  4656. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  4657. const el = document.getElementById(`nat-day-${d}`);
  4658. if (el) el.checked = true;
  4659. });
  4660. }
  4661. }
  4662. }
  4663. function setNATFieldVal(fieldKey, value, hasInvert = false) {
  4664. if (fieldKey === 'ipsec' && typeof value === 'string') value = value.replace(':', ',');
  4665. if (value !== undefined && value !== null && value !== '' && !(fieldKey === 'proto' && value === 'all')) {
  4666. toggleNATField(fieldKey, true);
  4667. let strVal = String(value);
  4668. if (hasInvert) {
  4669. const inv = strVal.startsWith('!');
  4670. if (inv) strVal = strVal.slice(1);
  4671. const invEl = document.getElementById(`nat-inv-${fieldKey}`);
  4672. if (invEl) invEl.checked = inv;
  4673. else if (inv) strVal = '!'+strVal;
  4674. }
  4675. const valEl = document.getElementById(`nat-val-${fieldKey}`);
  4676. 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; }
  4677. } else {
  4678. toggleNATField(fieldKey, false);
  4679. }
  4680. }
  4681. function getNATFieldVal(fieldKey, hasInvert = false) {
  4682. const fieldBox = document.getElementById(`nat-field-${fieldKey}`);
  4683. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  4684. const valEl = document.getElementById(`nat-val-${fieldKey}`);
  4685. let v = valEl ? valEl.value.trim() : '';
  4686. if (!v) return '';
  4687. if (hasInvert) {
  4688. const invEl = document.getElementById(`nat-inv-${fieldKey}`);
  4689. if (invEl && invEl.checked) {
  4690. v = '!' + v.replace(/^!/, '');
  4691. }
  4692. }
  4693. return v;
  4694. }
  4695. function toggleMaximizeNATModal() {
  4696. const win = document.getElementById('nat-modal-window');
  4697. if (!win) return;
  4698. if (win.classList.contains('max-w-[720px]')) {
  4699. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  4700. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  4701. } else {
  4702. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  4703. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  4704. }
  4705. }
  4706. function syncNATChainFromSelect() {
  4707. const sel = document.getElementById('nat-modal-chain-select');
  4708. const customWrap = document.getElementById('nat-modal-custom-wrap');
  4709. const customInput = document.getElementById('nat-modal-custom-input');
  4710. const chainInput = document.getElementById('nat-modal-chain');
  4711. if (!sel || !chainInput) return;
  4712. if (sel.value === '__custom__') {
  4713. if (customWrap) customWrap.classList.remove('hidden');
  4714. if (customInput) {
  4715. customInput.value = '';
  4716. customInput.focus();
  4717. }
  4718. chainInput.value = '';
  4719. } else {
  4720. if (customWrap) customWrap.classList.add('hidden');
  4721. chainInput.value = sel.value;
  4722. const actEl = document.getElementById('nat-modal-action');
  4723. if (actEl) {
  4724. const curAct = actEl.value;
  4725. if (sel.value === 'prerouting' && ['masquerade', 'src-nat'].includes(curAct)) {
  4726. actEl.value = 'dst-nat';
  4727. } else if (sel.value === 'postrouting' && ['dst-nat', 'redirect'].includes(curAct)) {
  4728. actEl.value = 'masquerade';
  4729. }
  4730. }
  4731. }
  4732. handleNATChainChange();
  4733. }
  4734. function syncNATCustomChainInput() {
  4735. const customInput = document.getElementById('nat-modal-custom-input');
  4736. const chainInput = document.getElementById('nat-modal-chain');
  4737. if (customInput && chainInput) {
  4738. chainInput.value = customInput.value.trim();
  4739. }
  4740. handleNATChainChange();
  4741. }
  4742. function handleNATChainChange() {
  4743. const chainInput = document.getElementById('nat-modal-chain');
  4744. const rawChain = (chainInput?.value || 'postrouting').trim();
  4745. const chain = nativeNATChain(rawChain).toLowerCase();
  4746. const sel = document.getElementById('nat-modal-chain-select');
  4747. if (sel && sel.value !== chain && sel.value !== '__custom__') {
  4748. if (['postrouting', 'prerouting', 'output', 'input'].includes(chain)) {
  4749. sel.value = chain;
  4750. }
  4751. }
  4752. const hintEl = document.getElementById('nat-chain-hint');
  4753. if (hintEl) {
  4754. if (chain === 'prerouting') {
  4755. hintEl.textContent = 'PREROUTING: destination NAT (DNAT / REDIRECT) before routing decision (In-Interface only).';
  4756. } else if (chain === 'postrouting') {
  4757. hintEl.textContent = 'POSTROUTING: source NAT (SNAT / MASQUERADE) after routing decision (Out-Interface only).';
  4758. } else if (chain === 'output') {
  4759. hintEl.textContent = 'OUTPUT: destination NAT for locally generated packets (Out-Interface only).';
  4760. } else if (chain === 'input') {
  4761. hintEl.textContent = 'INPUT: source NAT for packets destined to local sockets (In-Interface only).';
  4762. } else {
  4763. hintEl.textContent = `Custom chain "${rawChain}": user-defined NAT chain reached via JUMP.`;
  4764. }
  4765. }
  4766. const rowIn = document.getElementById('nat-row-iniface');
  4767. const rowInList = document.getElementById('nat-row-inifacelist');
  4768. const rowOut = document.getElementById('nat-row-outiface');
  4769. const rowOutList = document.getElementById('nat-row-outifacelist');
  4770. const rowInBridge = document.getElementById('nat-row-inbridgeport');
  4771. const rowOutBridge = document.getElementById('nat-row-outbridgeport');
  4772. const rowSrcMac = document.getElementById('nat-row-srcmac');
  4773. if (chain === 'prerouting' || chain === 'input') {
  4774. if (rowIn) rowIn.classList.remove('hidden');
  4775. if (rowInList) rowInList.classList.remove('hidden');
  4776. if (rowOut) rowOut.classList.add('hidden');
  4777. if (rowOutList) rowOutList.classList.add('hidden');
  4778. if (rowInBridge) rowInBridge.classList.remove('hidden');
  4779. if (rowOutBridge) rowOutBridge.classList.add('hidden');
  4780. if (rowSrcMac) rowSrcMac.classList.remove('hidden');
  4781. } else if (chain === 'postrouting' || chain === 'output') {
  4782. if (rowIn) rowIn.classList.add('hidden');
  4783. if (rowInList) rowInList.classList.add('hidden');
  4784. if (rowOut) rowOut.classList.remove('hidden');
  4785. if (rowOutList) rowOutList.classList.remove('hidden');
  4786. if (rowInBridge) rowInBridge.classList.add('hidden');
  4787. if (rowOutBridge) rowOutBridge.classList.remove('hidden');
  4788. if (rowSrcMac) rowSrcMac.classList.add('hidden');
  4789. } else {
  4790. if (rowIn) rowIn.classList.remove('hidden');
  4791. if (rowInList) rowInList.classList.remove('hidden');
  4792. if (rowOut) rowOut.classList.remove('hidden');
  4793. if (rowOutList) rowOutList.classList.remove('hidden');
  4794. if (rowInBridge) rowInBridge.classList.remove('hidden');
  4795. if (rowOutBridge) rowOutBridge.classList.remove('hidden');
  4796. if (rowSrcMac) rowSrcMac.classList.remove('hidden');
  4797. }
  4798. checkNATActionChainCompatibility();
  4799. toggleNATActionFields();
  4800. }
  4801. function checkNATActionChainCompatibility() {
  4802. const rawChain = (document.getElementById('nat-modal-chain')?.value || 'postrouting').trim();
  4803. const chain = nativeNATChain(rawChain).toLowerCase();
  4804. const action = (document.getElementById('nat-modal-action')?.value || '').toLowerCase();
  4805. const warnBox = document.getElementById('nat-action-incompatible-warn');
  4806. const warnMsg = document.getElementById('nat-action-incompatible-msg');
  4807. if (!warnBox || !warnMsg) return;
  4808. let msg = '';
  4809. if (['dst-nat', 'redirect'].includes(action)) {
  4810. if (chain !== 'prerouting' && chain !== 'output') {
  4811. msg = `${action === 'dst-nat' ? 'DNAT' : 'REDIRECT'} is only valid in PREROUTING or OUTPUT chains in iptables (current chain: ${chain.toUpperCase()}).`;
  4812. }
  4813. } else if (action === 'masquerade') {
  4814. if (chain !== 'postrouting') {
  4815. msg = `MASQUERADE is only valid in the POSTROUTING chain in iptables (current chain: ${chain.toUpperCase()}).`;
  4816. }
  4817. } else if (action === 'src-nat') {
  4818. if (chain !== 'postrouting' && chain !== 'input') {
  4819. msg = `SNAT is only valid in POSTROUTING or INPUT chains in iptables (current chain: ${chain.toUpperCase()}).`;
  4820. }
  4821. }
  4822. if (msg) {
  4823. warnMsg.textContent = msg;
  4824. warnBox.classList.remove('hidden');
  4825. } else {
  4826. warnBox.classList.add('hidden');
  4827. }
  4828. }
  4829. function toggleNATActionFields() {
  4830. const act = document.getElementById('nat-modal-action')?.value || 'masquerade';
  4831. const rowAddr = document.getElementById('nat-row-toaddr');
  4832. const rowPort = document.getElementById('nat-row-toport');
  4833. const jumpBox = document.getElementById('nat-action-jump-box');
  4834. const addrBox = document.getElementById('nat-action-addrlist-box');
  4835. // Hide all dynamic rows first
  4836. if (rowAddr) rowAddr.classList.add('hidden');
  4837. if (rowPort) rowPort.classList.add('hidden');
  4838. if (jumpBox) jumpBox.classList.add('hidden');
  4839. if (addrBox) addrBox.classList.add('hidden');
  4840. if (['src-nat', 'dst-nat', 'netmap'].includes(act)) {
  4841. if (rowAddr) rowAddr.classList.remove('hidden');
  4842. if (rowPort && act !== 'netmap') rowPort.classList.remove('hidden');
  4843. } else if (act === 'redirect' || act === 'masquerade') {
  4844. if (rowPort) rowPort.classList.remove('hidden');
  4845. } else if (act === 'jump') {
  4846. if (jumpBox) jumpBox.classList.remove('hidden');
  4847. } else if (act.includes('address-list') || act.includes('address list')) {
  4848. if (addrBox) addrBox.classList.remove('hidden');
  4849. }
  4850. if (act === 'log') {
  4851. const logEl = document.getElementById('nat-modal-log');
  4852. if (logEl) logEl.checked = true;
  4853. toggleNATField('logprefix', true);
  4854. }
  4855. }
  4856. function handleNATActionChange() {
  4857. toggleNATActionFields();
  4858. checkNATActionChainCompatibility();
  4859. }
  4860. function toggleNATLogPrefix() {
  4861. const isLog = document.getElementById('nat-modal-log')?.checked;
  4862. toggleNATField('logprefix', !!isLog);
  4863. }
  4864. function openAddNATModal() {
  4865. const tos = document.getElementById('nat-val-tos'); if (tos) tos.value = '';
  4866. switchNATRuleTab('general');
  4867. setFirewallDays('nat', '');
  4868. const badge = document.getElementById('nat-modal-badge');
  4869. if (badge) badge.innerText = 'New...';
  4870. document.getElementById('nat-modal-id').value = '';
  4871. document.getElementById('nat-modal-family').value = '4';
  4872. document.getElementById('nat-modal-enabled').checked = true;
  4873. document.getElementById('nat-modal-comment').value = '';
  4874. document.getElementById('nat-modal-chain').value = 'postrouting';
  4875. populateChainDropdown('nat', 'postrouting');
  4876. handleNATChainChange();
  4877. document.getElementById('nat-modal-action').value = 'masquerade';
  4878. document.getElementById('nat-modal-toaddr').value = '';
  4879. document.getElementById('nat-modal-toport').value = '';
  4880. document.getElementById('nat-modal-log').checked = false;
  4881. populateInterfaceSelect('nat-val-iniface');
  4882. populateInterfaceSelect('nat-val-outiface');
  4883. populateAddressListSelect('nat-val-srclist');
  4884. populateAddressListSelect('nat-val-dstlist');
  4885. populateGeoIPSelect('nat-val-srcgeo');
  4886. populateGeoIPSelect('nat-val-dstgeo');
  4887. const allFieldKeys = [
  4888. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  4889. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  4890. 'routingmark', 'conntype',
  4891. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  4892. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  4893. 'ipsec', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  4894. 'pktsize', 'random', 'icmpoptions', 'ipv4options', 'ttl',
  4895. 'time', 'days', 'limit', 'dstlimit', 'psd', 'logprefix'
  4896. ];
  4897. allFieldKeys.forEach(k => toggleNATField(k, false));
  4898. resetNATCounterDisplay();
  4899. toggleNATActionFields();
  4900. document.getElementById('nat-modal').classList.remove('hidden');
  4901. }
  4902. function openEditNATModal(id) {
  4903. id = decodeURIComponent(id);
  4904. const r = (state.natRules || []).find(rule => rule.id === id);
  4905. if (!r) return;
  4906. setFirewallDays('nat', r.days || '');
  4907. switchNATRuleTab('general');
  4908. const badge = document.getElementById('nat-modal-badge');
  4909. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  4910. document.getElementById('nat-modal-id').value = r.id;
  4911. document.getElementById('nat-modal-family').value = String(r.ip_version || 4);
  4912. document.getElementById('nat-modal-enabled').checked = !r.disabled;
  4913. document.getElementById('nat-modal-comment').value = r.comment || '';
  4914. const natChain = nativeNATChain(r.chain || 'postrouting');
  4915. document.getElementById('nat-modal-chain').value = natChain;
  4916. populateChainDropdown('nat', natChain);
  4917. handleNATChainChange();
  4918. setFirewallActionSelection('nat', r.action || 'accept');
  4919. document.getElementById('nat-modal-toaddr').value = r.to_addresses || '';
  4920. document.getElementById('nat-modal-toport').value = r.to_ports || '';
  4921. document.getElementById('nat-modal-log').checked = !!r.log;
  4922. populateInterfaceSelect('nat-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  4923. populateInterfaceSelect('nat-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  4924. populateAddressListSelect('nat-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  4925. populateAddressListSelect('nat-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  4926. populateGeoIPSelect('nat-val-srcgeo', r.src_geoip || '');
  4927. populateGeoIPSelect('nat-val-dstgeo', r.dst_geoip || '');
  4928. setNATFieldVal('src', r.src_address, true);
  4929. setNATFieldVal('dst', r.dst_address, true);
  4930. setNATFieldVal('srclist', r.src_address_list, true);
  4931. setNATFieldVal('dstlist', r.dst_address_list, true);
  4932. setNATFieldVal('srcgeo', r.src_geoip, true);
  4933. setNATFieldVal('dstgeo', r.dst_geoip, true);
  4934. if (r.protocol && r.protocol !== 'all') {
  4935. setNATFieldVal('proto', r.protocol, true);
  4936. } else {
  4937. toggleNATField('proto', false);
  4938. }
  4939. setNATFieldVal('sport', r.src_port, true);
  4940. setNATFieldVal('dport', r.dst_port, true);
  4941. setNATFieldVal('anyport', r.any_port, true);
  4942. setNATFieldVal('iniface', r.in_interface, true);
  4943. setNATFieldVal('outiface', r.out_interface, true);
  4944. setNATFieldVal('inifacelist', r.in_interface_list, true);
  4945. setNATFieldVal('outifacelist', r.out_interface_list, true);
  4946. setNATFieldVal('pktmark', r.packet_mark, true);
  4947. setNATFieldVal('connmark', r.connection_mark, true);
  4948. setNATFieldVal('routingmark', r.routing_mark, true);
  4949. setNATFieldVal('conntype', r.connection_type, false);
  4950. // Advanced tab fields
  4951. setNATFieldVal('layer7', r.layer7_protocol, false);
  4952. setNATFieldVal('content', r.content, false);
  4953. setNATFieldVal('connbytes', r.connection_bytes, false);
  4954. setNATFieldVal('connrate', r.connection_rate, false);
  4955. setNATFieldVal('pcc', r.pcc, false);
  4956. setNATFieldVal('srcmac', r.src_mac_address, true);
  4957. setNATFieldVal('outbridgeport', r.out_bridge_port, false);
  4958. setNATFieldVal('inbridgeport', r.in_bridge_port, false);
  4959. setNATFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  4960. setNATFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  4961. setNATFieldVal('ipsec', r.ipsec_policy, false);
  4962. setNATFieldVal('ingresspriority', r.ingress_priority, false);
  4963. setNATFieldVal('priority', r.priority, false);
  4964. setNATFieldVal('dscp', r.dscp, false);
  4965. setNATFieldVal('tcpmss', r.tcp_mss, false);
  4966. { const tosEl = document.getElementById('nat-val-tos'); if (tosEl) tosEl.value = r.tos || ''; }
  4967. setNATFieldVal('pktsize', r.packet_size, false);
  4968. setNATFieldVal('random', r.random, false);
  4969. setNATFieldVal('icmpoptions', r.icmp_options, false);
  4970. setNATFieldVal('ipv4options', r.ipv4_options, false);
  4971. setNATFieldVal('ttl', r.ttl, false);
  4972. // Extra tab fields
  4973. setNATFieldVal('time', r.time, false);
  4974. if (r.days) {
  4975. toggleNATField('days', true);
  4976. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  4977. const chk = document.getElementById(`nat-day-${d}`);
  4978. if (chk) chk.checked = r.days.toLowerCase().includes(d);
  4979. });
  4980. } else {
  4981. toggleNATField('days', false);
  4982. }
  4983. setNATFieldVal('limit', r.limit, false);
  4984. setNATFieldVal('dstlimit', r.dst_limit, false);
  4985. setNATFieldVal('psd', r.psd, false);
  4986. // Action fields
  4987. if (r.jump_target) {
  4988. const jtEl = document.getElementById('nat-modal-jumptarget');
  4989. if (jtEl) jtEl.value = r.jump_target;
  4990. }
  4991. if (r.address_list) {
  4992. const alEl = document.getElementById('nat-modal-action-addrlist');
  4993. if (alEl) alEl.value = r.address_list;
  4994. }
  4995. if (r.address_list_timeout) {
  4996. const toEl = document.getElementById('nat-modal-action-timeout');
  4997. if (toEl) toEl.value = r.address_list_timeout;
  4998. }
  4999. setNATFieldVal('logprefix', r.log_prefix, false);
  5000. // Statistics
  5001. const bEl = document.getElementById('nat-stat-bytes');
  5002. const pEl = document.getElementById('nat-stat-packets');
  5003. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  5004. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  5005. state.natLastBytes = r.bytes || 0;
  5006. state.natLastPackets = r.packets || 0;
  5007. state.natLastTimestamp = Date.now();
  5008. state.natStatRateHistory = new Array(30).fill(0);
  5009. state.natStatPktHistory = new Array(30).fill(0);
  5010. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  5011. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  5012. toggleNATActionFields();
  5013. document.getElementById('nat-modal').classList.remove('hidden');
  5014. }
  5015. function closeNATModal() {
  5016. stopNATStatPolling();
  5017. document.getElementById('nat-modal').classList.add('hidden');
  5018. }
  5019. function copyNATRule() {
  5020. document.getElementById('nat-modal-id').value = '';
  5021. const badge = document.getElementById('nat-modal-badge');
  5022. if (badge) badge.innerText = 'New...';
  5023. showToast('Rule Cloned', 'Ready to save as a new NAT rule copy', 'info');
  5024. }
  5025. function resetNATCounterDisplay() {
  5026. state.natStatRateHistory = new Array(30).fill(0);
  5027. state.natStatPktHistory = new Array(30).fill(0);
  5028. state.natLastBytes = 0;
  5029. state.natLastPackets = 0;
  5030. state.natLastTimestamp = Date.now();
  5031. const bEl = document.getElementById('nat-stat-bytes');
  5032. const pEl = document.getElementById('nat-stat-packets');
  5033. const rEl = document.getElementById('nat-stat-rate');
  5034. const prEl = document.getElementById('nat-stat-pktrate');
  5035. if (bEl) bEl.value = '0 B';
  5036. if (pEl) pEl.value = '0';
  5037. if (rEl) rEl.value = '0 bps';
  5038. if (prEl) prEl.value = '0 p/s';
  5039. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  5040. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  5041. showToast('Counters Reset', 'NAT rule counter display reset to 0', 'info');
  5042. }
  5043. async function applyNATRule(closeAfter = false) {
  5044. const id = document.getElementById('nat-modal-id').value;
  5045. if (!reviewLegacyFirewallSettings('nat', id)) return;
  5046. let selectedDays; try { selectedDays = getFirewallDays('nat'); } catch(error) { showToast('Error', error.message, 'error'); return; }
  5047. const chain = (document.getElementById('nat-modal-chain').value || '').trim();
  5048. const chainLower = nativeNATChain(chain).toLowerCase();
  5049. const action = document.getElementById('nat-modal-action').value;
  5050. const comment = document.getElementById('nat-modal-comment').value.trim();
  5051. const enabled = document.getElementById('nat-modal-enabled').checked;
  5052. const src = getNATFieldVal('src', true);
  5053. const dst = getNATFieldVal('dst', true);
  5054. const srclist = getNATFieldVal('srclist', true);
  5055. const dstlist = getNATFieldVal('dstlist', true);
  5056. const srcgeo = getNATFieldVal('srcgeo', true);
  5057. const dstgeo = getNATFieldVal('dstgeo', true);
  5058. const proto = getNATFieldVal('proto', true);
  5059. const sport = getNATFieldVal('sport', true);
  5060. const dport = getNATFieldVal('dport', true);
  5061. const anyport = getNATFieldVal('anyport', true);
  5062. let iniface = getNATFieldVal('iniface', true);
  5063. let outiface = getNATFieldVal('outiface', true);
  5064. let inifacelist = getNATFieldVal('inifacelist', true);
  5065. let outifacelist = getNATFieldVal('outifacelist', true);
  5066. if (chainLower === 'prerouting' || chainLower === 'input') {
  5067. outiface = '';
  5068. outifacelist = '';
  5069. } else if (chainLower === 'postrouting' || chainLower === 'output') {
  5070. iniface = '';
  5071. inifacelist = '';
  5072. }
  5073. const pktmark = getNATFieldVal('pktmark', true);
  5074. const connmark = getNATFieldVal('connmark', true);
  5075. const routingmark = getNATFieldVal('routingmark', true);
  5076. const conntype = getNATFieldVal('conntype', false);
  5077. const usesAddr = ['src-nat', 'dst-nat', 'netmap'].includes(action);
  5078. const usesPort = ['src-nat', 'dst-nat', 'redirect', 'masquerade'].includes(action);
  5079. if (!chain) { switchNATRuleTab('general'); showToast('NAT rule', 'Enter a chain.', 'error'); document.getElementById('nat-modal-chain').focus(); return; }
  5080. if (chainLower === 'forward') { switchNATRuleTab('general'); showToast('Invalid Chain', 'Chain FORWARD is not valid in the NAT table in iptables.', 'error'); return; }
  5081. if (['dst-nat', 'redirect'].includes(action) && chainLower !== 'prerouting' && chainLower !== 'output') {
  5082. switchNATRuleTab('general');
  5083. showToast('Invalid Target for Chain', `${action === 'dst-nat' ? 'DNAT' : 'REDIRECT'} requires PREROUTING or OUTPUT chain in iptables.`, 'error');
  5084. return;
  5085. }
  5086. if (action === 'masquerade' && chainLower !== 'postrouting') {
  5087. switchNATRuleTab('general');
  5088. showToast('Invalid Target for Chain', 'MASQUERADE requires POSTROUTING chain in iptables.', 'error');
  5089. return;
  5090. }
  5091. if (action === 'src-nat' && chainLower !== 'postrouting' && chainLower !== 'input') {
  5092. switchNATRuleTab('general');
  5093. showToast('Invalid Target for Chain', 'SNAT requires POSTROUTING or INPUT chain in iptables.', 'error');
  5094. return;
  5095. }
  5096. 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; }
  5097. if ((sport || dport || anyport || (usesPort && document.getElementById('nat-modal-toport').value.trim())) && !['tcp', 'udp'].includes(proto)) {
  5098. switchNATRuleTab('general'); toggleNATField('proto', true); document.getElementById('nat-val-proto').value = proto || 'all';
  5099. 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;
  5100. }
  5101. const payload = {
  5102. ip_version: Number(document.getElementById('nat-modal-family').value),
  5103. id,
  5104. chain,
  5105. action,
  5106. to_addresses: usesAddr ? (document.getElementById('nat-modal-toaddr')?.value.trim() || '') : '',
  5107. to_ports: usesPort ? (document.getElementById('nat-modal-toport')?.value.trim() || '') : '',
  5108. protocol: proto || 'all',
  5109. src_address: src,
  5110. dst_address: dst,
  5111. src_port: sport,
  5112. dst_port: dport,
  5113. any_port: anyport,
  5114. in_interface: iniface,
  5115. out_interface: outiface,
  5116. in_interface_list: inifacelist,
  5117. out_interface_list: outifacelist,
  5118. packet_mark: pktmark,
  5119. connection_mark: connmark,
  5120. routing_mark: routingmark,
  5121. connection_type: conntype,
  5122. src_address_list: srclist,
  5123. dst_address_list: dstlist,
  5124. src_geoip: srcgeo,
  5125. dst_geoip: dstgeo,
  5126. comment,
  5127. disabled: !enabled,
  5128. // Advanced tab
  5129. content: getNATFieldVal('content', false),
  5130. src_mac_address: (chainLower === 'output' || chainLower === 'postrouting') ? '' : getNATFieldVal('srcmac', true),
  5131. out_bridge_port: (chainLower === 'input' || chainLower === 'prerouting') ? '' : getNATFieldVal('outbridgeport', false),
  5132. in_bridge_port: (chainLower === 'output' || chainLower === 'postrouting') ? '' : getNATFieldVal('inbridgeport', false),
  5133. ipsec_policy: getNATFieldVal('ipsec', false),
  5134. dscp: getNATFieldVal('dscp', false),
  5135. tcp_mss: getNATFieldVal('tcpmss', false),
  5136. tos: document.getElementById('nat-val-tos')?.value || '',
  5137. packet_size: getNATFieldVal('pktsize', false),
  5138. random: getNATFieldVal('random', false),
  5139. icmp_options: getNATFieldVal('icmpoptions', false),
  5140. ttl: getNATFieldVal('ttl', false),
  5141. days: selectedDays,
  5142. // Extra tab
  5143. time: getNATFieldVal('time', false),
  5144. limit: getNATFieldVal('limit', false),
  5145. // Action tab
  5146. jump_target: action === 'jump' ? (document.getElementById('nat-modal-jumptarget')?.value || '') : '',
  5147. address_list: action.includes('address') ? (document.getElementById('nat-modal-action-addrlist')?.value || '') : '',
  5148. address_list_timeout: action.includes('address') ? (document.getElementById('nat-modal-action-timeout')?.value || '') : '',
  5149. log: document.getElementById('nat-modal-log')?.checked || false,
  5150. log_prefix: getNATFieldVal('logprefix', false)
  5151. };
  5152. try {
  5153. const res = await fetch(`${API_BASE}/firewall/nat`, {
  5154. method: 'POST',
  5155. headers: { 'Content-Type': 'application/json' },
  5156. body: JSON.stringify(payload)
  5157. });
  5158. if (res.ok) {
  5159. const data = await res.json();
  5160. showToast('NAT Rule Saved', 'NAT mapping updated', 'success');
  5161. loadFirewall(false);
  5162. if (closeAfter) {
  5163. closeNATModal();
  5164. } else {
  5165. if (data.id) {
  5166. document.getElementById('nat-modal-id').value = data.id;
  5167. const badge = document.getElementById('nat-modal-badge');
  5168. if (badge) badge.innerText = `#${data.id}`;
  5169. }
  5170. }
  5171. } else {
  5172. const err = await res.json();
  5173. showToast('Error', err.message || 'Failed to save rule', 'error');
  5174. }
  5175. } catch (err) {
  5176. showToast('Error', err.message, 'error');
  5177. }
  5178. }
  5179. function submitSaveNATRule(e) {
  5180. if (e && e.preventDefault) e.preventDefault();
  5181. return applyNATRule(true);
  5182. }
  5183. function startNATStatPolling() {
  5184. stopNATStatPolling();
  5185. pollNATRuleStats();
  5186. state.natStatInterval = setInterval(pollNATRuleStats, 1000);
  5187. }
  5188. function stopNATStatPolling() {
  5189. if (state.natStatInterval) {
  5190. clearInterval(state.natStatInterval);
  5191. state.natStatInterval = null;
  5192. }
  5193. }
  5194. async function pollNATRuleStats() {
  5195. const id = document.getElementById('nat-modal-id')?.value;
  5196. if (!id) {
  5197. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory || new Array(30).fill(0), 'bps', 'nat-stat-legend-rate');
  5198. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory || new Array(30).fill(0), 'p/s', 'nat-stat-legend-pktrate');
  5199. return;
  5200. }
  5201. try {
  5202. const res = await fetch(`${API_BASE}/firewall/nat`);
  5203. if (!res.ok) return;
  5204. const rules = await res.json();
  5205. const r = rules.find(x => x.id === id);
  5206. if (!r) return;
  5207. const now = Date.now();
  5208. const dt = Math.max(0.2, (now - (state.natLastTimestamp || now)) / 1000);
  5209. state.natLastTimestamp = now;
  5210. const curBytes = r.bytes || 0;
  5211. const curPackets = r.packets || 0;
  5212. const deltaBytes = Math.max(0, curBytes - (state.natLastBytes ?? curBytes));
  5213. const deltaPkts = Math.max(0, curPackets - (state.natLastPackets ?? curPackets));
  5214. state.natLastBytes = curBytes;
  5215. state.natLastPackets = curPackets;
  5216. const rateBps = Math.round((deltaBytes * 8) / dt);
  5217. const ratePkt = Math.round(deltaPkts / dt);
  5218. if (!state.natStatRateHistory) state.natStatRateHistory = new Array(30).fill(0);
  5219. if (!state.natStatPktHistory) state.natStatPktHistory = new Array(30).fill(0);
  5220. state.natStatRateHistory.push(rateBps);
  5221. if (state.natStatRateHistory.length > 30) state.natStatRateHistory.shift();
  5222. state.natStatPktHistory.push(ratePkt);
  5223. if (state.natStatPktHistory.length > 30) state.natStatPktHistory.shift();
  5224. const bEl = document.getElementById('nat-stat-bytes');
  5225. const pEl = document.getElementById('nat-stat-packets');
  5226. const rEl = document.getElementById('nat-stat-rate');
  5227. const prEl = document.getElementById('nat-stat-pktrate');
  5228. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  5229. if (pEl) pEl.value = curPackets.toLocaleString();
  5230. if (rEl) rEl.value = formatBps(rateBps);
  5231. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  5232. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  5233. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  5234. } catch (e) {
  5235. console.error('Error polling NAT rule stats', e);
  5236. }
  5237. }
  5238. async function moveNATRule(id, dir) {
  5239. id = decodeURIComponent(id);
  5240. try {
  5241. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/move`, {
  5242. method: 'POST',
  5243. headers: { 'Content-Type': 'application/json' },
  5244. body: JSON.stringify({ direction: dir })
  5245. });
  5246. if (!res.ok) throw new Error(await responseError(res));
  5247. await loadFirewall(false);
  5248. } catch (err) {
  5249. showToast('Error', err.message, 'error');
  5250. }
  5251. }
  5252. async function toggleNATRuleState(id, disabled) {
  5253. id = decodeURIComponent(id);
  5254. try {
  5255. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/state`, {
  5256. method: 'POST',
  5257. headers: { 'Content-Type': 'application/json' },
  5258. body: JSON.stringify({ disabled })
  5259. });
  5260. if (!res.ok) throw new Error(await responseError(res));
  5261. await loadFirewall(false);
  5262. } catch (err) {
  5263. showToast('Error', err.message, 'error');
  5264. }
  5265. }
  5266. async function deleteNATRule(id) {
  5267. id = decodeURIComponent(id);
  5268. if (!confirm('Are you sure you want to delete this NAT rule?')) return;
  5269. try {
  5270. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5271. if (!res.ok) throw new Error(await responseError(res));
  5272. {
  5273. showToast('Deleted', 'NAT rule removed', 'success');
  5274. loadFirewall(false);
  5275. }
  5276. } catch (err) {
  5277. showToast('Error', err.message, 'error');
  5278. }
  5279. }
  5280. // ----------------- Mangle Rules -----------------
  5281. function renderMangleRules() {
  5282. const chainFilter = document.getElementById('mangle-filter-chain')?.value || '';
  5283. const tbody = document.getElementById('mangle-table-body');
  5284. const empty = document.getElementById('mangle-empty');
  5285. if (!tbody) return;
  5286. tbody.innerHTML = '';
  5287. const rules = (state.mangleRules || []).filter(r => !chainFilter || (r.chain || '').toLowerCase() === chainFilter);
  5288. document.getElementById('mangle-count-badge').innerText = `${rules.length} Rules`;
  5289. if (rules.length === 0) {
  5290. empty?.classList.remove('hidden');
  5291. return;
  5292. }
  5293. empty?.classList.add('hidden');
  5294. rules.forEach((raw, idx) => {
  5295. const r = safeFirewallRow(raw);
  5296. const tr = document.createElement('tr');
  5297. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  5298. let markVal = '<span class="text-slate-500">-</span>';
  5299. if (r.new_connection_mark) markVal = `<span class="text-cyan-300 font-mono font-bold">${r.new_connection_mark}</span>`;
  5300. else if (r.new_routing_mark) markVal = `<span class="text-amber-300 font-mono font-bold">${r.new_routing_mark}</span>`;
  5301. else if (r.new_packet_mark) markVal = `<span class="text-emerald-300 font-mono font-bold">${r.new_packet_mark}</span>`;
  5302. else if (r.new_mss) markVal = `<span class="text-sky-300 font-mono font-bold">mss:${r.new_mss}</span>`;
  5303. else if (r.action === 'change-dscp') markVal = `<span class="text-purple-300 font-mono font-bold">dscp:${r.new_dscp}</span>`;
  5304. else if (r.new_ttl) markVal = `<span class="text-blue-300 font-mono font-bold">ttl:${r.new_ttl}</span>`;
  5305. else if (r.new_priority) markVal = `<span class="text-indigo-300 font-mono font-bold">prio:${r.new_priority}</span>`;
  5306. else if (r.route) markVal = `<span class="text-orange-300 font-mono font-bold">route:${r.route}</span>`;
  5307. else if (r.sniff_target) markVal = `<span class="text-pink-300 font-mono font-bold">sniff:${r.sniff_target}</span>`;
  5308. else if (r.action === 'jump') markVal = `<span class="text-yellow-300 font-mono font-bold">&rarr; ${r.jump_target || '-'}</span>`;
  5309. 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>`;
  5310. else if (r.action === 'log') markVal = `<span class="text-slate-400 font-mono font-bold">${r.log_prefix || 'log'}</span>`;
  5311. tr.innerHTML = `
  5312. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  5313. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  5314. <td class="py-2.5 px-3 font-bold text-purple-400">${(r.chain || '').toUpperCase()}</td>
  5315. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  5316. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  5317. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  5318. <td class="py-2.5 px-3 font-mono text-xs">${markVal}</td>
  5319. <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>
  5320. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  5321. <span class="text-slate-300" id="mangle-pkts-${r.id}">${(r.packets || 0).toLocaleString()}p</span> /
  5322. <span class="text-slate-500" id="mangle-bytes-${r.id}">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  5323. </td>
  5324. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  5325. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  5326. <button onclick="moveMangleRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  5327. <button onclick="moveMangleRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  5328. <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>
  5329. <button onclick="openEditMangleModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  5330. <button onclick="deleteMangleRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  5331. </td>
  5332. `;
  5333. tbody.appendChild(tr);
  5334. });
  5335. }
  5336. // ==================== FIREWALL MANGLE MODAL (DEBTIK WEBFIG / WINBOX V4) ====================
  5337. function switchMangleRuleTab(tab) {
  5338. state.activeMangleRuleTab = tab;
  5339. document.querySelectorAll('.mangle-rule-tab-btn').forEach(btn => {
  5340. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  5341. btn.classList.add('text-slate-400', 'border-transparent');
  5342. });
  5343. const activeBtn = document.getElementById(`mangle-tab-btn-${tab}`);
  5344. if (activeBtn) {
  5345. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  5346. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  5347. }
  5348. document.querySelectorAll('.mangle-rule-pane').forEach(p => p.classList.add('hidden'));
  5349. const activePane = document.getElementById(`mangle-pane-${tab}`);
  5350. if (activePane) activePane.classList.remove('hidden');
  5351. if (tab === 'statistics') {
  5352. startMangleStatPolling();
  5353. } else {
  5354. stopMangleStatPolling();
  5355. }
  5356. }
  5357. function toggleMangleField(fieldKey, expand) {
  5358. const plusBtn = document.getElementById(`mangle-plus-${fieldKey}`);
  5359. const fieldBox = document.getElementById(`mangle-field-${fieldKey}`);
  5360. if (!plusBtn || !fieldBox) return;
  5361. if (expand) {
  5362. plusBtn.classList.add('hidden');
  5363. fieldBox.classList.remove('hidden');
  5364. const valInput = document.getElementById(`mangle-val-${fieldKey}`);
  5365. if (valInput) valInput.focus();
  5366. } else {
  5367. fieldBox.classList.add('hidden');
  5368. plusBtn.classList.remove('hidden');
  5369. const valInput = document.getElementById(`mangle-val-${fieldKey}`);
  5370. if (valInput) {
  5371. if (valInput.tagName === 'SELECT') {
  5372. valInput.selectedIndex = 0;
  5373. } else {
  5374. valInput.value = '';
  5375. }
  5376. }
  5377. const invInput = document.getElementById(`mangle-inv-${fieldKey}`);
  5378. if (invInput) invInput.checked = false;
  5379. if (fieldKey === 'cs') {
  5380. ['mangle-modal-cs-established', 'mangle-modal-cs-related', 'mangle-modal-cs-new', 'mangle-modal-cs-invalid', 'mangle-modal-cs-untracked'].forEach(id => {
  5381. const el = document.getElementById(id);
  5382. if (el) el.checked = false;
  5383. });
  5384. }
  5385. if (fieldKey === 'natstate') {
  5386. ['mangle-modal-nat-srcnat', 'mangle-modal-nat-dstnat'].forEach(id => {
  5387. const el = document.getElementById(id);
  5388. if (el) el.checked = false;
  5389. });
  5390. }
  5391. }
  5392. }
  5393. function setMangleFieldVal(fieldKey, value, hasInvert = false) {
  5394. if (fieldKey === 'ipsec' && typeof value === 'string') value = value.replace(':', ',');
  5395. if (value !== undefined && value !== null && value !== '' && !(fieldKey === 'proto' && value === 'all')) {
  5396. toggleMangleField(fieldKey, true);
  5397. let strVal = String(value);
  5398. if (hasInvert) {
  5399. const inv = strVal.startsWith('!');
  5400. if (inv) strVal = strVal.slice(1);
  5401. const invEl = document.getElementById(`mangle-inv-${fieldKey}`);
  5402. if (invEl) invEl.checked = inv;
  5403. else if (inv) strVal = '!'+strVal;
  5404. }
  5405. const valEl = document.getElementById(`mangle-val-${fieldKey}`);
  5406. 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; }
  5407. } else {
  5408. toggleMangleField(fieldKey, false);
  5409. }
  5410. }
  5411. function getMangleFieldVal(fieldKey, hasInvert = false) {
  5412. const fieldBox = document.getElementById(`mangle-field-${fieldKey}`);
  5413. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  5414. const valEl = document.getElementById(`mangle-val-${fieldKey}`);
  5415. let v = valEl ? valEl.value.trim() : '';
  5416. if (!v) return '';
  5417. if (hasInvert) {
  5418. const invEl = document.getElementById(`mangle-inv-${fieldKey}`);
  5419. if (invEl && invEl.checked) {
  5420. v = '!' + v.replace(/^!/, '');
  5421. }
  5422. }
  5423. return v;
  5424. }
  5425. function toggleMaximizeMangleModal() {
  5426. const win = document.getElementById('mangle-modal-window');
  5427. if (!win) return;
  5428. if (win.classList.contains('max-w-[720px]')) {
  5429. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  5430. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  5431. } else {
  5432. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  5433. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  5434. }
  5435. }
  5436. function syncMangleChainFromSelect() {
  5437. const sel = document.getElementById('mangle-modal-chain-select');
  5438. const customWrap = document.getElementById('mangle-modal-custom-wrap');
  5439. const customInput = document.getElementById('mangle-modal-custom-input');
  5440. const chainInput = document.getElementById('mangle-modal-chain');
  5441. if (!sel || !chainInput) return;
  5442. if (sel.value === '__custom__') {
  5443. if (customWrap) customWrap.classList.remove('hidden');
  5444. if (customInput) {
  5445. customInput.value = '';
  5446. customInput.focus();
  5447. }
  5448. chainInput.value = '';
  5449. } else {
  5450. if (customWrap) customWrap.classList.add('hidden');
  5451. chainInput.value = sel.value;
  5452. }
  5453. handleMangleChainChange();
  5454. }
  5455. function syncMangleCustomChainInput() {
  5456. const customInput = document.getElementById('mangle-modal-custom-input');
  5457. const chainInput = document.getElementById('mangle-modal-chain');
  5458. if (customInput && chainInput) {
  5459. chainInput.value = customInput.value.trim();
  5460. }
  5461. handleMangleChainChange();
  5462. }
  5463. function handleMangleChainChange() {
  5464. const chainInput = document.getElementById('mangle-modal-chain');
  5465. const rawChain = (chainInput?.value || 'prerouting').trim();
  5466. const chain = rawChain.toLowerCase();
  5467. const sel = document.getElementById('mangle-modal-chain-select');
  5468. if (sel && sel.value !== chain && sel.value !== '__custom__') {
  5469. if (['prerouting', 'input', 'forward', 'output', 'postrouting'].includes(chain)) {
  5470. sel.value = chain;
  5471. }
  5472. }
  5473. const hintEl = document.getElementById('mangle-chain-hint');
  5474. if (hintEl) {
  5475. if (chain === 'prerouting') {
  5476. hintEl.textContent = 'PREROUTING: packets altered before routing decision (In-Interface only).';
  5477. } else if (chain === 'input') {
  5478. hintEl.textContent = 'INPUT: packets altered before local socket delivery (In-Interface only).';
  5479. } else if (chain === 'forward') {
  5480. hintEl.textContent = 'FORWARD: transit packets routed through this router (accepts both In and Out interfaces).';
  5481. } else if (chain === 'output') {
  5482. hintEl.textContent = 'OUTPUT: locally generated packets before routing decision (Out-Interface only).';
  5483. } else if (chain === 'postrouting') {
  5484. hintEl.textContent = 'POSTROUTING: packets altered after routing decision before transmission (Out-Interface only; CLASSIFY supported).';
  5485. } else {
  5486. hintEl.textContent = `Custom chain "${rawChain}": user-defined Mangle chain reached via JUMP.`;
  5487. }
  5488. }
  5489. const rowIn = document.getElementById('mangle-row-iniface');
  5490. const rowInList = document.getElementById('mangle-row-inifacelist');
  5491. const rowOut = document.getElementById('mangle-row-outiface');
  5492. const rowOutList = document.getElementById('mangle-row-outifacelist');
  5493. const rowInBridge = document.getElementById('mangle-row-inbridgeport');
  5494. const rowOutBridge = document.getElementById('mangle-row-outbridgeport');
  5495. const rowSrcMac = document.getElementById('mangle-row-srcmac');
  5496. if (chain === 'prerouting' || chain === 'input') {
  5497. if (rowIn) rowIn.classList.remove('hidden');
  5498. if (rowInList) rowInList.classList.remove('hidden');
  5499. if (rowOut) rowOut.classList.add('hidden');
  5500. if (rowOutList) rowOutList.classList.add('hidden');
  5501. if (rowInBridge) rowInBridge.classList.remove('hidden');
  5502. if (rowOutBridge) rowOutBridge.classList.add('hidden');
  5503. if (rowSrcMac) rowSrcMac.classList.remove('hidden');
  5504. } else if (chain === 'output' || chain === 'postrouting') {
  5505. if (rowIn) rowIn.classList.add('hidden');
  5506. if (rowInList) rowInList.classList.add('hidden');
  5507. if (rowOut) rowOut.classList.remove('hidden');
  5508. if (rowOutList) rowOutList.classList.remove('hidden');
  5509. if (rowInBridge) rowInBridge.classList.add('hidden');
  5510. if (rowOutBridge) rowOutBridge.classList.remove('hidden');
  5511. if (rowSrcMac) rowSrcMac.classList.add('hidden');
  5512. } else {
  5513. if (rowIn) rowIn.classList.remove('hidden');
  5514. if (rowInList) rowInList.classList.remove('hidden');
  5515. if (rowOut) rowOut.classList.remove('hidden');
  5516. if (rowOutList) rowOutList.classList.remove('hidden');
  5517. if (rowInBridge) rowInBridge.classList.remove('hidden');
  5518. if (rowOutBridge) rowOutBridge.classList.remove('hidden');
  5519. if (rowSrcMac) rowSrcMac.classList.remove('hidden');
  5520. }
  5521. checkMangleActionChainCompatibility();
  5522. toggleMangleActionFields();
  5523. }
  5524. function checkMangleActionChainCompatibility() {
  5525. const rawChain = (document.getElementById('mangle-modal-chain')?.value || 'prerouting').trim();
  5526. const chain = rawChain.toLowerCase();
  5527. const action = (document.getElementById('mangle-modal-action')?.value || '').toLowerCase();
  5528. const warnBox = document.getElementById('mangle-action-incompatible-warn');
  5529. const warnMsg = document.getElementById('mangle-action-incompatible-msg');
  5530. if (!warnBox || !warnMsg) return;
  5531. let msg = '';
  5532. if (action === 'set-priority' && chain !== 'postrouting') {
  5533. msg = 'CLASSIFY (set-priority) requires the POSTROUTING chain in iptables.';
  5534. }
  5535. if (msg) {
  5536. warnMsg.textContent = msg;
  5537. warnBox.classList.remove('hidden');
  5538. } else {
  5539. warnBox.classList.add('hidden');
  5540. }
  5541. }
  5542. function toggleMangleActionFields() {
  5543. const act = document.getElementById('mangle-modal-action')?.value || 'mark-connection';
  5544. // Hide all dynamic rows first
  5545. ['newconnmark', 'newroutingmark', 'newpktmark', 'newmss', 'newdscp', 'newttl', 'newpriority', 'route', 'sniff', 'passthrough'].forEach(id => {
  5546. const el = document.getElementById(`mangle-row-${id}`);
  5547. if (el) el.classList.add('hidden');
  5548. });
  5549. const jumpBox = document.getElementById('mangle-action-jump-box');
  5550. const addrBox = document.getElementById('mangle-action-addrlist-box');
  5551. if (jumpBox) jumpBox.classList.add('hidden');
  5552. if (addrBox) addrBox.classList.add('hidden');
  5553. // Activate matching rows
  5554. if (act === 'mark-connection') {
  5555. document.getElementById('mangle-row-newconnmark')?.classList.remove('hidden');
  5556. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5557. } else if (act === 'mark-routing') {
  5558. document.getElementById('mangle-row-newroutingmark')?.classList.remove('hidden');
  5559. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5560. } else if (act === 'mark-packet') {
  5561. document.getElementById('mangle-row-newpktmark')?.classList.remove('hidden');
  5562. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5563. } else if (act === 'change-mss') {
  5564. document.getElementById('mangle-row-newmss')?.classList.remove('hidden');
  5565. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5566. } else if (act === 'change-dscp') {
  5567. document.getElementById('mangle-row-newdscp')?.classList.remove('hidden');
  5568. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5569. } else if (act === 'change-ttl') {
  5570. document.getElementById('mangle-row-newttl')?.classList.remove('hidden');
  5571. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5572. } else if (act === 'set-priority') {
  5573. document.getElementById('mangle-row-newpriority')?.classList.remove('hidden');
  5574. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5575. } else if (act === 'route') {
  5576. document.getElementById('mangle-row-route')?.classList.remove('hidden');
  5577. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5578. } else if (act === 'sniff-pc' || act === 'sniff-tzsp') {
  5579. document.getElementById('mangle-row-sniff')?.classList.remove('hidden');
  5580. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5581. } else if (act === 'clear-df' || act === 'strip-ipv4-options') {
  5582. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5583. } else if (act === 'jump') {
  5584. if (jumpBox) jumpBox.classList.remove('hidden');
  5585. } else if (act.includes('address-list') || act.includes('address list')) {
  5586. if (addrBox) addrBox.classList.remove('hidden');
  5587. }
  5588. if (act === 'log') {
  5589. const logEl = document.getElementById('mangle-modal-log');
  5590. if (logEl) logEl.checked = true;
  5591. toggleMangleField('logprefix', true);
  5592. }
  5593. checkMangleActionChainCompatibility();
  5594. }
  5595. function toggleMangleLogPrefix() {
  5596. const isLog = document.getElementById('mangle-modal-log')?.checked;
  5597. toggleMangleField('logprefix', !!isLog);
  5598. }
  5599. const allMangleFieldKeys = [
  5600. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  5601. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  5602. 'routingmark', 'conntype', 'cs', 'natstate',
  5603. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  5604. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  5605. 'ipsec', 'tlshost', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  5606. 'pktsize', 'random', 'tcpflags', 'icmpoptions', 'ipv4options', 'ttl',
  5607. 'nth', 'connlimit', 'srcaddrtype', 'dstaddrtype', 'hotspot', 'ipfragment',
  5608. 'limit', 'dstlimit', 'time', 'psd', 'logprefix'
  5609. ];
  5610. function openAddMangleModal() {
  5611. const tos = document.getElementById('mangle-val-tos'); if (tos) tos.value = '';
  5612. switchMangleRuleTab('general');
  5613. const badge = document.getElementById('mangle-modal-badge');
  5614. if (badge) badge.innerText = 'New...';
  5615. document.getElementById('mangle-modal-id').value = '';
  5616. document.getElementById('mangle-modal-family').value = '4';
  5617. document.getElementById('mangle-modal-enabled').checked = true;
  5618. document.getElementById('mangle-modal-comment').value = '';
  5619. document.getElementById('mangle-modal-chain').value = 'prerouting';
  5620. populateChainDropdown('mangle', 'prerouting');
  5621. handleMangleChainChange();
  5622. document.getElementById('mangle-modal-action').value = 'mark-connection';
  5623. if (document.getElementById('mangle-modal-newconnmark')) document.getElementById('mangle-modal-newconnmark').value = '';
  5624. if (document.getElementById('mangle-modal-newroutingmark')) document.getElementById('mangle-modal-newroutingmark').value = '';
  5625. if (document.getElementById('mangle-modal-newpktmark')) document.getElementById('mangle-modal-newpktmark').value = '';
  5626. if (document.getElementById('mangle-modal-newmss')) document.getElementById('mangle-modal-newmss').value = '';
  5627. if (document.getElementById('mangle-modal-newdscp')) document.getElementById('mangle-modal-newdscp').value = '';
  5628. if (document.getElementById('mangle-modal-newttl')) document.getElementById('mangle-modal-newttl').value = '';
  5629. if (document.getElementById('mangle-modal-newpriority')) document.getElementById('mangle-modal-newpriority').value = '';
  5630. if (document.getElementById('mangle-modal-route')) document.getElementById('mangle-modal-route').value = '';
  5631. if (document.getElementById('mangle-modal-sniff')) document.getElementById('mangle-modal-sniff').value = '';
  5632. if (document.getElementById('mangle-modal-jumptarget')) document.getElementById('mangle-modal-jumptarget').value = '';
  5633. if (document.getElementById('mangle-modal-action-addrlist')) document.getElementById('mangle-modal-action-addrlist').value = '';
  5634. if (document.getElementById('mangle-modal-action-timeout')) document.getElementById('mangle-modal-action-timeout').value = '';
  5635. if (document.getElementById('mangle-modal-passthrough')) document.getElementById('mangle-modal-passthrough').checked = true;
  5636. if (document.getElementById('mangle-modal-log')) document.getElementById('mangle-modal-log').checked = false;
  5637. populateInterfaceSelect('mangle-val-iniface');
  5638. populateInterfaceSelect('mangle-val-outiface');
  5639. populateAddressListSelect('mangle-val-srclist');
  5640. populateAddressListSelect('mangle-val-dstlist');
  5641. populateGeoIPSelect('mangle-val-srcgeo');
  5642. populateGeoIPSelect('mangle-val-dstgeo');
  5643. allMangleFieldKeys.forEach(k => toggleMangleField(k, false));
  5644. resetMangleCounterDisplay();
  5645. toggleMangleActionFields();
  5646. document.getElementById('mangle-modal').classList.remove('hidden');
  5647. }
  5648. function openEditMangleModal(id) {
  5649. id = decodeURIComponent(id);
  5650. const r = (state.mangleRules || []).find(rule => rule.id === id);
  5651. if (!r) return;
  5652. switchMangleRuleTab('general');
  5653. const badge = document.getElementById('mangle-modal-badge');
  5654. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  5655. document.getElementById('mangle-modal-id').value = r.id;
  5656. document.getElementById('mangle-modal-family').value = String(r.ip_version || 4);
  5657. document.getElementById('mangle-modal-enabled').checked = !r.disabled;
  5658. document.getElementById('mangle-modal-comment').value = r.comment || '';
  5659. const mangleChain = r.chain || 'prerouting';
  5660. document.getElementById('mangle-modal-chain').value = mangleChain;
  5661. populateChainDropdown('mangle', mangleChain);
  5662. handleMangleChainChange();
  5663. setFirewallActionSelection('mangle', r.action || 'accept');
  5664. if (document.getElementById('mangle-modal-newconnmark')) document.getElementById('mangle-modal-newconnmark').value = r.new_connection_mark || '';
  5665. if (document.getElementById('mangle-modal-newroutingmark')) document.getElementById('mangle-modal-newroutingmark').value = r.new_routing_mark || '';
  5666. if (document.getElementById('mangle-modal-newpktmark')) document.getElementById('mangle-modal-newpktmark').value = r.new_packet_mark || '';
  5667. if (document.getElementById('mangle-modal-newmss')) document.getElementById('mangle-modal-newmss').value = r.new_mss || '';
  5668. if (document.getElementById('mangle-modal-newdscp')) document.getElementById('mangle-modal-newdscp').value = r.new_dscp != null ? r.new_dscp : '';
  5669. if (document.getElementById('mangle-modal-newttl')) document.getElementById('mangle-modal-newttl').value = r.new_ttl || '';
  5670. if (document.getElementById('mangle-modal-newpriority')) document.getElementById('mangle-modal-newpriority').value = r.new_priority || '';
  5671. if (document.getElementById('mangle-modal-route')) document.getElementById('mangle-modal-route').value = r.route || '';
  5672. if (document.getElementById('mangle-modal-sniff')) document.getElementById('mangle-modal-sniff').value = r.sniff_target || '';
  5673. if (document.getElementById('mangle-modal-jumptarget')) document.getElementById('mangle-modal-jumptarget').value = r.jump_target || '';
  5674. if (document.getElementById('mangle-modal-action-addrlist')) document.getElementById('mangle-modal-action-addrlist').value = r.address_list || '';
  5675. if (document.getElementById('mangle-modal-action-timeout')) document.getElementById('mangle-modal-action-timeout').value = r.address_list_timeout || '';
  5676. if (document.getElementById('mangle-modal-passthrough')) document.getElementById('mangle-modal-passthrough').checked = r.passthrough ?? true;
  5677. if (document.getElementById('mangle-modal-log')) document.getElementById('mangle-modal-log').checked = !!r.log;
  5678. populateInterfaceSelect('mangle-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  5679. populateInterfaceSelect('mangle-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  5680. populateAddressListSelect('mangle-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  5681. populateAddressListSelect('mangle-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  5682. populateGeoIPSelect('mangle-val-srcgeo', r.src_geoip || '');
  5683. populateGeoIPSelect('mangle-val-dstgeo', r.dst_geoip || '');
  5684. setMangleFieldVal('src', r.src_address, true);
  5685. setMangleFieldVal('dst', r.dst_address, true);
  5686. setMangleFieldVal('srclist', r.src_address_list, true);
  5687. setMangleFieldVal('dstlist', r.dst_address_list, true);
  5688. setMangleFieldVal('srcgeo', r.src_geoip, true);
  5689. setMangleFieldVal('dstgeo', r.dst_geoip, true);
  5690. if (r.protocol && r.protocol !== 'all') {
  5691. setMangleFieldVal('proto', r.protocol, true);
  5692. } else {
  5693. toggleMangleField('proto', false);
  5694. }
  5695. setMangleFieldVal('sport', r.src_port, true);
  5696. setMangleFieldVal('dport', r.dst_port, true);
  5697. setMangleFieldVal('anyport', r.any_port, true);
  5698. setMangleFieldVal('iniface', r.in_interface, true);
  5699. setMangleFieldVal('outiface', r.out_interface, true);
  5700. setMangleFieldVal('inifacelist', r.in_interface_list, true);
  5701. setMangleFieldVal('outifacelist', r.out_interface_list, true);
  5702. setMangleFieldVal('pktmark', r.packet_mark, true);
  5703. setMangleFieldVal('connmark', r.connection_mark, true);
  5704. setMangleFieldVal('routingmark', r.routing_mark, true);
  5705. setMangleFieldVal('conntype', r.connection_type, false);
  5706. // Connection State
  5707. const states = r.connection_state || [];
  5708. if (states.length > 0) {
  5709. toggleMangleField('cs', true);
  5710. ['established', 'related', 'new', 'invalid', 'untracked'].forEach(s => {
  5711. const el = document.getElementById(`mangle-modal-cs-${s}`);
  5712. if (el) el.checked = states.includes(s);
  5713. });
  5714. } else {
  5715. toggleMangleField('cs', false);
  5716. }
  5717. // Connection NAT State
  5718. const natStates = r.connection_nat_state || [];
  5719. if (natStates.length > 0) {
  5720. toggleMangleField('natstate', true);
  5721. ['srcnat', 'dstnat'].forEach(s => {
  5722. const el = document.getElementById(`mangle-modal-nat-${s}`);
  5723. if (el) el.checked = natStates.includes(s);
  5724. });
  5725. } else {
  5726. toggleMangleField('natstate', false);
  5727. }
  5728. // Advanced tab fields
  5729. setMangleFieldVal('layer7', r.layer7_protocol, false);
  5730. setMangleFieldVal('content', r.content, false);
  5731. setMangleFieldVal('connbytes', r.connection_bytes, false);
  5732. setMangleFieldVal('connrate', r.connection_rate, false);
  5733. setMangleFieldVal('pcc', r.pcc, false);
  5734. setMangleFieldVal('srcmac', r.src_mac_address, true);
  5735. setMangleFieldVal('outbridgeport', r.out_bridge_port, false);
  5736. setMangleFieldVal('inbridgeport', r.in_bridge_port, false);
  5737. setMangleFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  5738. setMangleFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  5739. setMangleFieldVal('ipsec', r.ipsec_policy, false);
  5740. setMangleFieldVal('tlshost', r.tls_host, false);
  5741. setMangleFieldVal('ingresspriority', r.ingress_priority, false);
  5742. setMangleFieldVal('priority', r.priority, false);
  5743. setMangleFieldVal('dscp', r.dscp, false);
  5744. setMangleFieldVal('tcpmss', r.tcp_mss, false);
  5745. { const tosEl = document.getElementById('mangle-val-tos'); if (tosEl) tosEl.value = r.tos || ''; }
  5746. setMangleFieldVal('pktsize', r.packet_size, false);
  5747. setMangleFieldVal('random', r.random, false);
  5748. setMangleFieldVal('tcpflags', r.tcp_flags, false);
  5749. setMangleFieldVal('icmpoptions', r.icmp_options, false);
  5750. setMangleFieldVal('ipv4options', r.ipv4_options, false);
  5751. setMangleFieldVal('ttl', r.ttl, false);
  5752. // Extra tab fields
  5753. setMangleFieldVal('nth', r.nth, false);
  5754. setMangleFieldVal('connlimit', r.connection_limit, false);
  5755. setMangleFieldVal('srcaddrtype', r.src_address_type, false);
  5756. setMangleFieldVal('dstaddrtype', r.dst_address_type, false);
  5757. setMangleFieldVal('hotspot', r.hotspot, false);
  5758. setMangleFieldVal('ipfragment', r.ip_fragment, false);
  5759. setMangleFieldVal('limit', r.limit, false);
  5760. setMangleFieldVal('dstlimit', r.dst_limit, false);
  5761. setMangleFieldVal('time', r.time, false);
  5762. setMangleFieldVal('psd', r.psd, false);
  5763. // Action fields
  5764. if (r.jump_target) {
  5765. const jtEl = document.getElementById('mangle-modal-jumptarget');
  5766. if (jtEl) jtEl.value = r.jump_target;
  5767. }
  5768. if (r.address_list) {
  5769. const alEl = document.getElementById('mangle-modal-action-addrlist');
  5770. if (alEl) alEl.value = r.address_list;
  5771. }
  5772. if (r.address_list_timeout) {
  5773. const toEl = document.getElementById('mangle-modal-action-timeout');
  5774. if (toEl) toEl.value = r.address_list_timeout;
  5775. }
  5776. setMangleFieldVal('logprefix', r.log_prefix, false);
  5777. // Statistics
  5778. const bEl = document.getElementById('mangle-stat-bytes');
  5779. const pEl = document.getElementById('mangle-stat-packets');
  5780. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  5781. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  5782. state.mangleLastBytes = r.bytes || 0;
  5783. state.mangleLastPackets = r.packets || 0;
  5784. state.mangleLastTimestamp = Date.now();
  5785. state.mangleStatRateHistory = new Array(30).fill(0);
  5786. state.mangleStatPktHistory = new Array(30).fill(0);
  5787. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  5788. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  5789. toggleMangleActionFields();
  5790. document.getElementById('mangle-modal').classList.remove('hidden');
  5791. }
  5792. function closeMangleModal() {
  5793. stopMangleStatPolling();
  5794. document.getElementById('mangle-modal').classList.add('hidden');
  5795. }
  5796. function copyMangleRule() {
  5797. document.getElementById('mangle-modal-id').value = '';
  5798. const badge = document.getElementById('mangle-modal-badge');
  5799. if (badge) badge.innerText = 'New...';
  5800. showToast('Rule Cloned', 'Ready to save as a new Mangle rule copy', 'info');
  5801. }
  5802. function resetMangleCounterDisplay() {
  5803. state.mangleStatRateHistory = new Array(30).fill(0);
  5804. state.mangleStatPktHistory = new Array(30).fill(0);
  5805. state.mangleLastBytes = 0;
  5806. state.mangleLastPackets = 0;
  5807. state.mangleLastTimestamp = Date.now();
  5808. const bEl = document.getElementById('mangle-stat-bytes');
  5809. const pEl = document.getElementById('mangle-stat-packets');
  5810. const rEl = document.getElementById('mangle-stat-rate');
  5811. const prEl = document.getElementById('mangle-stat-pktrate');
  5812. if (bEl) bEl.value = '0 B';
  5813. if (pEl) pEl.value = '0';
  5814. if (rEl) rEl.value = '0 bps';
  5815. if (prEl) prEl.value = '0 p/s';
  5816. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  5817. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  5818. showToast('Counters Reset', 'Mangle rule counter display reset to 0', 'info');
  5819. }
  5820. async function applyMangleRule(closeAfter = false) {
  5821. const id = document.getElementById('mangle-modal-id').value;
  5822. if (!reviewLegacyFirewallSettings('mangle', id)) return;
  5823. const chain = (document.getElementById('mangle-modal-chain').value || '').trim();
  5824. const chainLower = chain.toLowerCase();
  5825. const action = document.getElementById('mangle-modal-action').value;
  5826. const comment = document.getElementById('mangle-modal-comment').value.trim();
  5827. const enabled = document.getElementById('mangle-modal-enabled').checked;
  5828. const src = getMangleFieldVal('src', true);
  5829. const dst = getMangleFieldVal('dst', true);
  5830. const srclist = getMangleFieldVal('srclist', true);
  5831. const dstlist = getMangleFieldVal('dstlist', true);
  5832. const srcgeo = getMangleFieldVal('srcgeo', true);
  5833. const dstgeo = getMangleFieldVal('dstgeo', true);
  5834. const proto = getMangleFieldVal('proto', true);
  5835. const sport = getMangleFieldVal('sport', true);
  5836. const dport = getMangleFieldVal('dport', true);
  5837. const anyport = getMangleFieldVal('anyport', true);
  5838. if ((sport || dport || anyport) && !['tcp', 'udp'].includes(proto)) {
  5839. switchMangleRuleTab('general'); toggleMangleField('proto', true);
  5840. showToast('Select protocol', 'Port matches require TCP or UDP without protocol inversion.', 'error'); document.getElementById('mangle-val-proto').focus(); return;
  5841. }
  5842. let iniface = getMangleFieldVal('iniface', true);
  5843. let outiface = getMangleFieldVal('outiface', true);
  5844. let inifacelist = getMangleFieldVal('inifacelist', true);
  5845. let outifacelist = getMangleFieldVal('outifacelist', true);
  5846. if (chainLower === 'prerouting' || chainLower === 'input') {
  5847. outiface = '';
  5848. outifacelist = '';
  5849. } else if (chainLower === 'output' || chainLower === 'postrouting') {
  5850. iniface = '';
  5851. inifacelist = '';
  5852. }
  5853. if (!chain) { switchMangleRuleTab('general'); showToast('Mangle rule', 'Enter a chain.', 'error'); document.getElementById('mangle-modal-chain').focus(); return; }
  5854. if (action === 'set-priority' && chainLower !== 'postrouting') {
  5855. switchMangleRuleTab('general');
  5856. showToast('Invalid Target for Chain', 'CLASSIFY (set-priority) requires POSTROUTING chain in iptables.', 'error');
  5857. return;
  5858. }
  5859. const pktmark = getMangleFieldVal('pktmark', true);
  5860. const connmark = getMangleFieldVal('connmark', true);
  5861. const routingmark = getMangleFieldVal('routingmark', true);
  5862. const conntype = getMangleFieldVal('conntype', false);
  5863. const states = [];
  5864. const csBox = document.getElementById('mangle-field-cs');
  5865. if (csBox && !csBox.classList.contains('hidden')) {
  5866. ['established', 'related', 'new', 'invalid', 'untracked'].forEach(s => {
  5867. if (document.getElementById(`mangle-modal-cs-${s}`)?.checked) states.push(s);
  5868. });
  5869. }
  5870. const natStates = [];
  5871. const natBox = document.getElementById('mangle-field-natstate');
  5872. if (natBox && !natBox.classList.contains('hidden')) {
  5873. ['srcnat', 'dstnat'].forEach(s => {
  5874. if (document.getElementById(`mangle-modal-nat-${s}`)?.checked) natStates.push(s);
  5875. });
  5876. }
  5877. const payload = {
  5878. ip_version: Number(document.getElementById('mangle-modal-family').value),
  5879. id,
  5880. chain,
  5881. action,
  5882. protocol: proto || 'all',
  5883. src_address: src,
  5884. dst_address: dst,
  5885. src_port: sport,
  5886. dst_port: dport,
  5887. any_port: anyport,
  5888. in_interface: iniface,
  5889. out_interface: outiface,
  5890. in_interface_list: inifacelist,
  5891. out_interface_list: outifacelist,
  5892. packet_mark: pktmark,
  5893. connection_mark: connmark,
  5894. routing_mark: routingmark,
  5895. connection_type: conntype,
  5896. connection_state: states,
  5897. connection_nat_state: natStates,
  5898. src_address_list: srclist,
  5899. dst_address_list: dstlist,
  5900. src_geoip: srcgeo,
  5901. dst_geoip: dstgeo,
  5902. comment,
  5903. disabled: !enabled,
  5904. // Advanced tab
  5905. content: getMangleFieldVal('content', false),
  5906. src_mac_address: (chainLower === 'output' || chainLower === 'postrouting') ? '' : getMangleFieldVal('srcmac', true),
  5907. out_bridge_port: (chainLower === 'input' || chainLower === 'prerouting') ? '' : getMangleFieldVal('outbridgeport', false),
  5908. in_bridge_port: (chainLower === 'output' || chainLower === 'postrouting') ? '' : getMangleFieldVal('inbridgeport', false),
  5909. ipsec_policy: getMangleFieldVal('ipsec', false),
  5910. dscp: getMangleFieldVal('dscp', false),
  5911. tcp_mss: getMangleFieldVal('tcpmss', false),
  5912. tos: document.getElementById('mangle-val-tos')?.value || '',
  5913. packet_size: getMangleFieldVal('pktsize', false),
  5914. random: getMangleFieldVal('random', false),
  5915. tcp_flags: getMangleFieldVal('tcpflags', false),
  5916. icmp_options: getMangleFieldVal('icmpoptions', false),
  5917. ttl: getMangleFieldVal('ttl', false),
  5918. // Extra tab
  5919. nth: getMangleFieldVal('nth', false),
  5920. connection_limit: getMangleFieldVal('connlimit', false),
  5921. src_address_type: getMangleFieldVal('srcaddrtype', false),
  5922. dst_address_type: getMangleFieldVal('dstaddrtype', false),
  5923. ip_fragment: getMangleFieldVal('ipfragment', false),
  5924. limit: getMangleFieldVal('limit', false),
  5925. time: getMangleFieldVal('time', false),
  5926. // Action tab
  5927. new_connection_mark: action === 'mark-connection' ? (document.getElementById('mangle-modal-newconnmark')?.value.trim() || '') : '',
  5928. new_routing_mark: action === 'mark-routing' ? (document.getElementById('mangle-modal-newroutingmark')?.value.trim() || '') : '',
  5929. new_packet_mark: action === 'mark-packet' ? (document.getElementById('mangle-modal-newpktmark')?.value.trim() || '') : '',
  5930. new_mss: action === 'change-mss' ? (document.getElementById('mangle-modal-newmss')?.value.trim() || '') : '',
  5931. new_dscp: action === 'change-dscp' ? parseInt(document.getElementById('mangle-modal-newdscp')?.value || '0', 10) : 0,
  5932. new_ttl: action === 'change-ttl' ? (document.getElementById('mangle-modal-newttl')?.value.trim() || '') : '',
  5933. new_priority: action === 'set-priority' ? (document.getElementById('mangle-modal-newpriority')?.value.trim() || '') : '',
  5934. passthrough: document.getElementById('mangle-modal-passthrough')?.checked ?? true,
  5935. jump_target: action === 'jump' ? (document.getElementById('mangle-modal-jumptarget')?.value || '') : '',
  5936. address_list: action.includes('address') ? (document.getElementById('mangle-modal-action-addrlist')?.value || '') : '',
  5937. address_list_timeout: action.includes('address') ? (document.getElementById('mangle-modal-action-timeout')?.value || '') : '',
  5938. log: document.getElementById('mangle-modal-log')?.checked || false,
  5939. log_prefix: getMangleFieldVal('logprefix', false)
  5940. };
  5941. try {
  5942. const res = await fetch(`${API_BASE}/firewall/mangle`, {
  5943. method: 'POST',
  5944. headers: { 'Content-Type': 'application/json' },
  5945. body: JSON.stringify(payload)
  5946. });
  5947. if (res.ok) {
  5948. const data = await res.json();
  5949. showToast('Mangle Rule Saved', 'Marking rule updated', 'success');
  5950. loadFirewall(false);
  5951. if (closeAfter) {
  5952. closeMangleModal();
  5953. } else {
  5954. if (data.id) {
  5955. document.getElementById('mangle-modal-id').value = data.id;
  5956. const badge = document.getElementById('mangle-modal-badge');
  5957. if (badge) badge.innerText = `#${data.id}`;
  5958. }
  5959. }
  5960. } else {
  5961. const err = await res.json();
  5962. showToast('Error', err.message || 'Failed to save mangle rule', 'error');
  5963. }
  5964. } catch (err) {
  5965. showToast('Error', err.message, 'error');
  5966. }
  5967. }
  5968. function submitSaveMangleRule(e) {
  5969. if (e && e.preventDefault) e.preventDefault();
  5970. return applyMangleRule(true);
  5971. }
  5972. function startMangleStatPolling() {
  5973. stopMangleStatPolling();
  5974. pollMangleRuleStats();
  5975. state.mangleStatInterval = setInterval(pollMangleRuleStats, 1000);
  5976. }
  5977. function stopMangleStatPolling() {
  5978. if (state.mangleStatInterval) {
  5979. clearInterval(state.mangleStatInterval);
  5980. state.mangleStatInterval = null;
  5981. }
  5982. }
  5983. async function pollMangleRuleStats() {
  5984. const id = document.getElementById('mangle-modal-id')?.value;
  5985. if (!id) {
  5986. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory || new Array(30).fill(0), 'bps', 'mangle-stat-legend-rate');
  5987. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory || new Array(30).fill(0), 'p/s', 'mangle-stat-legend-pktrate');
  5988. return;
  5989. }
  5990. try {
  5991. const res = await fetch(`${API_BASE}/firewall/mangle`);
  5992. if (!res.ok) return;
  5993. const rules = await res.json();
  5994. const r = rules.find(x => x.id === id);
  5995. if (!r) return;
  5996. const now = Date.now();
  5997. const dt = Math.max(0.2, (now - (state.mangleLastTimestamp || now)) / 1000);
  5998. state.mangleLastTimestamp = now;
  5999. const curBytes = r.bytes || 0;
  6000. const curPackets = r.packets || 0;
  6001. const deltaBytes = Math.max(0, curBytes - (state.mangleLastBytes ?? curBytes));
  6002. const deltaPkts = Math.max(0, curPackets - (state.mangleLastPackets ?? curPackets));
  6003. state.mangleLastBytes = curBytes;
  6004. state.mangleLastPackets = curPackets;
  6005. const rateBps = Math.round((deltaBytes * 8) / dt);
  6006. const ratePkt = Math.round(deltaPkts / dt);
  6007. if (!state.mangleStatRateHistory) state.mangleStatRateHistory = new Array(30).fill(0);
  6008. if (!state.mangleStatPktHistory) state.mangleStatPktHistory = new Array(30).fill(0);
  6009. state.mangleStatRateHistory.push(rateBps);
  6010. if (state.mangleStatRateHistory.length > 30) state.mangleStatRateHistory.shift();
  6011. state.mangleStatPktHistory.push(ratePkt);
  6012. if (state.mangleStatPktHistory.length > 30) state.mangleStatPktHistory.shift();
  6013. const bEl = document.getElementById('mangle-stat-bytes');
  6014. const pEl = document.getElementById('mangle-stat-packets');
  6015. const rEl = document.getElementById('mangle-stat-rate');
  6016. const prEl = document.getElementById('mangle-stat-pktrate');
  6017. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  6018. if (pEl) pEl.value = curPackets.toLocaleString();
  6019. if (rEl) rEl.value = formatBps(rateBps);
  6020. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  6021. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  6022. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  6023. } catch (e) {
  6024. console.error('Error polling Mangle rule stats', e);
  6025. }
  6026. }
  6027. async function moveMangleRule(id, dir) {
  6028. id = decodeURIComponent(id);
  6029. try {
  6030. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/move`, {
  6031. method: 'POST',
  6032. headers: { 'Content-Type': 'application/json' },
  6033. body: JSON.stringify({ direction: dir })
  6034. });
  6035. if (!res.ok) throw new Error(await responseError(res));
  6036. await loadFirewall(false);
  6037. } catch (err) {
  6038. showToast('Error', err.message, 'error');
  6039. }
  6040. }
  6041. async function toggleMangleRuleState(id, disabled) {
  6042. id = decodeURIComponent(id);
  6043. try {
  6044. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/state`, {
  6045. method: 'POST',
  6046. headers: { 'Content-Type': 'application/json' },
  6047. body: JSON.stringify({ disabled })
  6048. });
  6049. if (!res.ok) throw new Error(await responseError(res));
  6050. await loadFirewall(false);
  6051. } catch (err) {
  6052. showToast('Error', err.message, 'error');
  6053. }
  6054. }
  6055. async function deleteMangleRule(id) {
  6056. id = decodeURIComponent(id);
  6057. if (!confirm('Are you sure you want to delete this mangle rule?')) return;
  6058. try {
  6059. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6060. if (!res.ok) throw new Error(await responseError(res));
  6061. {
  6062. showToast('Deleted', 'Mangle rule removed', 'success');
  6063. loadFirewall(false);
  6064. }
  6065. } catch (err) {
  6066. showToast('Error', err.message, 'error');
  6067. }
  6068. }
  6069. // ----------------- Address Lists -----------------
  6070. function renderAddressLists() {
  6071. const filterList = document.getElementById('addrlist-filter-name')?.value || '';
  6072. const tbody = document.getElementById('addrlist-table-body');
  6073. const empty = document.getElementById('addrlist-empty');
  6074. if (!tbody) return;
  6075. tbody.innerHTML = '';
  6076. const entries = (state.addressLists || []).filter(e => !filterList || e.name === filterList);
  6077. document.getElementById('addrlist-count-badge').innerText = `${entries.length} Entries${entries.filter(e => e.dynamic).length >= 2000 ? ' (dynamic results capped at 2000)' : ''}`;
  6078. // Update filter select
  6079. const sel = document.getElementById('addrlist-filter-name');
  6080. if (sel) {
  6081. const cur = sel.value;
  6082. sel.innerHTML = '<option value="">All Lists</option>';
  6083. const set = new Set((state.addressLists || []).map(a => a.name));
  6084. set.forEach(n => {
  6085. const opt = document.createElement('option');
  6086. opt.value = n;
  6087. opt.innerText = n;
  6088. if (n === cur) opt.selected = true;
  6089. sel.appendChild(opt);
  6090. });
  6091. }
  6092. if (entries.length === 0) {
  6093. empty?.classList.remove('hidden');
  6094. return;
  6095. }
  6096. empty?.classList.add('hidden');
  6097. entries.forEach((raw, idx) => {
  6098. const e = safeFirewallRow(raw);
  6099. const tr = document.createElement('tr');
  6100. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${e.disabled ? 'opacity-50' : ''}`;
  6101. if (!e.dynamic) tr.setAttribute('ondblclick', `openEditAddrListModal('${e.id}')`);
  6102. tr.innerHTML = `
  6103. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  6104. <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>
  6105. <td class="py-2.5 px-3 font-bold text-white font-mono">${e.name}</td>
  6106. <td class="py-2.5 px-3 font-mono font-bold text-emerald-400">${e.address}</td>
  6107. <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>
  6108. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  6109. ${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>
  6110. <button onclick="openEditAddrListModal('${e.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-medium">Edit</button>
  6111. `}
  6112. <button onclick="deleteAddrList('${e.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  6113. </td>
  6114. `;
  6115. tbody.appendChild(tr);
  6116. });
  6117. populateCommonAddrListDatalist();
  6118. }
  6119. function openAddAddrListModal() {
  6120. document.getElementById('addrlist-modal-title').innerText = 'Add Address List Entry';
  6121. document.getElementById('addrlist-modal-id').value = '';
  6122. document.getElementById('addrlist-modal-name').value = '';
  6123. document.getElementById('addrlist-modal-addr').value = '';
  6124. document.getElementById('addrlist-modal-comment').value = '';
  6125. document.getElementById('addrlist-modal-disabled').checked = false;
  6126. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  6127. if (submitBtn) submitBtn.innerText = 'Add to List';
  6128. document.getElementById('addrlist-modal').classList.remove('hidden');
  6129. }
  6130. function openEditAddrListModal(id) {
  6131. id = decodeURIComponent(id);
  6132. const e = (state.addressLists || []).find(item => item.id === id);
  6133. if (!e) return;
  6134. document.getElementById('addrlist-modal-title').innerText = `Edit Address List Entry: ${e.name}`;
  6135. document.getElementById('addrlist-modal-id').value = e.id;
  6136. document.getElementById('addrlist-modal-name').value = e.name;
  6137. document.getElementById('addrlist-modal-addr').value = e.address;
  6138. document.getElementById('addrlist-modal-comment').value = e.comment || '';
  6139. document.getElementById('addrlist-modal-disabled').checked = !!e.disabled;
  6140. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  6141. if (submitBtn) submitBtn.innerText = 'Save Changes';
  6142. document.getElementById('addrlist-modal').classList.remove('hidden');
  6143. }
  6144. function closeAddrListModal() {
  6145. document.getElementById('addrlist-modal').classList.add('hidden');
  6146. }
  6147. async function submitSaveAddrList(e) {
  6148. e.preventDefault();
  6149. const id = document.getElementById('addrlist-modal-id').value;
  6150. const name = document.getElementById('addrlist-modal-name').value.trim();
  6151. const addr = document.getElementById('addrlist-modal-addr').value.trim();
  6152. const comment = document.getElementById('addrlist-modal-comment').value.trim();
  6153. const disabled = document.getElementById('addrlist-modal-disabled').checked;
  6154. try {
  6155. const res = await fetch(`${API_BASE}/firewall/address-lists`, {
  6156. method: 'POST',
  6157. headers: { 'Content-Type': 'application/json' },
  6158. body: JSON.stringify({ id, name, address: addr, comment, disabled })
  6159. });
  6160. if (res.ok) {
  6161. showToast('Address List Item Saved', `Saved ${addr} in ${name}`, 'success');
  6162. closeAddrListModal();
  6163. loadFirewall(false);
  6164. } else {
  6165. const err = await res.json();
  6166. showToast('Error', err.message || 'Failed to save address list', 'error');
  6167. }
  6168. } catch (err) {
  6169. showToast('Error', err.message, 'error');
  6170. }
  6171. }
  6172. async function toggleAddrListState(id, disabled) {
  6173. id = decodeURIComponent(id);
  6174. try {
  6175. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}/state`, {
  6176. method: 'POST',
  6177. headers: { 'Content-Type': 'application/json' },
  6178. body: JSON.stringify({ disabled })
  6179. });
  6180. if (res.ok) {
  6181. loadFirewall(false);
  6182. }
  6183. } catch (err) {
  6184. showToast('Error', err.message, 'error');
  6185. }
  6186. }
  6187. async function deleteAddrList(id) {
  6188. id = decodeURIComponent(id);
  6189. if (!confirm('Are you sure you want to delete this address list item?')) return;
  6190. try {
  6191. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6192. if (res.ok) {
  6193. showToast('Deleted', 'Address list item removed', 'info');
  6194. loadFirewall(false);
  6195. }
  6196. } catch (err) {
  6197. showToast('Error', err.message, 'error');
  6198. }
  6199. }
  6200. // ----------------- Geo-Location IP Management -----------------
  6201. async function loadGeoIP() {
  6202. try {
  6203. const [statusRes, countriesRes] = await Promise.all([
  6204. fetch(`${API_BASE}/firewall/geoip/status`),
  6205. fetch(`${API_BASE}/firewall/geoip/countries`)
  6206. ]);
  6207. if (statusRes.ok) state.geoStatus = await statusRes.json();
  6208. if (countriesRes.ok) state.geoCountries = await countriesRes.json();
  6209. updateGeoHeader();
  6210. renderGeoCountries();
  6211. } catch (err) {
  6212. console.error('Failed to load GeoIP:', err);
  6213. }
  6214. }
  6215. function getGeoUsageMap() {
  6216. const usage = {};
  6217. const checkRule = (r, type) => {
  6218. ['src_geoip', 'dst_geoip'].forEach(field => {
  6219. let val = (r && r[field]) || '';
  6220. let code = val.replace(/^!/, '').replace(/^geo:/, '').replace(/^geo_/, '').toUpperCase().trim();
  6221. if (code) {
  6222. if (!usage[code]) usage[code] = [];
  6223. const label = `${type} #${r.priority !== undefined ? r.priority : (r.id || '')}`;
  6224. if (!usage[code].includes(label)) usage[code].push(label);
  6225. }
  6226. });
  6227. };
  6228. (state.filterRules || []).forEach(r => checkRule(r, 'Filter'));
  6229. (state.natRules || []).forEach(r => checkRule(r, 'NAT'));
  6230. (state.mangleRules || []).forEach(r => checkRule(r, 'Mangle'));
  6231. return usage;
  6232. }
  6233. function updateGeoHeader() {
  6234. const s = state.geoStatus || {};
  6235. const statusBadge = document.getElementById('geo-status-badge');
  6236. if (statusBadge) {
  6237. statusBadge.innerText = s.auto_update ? 'Auto-Update ON' : 'Auto-Update OFF';
  6238. statusBadge.className = s.auto_update
  6239. ? 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-emerald-500/20 text-emerald-300 border border-emerald-500/30'
  6240. : 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 text-slate-400';
  6241. }
  6242. const intervalLabel = document.getElementById('geo-interval-label');
  6243. if (intervalLabel) {
  6244. intervalLabel.innerText = `Every ${s.interval_hours || 24}h`;
  6245. }
  6246. const usageMap = getGeoUsageMap();
  6247. const inUseCount = Object.keys(usageMap).length;
  6248. const activeCountEl = document.getElementById('geo-stat-active-countries');
  6249. if (activeCountEl) activeCountEl.innerText = inUseCount.toLocaleString();
  6250. const totalSubnetsEl = document.getElementById('geo-stat-total-subnets');
  6251. if (totalSubnetsEl) totalSubnetsEl.innerText = (s.total_subnets || 0).toLocaleString();
  6252. const lastSyncEl = document.getElementById('geo-stat-last-sync');
  6253. if (lastSyncEl) {
  6254. if (s.last_updated && !s.last_updated.startsWith('0001')) {
  6255. const d = new Date(s.last_updated);
  6256. lastSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  6257. } else {
  6258. lastSyncEl.innerText = 'Never (Sync Pending)';
  6259. }
  6260. }
  6261. const nextSyncEl = document.getElementById('geo-stat-next-sync');
  6262. if (nextSyncEl) {
  6263. if (s.next_update && !s.next_update.startsWith('0001')) {
  6264. const d = new Date(s.next_update);
  6265. nextSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  6266. } else {
  6267. nextSyncEl.innerText = '-';
  6268. }
  6269. }
  6270. const badge = document.getElementById('fw-badge-geo');
  6271. if (badge) badge.innerText = inUseCount || (state.geoCountries || []).filter(c => c.subnet_count > 0).length || 0;
  6272. }
  6273. function renderGeoCountries() {
  6274. const tbody = document.getElementById('geo-table-body');
  6275. const empty = document.getElementById('geo-empty');
  6276. if (!tbody) return;
  6277. tbody.innerHTML = '';
  6278. const q = (document.getElementById('geo-search-input')?.value || '').trim().toLowerCase();
  6279. const continent = document.getElementById('geo-continent-filter')?.value || '';
  6280. const inUseOnly = document.getElementById('geo-filter-inuse-only')?.checked;
  6281. const cachedOnly = document.getElementById('geo-filter-cached-only')?.checked;
  6282. const usageMap = getGeoUsageMap();
  6283. const countries = (state.geoCountries || []).filter(c => {
  6284. const isUsed = !!usageMap[c.code];
  6285. if (inUseOnly && !isUsed) return false;
  6286. if (cachedOnly && (!c.subnet_count || c.subnet_count === 0)) return false;
  6287. if (continent && c.continent !== continent) return false;
  6288. if (q) {
  6289. const matchCode = c.code.toLowerCase().includes(q);
  6290. const matchName = c.name.toLowerCase().includes(q);
  6291. if (!matchCode && !matchName) return false;
  6292. }
  6293. return true;
  6294. });
  6295. if (countries.length === 0) {
  6296. empty?.classList.remove('hidden');
  6297. return;
  6298. }
  6299. empty?.classList.add('hidden');
  6300. countries.forEach(c => {
  6301. const tr = document.createElement('tr');
  6302. const isUsed = !!usageMap[c.code];
  6303. const rulesUsing = usageMap[c.code] || [];
  6304. tr.className = `hover:bg-slate-800/40 transition text-xs ${isUsed ? 'bg-emerald-950/20' : ''}`;
  6305. let statusHtml = '';
  6306. if (isUsed) {
  6307. 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>`;
  6308. } else if (c.subnet_count > 0) {
  6309. 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>';
  6310. } else {
  6311. statusHtml = '<span class="px-2 py-0.5 rounded text-[10px] font-mono text-slate-500 bg-slate-800/60">READY</span>';
  6312. }
  6313. tr.innerHTML = `
  6314. <td class="py-2.5 px-3 text-center">
  6315. <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'}">
  6316. ${c.code}
  6317. </span>
  6318. </td>
  6319. <td class="py-2.5 px-3 font-bold text-white">${c.name}</td>
  6320. <td class="py-2.5 px-3 text-slate-400">${c.continent}</td>
  6321. <td class="py-2.5 px-3 font-mono ${c.subnet_count > 0 ? 'text-emerald-400 font-bold' : 'text-slate-500'}">
  6322. ${c.subnet_count > 0 ? c.subnet_count.toLocaleString() + ' CIDRs' : 'Not Cached'}
  6323. </td>
  6324. <td class="py-2.5 px-3 font-mono text-purple-300">${c.ipset_name}</td>
  6325. <td class="py-2.5 px-3">
  6326. ${statusHtml}
  6327. </td>
  6328. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  6329. <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>
  6330. <button onclick="viewGeoSubnets('${c.code}')" class="text-xs text-slate-400 hover:text-white" title="Preview Subnet Ranges">View</button>
  6331. </td>
  6332. `;
  6333. tbody.appendChild(tr);
  6334. });
  6335. }
  6336. function quickFilterGeo(preset) {
  6337. const searchInput = document.getElementById('geo-search-input');
  6338. const continentSel = document.getElementById('geo-continent-filter');
  6339. const inUseCheck = document.getElementById('geo-filter-inuse-only');
  6340. const cachedCheck = document.getElementById('geo-filter-cached-only');
  6341. if (searchInput) searchInput.value = '';
  6342. if (continentSel) continentSel.value = '';
  6343. if (inUseCheck) inUseCheck.checked = false;
  6344. if (cachedCheck) cachedCheck.checked = false;
  6345. if (preset === 'GR') {
  6346. if (searchInput) searchInput.value = 'Greece';
  6347. } else if (preset === 'Europe') {
  6348. if (continentSel) continentSel.value = 'Europe';
  6349. } else if (preset === 'HIGHRISK') {
  6350. if (searchInput) searchInput.value = 'China';
  6351. }
  6352. renderGeoCountries();
  6353. }
  6354. async function toggleGeoCountry(code, enabled) {
  6355. try {
  6356. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/toggle`, {
  6357. method: 'POST',
  6358. headers: { 'Content-Type': 'application/json' },
  6359. body: JSON.stringify({ enabled })
  6360. });
  6361. if (res.ok) {
  6362. showToast(enabled ? 'Country Enabled' : 'Country Disabled', `${code} ${enabled ? 'active in firewall' : 'removed from firewall'}`, 'success');
  6363. loadGeoIP();
  6364. } else {
  6365. const err = await res.json();
  6366. showToast('Error', err.message || 'Failed to toggle country', 'error');
  6367. }
  6368. } catch (err) {
  6369. showToast('Error', err.message, 'error');
  6370. }
  6371. }
  6372. async function updateGeoCountry(code) {
  6373. try {
  6374. showToast('Syncing Country', `Downloading latest IP blocks for ${code}...`, 'info');
  6375. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/update`, { method: 'POST' });
  6376. if (res.ok) {
  6377. const data = await res.json();
  6378. showToast('Synced', `Loaded ${data.subnets} CIDR blocks for ${code}`, 'success');
  6379. loadGeoIP();
  6380. } else {
  6381. const err = await res.json();
  6382. showToast('Sync Error', err.message || 'Failed to sync country', 'error');
  6383. }
  6384. } catch (err) {
  6385. showToast('Error', err.message, 'error');
  6386. }
  6387. }
  6388. async function triggerGeoUpdateNow() {
  6389. const spinner = document.getElementById('geo-update-spinner');
  6390. if (spinner) spinner.classList.remove('hidden');
  6391. try {
  6392. const res = await fetch(`${API_BASE}/firewall/geoip/update-now`, { method: 'POST' });
  6393. if (res.ok) {
  6394. showToast('Update Started', 'Updating all active GeoIP country zones in background...', 'info');
  6395. setTimeout(() => {
  6396. loadGeoIP();
  6397. if (spinner) spinner.classList.add('hidden');
  6398. }, 2500);
  6399. } else {
  6400. const err = await res.json();
  6401. showToast('Notice', err.message || 'Update in progress', 'info');
  6402. if (spinner) spinner.classList.add('hidden');
  6403. }
  6404. } catch (err) {
  6405. showToast('Error', err.message, 'error');
  6406. if (spinner) spinner.classList.add('hidden');
  6407. }
  6408. }
  6409. async function applyGeoPreset(preset) {
  6410. try {
  6411. const res = await fetch(`${API_BASE}/firewall/geoip/batch-toggle`, {
  6412. method: 'POST',
  6413. headers: { 'Content-Type': 'application/json' },
  6414. body: JSON.stringify({ preset, enabled: preset !== 'NONE' })
  6415. });
  6416. if (res.ok) {
  6417. showToast('Preset Applied', `Preset ${preset} updated in firewall`, 'success');
  6418. loadGeoIP();
  6419. }
  6420. } catch (err) {
  6421. showToast('Error', err.message, 'error');
  6422. }
  6423. }
  6424. function openGeoIntervalModal() {
  6425. const s = state.geoStatus || {};
  6426. document.getElementById('geo-cfg-autoupdate').checked = s.auto_update !== false;
  6427. const sel = document.getElementById('geo-cfg-interval');
  6428. const customBox = document.getElementById('geo-cfg-custom-box');
  6429. const customHoursInput = document.getElementById('geo-cfg-custom-hours');
  6430. const curHours = s.interval_hours || 24;
  6431. const matchOption = Array.from(sel.options).find(o => parseInt(o.value, 10) === curHours);
  6432. if (matchOption) {
  6433. sel.value = String(curHours);
  6434. customBox.classList.add('hidden');
  6435. } else {
  6436. sel.value = 'custom';
  6437. customHoursInput.value = curHours;
  6438. customBox.classList.remove('hidden');
  6439. }
  6440. document.getElementById('geo-interval-modal').classList.remove('hidden');
  6441. }
  6442. function closeGeoIntervalModal() {
  6443. document.getElementById('geo-interval-modal').classList.add('hidden');
  6444. }
  6445. function toggleCustomGeoInterval() {
  6446. const val = document.getElementById('geo-cfg-interval').value;
  6447. const customBox = document.getElementById('geo-cfg-custom-box');
  6448. if (val === 'custom') {
  6449. customBox.classList.remove('hidden');
  6450. } else {
  6451. customBox.classList.add('hidden');
  6452. }
  6453. }
  6454. async function submitGeoIntervalSettings(e) {
  6455. e.preventDefault();
  6456. const autoUpdate = document.getElementById('geo-cfg-autoupdate').checked;
  6457. const intervalVal = document.getElementById('geo-cfg-interval').value;
  6458. let hours = 24;
  6459. if (intervalVal === 'custom') {
  6460. hours = parseInt(document.getElementById('geo-cfg-custom-hours').value, 10) || 24;
  6461. } else {
  6462. hours = parseInt(intervalVal, 10) || 24;
  6463. }
  6464. try {
  6465. const res = await fetch(`${API_BASE}/firewall/geoip/config`, {
  6466. method: 'POST',
  6467. headers: { 'Content-Type': 'application/json' },
  6468. body: JSON.stringify({ auto_update: autoUpdate, interval_hours: hours })
  6469. });
  6470. if (res.ok) {
  6471. showToast('Schedule Saved', `Auto-update set to every ${hours} hours`, 'success');
  6472. closeGeoIntervalModal();
  6473. loadGeoIP();
  6474. } else {
  6475. const err = await res.json();
  6476. showToast('Error', err.message || 'Failed to save schedule', 'error');
  6477. }
  6478. } catch (err) {
  6479. showToast('Error', err.message, 'error');
  6480. }
  6481. }
  6482. async function viewGeoSubnets(code, name) {
  6483. if (!name) {
  6484. const found = (state.geoCountries || []).find(x => x.code === code);
  6485. name = found ? found.name : code;
  6486. }
  6487. document.getElementById('geo-subnets-title').innerText = `${name} (${code}) Subnets`;
  6488. document.getElementById('geo-subnets-subtitle').innerText = `Kernel IPSet: mk_geo_${code}`;
  6489. const listEl = document.getElementById('geo-subnets-list');
  6490. listEl.innerHTML = '<span class="text-slate-500">Loading subnets...</span>';
  6491. document.getElementById('geo-subnets-modal').classList.remove('hidden');
  6492. try {
  6493. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/subnets`);
  6494. if (res.ok) {
  6495. const data = await res.json();
  6496. const subnets = data.subnets || [];
  6497. if (subnets.length === 0) {
  6498. listEl.innerHTML = '<span class="text-slate-500">No cached subnets found. Click Sync to download this zone.</span>';
  6499. } else {
  6500. listEl.innerHTML = subnets.map(s => `<div>${s}</div>`).join('');
  6501. }
  6502. } else {
  6503. listEl.innerHTML = '<span class="text-rose-400">Failed to load subnets.</span>';
  6504. }
  6505. } catch (err) {
  6506. listEl.innerHTML = `<span class="text-rose-400">Error: ${err.message}</span>`;
  6507. }
  6508. }
  6509. function closeGeoSubnetsModal() {
  6510. document.getElementById('geo-subnets-modal').classList.add('hidden');
  6511. }
  6512. // ----------------- Active Connections Tracking -----------------
  6513. async function loadConnections() {
  6514. try {
  6515. const res = await fetch(`${API_BASE}/firewall/connections`);
  6516. const data = await res.json();
  6517. if (!res.ok) throw new Error(data.message || 'Connection tracking unavailable');
  6518. state.connections = Array.isArray(data) ? data : [];
  6519. document.getElementById('fw-badge-connections').innerText = state.connections.length;
  6520. document.getElementById('conns-count-badge').innerText = `${state.connections.length} Flows`;
  6521. renderConnections();
  6522. } catch (err) {
  6523. console.error('Failed to load connections:', err);
  6524. const badge=document.getElementById('conns-count-badge'); if(badge) badge.textContent='Unavailable: '+err.message;
  6525. }
  6526. }
  6527. function renderConnections() {
  6528. const search = (document.getElementById('conns-search-input')?.value || '').toLowerCase();
  6529. const protoFilter = document.getElementById('conns-filter-proto')?.value || '';
  6530. const tbody = document.getElementById('conns-table-body');
  6531. const empty = document.getElementById('conns-empty');
  6532. if (!tbody) return;
  6533. tbody.innerHTML = '';
  6534. const conns = (state.connections || []).filter(c => {
  6535. if (protoFilter && c.protocol !== protoFilter) return false;
  6536. if (search) {
  6537. const line = `${c.protocol} ${c.src_address} ${c.dst_address} ${c.src_port} ${c.dst_port} ${c.tcp_state} ${c.connection_mark}`.toLowerCase();
  6538. if (!line.includes(search)) return false;
  6539. }
  6540. return true;
  6541. });
  6542. if (conns.length === 0) {
  6543. empty?.classList.remove('hidden');
  6544. return;
  6545. }
  6546. empty?.classList.add('hidden');
  6547. conns.slice(0, 150).forEach(c => {
  6548. const tr = document.createElement('tr');
  6549. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  6550. let stateColor = 'text-slate-400';
  6551. if (c.tcp_state === 'ESTABLISHED') stateColor = 'text-emerald-400 font-bold';
  6552. else if (c.tcp_state === 'TIME_WAIT' || c.tcp_state === 'SYN_SENT') stateColor = 'text-amber-400';
  6553. tr.innerHTML = `
  6554. <td class="py-2.5 px-3 font-bold text-cyan-400">${c.protocol}</td>
  6555. <td class="py-2.5 px-3 font-mono text-white">${c.src_address}:${c.src_port}</td>
  6556. <td class="py-2.5 px-3 font-mono text-white">${c.dst_address}:${c.dst_port}</td>
  6557. <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>
  6558. <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>
  6559. <td class="py-2.5 px-3 font-mono ${stateColor}">${c.tcp_state}</td>
  6560. <td class="py-2.5 px-3 font-mono text-purple-300">${c.connection_mark || '-'}</td>
  6561. <td class="py-2.5 px-3 text-slate-500">${c.timeout ? c.timeout + 's' : '-'}</td>
  6562. <td class="py-2.5 px-3 text-right font-sans">
  6563. ${['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>` : ''}
  6564. </td>
  6565. `;
  6566. tbody.appendChild(tr);
  6567. });
  6568. }
  6569. async function killConnection(protocol, src, sport, dst, dport, ip_version, zone, icmp_id, icmp_type, icmp_code) {
  6570. try {
  6571. const res = await fetch(`${API_BASE}/firewall/connections/kill`, {
  6572. method: 'POST',
  6573. headers: { 'Content-Type': 'application/json' },
  6574. body: JSON.stringify({ protocol, src, sport, dst, dport, ip_version, zone, icmp_id, icmp_type, icmp_code })
  6575. });
  6576. if (res.ok) {
  6577. showToast('Terminated', `Killed flow ${src}:${sport} -> ${dst}:${dport}`, 'info');
  6578. loadConnections();
  6579. } else { const error = await res.json(); showToast('Error', error.message || 'Unable to terminate this flow', 'error'); }
  6580. } catch (err) {
  6581. showToast('Error', err.message, 'error');
  6582. }
  6583. }
  6584. async function resetFirewallCounters() {
  6585. if (!confirm('Reset all firewall packet and byte counters to zero?')) return;
  6586. try {
  6587. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  6588. if (res.ok) {
  6589. showToast('Counters Reset', 'All rules counters reset to 0', 'success');
  6590. loadFirewall(false);
  6591. }
  6592. } catch (err) {
  6593. showToast('Error', err.message, 'error');
  6594. }
  6595. }
  6596. // ======================== MIKROTIK ROUTING & POLICY (/ip route) ========================
  6597. function switchRoutesSubTab(tab) {
  6598. state.routesSubTab = tab;
  6599. const tabs = ['routes', 'rules', 'tables'];
  6600. tabs.forEach(t => {
  6601. const panel = document.getElementById(`routes-subtab-${t}`);
  6602. const btn = document.getElementById(`routes-subtab-btn-${t}`);
  6603. if (panel) {
  6604. if (t === tab) panel.classList.remove('hidden');
  6605. else panel.classList.add('hidden');
  6606. }
  6607. if (btn) {
  6608. if (t === tab) {
  6609. 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';
  6610. } else {
  6611. 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';
  6612. }
  6613. }
  6614. });
  6615. setTimeout(initTableSorting, 50);
  6616. }
  6617. async function loadRoutes() {
  6618. try {
  6619. const [routesRes, rulesRes, tablesRes] = await Promise.all([
  6620. fetch(`${API_BASE}/routes`),
  6621. fetch(`${API_BASE}/routing/rules`),
  6622. fetch(`${API_BASE}/routing/tables`)
  6623. ]);
  6624. if (routesRes.ok) state.routes = await routesRes.json();
  6625. if (rulesRes.ok) state.policyRules = await rulesRes.json();
  6626. if (tablesRes.ok) state.routingTables = await tablesRes.json();
  6627. const bRoutes = document.getElementById('routes-badge-routes');
  6628. if (bRoutes) bRoutes.innerText = (state.routes || []).length;
  6629. const showSystem = document.getElementById('prule-show-system')?.checked;
  6630. const userRules = (state.policyRules || []).filter(pr => showSystem || (!pr.is_default && !pr.is_system));
  6631. const bRules = document.getElementById('routes-badge-rules');
  6632. if (bRules) bRules.innerText = userRules.length;
  6633. const bTables = document.getElementById('routes-badge-tables');
  6634. if (bTables) bTables.innerText = (state.routingTables || []).length;
  6635. const bRoutesCount = document.getElementById('badge-routes-count');
  6636. if (bRoutesCount) bRoutesCount.innerText = (state.routes || []).length;
  6637. renderRoutesList();
  6638. renderPolicyRules();
  6639. renderRoutingTables();
  6640. } catch (err) {
  6641. console.error('Failed to load routing:', err);
  6642. }
  6643. }
  6644. function getRouteProtocolBadge(proto) {
  6645. const p = (proto || 'static').toLowerCase();
  6646. switch (p) {
  6647. case 'bgp':
  6648. 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>`;
  6649. case 'ibgp':
  6650. 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>`;
  6651. case 'ospf':
  6652. 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>`;
  6653. case 'rip':
  6654. 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>`;
  6655. case 'static':
  6656. 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>`;
  6657. case 'connected':
  6658. 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>`;
  6659. case 'dhcp':
  6660. 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>`;
  6661. case 'multicast':
  6662. 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>`;
  6663. default:
  6664. 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>`;
  6665. }
  6666. }
  6667. function renderRoutesList() {
  6668. const tableFilter = document.getElementById('routes-filter-table')?.value || '';
  6669. const typeFilter = document.getElementById('routes-filter-type')?.value || '';
  6670. const tbody = document.getElementById('routes-table-body');
  6671. const empty = document.getElementById('routes-empty');
  6672. if (!tbody) return;
  6673. // Update table filter select
  6674. const sel = document.getElementById('routes-filter-table');
  6675. if (sel) {
  6676. const cur = sel.value;
  6677. sel.innerHTML = '<option value="">All Tables</option>';
  6678. (state.routingTables || []).forEach(t => {
  6679. const opt = document.createElement('option');
  6680. opt.value = t.name;
  6681. opt.innerText = t.name;
  6682. if (t.name === cur) opt.selected = true;
  6683. sel.appendChild(opt);
  6684. });
  6685. }
  6686. const routes = (state.routes || []).filter(r => {
  6687. if (tableFilter && r.routing_table !== tableFilter) return false;
  6688. if (typeFilter === 'ecmp' && !r.ecmp) return false;
  6689. if (typeFilter === 'multicast' && !r.multicast) return false;
  6690. if (typeFilter === 'static' && !r.static) return false;
  6691. if (typeFilter === 'dynamic' && !r.dynamic) return false;
  6692. if (typeFilter === 'connected' && !r.connect) return false;
  6693. if (typeFilter === 'bgp' && (r.protocol || '').toLowerCase() !== 'bgp' && (r.protocol || '').toLowerCase() !== 'ibgp') return false;
  6694. if (typeFilter === 'ospf' && (r.protocol || '').toLowerCase() !== 'ospf') return false;
  6695. if (typeFilter === 'dhcp' && (r.protocol || '').toLowerCase() !== 'dhcp') return false;
  6696. return true;
  6697. });
  6698. const ecmpCount = (state.routes || []).filter(r => r.ecmp).length;
  6699. const mcCount = (state.routes || []).filter(r => r.multicast).length;
  6700. let summaryText = `${routes.length} Routes`;
  6701. if (ecmpCount > 0) summaryText += ` • ${ecmpCount} ECMP`;
  6702. if (mcCount > 0) summaryText += ` • ${mcCount} Multicast/IGMP`;
  6703. const badgeEl = document.getElementById('routes-count-badge');
  6704. if (badgeEl) badgeEl.innerText = summaryText;
  6705. if (routes.length === 0) {
  6706. empty?.classList.remove('hidden');
  6707. tbody.innerHTML = '';
  6708. return;
  6709. }
  6710. empty?.classList.add('hidden');
  6711. const sig = `${tableFilter}|${typeFilter}|` + routes.map(r => `${r.id}:${r.active}:${r.disabled}:${r.distance}:${r.protocol}:${r.health_status}:${(r.health_rtt_ms || 0).toFixed(0)}`).join(';');
  6712. if (tbody.dataset.sig === sig) {
  6713. return; // Routes table unchanged! Do not wipe DOM or flicker!
  6714. }
  6715. tbody.dataset.sig = sig;
  6716. tbody.innerHTML = '';
  6717. routes.forEach(r => {
  6718. const tr = document.createElement('tr');
  6719. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${r.disabled ? 'opacity-50' : ''}`;
  6720. tr.setAttribute('ondblclick', `openEditRouteModal('${r.id}')`);
  6721. // Routing Flags string: D=Dynamic, A=Active, C=Connect, S=Static, E=ECMP, M=Multicast, X=Disabled
  6722. let flags = '';
  6723. if (r.dynamic) flags += 'D';
  6724. if (r.active) flags += 'A';
  6725. if (r.connect) flags += 'C';
  6726. if (r.static) flags += 'S';
  6727. if (r.ecmp) flags += 'E';
  6728. if (r.multicast) flags += 'M';
  6729. if (r.disabled) flags += 'X';
  6730. const isDefault = r.dst_address === 'default' || r.dst_address === '0.0.0.0/0';
  6731. let healthCell = `<span class="text-slate-600 font-mono text-[11px]">-</span>`;
  6732. if (r.check_gateway === 'internet') {
  6733. if (r.health_status === 'online') {
  6734. const ms = (r.health_rtt_ms || 0).toFixed(0);
  6735. healthCell = `
  6736. <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)">
  6737. <span class="w-1.5 h-1.5 rounded-full bg-emerald-400 animate-pulse"></span>
  6738. <span>Internet OK (${ms}ms)</span>
  6739. </span>
  6740. `;
  6741. } else if (r.health_status === 'offline') {
  6742. healthCell = `
  6743. <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.">
  6744. <span class="w-1.5 h-1.5 rounded-full bg-rose-400"></span>
  6745. <span>Internet Down</span>
  6746. </span>
  6747. `;
  6748. } else {
  6749. healthCell = `
  6750. <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">
  6751. <span class="w-1.5 h-1.5 rounded-full bg-amber-400 animate-ping"></span>
  6752. <span>Checking...</span>
  6753. </span>
  6754. `;
  6755. }
  6756. } else if (r.check_gateway === 'ping') {
  6757. if (r.health_status === 'online') {
  6758. healthCell = `
  6759. <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">
  6760. <span class="w-1.5 h-1.5 rounded-full bg-cyan-400"></span>
  6761. <span>Gateway OK (${(r.health_rtt_ms || 0).toFixed(0)}ms)</span>
  6762. </span>
  6763. `;
  6764. } else if (r.health_status === 'offline') {
  6765. healthCell = `
  6766. <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">
  6767. <span class="w-1.5 h-1.5 rounded-full bg-rose-400"></span>
  6768. <span>Gateway Dead</span>
  6769. </span>
  6770. `;
  6771. }
  6772. }
  6773. const flagDescriptions = [];
  6774. if (r.dynamic) flagDescriptions.push('Dynamic (D)');
  6775. if (r.active) flagDescriptions.push('Active (A)');
  6776. if (r.connect) flagDescriptions.push('Connected (C)');
  6777. if (r.static) flagDescriptions.push('Static (S)');
  6778. if (r.ecmp) flagDescriptions.push('ECMP - Equal-Cost Multi-Path (E)');
  6779. if (r.multicast) flagDescriptions.push('Multicast / IGMP Group (M)');
  6780. if (r.disabled) flagDescriptions.push('Disabled (X)');
  6781. tr.innerHTML = `
  6782. <td class="py-2.5 px-3 text-center">
  6783. <span class="px-1.5 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 ${
  6784. 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')
  6785. }" title="Flags: ${flagDescriptions.join(', ')}">
  6786. ${flags || '-'}
  6787. </span>
  6788. </td>
  6789. <td class="py-2.5 px-3">
  6790. <div class="flex items-center gap-1.5 flex-wrap">
  6791. <span class="font-bold ${isDefault ? 'text-cyan-300' : 'text-white'}">${escapeHtml(r.dst_address)}</span>
  6792. ${r.ecmp ? `
  6793. <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)">
  6794. <span>⚡ ECMP</span>
  6795. </span>
  6796. ` : ''}
  6797. ${r.multicast ? `
  6798. <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">
  6799. <span>IGMP</span>
  6800. </span>
  6801. ` : ''}
  6802. </div>
  6803. </td>
  6804. <td class="py-2.5 px-3">${getRouteProtocolBadge(r.protocol)}</td>
  6805. <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>
  6806. <td class="py-2.5 px-3 text-slate-400 font-mono">${(r.distance !== undefined && r.distance !== null) ? r.distance : 0}</td>
  6807. <td class="py-2.5 px-3 font-mono font-semibold text-purple-300">${r.routing_table || 'main'}</td>
  6808. <td class="py-2.5 px-3 text-emerald-400 font-mono">${r.interface || '-'}</td>
  6809. <td class="py-2.5 px-3">${healthCell}</td>
  6810. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]">${r.comment || '-'}</td>
  6811. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  6812. ${r.static ? `
  6813. <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>
  6814. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold">Edit</button>
  6815. <button onclick="deleteRoute('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  6816. ` : `
  6817. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">View</button>
  6818. `}
  6819. </td>
  6820. `;
  6821. tbody.appendChild(tr);
  6822. });
  6823. }
  6824. function openAddRouteModal() {
  6825. document.getElementById('route-modal-title').innerText = 'Add Static Route';
  6826. document.getElementById('route-modal-id').value = '';
  6827. document.getElementById('route-modal-old-dst').value = '';
  6828. document.getElementById('route-modal-old-gw').value = '';
  6829. document.getElementById('route-modal-old-distance').value = '';
  6830. document.getElementById('route-modal-old-table').value = '';
  6831. document.getElementById('route-modal-old-iface').value = '';
  6832. const dstInput = document.getElementById('route-modal-dst');
  6833. const gwInput = document.getElementById('route-modal-gw');
  6834. const distInput = document.getElementById('route-modal-distance');
  6835. const ifaceSelect = document.getElementById('route-modal-iface');
  6836. const tableSelect = document.getElementById('route-modal-table');
  6837. const commentInput = document.getElementById('route-modal-comment');
  6838. const disCheck = document.getElementById('route-modal-disabled');
  6839. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  6840. dstInput.disabled = false;
  6841. dstInput.value = '0.0.0.0/0';
  6842. gwInput.disabled = false;
  6843. gwInput.value = '';
  6844. distInput.disabled = false;
  6845. distInput.value = '1';
  6846. ifaceSelect.disabled = false;
  6847. tableSelect.disabled = false;
  6848. commentInput.disabled = false;
  6849. commentInput.value = '';
  6850. disCheck.disabled = false;
  6851. disCheck.checked = false;
  6852. if (saveBtn) saveBtn.classList.remove('hidden');
  6853. const checkGw = document.getElementById('route-modal-check-gw');
  6854. if (checkGw) checkGw.value = 'internet';
  6855. const checkTarget = document.getElementById('route-modal-check-target');
  6856. if (checkTarget) checkTarget.value = '1.1.1.1';
  6857. const checkInterval = document.getElementById('route-modal-check-interval');
  6858. if (checkInterval) checkInterval.value = '5';
  6859. const checkThresh = document.getElementById('route-modal-check-threshold');
  6860. if (checkThresh) checkThresh.value = '3';
  6861. toggleRouteCheckModeUI();
  6862. populateInterfaceSelect('route-modal-iface');
  6863. // Populate tables
  6864. tableSelect.innerHTML = '';
  6865. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  6866. const opt = document.createElement('option');
  6867. opt.value = t.name;
  6868. opt.innerText = t.name;
  6869. if (t.name === 'main') opt.selected = true;
  6870. tableSelect.appendChild(opt);
  6871. });
  6872. document.getElementById('route-modal').classList.remove('hidden');
  6873. }
  6874. function openEditRouteModal(id) {
  6875. const r = (state.routes || []).find(route => route.id === id);
  6876. if (!r) return;
  6877. const isStatic = !!r.static;
  6878. document.getElementById('route-modal-title').innerText = isStatic
  6879. ? `Edit Route: ${r.dst_address}`
  6880. : `Route Properties (Read Only): ${r.dst_address}`;
  6881. document.getElementById('route-modal-id').value = r.id;
  6882. document.getElementById('route-modal-old-dst').value = r.dst_address || '';
  6883. document.getElementById('route-modal-old-gw').value = r.gateway || '';
  6884. document.getElementById('route-modal-old-distance').value = (r.distance !== undefined && r.distance !== null) ? r.distance : '';
  6885. document.getElementById('route-modal-old-table').value = r.routing_table || 'main';
  6886. document.getElementById('route-modal-old-iface').value = r.interface || '';
  6887. const dstInput = document.getElementById('route-modal-dst');
  6888. const gwInput = document.getElementById('route-modal-gw');
  6889. const distInput = document.getElementById('route-modal-distance');
  6890. const ifaceSelect = document.getElementById('route-modal-iface');
  6891. const tableSelect = document.getElementById('route-modal-table');
  6892. const commentInput = document.getElementById('route-modal-comment');
  6893. const disCheck = document.getElementById('route-modal-disabled');
  6894. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  6895. dstInput.value = r.dst_address;
  6896. gwInput.value = r.gateway || '';
  6897. distInput.value = (r.distance !== undefined && r.distance !== null) ? r.distance : 1;
  6898. commentInput.value = r.comment || '';
  6899. disCheck.checked = !!r.disabled;
  6900. const checkGw = document.getElementById('route-modal-check-gw');
  6901. if (checkGw) checkGw.value = r.check_gateway || 'none';
  6902. const checkTarget = document.getElementById('route-modal-check-target');
  6903. if (checkTarget) checkTarget.value = r.check_target || '1.1.1.1';
  6904. const checkInterval = document.getElementById('route-modal-check-interval');
  6905. if (checkInterval) checkInterval.value = r.check_interval || 5;
  6906. const checkThresh = document.getElementById('route-modal-check-threshold');
  6907. if (checkThresh) checkThresh.value = r.check_threshold || 3;
  6908. toggleRouteCheckModeUI();
  6909. dstInput.disabled = !isStatic;
  6910. gwInput.disabled = !isStatic;
  6911. distInput.disabled = !isStatic;
  6912. ifaceSelect.disabled = !isStatic;
  6913. tableSelect.disabled = !isStatic;
  6914. commentInput.disabled = !isStatic;
  6915. disCheck.disabled = !isStatic;
  6916. if (checkGw) checkGw.disabled = !isStatic;
  6917. if (checkTarget) checkTarget.disabled = !isStatic;
  6918. if (checkInterval) checkInterval.disabled = !isStatic;
  6919. if (checkThresh) checkThresh.disabled = !isStatic;
  6920. if (saveBtn) {
  6921. if (isStatic) {
  6922. saveBtn.classList.remove('hidden');
  6923. } else {
  6924. saveBtn.classList.add('hidden');
  6925. }
  6926. }
  6927. populateInterfaceSelect('route-modal-iface', r.interface);
  6928. tableSelect.innerHTML = '';
  6929. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  6930. const opt = document.createElement('option');
  6931. opt.value = t.name;
  6932. opt.innerText = t.name;
  6933. if (t.name === (r.routing_table || 'main')) opt.selected = true;
  6934. tableSelect.appendChild(opt);
  6935. });
  6936. document.getElementById('route-modal').classList.remove('hidden');
  6937. }
  6938. function closeRouteModal() {
  6939. document.getElementById('route-modal').classList.add('hidden');
  6940. }
  6941. function setRouteCheckTarget(ip) {
  6942. const inp = document.getElementById('route-modal-check-target');
  6943. if (inp) inp.value = ip;
  6944. }
  6945. function toggleRouteCheckModeUI() {
  6946. const mode = document.getElementById('route-modal-check-gw')?.value || 'none';
  6947. const targetRow = document.getElementById('route-row-check-target');
  6948. const paramsRow = document.getElementById('route-row-check-params');
  6949. if (mode === 'none') {
  6950. if (targetRow) targetRow.classList.add('opacity-40', 'pointer-events-none');
  6951. if (paramsRow) paramsRow.classList.add('opacity-40', 'pointer-events-none');
  6952. } else if (mode === 'ping') {
  6953. if (targetRow) targetRow.classList.add('opacity-40', 'pointer-events-none');
  6954. if (paramsRow) paramsRow.classList.remove('opacity-40', 'pointer-events-none');
  6955. } else { // internet
  6956. if (targetRow) targetRow.classList.remove('opacity-40', 'pointer-events-none');
  6957. if (paramsRow) paramsRow.classList.remove('opacity-40', 'pointer-events-none');
  6958. }
  6959. }
  6960. async function submitSaveRoute(e) {
  6961. e.preventDefault();
  6962. const id = document.getElementById('route-modal-id').value;
  6963. const oldDst = document.getElementById('route-modal-old-dst')?.value || '';
  6964. const oldGw = document.getElementById('route-modal-old-gw')?.value || '';
  6965. const oldDistStr = document.getElementById('route-modal-old-distance')?.value;
  6966. const oldTable = document.getElementById('route-modal-old-table')?.value || '';
  6967. const oldIface = document.getElementById('route-modal-old-iface')?.value || '';
  6968. const dst = document.getElementById('route-modal-dst').value.trim();
  6969. const gw = document.getElementById('route-modal-gw').value.trim();
  6970. const table = document.getElementById('route-modal-table').value;
  6971. const distance = parseInt(document.getElementById('route-modal-distance').value, 10) || 0;
  6972. const iface = document.getElementById('route-modal-iface').value;
  6973. const comment = document.getElementById('route-modal-comment').value.trim();
  6974. const disabled = document.getElementById('route-modal-disabled').checked;
  6975. const check_gateway = document.getElementById('route-modal-check-gw')?.value || 'none';
  6976. const check_target = document.getElementById('route-modal-check-target')?.value.trim() || '1.1.1.1';
  6977. const check_interval = parseInt(document.getElementById('route-modal-check-interval')?.value, 10) || 5;
  6978. const check_threshold = parseInt(document.getElementById('route-modal-check-threshold')?.value, 10) || 3;
  6979. if (!dst) {
  6980. showToast('Error', 'Destination address is required', 'error');
  6981. return;
  6982. }
  6983. if (!gw && !iface) {
  6984. showToast('Error', 'Either Gateway IP or Interface must be specified', 'error');
  6985. return;
  6986. }
  6987. const payload = {
  6988. id,
  6989. old_dst_address: oldDst,
  6990. old_gateway: oldGw,
  6991. old_routing_table: oldTable,
  6992. old_interface: oldIface,
  6993. dst_address: dst,
  6994. gateway: gw || iface,
  6995. routing_table: table,
  6996. distance,
  6997. interface: iface,
  6998. comment,
  6999. disabled,
  7000. check_gateway,
  7001. check_target,
  7002. check_interval,
  7003. check_threshold
  7004. };
  7005. if (oldDistStr !== undefined && oldDistStr !== '') {
  7006. payload.old_distance = parseInt(oldDistStr, 10);
  7007. }
  7008. try {
  7009. const res = await fetch(`${API_BASE}/routes`, {
  7010. method: 'POST',
  7011. headers: { 'Content-Type': 'application/json' },
  7012. body: JSON.stringify(payload)
  7013. });
  7014. if (res.ok) {
  7015. showToast('Route Saved', `Route to ${dst} installed`, 'success');
  7016. closeRouteModal();
  7017. loadRoutes();
  7018. } else {
  7019. const err = await res.json();
  7020. showToast('Error', err.message || 'Failed to save route', 'error');
  7021. }
  7022. } catch (err) {
  7023. showToast('Error', err.message, 'error');
  7024. }
  7025. }
  7026. async function toggleRouteState(id, disabled) {
  7027. try {
  7028. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}/state`, {
  7029. method: 'POST',
  7030. headers: { 'Content-Type': 'application/json' },
  7031. body: JSON.stringify({ disabled })
  7032. });
  7033. if (res.ok) loadRoutes();
  7034. } catch (err) {
  7035. showToast('Error', err.message, 'error');
  7036. }
  7037. }
  7038. async function deleteRoute(id) {
  7039. if (!confirm('Are you sure you want to delete this route?')) return;
  7040. try {
  7041. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7042. if (res.ok) {
  7043. showToast('Deleted', 'Route removed', 'success');
  7044. loadRoutes();
  7045. }
  7046. } catch (err) {
  7047. showToast('Error', err.message, 'error');
  7048. }
  7049. }
  7050. // ----------------- Policy Rules (/ip route rule) -----------------
  7051. function renderPolicyRules() {
  7052. const tbody = document.getElementById('rules-table-body');
  7053. const empty = document.getElementById('rules-empty');
  7054. if (!tbody) return;
  7055. const showSystem = document.getElementById('prule-show-system')?.checked;
  7056. const filtered = (state.policyRules || []).filter(pr => showSystem || (!pr.is_default && !pr.is_system));
  7057. const countBadge = document.getElementById('rules-count-badge');
  7058. if (countBadge) countBadge.innerText = `${filtered.length} Rules`;
  7059. const bRules = document.getElementById('routes-badge-rules');
  7060. if (bRules) bRules.innerText = filtered.length;
  7061. if (filtered.length === 0) {
  7062. empty?.classList.remove('hidden');
  7063. tbody.innerHTML = '';
  7064. return;
  7065. }
  7066. empty?.classList.add('hidden');
  7067. const sig = `${showSystem}|` + filtered.map(pr => `${pr.id}:${pr.priority}:${pr.src_address}:${pr.dst_address}:${pr.table}:${pr.routing_mark}`).join(';');
  7068. if (tbody.dataset.sig === sig) return;
  7069. tbody.dataset.sig = sig;
  7070. tbody.innerHTML = '';
  7071. filtered.forEach(pr => {
  7072. const isSys = pr.is_default || pr.is_system;
  7073. const tr = document.createElement('tr');
  7074. tr.className = `hover:bg-slate-800/40 transition text-xs ${isSys ? 'opacity-70 bg-slate-950/20' : ''}`;
  7075. tr.innerHTML = `
  7076. <td class="py-2.5 px-3 font-mono text-cyan-400 font-bold">${pr.priority}</td>
  7077. <td class="py-2.5 px-3 font-mono text-white">${pr.src_address || '<span class="text-slate-600">all</span>'}</td>
  7078. <td class="py-2.5 px-3 font-mono text-white">${pr.dst_address || '<span class="text-slate-600">all</span>'}</td>
  7079. <td class="py-2.5 px-3 font-mono font-bold text-purple-300">${pr.routing_mark || '<span class="text-slate-600">-</span>'}</td>
  7080. <td class="py-2.5 px-3 font-mono font-bold text-amber-300">${pr.table}</td>
  7081. <td class="py-2.5 px-3 font-mono text-slate-300">${pr.action}</td>
  7082. <td class="py-2.5 px-3 text-right font-sans">
  7083. ${!pr.is_default ? `
  7084. <button onclick="deletePolicyRule('${pr.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  7085. ` : `<span class="text-slate-600 text-[10px]">Default</span>`}
  7086. </td>
  7087. `;
  7088. tbody.appendChild(tr);
  7089. });
  7090. }
  7091. function openAddPolicyRuleModal() {
  7092. const userRules = (state.policyRules || []).filter(pr => !pr.is_default && !pr.is_system);
  7093. document.getElementById('prule-modal-pref').value = userRules.length * 10 + 1000;
  7094. document.getElementById('prule-modal-mark').value = '';
  7095. document.getElementById('prule-modal-src').value = '';
  7096. document.getElementById('prule-modal-dst').value = '';
  7097. const sel = document.getElementById('prule-modal-table');
  7098. sel.innerHTML = '';
  7099. (state.routingTables || []).forEach(t => {
  7100. const opt = document.createElement('option');
  7101. opt.value = t.name;
  7102. opt.innerText = t.name;
  7103. sel.appendChild(opt);
  7104. });
  7105. document.getElementById('prule-modal').classList.remove('hidden');
  7106. }
  7107. function closePolicyRuleModal() {
  7108. document.getElementById('prule-modal').classList.add('hidden');
  7109. }
  7110. async function submitSavePolicyRule(e) {
  7111. e.preventDefault();
  7112. const pref = parseInt(document.getElementById('prule-modal-pref').value, 10) || 1000;
  7113. const mark = document.getElementById('prule-modal-mark').value.trim();
  7114. const src = document.getElementById('prule-modal-src').value.trim();
  7115. const dst = document.getElementById('prule-modal-dst').value.trim();
  7116. const table = document.getElementById('prule-modal-table').value;
  7117. const action = document.getElementById('prule-modal-action').value;
  7118. try {
  7119. const res = await fetch(`${API_BASE}/routing/rules`, {
  7120. method: 'POST',
  7121. headers: { 'Content-Type': 'application/json' },
  7122. body: JSON.stringify({ priority: pref, routing_mark: mark, src_address: src, dst_address: dst, table, action })
  7123. });
  7124. if (res.ok) {
  7125. showToast('Rule Added', `Policy rule installed for table ${table}`, 'success');
  7126. closePolicyRuleModal();
  7127. loadRoutes();
  7128. } else {
  7129. const err = await res.json();
  7130. showToast('Error', err.message, 'error');
  7131. }
  7132. } catch (err) {
  7133. showToast('Error', err.message, 'error');
  7134. }
  7135. }
  7136. async function deletePolicyRule(id) {
  7137. if (!confirm('Are you sure you want to remove this policy rule?')) return;
  7138. try {
  7139. const res = await fetch(`${API_BASE}/routing/rules/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7140. if (res.ok) {
  7141. showToast('Rule Removed', 'Policy rule deleted', 'success');
  7142. loadRoutes();
  7143. }
  7144. } catch (err) {
  7145. showToast('Error', err.message, 'error');
  7146. }
  7147. }
  7148. // ----------------- Routing Tables -----------------
  7149. function renderRoutingTables() {
  7150. const tbody = document.getElementById('tables-table-body');
  7151. if (!tbody) return;
  7152. const tables = state.routingTables || [];
  7153. const sig = tables.map(t => `${t.table_id}:${t.name}:${t.comment}`).join(';');
  7154. if (tbody.dataset.sig === sig) return;
  7155. tbody.dataset.sig = sig;
  7156. tbody.innerHTML = '';
  7157. (state.routingTables || []).forEach(t => {
  7158. const tr = document.createElement('tr');
  7159. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  7160. tr.innerHTML = `
  7161. <td class="py-2.5 px-3 text-cyan-400 font-bold">${t.table_id}</td>
  7162. <td class="py-2.5 px-3 font-bold text-white">${t.name}</td>
  7163. <td class="py-2.5 px-3 text-slate-400 italic">${t.comment || '-'}</td>
  7164. `;
  7165. tbody.appendChild(tr);
  7166. });
  7167. }
  7168. function openAddTableModal() {
  7169. document.getElementById('table-modal-name').value = '';
  7170. document.getElementById('table-modal-id').value = '';
  7171. document.getElementById('table-modal-comment').value = '';
  7172. document.getElementById('table-modal').classList.remove('hidden');
  7173. }
  7174. function closeTableModal() {
  7175. document.getElementById('table-modal').classList.add('hidden');
  7176. }
  7177. async function submitSaveTable(e) {
  7178. e.preventDefault();
  7179. const name = document.getElementById('table-modal-name').value.trim();
  7180. const id = parseInt(document.getElementById('table-modal-id').value, 10) || 0;
  7181. const comment = document.getElementById('table-modal-comment').value.trim();
  7182. try {
  7183. const res = await fetch(`${API_BASE}/routing/tables`, {
  7184. method: 'POST',
  7185. headers: { 'Content-Type': 'application/json' },
  7186. body: JSON.stringify({ name, table_id: id, comment })
  7187. });
  7188. if (res.ok) {
  7189. showToast('Table Created', `Routing table ${name} registered`, 'success');
  7190. closeTableModal();
  7191. loadRoutes();
  7192. } else {
  7193. const err = await res.json();
  7194. showToast('Error', err.message, 'error');
  7195. }
  7196. } catch (err) {
  7197. showToast('Error', err.message, 'error');
  7198. }
  7199. }
  7200. async function loadDebianConfig() {
  7201. const view = document.getElementById('debian-config-view');
  7202. view.innerText = 'Generating live configuration...';
  7203. try {
  7204. const res = await fetch(`${API_BASE}/debian/config`);
  7205. const data = await res.json();
  7206. view.innerText = data.content || '# Empty config';
  7207. } catch (err) {
  7208. view.innerText = 'Failed to generate Debian network config.';
  7209. }
  7210. }
  7211. async function saveDebianConfig() {
  7212. try {
  7213. const res = await fetch(`${API_BASE}/debian/apply`, { method: 'POST' });
  7214. const data = await res.json();
  7215. if (res.ok) {
  7216. showToast('Configuration Saved', data.message || 'Saved to /etc/network/interfaces.d/vlans.cfg', 'success');
  7217. loadDebianConfig();
  7218. }
  7219. } catch (err) {
  7220. showToast('Error', err.message, 'error');
  7221. }
  7222. }
  7223. function showToast(title, message, type = 'info') {
  7224. const container = document.getElementById('toast-container');
  7225. const toast = document.createElement('div');
  7226. const borderColors = {
  7227. success: 'border-emerald-500/40 bg-slate-900/95 text-emerald-400',
  7228. error: 'border-rose-500/40 bg-slate-900/95 text-rose-400',
  7229. info: 'border-cyan-500/40 bg-slate-900/95 text-cyan-400'
  7230. };
  7231. 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}`;
  7232. toast.innerHTML = `
  7233. <div class="flex-1">
  7234. <div class="font-bold text-xs text-white">${escapeHtml(title)}</div>
  7235. <div class="text-[11px] text-slate-300 mt-0.5 leading-relaxed font-sans">${escapeHtml(message)}</div>
  7236. </div>
  7237. `;
  7238. container.appendChild(toast);
  7239. requestAnimationFrame(() => toast.classList.remove('translate-y-2', 'opacity-0'));
  7240. setTimeout(() => {
  7241. toast.classList.add('opacity-0', 'translate-y-2');
  7242. setTimeout(() => toast.remove(), 300);
  7243. }, 4000);
  7244. }
  7245. function formatTraffic(bytesPerSec) {
  7246. if (bytesPerSec < 1024) return `${Math.round(bytesPerSec)} B/s`;
  7247. const kb = bytesPerSec / 1024;
  7248. if (kb < 1024) return `${kb.toFixed(1)} KB/s`;
  7249. const mb = kb / 1024;
  7250. return `${mb.toFixed(2)} MB/s`;
  7251. }
  7252. function toggleSidebar() {
  7253. const sb = document.getElementById('sidebar');
  7254. sb.classList.toggle('-translate-x-full');
  7255. }
  7256. // ======================== EoIP (Ethernet over IP) ========================
  7257. async function loadEoIP(populate = true) {
  7258. try {
  7259. const res = await fetch(`${API_BASE}/vpn/eoip`);
  7260. const data = await res.json();
  7261. state.eoipTunnels = Array.isArray(data) ? data : [];
  7262. const badge = document.getElementById('eoip-count-badge');
  7263. if (badge) badge.innerText = `${state.eoipTunnels.length} Tunnels`;
  7264. const sideBadge = document.getElementById('badge-eoip-count');
  7265. if (sideBadge) sideBadge.innerText = state.eoipTunnels.length;
  7266. renderEoIPTunnels();
  7267. } catch (err) {
  7268. console.error('Failed to load EoIP:', err);
  7269. }
  7270. }
  7271. function renderEoIPTunnels() {
  7272. const tbody = document.getElementById('eoip-table-body');
  7273. const empty = document.getElementById('eoip-empty');
  7274. if (!tbody) return;
  7275. tbody.innerHTML = '';
  7276. const tunnels = state.eoipTunnels || [];
  7277. if (tunnels.length === 0) {
  7278. empty?.classList.remove('hidden');
  7279. return;
  7280. }
  7281. empty?.classList.add('hidden');
  7282. tunnels.forEach(t => {
  7283. const tr = document.createElement('tr');
  7284. tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
  7285. tr.innerHTML = `
  7286. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.running, t.disabled)}</td>
  7287. <td class="py-2.5 px-3 font-bold text-white font-mono">${t.name}</td>
  7288. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${t.tunnel_id}</td>
  7289. <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>
  7290. <td class="py-2.5 px-3 text-cyan-300 font-mono">${t.remote_address}</td>
  7291. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.local_address || '(any)'}</td>
  7292. <td class="py-2.5 px-3 text-slate-300 font-mono text-[11px]">${t.mac_address || '-'}</td>
  7293. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.mtu || 1500}</td>
  7294. <td class="py-2.5 px-3 font-mono text-[11px]">
  7295. <span class="text-emerald-400">↓ ${t.rx_human || '0 B'}</span>
  7296. <span class="text-cyan-400 ml-1">↑ ${t.tx_human || '0 B'}</span>
  7297. </td>
  7298. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${t.comment || ''}">${t.comment || '-'}</td>
  7299. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  7300. <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>
  7301. <button onclick="openEditEoIPModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  7302. <button onclick="deleteEoIP('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  7303. </td>
  7304. `;
  7305. tbody.appendChild(tr);
  7306. });
  7307. }
  7308. function openAddEoIPModal() {
  7309. document.getElementById('eoip-modal-title').innerText = 'Add EoIP Tunnel';
  7310. document.getElementById('eoip-modal-id').value = '';
  7311. document.getElementById('eoip-modal-name').value = `eoip-tunnel${(state.eoipTunnels || []).length + 1}`;
  7312. document.getElementById('eoip-modal-tunnelid').value = (state.eoipTunnels || []).length + 10;
  7313. document.getElementById('eoip-modal-remote').value = '';
  7314. document.getElementById('eoip-modal-ip').value = '';
  7315. document.getElementById('eoip-modal-local').value = '';
  7316. document.getElementById('eoip-modal-mac').value = '';
  7317. document.getElementById('eoip-modal-mtu').value = '1500';
  7318. document.getElementById('eoip-modal-comment').value = '';
  7319. document.getElementById('eoip-modal-clampmss').checked = true;
  7320. document.getElementById('eoip-modal-disabled').checked = false;
  7321. document.getElementById('eoip-modal').classList.remove('hidden');
  7322. }
  7323. function openEditEoIPModal(id) {
  7324. const t = (state.eoipTunnels || []).find(tun => tun.id === id);
  7325. if (!t) return;
  7326. document.getElementById('eoip-modal-title').innerText = `Edit EoIP Tunnel (${t.name})`;
  7327. document.getElementById('eoip-modal-id').value = t.id;
  7328. document.getElementById('eoip-modal-name').value = t.name;
  7329. document.getElementById('eoip-modal-tunnelid').value = t.tunnel_id;
  7330. document.getElementById('eoip-modal-remote').value = t.remote_address;
  7331. document.getElementById('eoip-modal-ip').value = t.ip_address || '';
  7332. document.getElementById('eoip-modal-local').value = t.local_address || '';
  7333. document.getElementById('eoip-modal-mac').value = t.mac_address || '';
  7334. document.getElementById('eoip-modal-mtu').value = t.mtu || 1500;
  7335. document.getElementById('eoip-modal-comment').value = t.comment || '';
  7336. document.getElementById('eoip-modal-clampmss').checked = !!t.clamp_mss;
  7337. document.getElementById('eoip-modal-disabled').checked = !!t.disabled;
  7338. document.getElementById('eoip-modal').classList.remove('hidden');
  7339. }
  7340. function closeEoIPModal() {
  7341. document.getElementById('eoip-modal').classList.add('hidden');
  7342. }
  7343. async function submitSaveEoIP(e) {
  7344. e.preventDefault();
  7345. const id = document.getElementById('eoip-modal-id').value;
  7346. const name = document.getElementById('eoip-modal-name').value.trim();
  7347. const tunnelId = parseInt(document.getElementById('eoip-modal-tunnelid').value);
  7348. const remote = document.getElementById('eoip-modal-remote').value.trim();
  7349. const ipAddress = document.getElementById('eoip-modal-ip').value.trim();
  7350. const local = document.getElementById('eoip-modal-local').value.trim();
  7351. const mac = document.getElementById('eoip-modal-mac').value.trim();
  7352. const mtu = parseInt(document.getElementById('eoip-modal-mtu').value) || 1500;
  7353. const comment = document.getElementById('eoip-modal-comment').value.trim();
  7354. const clampMss = document.getElementById('eoip-modal-clampmss').checked;
  7355. const disabled = document.getElementById('eoip-modal-disabled').checked;
  7356. try {
  7357. const res = await fetch(`${API_BASE}/vpn/eoip`, {
  7358. method: 'POST',
  7359. headers: { 'Content-Type': 'application/json' },
  7360. body: JSON.stringify({
  7361. id,
  7362. name,
  7363. tunnel_id: tunnelId,
  7364. remote_address: remote,
  7365. ip_address: ipAddress,
  7366. local_address: local,
  7367. mac_address: mac,
  7368. mtu,
  7369. clamp_mss: clampMss,
  7370. comment,
  7371. disabled
  7372. })
  7373. });
  7374. if (res.ok) {
  7375. showToast('EoIP Saved', `Tunnel ${name} configured successfully`, 'success');
  7376. closeEoIPModal();
  7377. loadEoIP(false);
  7378. fetchData(false);
  7379. } else {
  7380. const err = await res.json();
  7381. showToast('Error', err.message, 'error');
  7382. }
  7383. } catch (err) {
  7384. showToast('Error', err.message, 'error');
  7385. }
  7386. }
  7387. async function toggleEoIPState(id, disabled) {
  7388. try {
  7389. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}/state`, {
  7390. method: 'POST',
  7391. headers: { 'Content-Type': 'application/json' },
  7392. body: JSON.stringify({ disabled })
  7393. });
  7394. if (res.ok) {
  7395. showToast(disabled ? 'Disabled' : 'Enabled', 'EoIP tunnel state updated', 'info');
  7396. loadEoIP(false);
  7397. fetchData(false);
  7398. }
  7399. } catch (err) {
  7400. showToast('Error', err.message, 'error');
  7401. }
  7402. }
  7403. async function deleteEoIP(id) {
  7404. if (!confirm('Are you sure you want to delete this EoIP tunnel?')) return;
  7405. try {
  7406. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7407. if (res.ok) {
  7408. showToast('Deleted', 'EoIP tunnel removed', 'success');
  7409. loadEoIP(false);
  7410. fetchData(false);
  7411. }
  7412. } catch (err) {
  7413. showToast('Error', err.message, 'error');
  7414. }
  7415. }
  7416. // ======================== VXLAN (Virtual Extensible LAN) ========================
  7417. async function loadVXLAN(populate = true) {
  7418. try {
  7419. const [tunnelsRes, vtepsRes] = await Promise.all([
  7420. fetch(`${API_BASE}/vpn/vxlan`),
  7421. fetch(`${API_BASE}/vpn/vxlan/vteps`)
  7422. ]);
  7423. if (tunnelsRes.ok) {
  7424. state.vxlanTunnels = await tunnelsRes.json() || [];
  7425. }
  7426. if (vtepsRes.ok) {
  7427. state.vxlanVteps = await vtepsRes.json() || [];
  7428. }
  7429. renderVXLANTable();
  7430. renderVXLANVtepsTable();
  7431. const countBadge = document.getElementById('vxlan-count-badge');
  7432. if (countBadge) countBadge.innerText = `${(state.vxlanTunnels || []).length} Tunnels`;
  7433. const vtepsCountBadge = document.getElementById('vxlan-vteps-count-badge');
  7434. if (vtepsCountBadge) vtepsCountBadge.innerText = `${(state.vxlanVteps || []).length} VTEPs`;
  7435. const navBadge = document.getElementById('badge-vxlan-count');
  7436. if (navBadge) navBadge.innerText = (state.vxlanTunnels || []).length;
  7437. } catch (err) {
  7438. console.error('Error loading VXLAN:', err);
  7439. }
  7440. }
  7441. function renderVXLANTable() {
  7442. const tbody = document.getElementById('vxlan-table-body');
  7443. const empty = document.getElementById('vxlan-empty');
  7444. if (!tbody || !empty) return;
  7445. tbody.innerHTML = '';
  7446. const tunnels = state.vxlanTunnels || [];
  7447. if (tunnels.length === 0) {
  7448. empty.classList.remove('hidden');
  7449. return;
  7450. }
  7451. empty.classList.add('hidden');
  7452. tunnels.forEach(t => {
  7453. const tr = document.createElement('tr');
  7454. tr.className = 'hover:bg-slate-800/40 transition border-b border-slate-800/60';
  7455. let flag = '';
  7456. if (t.disabled) {
  7457. 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>';
  7458. } else if (t.running) {
  7459. 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>';
  7460. } else {
  7461. 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>';
  7462. }
  7463. const vtepCount = (t.vteps || []).length;
  7464. const underlayDesc = t.parent_interface || t.local_address ? `${t.parent_interface || '-'}${t.local_address ? ' / ' + t.local_address : ''}` : '(any)';
  7465. tr.innerHTML = `
  7466. <td class="py-2.5 px-3 text-center">${flag}</td>
  7467. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(t.name)}</td>
  7468. <td class="py-2.5 px-3 font-bold text-amber-400 font-mono">${t.vni}</td>
  7469. <td class="py-2.5 px-3 text-slate-300 font-mono">${t.port || 4789}</td>
  7470. <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>
  7471. <td class="py-2.5 px-3 text-slate-300 font-mono text-[11px]">${escapeHtml(underlayDesc)}</td>
  7472. <td class="py-2.5 px-3 text-slate-400 font-mono text-[11px]">${escapeHtml(t.mac_address || '-')}</td>
  7473. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.mtu || 1500}</td>
  7474. <td class="py-2.5 px-3 font-mono">
  7475. <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>
  7476. </td>
  7477. <td class="py-2.5 px-3 font-mono text-[11px]">
  7478. <span class="text-emerald-400">↓ ${t.rx_human || '0 B'}</span>
  7479. <span class="text-amber-400 ml-1">↑ ${t.tx_human || '0 B'}</span>
  7480. </td>
  7481. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(t.comment || '')}">${escapeHtml(t.comment || '-')}</td>
  7482. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  7483. <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>
  7484. <button onclick="openEditVXLANModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  7485. <button onclick="deleteVXLAN('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  7486. </td>
  7487. `;
  7488. tbody.appendChild(tr);
  7489. });
  7490. }
  7491. function renderVXLANVtepsTable() {
  7492. const tbody = document.getElementById('vxlan-vteps-table-body');
  7493. const empty = document.getElementById('vxlan-vteps-empty');
  7494. if (!tbody || !empty) return;
  7495. tbody.innerHTML = '';
  7496. const vteps = state.vxlanVteps || [];
  7497. if (vteps.length === 0) {
  7498. empty.classList.remove('hidden');
  7499. return;
  7500. }
  7501. empty.classList.add('hidden');
  7502. vteps.forEach(v => {
  7503. const tr = document.createElement('tr');
  7504. tr.className = 'hover:bg-slate-800/40 transition border-b border-slate-800/60';
  7505. tr.innerHTML = `
  7506. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(v.interface)}</td>
  7507. <td class="py-2.5 px-3 text-amber-400 font-mono font-semibold">${escapeHtml(v.remote_ip)}</td>
  7508. <td class="py-2.5 px-3 text-slate-300 font-mono">${v.port > 0 ? v.port : 'default'}</td>
  7509. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[150px]" title="${escapeHtml(v.comment || '')}">${escapeHtml(v.comment || '-')}</td>
  7510. <td class="py-2.5 px-3 text-right font-sans whitespace-nowrap">
  7511. <button onclick="deleteVXLANVtep('${escapeHtml(v.interface)}', '${escapeHtml(v.id || v.remote_ip)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  7512. </td>
  7513. `;
  7514. tbody.appendChild(tr);
  7515. });
  7516. }
  7517. function openAddVXLANModal() {
  7518. document.getElementById('vxlan-modal-title').innerText = 'Add VXLAN Interface';
  7519. document.getElementById('vxlan-modal-id').value = '';
  7520. document.getElementById('vxlan-modal-name').value = `vxlan${(state.vxlanTunnels || []).length + 100}`;
  7521. document.getElementById('vxlan-modal-vni').value = (state.vxlanTunnels || []).length + 100;
  7522. document.getElementById('vxlan-modal-port').value = '4789';
  7523. document.getElementById('vxlan-modal-ip').value = '';
  7524. document.getElementById('vxlan-modal-parent').value = '';
  7525. document.getElementById('vxlan-modal-local').value = '';
  7526. document.getElementById('vxlan-modal-remote').value = '';
  7527. document.getElementById('vxlan-modal-group').value = '';
  7528. document.getElementById('vxlan-modal-mac').value = '';
  7529. document.getElementById('vxlan-modal-mtu').value = '1500';
  7530. document.getElementById('vxlan-modal-comment').value = '';
  7531. document.getElementById('vxlan-modal-learning').checked = true;
  7532. document.getElementById('vxlan-modal-disabled').checked = false;
  7533. document.getElementById('vxlan-modal').classList.remove('hidden');
  7534. }
  7535. function openEditVXLANModal(id) {
  7536. const t = (state.vxlanTunnels || []).find(tun => tun.id === id);
  7537. if (!t) return;
  7538. document.getElementById('vxlan-modal-title').innerText = `Edit VXLAN Interface (${t.name})`;
  7539. document.getElementById('vxlan-modal-id').value = t.id;
  7540. document.getElementById('vxlan-modal-name').value = t.name;
  7541. document.getElementById('vxlan-modal-vni').value = t.vni;
  7542. document.getElementById('vxlan-modal-port').value = t.port || 4789;
  7543. document.getElementById('vxlan-modal-ip').value = t.ip_address || '';
  7544. document.getElementById('vxlan-modal-parent').value = t.parent_interface || '';
  7545. document.getElementById('vxlan-modal-local').value = t.local_address || '';
  7546. document.getElementById('vxlan-modal-remote').value = t.remote_address || '';
  7547. document.getElementById('vxlan-modal-group').value = t.group || '';
  7548. document.getElementById('vxlan-modal-mac').value = t.mac_address || '';
  7549. document.getElementById('vxlan-modal-mtu').value = t.mtu || 1500;
  7550. document.getElementById('vxlan-modal-comment').value = t.comment || '';
  7551. document.getElementById('vxlan-modal-learning').checked = t.learning !== false;
  7552. document.getElementById('vxlan-modal-disabled').checked = !!t.disabled;
  7553. document.getElementById('vxlan-modal').classList.remove('hidden');
  7554. }
  7555. function closeVXLANModal() {
  7556. document.getElementById('vxlan-modal').classList.add('hidden');
  7557. }
  7558. async function submitSaveVXLAN(e) {
  7559. e.preventDefault();
  7560. const id = document.getElementById('vxlan-modal-id').value;
  7561. const name = document.getElementById('vxlan-modal-name').value.trim();
  7562. const vni = parseInt(document.getElementById('vxlan-modal-vni').value);
  7563. const port = parseInt(document.getElementById('vxlan-modal-port').value) || 4789;
  7564. const ipAddress = document.getElementById('vxlan-modal-ip').value.trim();
  7565. const parentInterface = document.getElementById('vxlan-modal-parent').value.trim();
  7566. const local = document.getElementById('vxlan-modal-local').value.trim();
  7567. const remote = document.getElementById('vxlan-modal-remote').value.trim();
  7568. const group = document.getElementById('vxlan-modal-group').value.trim();
  7569. const mac = document.getElementById('vxlan-modal-mac').value.trim();
  7570. const mtu = parseInt(document.getElementById('vxlan-modal-mtu').value) || 1500;
  7571. const comment = document.getElementById('vxlan-modal-comment').value.trim();
  7572. const learning = document.getElementById('vxlan-modal-learning').checked;
  7573. const disabled = document.getElementById('vxlan-modal-disabled').checked;
  7574. try {
  7575. const res = await fetch(`${API_BASE}/vpn/vxlan`, {
  7576. method: 'POST',
  7577. headers: { 'Content-Type': 'application/json' },
  7578. body: JSON.stringify({
  7579. id,
  7580. name,
  7581. vni,
  7582. port,
  7583. ip_address: ipAddress,
  7584. parent_interface: parentInterface,
  7585. local_address: local,
  7586. remote_address: remote,
  7587. group,
  7588. mac_address: mac,
  7589. mtu,
  7590. learning,
  7591. comment,
  7592. disabled
  7593. })
  7594. });
  7595. if (res.ok) {
  7596. showToast('VXLAN Saved', `Interface ${name} configured successfully`, 'success');
  7597. closeVXLANModal();
  7598. loadVXLAN(false);
  7599. fetchData(false);
  7600. } else {
  7601. const err = await res.json();
  7602. showToast('Error', err.message, 'error');
  7603. }
  7604. } catch (err) {
  7605. showToast('Error', err.message, 'error');
  7606. }
  7607. }
  7608. async function toggleVXLANState(id, disabled) {
  7609. try {
  7610. const res = await fetch(`${API_BASE}/vpn/vxlan/${encodeURIComponent(id)}/state`, {
  7611. method: 'POST',
  7612. headers: { 'Content-Type': 'application/json' },
  7613. body: JSON.stringify({ disabled })
  7614. });
  7615. if (res.ok) {
  7616. showToast(disabled ? 'Disabled' : 'Enabled', 'VXLAN interface state updated', 'info');
  7617. loadVXLAN(false);
  7618. fetchData(false);
  7619. }
  7620. } catch (err) {
  7621. showToast('Error', err.message, 'error');
  7622. }
  7623. }
  7624. async function deleteVXLAN(id) {
  7625. if (!confirm('Are you sure you want to delete this VXLAN interface?')) return;
  7626. try {
  7627. const res = await fetch(`${API_BASE}/vpn/vxlan/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7628. if (res.ok) {
  7629. showToast('Deleted', 'VXLAN interface removed', 'success');
  7630. loadVXLAN(false);
  7631. fetchData(false);
  7632. }
  7633. } catch (err) {
  7634. showToast('Error', err.message, 'error');
  7635. }
  7636. }
  7637. function openAddVXLANVtepModal(defaultIface = '') {
  7638. const sel = document.getElementById('vxlan-vtep-modal-interface');
  7639. if (sel) {
  7640. sel.innerHTML = '';
  7641. const tunnels = state.vxlanTunnels || [];
  7642. tunnels.forEach(t => {
  7643. const opt = document.createElement('option');
  7644. opt.value = t.name;
  7645. opt.innerText = `${t.name} (VNI ${t.vni})`;
  7646. if (defaultIface && t.name === defaultIface) {
  7647. opt.selected = true;
  7648. }
  7649. sel.appendChild(opt);
  7650. });
  7651. }
  7652. document.getElementById('vxlan-vtep-modal-remote').value = '';
  7653. document.getElementById('vxlan-vtep-modal-port').value = '';
  7654. document.getElementById('vxlan-vtep-modal-comment').value = '';
  7655. document.getElementById('vxlan-vtep-modal').classList.remove('hidden');
  7656. }
  7657. function closeVXLANVtepModal() {
  7658. document.getElementById('vxlan-vtep-modal').classList.add('hidden');
  7659. }
  7660. async function submitSaveVXLANVtep(e) {
  7661. e.preventDefault();
  7662. const iface = document.getElementById('vxlan-vtep-modal-interface').value;
  7663. const remote = document.getElementById('vxlan-vtep-modal-remote').value.trim();
  7664. const port = parseInt(document.getElementById('vxlan-vtep-modal-port').value) || 0;
  7665. const comment = document.getElementById('vxlan-vtep-modal-comment').value.trim();
  7666. try {
  7667. const res = await fetch(`${API_BASE}/vpn/vxlan/vteps`, {
  7668. method: 'POST',
  7669. headers: { 'Content-Type': 'application/json' },
  7670. body: JSON.stringify({
  7671. interface: iface,
  7672. remote_ip: remote,
  7673. port,
  7674. comment
  7675. })
  7676. });
  7677. if (res.ok) {
  7678. showToast('VTEP Added', `Peer ${remote} added to ${iface}`, 'success');
  7679. closeVXLANVtepModal();
  7680. loadVXLAN(false);
  7681. fetchData(false);
  7682. } else {
  7683. const err = await res.json();
  7684. showToast('Error', err.message, 'error');
  7685. }
  7686. } catch (err) {
  7687. showToast('Error', err.message, 'error');
  7688. }
  7689. }
  7690. async function deleteVXLANVtep(iface, vtepIdOrIp) {
  7691. if (!confirm(`Are you sure you want to remove VTEP ${vtepIdOrIp} from ${iface}?`)) return;
  7692. try {
  7693. const res = await fetch(`${API_BASE}/vpn/vxlan/${encodeURIComponent(iface)}/vteps/${encodeURIComponent(vtepIdOrIp)}`, {
  7694. method: 'DELETE'
  7695. });
  7696. if (res.ok) {
  7697. showToast('Deleted', 'Remote VTEP removed', 'success');
  7698. loadVXLAN(false);
  7699. fetchData(false);
  7700. }
  7701. } catch (err) {
  7702. showToast('Error', err.message, 'error');
  7703. }
  7704. }
  7705. // ======================== AeroTUN (Custom Encrypted VPN with Adaptive LZ4) ========================
  7706. const aeroRateSamples = new Map();
  7707. const aeroLiveRates = new Map();
  7708. async function loadAeroTUN(populate = true) {
  7709. try {
  7710. const [tunnelsRes, statsRes] = await Promise.all([
  7711. fetch(`${API_BASE}/vpn/aerotun/tunnels`),
  7712. fetch(`${API_BASE}/vpn/aerotun/stats`)
  7713. ]);
  7714. if (tunnelsRes.ok) {
  7715. const data = await tunnelsRes.json();
  7716. state.aerotunTunnels = Array.isArray(data) ? data : [];
  7717. const now = Date.now();
  7718. for (const t of state.aerotunTunnels) {
  7719. const old = aeroRateSamples.get(t.id), seconds = old ? (now-old.time)/1000 : 0;
  7720. 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) {
  7721. 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});
  7722. } else if (!old || seconds > 60 || t.rx_bytes < old.rx || t.tx_bytes < old.tx) aeroLiveRates.delete(t.id);
  7723. 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});
  7724. }
  7725. }
  7726. if (statsRes.ok) {
  7727. state.aerotunStats = await statsRes.json();
  7728. }
  7729. const countBadge = document.getElementById('aerotun-count-badge');
  7730. if (countBadge) countBadge.innerText = `${(state.aerotunTunnels || []).length} Tunnels`;
  7731. const sideBadge = document.getElementById('badge-aerotun-count');
  7732. if (sideBadge) sideBadge.innerText = (state.aerotunTunnels || []).length;
  7733. renderAeroTUN();
  7734. if (state.aeroHealthSelected) await refreshAeroTUNHealth();
  7735. } catch (err) {
  7736. console.error('Failed to load AeroTUN:', err);
  7737. }
  7738. }
  7739. function renderAeroTUN() {
  7740. const tbody = document.getElementById('aerotun-table-body');
  7741. const empty = document.getElementById('aerotun-empty');
  7742. // Update summary cards
  7743. const stats = state.aerotunStats || {};
  7744. const tunnels = state.aerotunTunnels || [];
  7745. const statActive = document.getElementById('aerotun-stat-active');
  7746. if (statActive) {
  7747. const activeCount = tunnels.filter(t => t.connected).length;
  7748. statActive.innerText = `${activeCount} / ${tunnels.length}`;
  7749. }
  7750. const statSaved = document.getElementById('aerotun-stat-saved');
  7751. if (statSaved) {
  7752. statSaved.innerText = formatBytes(stats.total_saved_bytes || 0);
  7753. }
  7754. const statRatio = document.getElementById('aerotun-stat-ratio');
  7755. if (statRatio) {
  7756. statRatio.innerText = stats.average_ratio || '1.00x (0% saved)';
  7757. }
  7758. const statTraffic = document.getElementById('aerotun-stat-traffic');
  7759. if (statTraffic) {
  7760. statTraffic.innerText = `↓ ${formatBytes(stats.total_rx_bytes || 0)} / ↑ ${formatBytes(stats.total_tx_bytes || 0)}`;
  7761. }
  7762. if (!tbody) return;
  7763. tbody.innerHTML = '';
  7764. if (tunnels.length === 0) {
  7765. empty?.classList.remove('hidden');
  7766. return;
  7767. }
  7768. empty?.classList.add('hidden');
  7769. tunnels.forEach(t => {
  7770. const tr = document.createElement('tr');
  7771. tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
  7772. const modeBadge = t.mode === 'server'
  7773. ? `<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>`
  7774. : `<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>`;
  7775. const endpointInfo = t.mode === 'server'
  7776. ? `<span class="text-sky-300 font-mono">Port :${t.listen_port || 51830}</span>`
  7777. : `<span class="text-indigo-300 font-mono">${escapeHtml(t.remote_endpoint || '(not set)')}</span>`;
  7778. const compBadge = t.compression
  7779. ? `<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>`
  7780. : `<span class="text-slate-500 text-[10px]">Off</span>`;
  7781. const activePeer = t.connected && t.active_peer_endpoint
  7782. ? `<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>`
  7783. : `<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>`;
  7784. const rawRx = formatBytes(t.rx_bytes || 0);
  7785. const rawTx = formatBytes(t.tx_bytes || 0);
  7786. const wireRx = formatBytes(t.wire_bytes_in || 0);
  7787. const wireTx = formatBytes(t.wire_bytes_out || 0);
  7788. const rate = aeroLiveRates.get(t.id);
  7789. const id = encodeURIComponent(String(t.id || '')).replace(/'/g, '%27');
  7790. tr.innerHTML = `
  7791. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.connected, t.disabled)}</td>
  7792. <td class="py-2.5 px-3 font-bold text-white font-mono flex items-center gap-1.5">
  7793. <span>${escapeHtml(t.name)}</span>
  7794. ${t.default_route ? '<span class="text-[9px] px-1 rounded bg-amber-500/20 text-amber-300 border border-amber-500/30">DEF</span>' : ''}
  7795. <span class="text-slate-400 text-[10px]">v${t.protocol_version || 2}</span>
  7796. </td>
  7797. <td class="py-2.5 px-3">${modeBadge}</td>
  7798. <td class="py-2.5 px-3 text-xs font-mono">${endpointInfo}</td>
  7799. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${escapeHtml(t.local_address || '-')}</td>
  7800. <td class="py-2.5 px-3">${compBadge}</td>
  7801. <td class="py-2.5 px-3">${activePeer}</td>
  7802. <td class="py-2.5 px-3 font-mono text-[11px]">
  7803. <span class="text-emerald-400">↓ ${rawRx}</span>
  7804. <span class="text-cyan-400 ml-1">↑ ${rawTx}</span>
  7805. ${rate ? `<div class="text-slate-400">↓ ${rate.rx.toFixed(2)} / ↑ ${rate.tx.toFixed(2)} Mbit/s</div>` : ''}
  7806. </td>
  7807. <td class="py-2.5 px-3 font-mono text-[11px]">
  7808. <span class="text-slate-400">↓ ${wireRx}</span>
  7809. <span class="text-slate-400 ml-1">↑ ${wireTx}</span>
  7810. </td>
  7811. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(t.comment || '')}">${escapeHtml(t.comment || '-')}</td>
  7812. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  7813. <button onclick="openAeroTUNHealth('${id}')" class="text-xs text-sky-400 hover:text-sky-300 font-medium">Health</button>
  7814. ${t.running
  7815. ? `<button onclick="stopAeroTUNTunnel('${t.id}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Stop</button>`
  7816. : `<button onclick="startAeroTUNTunnel('${t.id}')" class="text-xs text-emerald-400 hover:text-emerald-300 font-medium">Start</button>`
  7817. }
  7818. <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>
  7819. <button onclick="openEditAeroTUNModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  7820. <button onclick="deleteAeroTUN('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  7821. </td>
  7822. `;
  7823. tbody.appendChild(tr);
  7824. });
  7825. }
  7826. async function openAeroTUNHealth(encodedID) {
  7827. state.aeroHealthSelected = decodeURIComponent(encodedID);
  7828. const tunnel=(state.aerotunTunnels||[]).find(x=>x.id===state.aeroHealthSelected);
  7829. let underlay='';try {underlay=new URL(`http://${tunnel?.remote_endpoint||tunnel?.active_peer_endpoint||''}`).hostname.replace(/^\[|\]$/g,'')} catch {}
  7830. document.getElementById('aerotun-compare-host').value=underlay;
  7831. document.getElementById('aerotun-compare-result').textContent='';
  7832. document.getElementById('aerotun-health-result').textContent = '';
  7833. document.getElementById('aerotun-health-panel').classList.remove('hidden');
  7834. await refreshAeroTUNHealth();
  7835. document.getElementById('aerotun-health-panel').scrollIntoView({behavior:'smooth',block:'nearest'});
  7836. }
  7837. function closeAeroTUNHealth() { aeroCompareCancel=true; state.aeroHealthSelected = ''; document.getElementById('aerotun-health-panel').classList.add('hidden'); }
  7838. async function refreshAeroTUNHealth() {
  7839. const id=state.aeroHealthSelected,t=(state.aerotunTunnels||[]).find(x=>x.id===id);if(!id)return;
  7840. if(!t){document.getElementById('aerotun-health-status').textContent='Tunnel no longer exists.';return}
  7841. document.getElementById('aerotun-health-title').textContent=`Health: ${t.name}`;
  7842. try {
  7843. 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;
  7844. 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);
  7845. const d=t.drop_breakdown;
  7846. 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}`:''}`;
  7847. const events=(data.events||[]).filter(e=>e.tunnel_id===id).slice(0,100),node=document.getElementById('aerotun-health-history');node.replaceChildren();
  7848. if(!events.length){node.textContent='No events recorded yet.';return}
  7849. 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)}
  7850. } catch(e){document.getElementById('aerotun-health-history').textContent=`Health history unavailable: ${e.message}`}
  7851. }
  7852. async function runAeroTUNHealthCheck() {
  7853. 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…';
  7854. 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()}
  7855. catch(e){if(state.aeroHealthSelected===id)output.textContent=`Health check failed: ${e.message}`}
  7856. finally {button.disabled=false}
  7857. }
  7858. let aeroCompareRunning=false, aeroCompareCancel=false;
  7859. function stopAeroTUNComparison() { aeroCompareCancel=true;document.getElementById('aerotun-compare-result').textContent+='\nStopping after the current test.'; }
  7860. async function runAeroTUNComparison() {
  7861. if(aeroCompareRunning)return;
  7862. 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();
  7863. const output=document.getElementById('aerotun-compare-result'),button=document.getElementById('aerotun-compare-btn'),stop=document.getElementById('aerotun-compare-stop');
  7864. 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}
  7865. if(peer.includes(':')||direct.includes(':')){output.textContent='This comparison currently supports IPv4 addresses or IPv4-resolvable hostnames.';return}
  7866. aeroCompareRunning=true;aeroCompareCancel=false;button.disabled=true;stop.classList.remove('hidden');output.textContent='Starting. The direct address uses the system routing table.';
  7867. 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()};
  7868. const results=[];
  7869. try {
  7870. for(const [path,target,direction] of [['Tunnel',peer,'tx'],['Tunnel',peer,'rx'],['Direct',direct,'tx'],['Direct',direct,'rx']]) {
  7871. if(aeroCompareCancel)break;
  7872. if((await get('/tools/bwtest/status')).running)throw new Error('Another bandwidth test is running; comparison stopped.');
  7873. output.textContent+=`\n${path} ${direction.toUpperCase()}: testing…`;
  7874. 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;
  7875. 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}}
  7876. if(!complete)throw new Error('Timed out waiting for the bandwidth test.');if(status.error)throw new Error(`${path} ${direction.toUpperCase()}: ${status.error}`);
  7877. 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.`);
  7878. results.push(`${path} ${direction.toUpperCase()}: ${value.toFixed(2)} Mbit/s`);output.textContent='Results:\n'+results.join('\n');
  7879. }
  7880. if(aeroCompareCancel)output.textContent+='\nComparison stopped.';
  7881. else output.textContent+='\nDirect results are meaningful only if both addresses reach the same server over different routes.';
  7882. } catch(e){output.textContent+=`\nComparison incomplete: ${e.message}`}
  7883. finally {aeroCompareRunning=false;button.disabled=false;stop.classList.add('hidden')}
  7884. }
  7885. let aeroModalGeneration = 0;
  7886. let aeroIdentityDraft = '';
  7887. let aeroSaving = false;
  7888. let aeroPSKRequest = 0;
  7889. function discardAeroIdentityDraft(id) {
  7890. if (id) fetch(`${API_BASE}/vpn/aerotun/identity-drafts/${encodeURIComponent(id)}`, {method:'DELETE'}).catch(() => {});
  7891. }
  7892. async function generateAeroTUNIdentity() {
  7893. const generation = aeroModalGeneration;
  7894. const retry = document.getElementById('aerotun-retry-identity');
  7895. if (aeroIdentityDraft) { discardAeroIdentityDraft(aeroIdentityDraft); aeroIdentityDraft = ''; }
  7896. retry.classList.add('hidden');
  7897. document.getElementById('aerotun-modal-public').value = '';
  7898. try {
  7899. const res = await fetch(`${API_BASE}/vpn/aerotun/identity-drafts`, {method:'POST'});
  7900. if (!res.ok) throw new Error(await responseError(res));
  7901. const draft = await res.json();
  7902. if (generation !== aeroModalGeneration) { discardAeroIdentityDraft(draft.draft_id); return; }
  7903. aeroIdentityDraft = draft.draft_id;
  7904. document.getElementById('aerotun-modal-public').value = draft.public_key;
  7905. updateAeroTUNSetupHint();
  7906. } catch (err) {
  7907. if (generation !== aeroModalGeneration) return;
  7908. retry.classList.remove('hidden');
  7909. updateAeroTUNSetupHint();
  7910. showToast('Identity Generation Failed', err.message, 'error');
  7911. }
  7912. }
  7913. function onAeroTUNModeChange() {
  7914. const mode = document.getElementById('aerotun-modal-mode').value;
  7915. const endpointInput = document.getElementById('aerotun-modal-endpoint');
  7916. const portInput = document.getElementById('aerotun-modal-port');
  7917. if (mode === 'server') {
  7918. if (!portInput.value) portInput.value = '51830';
  7919. endpointInput.placeholder = 'Optional / learned roaming peer';
  7920. } else {
  7921. endpointInput.placeholder = 'vpn.example.com:51830 (required)';
  7922. if (!portInput.value) portInput.value = '';
  7923. }
  7924. }
  7925. function onAeroTUNPeerChange() {
  7926. const peer = document.getElementById('aerotun-modal-peer');
  7927. const allowed = document.getElementById('aerotun-modal-allowed');
  7928. const previous = peer.dataset.allowedDefault || '';
  7929. const host = peer.value.trim().split('/')[0];
  7930. const next = host ? `${host}/${host.includes(':') ? 128 : 32}` : '';
  7931. if (allowed.value.trim() === previous) allowed.value = next;
  7932. peer.dataset.allowedDefault = next;
  7933. }
  7934. async function generateAeroTUNKey(automatic = false) {
  7935. const generation = aeroModalGeneration, request = ++aeroPSKRequest;
  7936. const input = document.getElementById('aerotun-modal-psk'), previous = input.value;
  7937. try {
  7938. const res = await fetch(`${API_BASE}/vpn/aerotun/genkey`);
  7939. if (!res.ok) throw new Error(await responseError(res));
  7940. const data = await res.json();
  7941. if (generation !== aeroModalGeneration || request !== aeroPSKRequest || (automatic && input.value !== previous)) return;
  7942. input.value = data.key;
  7943. if (!automatic) showToast('Key Generated', 'Share this PSK securely with the peer before enabling', 'success');
  7944. } catch (err) {
  7945. if (generation === aeroModalGeneration && request === aeroPSKRequest) showToast('Key Generation Failed', err.message, 'error');
  7946. }
  7947. }
  7948. function updateAeroTUNSetupHint() {
  7949. const version = document.getElementById('aerotun-modal-protocol').value;
  7950. const key = document.getElementById('aerotun-modal-public').value;
  7951. const peer = document.getElementById('aerotun-modal-peerkey').value.trim();
  7952. const hint = document.getElementById('aerotun-setup-hint');
  7953. document.getElementById('aerotun-v3-fields').classList.toggle('hidden', version !== '3');
  7954. if (!hint) return;
  7955. 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.';
  7956. }
  7957. async function copyAeroTUNPublicKey() {
  7958. const input = document.getElementById('aerotun-modal-public');
  7959. if (!input.value) { showToast('Key Not Ready', 'Wait for the local identity or retry key generation.', 'info'); return; }
  7960. try {
  7961. await navigator.clipboard.writeText(input.value);
  7962. showToast('Public Key Copied', 'Paste it into the other endpoint’s pinned peer key', 'success');
  7963. } catch {
  7964. input.focus(); input.select();
  7965. showToast('Copy Public Key', 'Key selected; press Ctrl+C to copy', 'info');
  7966. }
  7967. }
  7968. async function copyAeroTUNPSK() {
  7969. const input = document.getElementById('aerotun-modal-psk');
  7970. if (!input.value) { showToast('PSK Not Available', 'Generate or enter a PSK to copy it. Existing keys are not displayed.', 'info'); return; }
  7971. try { await navigator.clipboard.writeText(input.value); showToast('PSK Copied', 'Share it securely with the peer.', 'success'); }
  7972. catch { input.type = 'text'; input.focus(); input.select(); showToast('Copy PSK', 'Key selected; press Ctrl+C to copy.', 'info'); }
  7973. }
  7974. function openAddAeroTUNModal() {
  7975. if (aeroSaving) return;
  7976. aeroModalGeneration++; discardAeroIdentityDraft(aeroIdentityDraft); aeroIdentityDraft = '';
  7977. const tunnels = state.aerotunTunnels || [];
  7978. const usedNames = new Set(tunnels.map(t => t.name));
  7979. const usedPorts = new Set(tunnels.map(t => Number(t.listen_port)));
  7980. 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++;
  7981. if (index >= 256) index = 0;
  7982. document.getElementById('aerotun-modal-title').innerText = 'Add AeroTUN Interface';
  7983. document.getElementById('aerotun-modal-id').value = '';
  7984. document.getElementById('aerotun-modal-protocol').value='3';
  7985. document.getElementById('aerotun-modal-public').value='';
  7986. document.getElementById('aerotun-modal-peerkey').value='';
  7987. document.getElementById('aerotun-modal-allowed').value=`10.99.${index}.2/32`;
  7988. document.getElementById('aerotun-modal-name').value = `aerotun${index}`;
  7989. document.getElementById('aerotun-modal-mode').value = 'server';
  7990. document.getElementById('aerotun-modal-port').value = 51830 + index;
  7991. document.getElementById('aerotun-modal-endpoint').value = '';
  7992. document.getElementById('aerotun-modal-local').value = `10.99.${index}.1/24`;
  7993. document.getElementById('aerotun-modal-peer').value = `10.99.${index}.2/24`;
  7994. document.getElementById('aerotun-modal-peer').dataset.allowedDefault = `10.99.${index}.2/32`;
  7995. document.getElementById('aerotun-modal-psk').value = '';
  7996. document.getElementById('aerotun-modal-mtu').value = '1420';
  7997. document.getElementById('aerotun-modal-comment').value = '';
  7998. document.getElementById('aerotun-modal-compression').checked = false;
  7999. document.getElementById('aerotun-modal-defroute').checked = false;
  8000. document.getElementById('aerotun-modal-disabled').checked = true;
  8001. document.getElementById('aerotun-modal-psk').type = 'password';
  8002. document.getElementById('aerotun-modal-psk').placeholder = 'Generate or enter the shared key';
  8003. onAeroTUNModeChange();
  8004. updateAeroTUNSetupHint();
  8005. document.getElementById('aerotun-modal').classList.remove('hidden');
  8006. generateAeroTUNKey(true);
  8007. generateAeroTUNIdentity();
  8008. }
  8009. function openEditAeroTUNModal(id) {
  8010. if (aeroSaving) return;
  8011. const t = (state.aerotunTunnels || []).find(tun => tun.id === id);
  8012. if (!t) return;
  8013. aeroModalGeneration++; discardAeroIdentityDraft(aeroIdentityDraft); aeroIdentityDraft = '';
  8014. document.getElementById('aerotun-retry-identity').classList.add('hidden');
  8015. document.getElementById('aerotun-modal-title').innerText = `Edit AeroTUN Interface (${t.name})`;
  8016. document.getElementById('aerotun-modal-id').value = t.id;
  8017. document.getElementById('aerotun-modal-protocol').value=String(t.protocol_version || 2);
  8018. document.getElementById('aerotun-modal-public').value=t.public_key || '';
  8019. document.getElementById('aerotun-modal-peerkey').value=t.peer_public_key || '';
  8020. document.getElementById('aerotun-modal-allowed').value=(t.allowed_ips || []).join(', ');
  8021. document.getElementById('aerotun-modal-name').value = t.name;
  8022. document.getElementById('aerotun-modal-mode').value = t.mode || 'server';
  8023. document.getElementById('aerotun-modal-port').value = t.listen_port || '';
  8024. document.getElementById('aerotun-modal-endpoint').value = t.remote_endpoint || '';
  8025. document.getElementById('aerotun-modal-local').value = t.local_address || '';
  8026. document.getElementById('aerotun-modal-peer').value = t.peer_address || '';
  8027. const peerHost = (t.peer_address || '').split('/')[0];
  8028. document.getElementById('aerotun-modal-peer').dataset.allowedDefault = peerHost ? `${peerHost}/${peerHost.includes(':') ? 128 : 32}` : '';
  8029. document.getElementById('aerotun-modal-psk').value = '';
  8030. document.getElementById('aerotun-modal-psk').type = 'password';
  8031. document.getElementById('aerotun-modal-psk').placeholder = t.has_psk ? 'Leave blank to keep the existing key' : 'New random 256-bit PSK';
  8032. document.getElementById('aerotun-modal-mtu').value = t.configured_mtu || t.mtu || 1420;
  8033. document.getElementById('aerotun-modal-comment').value = t.comment || '';
  8034. document.getElementById('aerotun-modal-compression').checked = !!t.compression;
  8035. document.getElementById('aerotun-modal-defroute').checked = !!t.default_route;
  8036. document.getElementById('aerotun-modal-disabled').checked = !!t.disabled;
  8037. onAeroTUNModeChange();
  8038. updateAeroTUNSetupHint();
  8039. document.getElementById('aerotun-modal').classList.remove('hidden');
  8040. }
  8041. function closeAeroTUNModal() {
  8042. if (aeroSaving) return;
  8043. aeroModalGeneration++; discardAeroIdentityDraft(aeroIdentityDraft); aeroIdentityDraft = '';
  8044. document.getElementById('aerotun-modal-psk').value = '';
  8045. document.getElementById('aerotun-modal').classList.add('hidden');
  8046. }
  8047. async function submitSaveAeroTUN(e) {
  8048. e.preventDefault();
  8049. if (aeroSaving) return;
  8050. const id = document.getElementById('aerotun-modal-id').value;
  8051. const name = document.getElementById('aerotun-modal-name').value.trim();
  8052. const mode = document.getElementById('aerotun-modal-mode').value;
  8053. const port = parseInt(document.getElementById('aerotun-modal-port').value) || 0;
  8054. const endpoint = document.getElementById('aerotun-modal-endpoint').value.trim();
  8055. const local = document.getElementById('aerotun-modal-local').value.trim();
  8056. const peer = document.getElementById('aerotun-modal-peer').value.trim();
  8057. const psk = document.getElementById('aerotun-modal-psk').value.trim();
  8058. const mtuValue = document.getElementById('aerotun-modal-mtu').value;
  8059. const mtu = mtuValue === '' ? 1420 : Number(mtuValue);
  8060. const comment = document.getElementById('aerotun-modal-comment').value.trim();
  8061. const compression = document.getElementById('aerotun-modal-compression').checked;
  8062. const defaultRoute = document.getElementById('aerotun-modal-defroute').checked;
  8063. const disabled = document.getElementById('aerotun-modal-disabled').checked;
  8064. if (mode === 'client' && !endpoint) {
  8065. showToast('Validation Error', 'Remote endpoint (host:port) is required in client mode', 'error');
  8066. return;
  8067. }
  8068. if (defaultRoute && (mode !== 'client' || !endpoint)) {
  8069. showToast('Validation Error', 'Default route requires client mode and a fixed remote endpoint.', 'error');
  8070. return;
  8071. }
  8072. if (!Number.isInteger(mtu) || mtu < 576 || mtu > 9000) {
  8073. showToast('Validation Error', 'MTU must be between 576 and 9000.', 'error');
  8074. return;
  8075. }
  8076. const version = parseInt(document.getElementById('aerotun-modal-protocol').value, 10);
  8077. if (version === 3 && !id && !aeroIdentityDraft) {
  8078. showToast('Local Key Not Ready', 'Wait for the local identity or retry key generation before saving.', 'error');
  8079. return;
  8080. }
  8081. if (version === 3 && !document.getElementById('aerotun-modal-allowed').value.trim()) {
  8082. showToast('Allowed Prefix Required', 'Enter at least one allowed peer source prefix, such as the peer tunnel IP /32.', 'error');
  8083. document.getElementById('aerotun-modal-allowed').focus();
  8084. return;
  8085. }
  8086. if (version === 3 && !disabled && !document.getElementById('aerotun-modal-peerkey').value.trim()) {
  8087. showToast('Peer Key Required', 'Enter the peer public key, or save this tunnel disabled until it is available.', 'error');
  8088. return;
  8089. }
  8090. if (!psk && !id) {
  8091. showToast('Validation Error', 'Pre-shared key (PSK) is required', 'error');
  8092. return;
  8093. }
  8094. aeroSaving = true;
  8095. const submit = document.querySelector('#aerotun-modal button[type="submit"]');
  8096. if (submit) submit.disabled = true;
  8097. try {
  8098. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels`, {
  8099. method: 'POST',
  8100. headers: { 'Content-Type': 'application/json' },
  8101. body: JSON.stringify({
  8102. protocol_version:parseInt(document.getElementById('aerotun-modal-protocol').value,10),
  8103. identity_draft_id: version === 3 && !id ? aeroIdentityDraft : '',
  8104. peer_public_key:document.getElementById('aerotun-modal-peerkey').value.trim(),
  8105. allowed_ips:document.getElementById('aerotun-modal-allowed').value.split(',').map(s=>s.trim()).filter(Boolean),
  8106. id,
  8107. name,
  8108. mode,
  8109. listen_port: port,
  8110. remote_endpoint: endpoint,
  8111. local_address: local,
  8112. peer_address: peer,
  8113. psk,
  8114. mtu,
  8115. compression,
  8116. default_route: defaultRoute,
  8117. comment,
  8118. disabled
  8119. })
  8120. });
  8121. if (res.ok) {
  8122. await res.json();
  8123. if (version !== 3) discardAeroIdentityDraft(aeroIdentityDraft);
  8124. aeroIdentityDraft = '';
  8125. aeroSaving = false;
  8126. closeAeroTUNModal();
  8127. await loadAeroTUN(false);
  8128. showToast('AeroTUN Saved', disabled ? 'Configuration saved; tunnel is disabled' : 'Configuration saved; waiting for authenticated peer traffic', 'success');
  8129. fetchData(false);
  8130. } else {
  8131. const err = await responseError(res);
  8132. if (err.includes('configuration saved but tunnel failed to start')) {
  8133. aeroIdentityDraft = '';
  8134. aeroSaving = false;
  8135. closeAeroTUNModal();
  8136. await loadAeroTUN(false);
  8137. showToast('Saved, but not started', err, 'error');
  8138. } else showToast('Error Saving Tunnel', err, 'error');
  8139. }
  8140. } catch (err) {
  8141. showToast('Network Error', err.message, 'error');
  8142. } finally {
  8143. aeroSaving = false;
  8144. if (submit) submit.disabled = false;
  8145. }
  8146. }
  8147. async function startAeroTUNTunnel(id) {
  8148. try {
  8149. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/start`, { method: 'POST' });
  8150. if (res.ok) {
  8151. showToast('AeroTUN Started', 'Interface started; connection is confirmed by authenticated peer traffic', 'info');
  8152. loadAeroTUN(false);
  8153. fetchData(false);
  8154. } else {
  8155. const err = await res.text();
  8156. showToast('Failed to Start', err, 'error');
  8157. }
  8158. } catch (err) {
  8159. showToast('Error', err.message, 'error');
  8160. }
  8161. }
  8162. async function stopAeroTUNTunnel(id) {
  8163. try {
  8164. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/stop`, { method: 'POST' });
  8165. if (res.ok) {
  8166. showToast('AeroTUN Stopped', 'Tunnel stopped', 'info');
  8167. loadAeroTUN(false);
  8168. fetchData(false);
  8169. } else {
  8170. const err = await res.text();
  8171. showToast('Failed to Stop', err, 'error');
  8172. }
  8173. } catch (err) {
  8174. showToast('Error', err.message, 'error');
  8175. }
  8176. }
  8177. async function toggleAeroTUNState(id, disabled) {
  8178. try {
  8179. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/state`, {
  8180. method: 'POST',
  8181. headers: { 'Content-Type': 'application/json' },
  8182. body: JSON.stringify({ disabled })
  8183. });
  8184. if (res.ok) {
  8185. showToast('State Updated', disabled ? 'Tunnel disabled' : 'Tunnel enabled', 'info');
  8186. loadAeroTUN(false);
  8187. fetchData(false);
  8188. }
  8189. } catch (err) {
  8190. showToast('Error', err.message, 'error');
  8191. }
  8192. }
  8193. async function deleteAeroTUN(id) {
  8194. if (!confirm('Are you sure you want to delete this AeroTUN tunnel?')) return;
  8195. try {
  8196. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8197. if (res.ok) {
  8198. showToast('Deleted', 'AeroTUN tunnel removed', 'success');
  8199. loadAeroTUN(false);
  8200. fetchData(false);
  8201. }
  8202. } catch (err) {
  8203. showToast('Error', err.message, 'error');
  8204. }
  8205. }
  8206. // ======================== PPP Central Hub & Servers ========================
  8207. function switchPPPSubTab(tab) {
  8208. state.pppSubTab = tab;
  8209. const tabs = ['secrets', 'profiles', 'pppoe', 'pptp', 'l2tp', 'active'];
  8210. tabs.forEach(t => {
  8211. const panel = document.getElementById(`ppp-subtab-${t}`);
  8212. const btn = document.getElementById(`ppp-subtab-btn-${t}`);
  8213. if (panel) {
  8214. if (t === tab) panel.classList.remove('hidden');
  8215. else panel.classList.add('hidden');
  8216. }
  8217. if (btn) {
  8218. if (t === tab) {
  8219. 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';
  8220. } else {
  8221. 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';
  8222. }
  8223. }
  8224. });
  8225. const addBtn = document.getElementById('ppp-primary-add-btn');
  8226. if (addBtn) {
  8227. if (tab === 'secrets') addBtn.innerHTML = '<span>+ Add User (Secret)</span>';
  8228. else if (tab === 'profiles') addBtn.innerHTML = '<span>+ Add Profile</span>';
  8229. else if (tab === 'active') addBtn.innerHTML = '<span>Refresh Sessions</span>';
  8230. else addBtn.innerHTML = '<span>Save Config</span>';
  8231. }
  8232. if (tab === 'active') loadPPPSessions();
  8233. }
  8234. function openCurrentPPPModal() {
  8235. if (state.pppSubTab === 'secrets') openAddPPPSecretModal();
  8236. else if (state.pppSubTab === 'profiles') openAddPPPProfileModal();
  8237. else if (state.pppSubTab === 'active') loadPPPSessions();
  8238. else if (state.pppSubTab === 'pppoe') document.querySelector('#ppp-subtab-pppoe form')?.requestSubmit();
  8239. else if (state.pppSubTab === 'pptp') document.querySelector('#ppp-subtab-pptp form')?.requestSubmit();
  8240. else if (state.pppSubTab === 'l2tp') document.querySelector('#ppp-subtab-l2tp form')?.requestSubmit();
  8241. }
  8242. async function loadPPP(populateDropdowns = true) {
  8243. await Promise.all([
  8244. loadPPPSecrets(),
  8245. loadPPPProfiles(),
  8246. loadPPPServers(),
  8247. loadPPPSessions()
  8248. ]);
  8249. }
  8250. async function loadPPPSecrets() {
  8251. try {
  8252. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`);
  8253. const data = await res.json();
  8254. state.pppSecrets = Array.isArray(data) ? data : [];
  8255. const b = document.getElementById('ppp-badge-secrets');
  8256. if (b) b.innerText = state.pppSecrets.length;
  8257. const b2 = document.getElementById('secrets-count-badge');
  8258. if (b2) b2.innerText = `${state.pppSecrets.length} Users`;
  8259. renderPPPSecrets();
  8260. } catch (err) {
  8261. console.error('Failed to load PPP secrets:', err);
  8262. }
  8263. }
  8264. function renderPPPSecrets() {
  8265. const tbody = document.getElementById('secrets-table-body');
  8266. const empty = document.getElementById('secrets-empty');
  8267. if (!tbody) return;
  8268. tbody.innerHTML = '';
  8269. const secrets = state.pppSecrets || [];
  8270. if (secrets.length === 0) {
  8271. empty?.classList.remove('hidden');
  8272. return;
  8273. }
  8274. empty?.classList.add('hidden');
  8275. secrets.forEach(s => {
  8276. const tr = document.createElement('tr');
  8277. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  8278. tr.innerHTML = `
  8279. <td class="py-2.5 px-3 text-center">${renderRuleFlag(s.disabled, !!s.comment)}</td>
  8280. <td class="py-2.5 px-3 font-bold text-white font-mono">${s.name}</td>
  8281. <td class="py-2.5 px-3 text-purple-300 font-mono font-semibold">${s.service}</td>
  8282. <td class="py-2.5 px-3 text-amber-300 font-mono">${s.profile}</td>
  8283. <td class="py-2.5 px-3 text-slate-400 font-mono">${s.local_address || '(profile)'}</td>
  8284. <td class="py-2.5 px-3 text-cyan-400 font-mono font-bold">${s.remote_address || '(profile)'}</td>
  8285. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]">${s.comment || '-'}</td>
  8286. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  8287. <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>
  8288. <button onclick="openEditPPPSecretModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  8289. <button onclick="deletePPPSecret('${s.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  8290. </td>
  8291. `;
  8292. tbody.appendChild(tr);
  8293. });
  8294. }
  8295. async function loadPPPProfiles() {
  8296. try {
  8297. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`);
  8298. const data = await res.json();
  8299. state.pppProfiles = Array.isArray(data) ? data : [];
  8300. const b = document.getElementById('ppp-badge-profiles');
  8301. if (b) b.innerText = state.pppProfiles.length;
  8302. const b2 = document.getElementById('profiles-count-badge');
  8303. if (b2) b2.innerText = `${state.pppProfiles.length} Profiles`;
  8304. // Populate profile selects across modals
  8305. const selects = ['secret-modal-profile', 'pppoe-server-profile', 'pptp-server-profile', 'l2tp-server-profile'];
  8306. selects.forEach(sid => {
  8307. const el = document.getElementById(sid);
  8308. if (!el) return;
  8309. const cur = el.value;
  8310. el.innerHTML = '';
  8311. state.pppProfiles.forEach(p => {
  8312. const opt = document.createElement('option');
  8313. opt.value = p.name;
  8314. opt.innerText = `${p.name} (${p.remote_address})`;
  8315. if (p.name === cur) opt.selected = true;
  8316. el.appendChild(opt);
  8317. });
  8318. });
  8319. renderPPPProfiles();
  8320. } catch (err) {
  8321. console.error('Failed to load PPP profiles:', err);
  8322. }
  8323. }
  8324. function renderPPPProfiles() {
  8325. const tbody = document.getElementById('profiles-table-body');
  8326. if (!tbody) return;
  8327. tbody.innerHTML = '';
  8328. (state.pppProfiles || []).forEach(p => {
  8329. const isDefault = p.name.startsWith('default');
  8330. const tr = document.createElement('tr');
  8331. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  8332. tr.innerHTML = `
  8333. <td class="py-2.5 px-3 font-bold text-white">${p.name}</td>
  8334. <td class="py-2.5 px-3 text-slate-300">${p.local_address}</td>
  8335. <td class="py-2.5 px-3 text-cyan-400 font-bold">${p.remote_address}</td>
  8336. <td class="py-2.5 px-3 text-slate-400">${p.dns_servers || '-'}</td>
  8337. <td class="py-2.5 px-3 text-purple-300 font-semibold">${p.use_encryption}</td>
  8338. <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>
  8339. <td class="py-2.5 px-3 text-slate-400 italic">${p.comment || '-'}</td>
  8340. <td class="py-2.5 px-3 text-right font-sans whitespace-nowrap">
  8341. ${!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>`}
  8342. </td>
  8343. `;
  8344. tbody.appendChild(tr);
  8345. });
  8346. }
  8347. async function loadPPPServers() {
  8348. try {
  8349. const [pppoeRes, pptpRes, l2tpRes, ipsecRes] = await Promise.all([
  8350. fetch(`${API_BASE}/vpn/servers/pppoe`),
  8351. fetch(`${API_BASE}/vpn/servers/pptp`),
  8352. fetch(`${API_BASE}/vpn/servers/l2tp`),
  8353. fetch(`${API_BASE}/vpn/servers/ipsec`)
  8354. ]);
  8355. if (pppoeRes.ok) {
  8356. state.pppoeServer = await pppoeRes.json();
  8357. const s = state.pppoeServer;
  8358. document.getElementById('pppoe-server-enabled').checked = !!s.enabled;
  8359. document.getElementById('pppoe-server-name').value = s.service_name || 'debtik-pppoe';
  8360. populateInterfaceSelect('pppoe-server-iface', s.interface || 'eth0');
  8361. document.getElementById('pppoe-server-profile').value = s.default_profile || 'default';
  8362. document.getElementById('pppoe-server-mtu').value = s.max_mtu || 1480;
  8363. document.getElementById('pppoe-server-onesession').checked = !!s.one_session_per_host;
  8364. const pill = document.getElementById('pppoe-server-status-pill');
  8365. if (pill) {
  8366. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  8367. 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';
  8368. }
  8369. setDotBadge('ppp-badge-pppoe-state', s.running);
  8370. }
  8371. if (pptpRes.ok) {
  8372. state.pptpServer = await pptpRes.json();
  8373. const s = state.pptpServer;
  8374. document.getElementById('pptp-server-enabled').checked = !!s.enabled;
  8375. document.getElementById('pptp-server-port').value = s.port || 1723;
  8376. document.getElementById('pptp-server-profile').value = s.default_profile || 'default-encryption';
  8377. document.getElementById('pptp-server-mppe').checked = s.require_mppe !== false;
  8378. const pill = document.getElementById('pptp-server-status-pill');
  8379. if (pill) {
  8380. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  8381. 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';
  8382. }
  8383. setDotBadge('ppp-badge-pptp-state', s.running);
  8384. }
  8385. if (l2tpRes.ok) {
  8386. state.l2tpServer = await l2tpRes.json();
  8387. const s = state.l2tpServer;
  8388. document.getElementById('l2tp-server-enabled').checked = !!s.enabled;
  8389. document.getElementById('l2tp-server-port').value = s.port || 1701;
  8390. document.getElementById('l2tp-server-profile').value = s.default_profile || 'default';
  8391. document.getElementById('l2tp-server-useipsec').value = s.use_ipsec || 'no';
  8392. document.getElementById('l2tp-server-ipsecsecret').value = s.ipsec_secret || '';
  8393. const pill = document.getElementById('l2tp-server-status-pill');
  8394. if (pill) {
  8395. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  8396. 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';
  8397. }
  8398. setDotBadge('ppp-badge-l2tp-state', s.running);
  8399. }
  8400. if (ipsecRes.ok) {
  8401. state.ipsecServer = await ipsecRes.json();
  8402. const s = state.ipsecServer;
  8403. const modalEn = document.getElementById('modal-ipsec-server-enabled');
  8404. if (modalEn) modalEn.checked = !!s.enabled;
  8405. const modalPsk = document.getElementById('modal-ipsec-server-psk');
  8406. if (modalPsk) modalPsk.value = s.preshared_key || '';
  8407. const modalPool = document.getElementById('modal-ipsec-server-pool');
  8408. if (modalPool) modalPool.value = s.pool_address || '10.10.30.0/24';
  8409. const modalDns = document.getElementById('modal-ipsec-server-dns');
  8410. if (modalDns) modalDns.value = s.dns_servers || '1.1.1.1,8.8.8.8';
  8411. const modalSubnet = document.getElementById('modal-ipsec-server-subnet');
  8412. if (modalSubnet) modalSubnet.value = s.local_subnet || '0.0.0.0/0';
  8413. const pill = document.getElementById('modal-ipsec-server-status');
  8414. if (pill) {
  8415. pill.innerText = s.running ? 'ACTIVE RESPONDER' : 'STOPPED';
  8416. 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';
  8417. }
  8418. }
  8419. } catch (err) {
  8420. console.error('Failed to load VPN servers:', err);
  8421. }
  8422. }
  8423. async function loadPPPSessions() {
  8424. try {
  8425. const res = await fetch(`${API_BASE}/vpn/ppp/active`);
  8426. const data = await res.json();
  8427. state.pppActiveSessions = Array.isArray(data) ? data : [];
  8428. const b = document.getElementById('ppp-badge-active');
  8429. if (b) b.innerText = state.pppActiveSessions.length;
  8430. const sideB = document.getElementById('badge-ppp-sessions');
  8431. if (sideB) sideB.innerText = state.pppActiveSessions.length;
  8432. renderPPPSessions();
  8433. } catch (err) {
  8434. console.error('Failed to load active PPP sessions:', err);
  8435. }
  8436. }
  8437. function renderPPPSessions() {
  8438. const tbody = document.getElementById('active-ppp-table-body');
  8439. const empty = document.getElementById('active-ppp-empty');
  8440. if (!tbody) return;
  8441. tbody.innerHTML = '';
  8442. const list = state.pppActiveSessions || [];
  8443. if (list.length === 0) {
  8444. empty?.classList.remove('hidden');
  8445. return;
  8446. }
  8447. empty?.classList.add('hidden');
  8448. list.forEach(s => {
  8449. const tr = document.createElement('tr');
  8450. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  8451. tr.innerHTML = `
  8452. <td class="py-2.5 px-3 font-bold text-white">${s.interface}</td>
  8453. <td class="py-2.5 px-3 font-semibold text-violet-300">${s.username}</td>
  8454. <td class="py-2.5 px-3 text-cyan-400 uppercase">${s.service}</td>
  8455. <td class="py-2.5 px-3 text-emerald-400 font-bold">${s.address || '-'}</td>
  8456. <td class="py-2.5 px-3 text-slate-400">${s.uptime}</td>
  8457. <td class="py-2.5 px-3 text-[11px]">
  8458. <span class="text-emerald-400">↓ ${s.rx_human || '0 B'}</span>
  8459. <span class="text-cyan-400 ml-1">↑ ${s.tx_human || '0 B'}</span>
  8460. </td>
  8461. <td class="py-2.5 px-3 text-right font-sans">
  8462. <button onclick="disconnectPPPSession('${s.interface}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  8463. </td>
  8464. `;
  8465. tbody.appendChild(tr);
  8466. });
  8467. }
  8468. async function disconnectPPPSession(iface) {
  8469. if (!confirm(`Disconnect session ${iface}?`)) return;
  8470. try {
  8471. const res = await fetch(`${API_BASE}/vpn/ppp/active/${encodeURIComponent(iface)}`, { method: 'DELETE' });
  8472. if (res.ok) {
  8473. showToast('Disconnected', `Session ${iface} terminated`, 'info');
  8474. loadPPPSessions();
  8475. }
  8476. } catch (err) {
  8477. showToast('Error', err.message, 'error');
  8478. }
  8479. }
  8480. // PPP Secret Modal handlers
  8481. function openAddPPPSecretModal() {
  8482. document.getElementById('secret-modal-title').innerText = 'Add PPP Secret';
  8483. document.getElementById('secret-modal-id').value = '';
  8484. document.getElementById('secret-modal-name').value = '';
  8485. document.getElementById('secret-modal-password').value = '';
  8486. document.getElementById('secret-modal-service').value = 'any';
  8487. document.getElementById('secret-modal-profile').value = 'default';
  8488. document.getElementById('secret-modal-local').value = '';
  8489. document.getElementById('secret-modal-remote').value = '';
  8490. document.getElementById('secret-modal-comment').value = '';
  8491. document.getElementById('secret-modal-disabled').checked = false;
  8492. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  8493. }
  8494. function openEditPPPSecretModal(id) {
  8495. const s = (state.pppSecrets || []).find(sec => sec.id === id);
  8496. if (!s) return;
  8497. document.getElementById('secret-modal-title').innerText = `Edit PPP Secret (${s.name})`;
  8498. document.getElementById('secret-modal-id').value = s.id;
  8499. document.getElementById('secret-modal-name').value = s.name;
  8500. document.getElementById('secret-modal-password').value = s.password;
  8501. document.getElementById('secret-modal-service').value = s.service || 'any';
  8502. document.getElementById('secret-modal-profile').value = s.profile || 'default';
  8503. document.getElementById('secret-modal-local').value = s.local_address || '';
  8504. document.getElementById('secret-modal-remote').value = s.remote_address || '';
  8505. document.getElementById('secret-modal-comment').value = s.comment || '';
  8506. document.getElementById('secret-modal-disabled').checked = !!s.disabled;
  8507. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  8508. }
  8509. function closePPPSecretModal() {
  8510. document.getElementById('ppp-secret-modal').classList.add('hidden');
  8511. }
  8512. async function submitSavePPPSecret(e) {
  8513. e.preventDefault();
  8514. const id = document.getElementById('secret-modal-id').value;
  8515. const name = document.getElementById('secret-modal-name').value.trim();
  8516. const password = document.getElementById('secret-modal-password').value.trim();
  8517. const service = document.getElementById('secret-modal-service').value;
  8518. const profile = document.getElementById('secret-modal-profile').value;
  8519. const local = document.getElementById('secret-modal-local').value.trim();
  8520. const remote = document.getElementById('secret-modal-remote').value.trim();
  8521. const comment = document.getElementById('secret-modal-comment').value.trim();
  8522. const disabled = document.getElementById('secret-modal-disabled').checked;
  8523. try {
  8524. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`, {
  8525. method: 'POST',
  8526. headers: { 'Content-Type': 'application/json' },
  8527. body: JSON.stringify({
  8528. id,
  8529. name,
  8530. password,
  8531. service,
  8532. profile,
  8533. local_address: local,
  8534. remote_address: remote,
  8535. comment,
  8536. disabled
  8537. })
  8538. });
  8539. if (res.ok) {
  8540. showToast('Secret Saved', `User ${name} saved to PPP database`, 'success');
  8541. closePPPSecretModal();
  8542. loadPPPSecrets();
  8543. } else {
  8544. const err = await res.json();
  8545. showToast('Error', err.message, 'error');
  8546. }
  8547. } catch (err) {
  8548. showToast('Error', err.message, 'error');
  8549. }
  8550. }
  8551. async function togglePPPSecretState(id, disabled) {
  8552. try {
  8553. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}/state`, {
  8554. method: 'POST',
  8555. headers: { 'Content-Type': 'application/json' },
  8556. body: JSON.stringify({ disabled })
  8557. });
  8558. if (res.ok) {
  8559. showToast(disabled ? 'Disabled' : 'Enabled', 'Secret user state updated', 'info');
  8560. loadPPPSecrets();
  8561. }
  8562. } catch (err) {
  8563. showToast('Error', err.message, 'error');
  8564. }
  8565. }
  8566. async function deletePPPSecret(id) {
  8567. if (!confirm('Are you sure you want to delete this secret account?')) return;
  8568. try {
  8569. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8570. if (res.ok) {
  8571. showToast('Deleted', 'Secret account removed', 'success');
  8572. loadPPPSecrets();
  8573. }
  8574. } catch (err) {
  8575. showToast('Error', err.message, 'error');
  8576. }
  8577. }
  8578. // PPP Profile Modal handlers
  8579. function openAddPPPProfileModal() {
  8580. document.getElementById('profile-modal-name').value = '';
  8581. document.getElementById('profile-modal-local').value = '10.10.10.1';
  8582. document.getElementById('profile-modal-remote').value = '10.10.10.10-10.10.10.50';
  8583. document.getElementById('profile-modal-dns').value = '1.1.1.1,8.8.8.8';
  8584. document.getElementById('profile-modal-encryption').value = 'required';
  8585. document.getElementById('profile-modal-onlyone').checked = true;
  8586. document.getElementById('profile-modal-comment').value = '';
  8587. document.getElementById('ppp-profile-modal').classList.remove('hidden');
  8588. }
  8589. function closePPPProfileModal() {
  8590. document.getElementById('ppp-profile-modal').classList.add('hidden');
  8591. }
  8592. async function submitSavePPPProfile(e) {
  8593. e.preventDefault();
  8594. const name = document.getElementById('profile-modal-name').value.trim();
  8595. const local = document.getElementById('profile-modal-local').value.trim();
  8596. const remote = document.getElementById('profile-modal-remote').value.trim();
  8597. const dns = document.getElementById('profile-modal-dns').value.trim();
  8598. const enc = document.getElementById('profile-modal-encryption').value;
  8599. const onlyone = document.getElementById('profile-modal-onlyone').checked;
  8600. const comment = document.getElementById('profile-modal-comment').value.trim();
  8601. try {
  8602. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`, {
  8603. method: 'POST',
  8604. headers: { 'Content-Type': 'application/json' },
  8605. body: JSON.stringify({
  8606. id: name,
  8607. name,
  8608. local_address: local,
  8609. remote_address: remote,
  8610. dns_servers: dns,
  8611. use_encryption: enc,
  8612. only_one: onlyone,
  8613. comment
  8614. })
  8615. });
  8616. if (res.ok) {
  8617. showToast('Profile Saved', `PPP profile ${name} created`, 'success');
  8618. closePPPProfileModal();
  8619. loadPPPProfiles();
  8620. } else {
  8621. const err = await res.json();
  8622. showToast('Error', err.message, 'error');
  8623. }
  8624. } catch (err) {
  8625. showToast('Error', err.message, 'error');
  8626. }
  8627. }
  8628. async function deletePPPProfile(name) {
  8629. if (!confirm(`Delete PPP profile ${name}?`)) return;
  8630. try {
  8631. const res = await fetch(`${API_BASE}/vpn/ppp/profiles/${encodeURIComponent(name)}`, { method: 'DELETE' });
  8632. if (res.ok) {
  8633. showToast('Deleted', 'Profile removed', 'success');
  8634. loadPPPProfiles();
  8635. } else {
  8636. const err = await res.json();
  8637. showToast('Error', err.message, 'error');
  8638. }
  8639. } catch (err) {
  8640. showToast('Error', err.message, 'error');
  8641. }
  8642. }
  8643. // Server Config submissions
  8644. async function savePPPoEServerConfig(e) {
  8645. e.preventDefault();
  8646. const enabled = document.getElementById('pppoe-server-enabled').checked;
  8647. const name = document.getElementById('pppoe-server-name').value.trim();
  8648. const iface = document.getElementById('pppoe-server-iface').value;
  8649. const profile = document.getElementById('pppoe-server-profile').value;
  8650. const mtu = parseInt(document.getElementById('pppoe-server-mtu').value) || 1480;
  8651. const onesession = document.getElementById('pppoe-server-onesession').checked;
  8652. try {
  8653. const res = await fetch(`${API_BASE}/vpn/servers/pppoe`, {
  8654. method: 'POST',
  8655. headers: { 'Content-Type': 'application/json' },
  8656. body: JSON.stringify({
  8657. enabled,
  8658. service_name: name,
  8659. interface: iface,
  8660. default_profile: profile,
  8661. max_mtu: mtu,
  8662. max_mru: mtu,
  8663. one_session_per_host: onesession
  8664. })
  8665. });
  8666. if (res.ok) {
  8667. showToast('PPPoE Server', enabled ? 'PPPoE Server started' : 'PPPoE Server stopped', 'success');
  8668. loadPPPServers();
  8669. fetchData(false);
  8670. } else {
  8671. const err = await res.json();
  8672. showToast('Error', err.message, 'error');
  8673. }
  8674. } catch (err) {
  8675. showToast('Error', err.message, 'error');
  8676. }
  8677. }
  8678. async function savePPTPServerConfig(e) {
  8679. e.preventDefault();
  8680. const enabled = document.getElementById('pptp-server-enabled').checked;
  8681. const port = parseInt(document.getElementById('pptp-server-port').value) || 1723;
  8682. const profile = document.getElementById('pptp-server-profile').value;
  8683. const mppe = document.getElementById('pptp-server-mppe').checked;
  8684. try {
  8685. const res = await fetch(`${API_BASE}/vpn/servers/pptp`, {
  8686. method: 'POST',
  8687. headers: { 'Content-Type': 'application/json' },
  8688. body: JSON.stringify({
  8689. enabled,
  8690. port,
  8691. default_profile: profile,
  8692. require_mppe: mppe
  8693. })
  8694. });
  8695. if (res.ok) {
  8696. showToast('PPTP Server', enabled ? 'PPTP Server started' : 'PPTP Server stopped', 'success');
  8697. loadPPPServers();
  8698. fetchData(false);
  8699. } else {
  8700. const err = await res.json();
  8701. showToast('Error', err.message, 'error');
  8702. }
  8703. } catch (err) {
  8704. showToast('Error', err.message, 'error');
  8705. }
  8706. }
  8707. async function saveL2TPServerConfig(e) {
  8708. e.preventDefault();
  8709. const enabled = document.getElementById('l2tp-server-enabled').checked;
  8710. const port = parseInt(document.getElementById('l2tp-server-port').value) || 1701;
  8711. const profile = document.getElementById('l2tp-server-profile').value;
  8712. const useipsec = document.getElementById('l2tp-server-useipsec').value;
  8713. const psk = document.getElementById('l2tp-server-ipsecsecret').value.trim();
  8714. try {
  8715. const res = await fetch(`${API_BASE}/vpn/servers/l2tp`, {
  8716. method: 'POST',
  8717. headers: { 'Content-Type': 'application/json' },
  8718. body: JSON.stringify({
  8719. enabled,
  8720. port,
  8721. default_profile: profile,
  8722. use_ipsec: useipsec,
  8723. ipsec_secret: psk
  8724. })
  8725. });
  8726. if (res.ok) {
  8727. showToast('L2TP Server', enabled ? 'L2TP Server started' : 'L2TP Server stopped', 'success');
  8728. loadPPPServers();
  8729. fetchData(false);
  8730. } else {
  8731. const err = await res.json();
  8732. showToast('Error', err.message, 'error');
  8733. }
  8734. } catch (err) {
  8735. showToast('Error', err.message, 'error');
  8736. }
  8737. }
  8738. // IPSec Server Modal
  8739. function openIPSecServerModal() {
  8740. loadPPPServers();
  8741. document.getElementById('ipsec-server-modal').classList.remove('hidden');
  8742. }
  8743. function closeIPSecServerModal() {
  8744. document.getElementById('ipsec-server-modal').classList.add('hidden');
  8745. }
  8746. async function submitSaveIPSecServer(e) {
  8747. e.preventDefault();
  8748. const enabled = document.getElementById('modal-ipsec-server-enabled').checked;
  8749. const psk = document.getElementById('modal-ipsec-server-psk').value.trim();
  8750. const pool = document.getElementById('modal-ipsec-server-pool').value.trim();
  8751. const dns = document.getElementById('modal-ipsec-server-dns').value.trim();
  8752. const subnet = document.getElementById('modal-ipsec-server-subnet').value.trim();
  8753. try {
  8754. const res = await fetch(`${API_BASE}/vpn/servers/ipsec`, {
  8755. method: 'POST',
  8756. headers: { 'Content-Type': 'application/json' },
  8757. body: JSON.stringify({
  8758. enabled,
  8759. preshared_key: psk,
  8760. pool_address: pool,
  8761. dns_servers: dns,
  8762. local_subnet: subnet
  8763. })
  8764. });
  8765. if (res.ok) {
  8766. showToast('IPSec Server', enabled ? 'IKEv2 Roadwarrior responder active' : 'IPSec Server stopped', 'success');
  8767. closeIPSecServerModal();
  8768. loadPPPServers();
  8769. fetchData(false);
  8770. } else {
  8771. const err = await res.json();
  8772. showToast('Error', err.message, 'error');
  8773. }
  8774. } catch (err) {
  8775. showToast('Error', err.message, 'error');
  8776. }
  8777. }
  8778. // WireGuard Client Config Viewer
  8779. let currentWGClientConf = '';
  8780. async function openWGClientConfModal(iface, clientIP) {
  8781. try {
  8782. const res = await fetch(`${API_BASE}/vpn/wireguard/client-config`, {
  8783. method: 'POST',
  8784. headers: { 'Content-Type': 'application/json' },
  8785. body: JSON.stringify({
  8786. interface: iface,
  8787. address: clientIP || '10.10.0.2/32',
  8788. dns: '1.1.1.1, 8.8.8.8'
  8789. })
  8790. });
  8791. if (res.ok) {
  8792. const data = await res.json();
  8793. currentWGClientConf = data.config;
  8794. document.getElementById('wg-client-conf-text').value = currentWGClientConf;
  8795. document.getElementById('wg-client-conf-modal').classList.remove('hidden');
  8796. } else {
  8797. const err = await res.json();
  8798. showToast('Error', err.message, 'error');
  8799. }
  8800. } catch (err) {
  8801. showToast('Error', err.message, 'error');
  8802. }
  8803. }
  8804. function closeWGClientConfModal() {
  8805. document.getElementById('wg-client-conf-modal').classList.add('hidden');
  8806. }
  8807. function copyWGClientConf() {
  8808. if (!currentWGClientConf) return;
  8809. copyToClipboard(currentWGClientConf, 'WireGuard Client Profile');
  8810. }
  8811. function downloadWGClientConf() {
  8812. if (!currentWGClientConf) return;
  8813. const blob = new Blob([currentWGClientConf], { type: 'text/plain;charset=utf-8' });
  8814. const a = document.createElement('a');
  8815. a.href = URL.createObjectURL(blob);
  8816. a.download = 'wireguard-client.conf';
  8817. document.body.appendChild(a);
  8818. a.click();
  8819. document.body.removeChild(a);
  8820. showToast('Downloaded', 'wireguard-client.conf saved', 'success');
  8821. }
  8822. // =========================================================================
  8823. // DYNAMIC ROUTING (FRRouting BGP & OSPFv2)
  8824. // =========================================================================
  8825. state.activeDynSubTab = 'bgp-peers';
  8826. state.activeBgpSubTab = 'bgp-peers';
  8827. state.activeOspfTab = 'instances';
  8828. state.bgpInstance = null;
  8829. state.bgpPeers = [];
  8830. state.bgpNets = [];
  8831. state.bgpRoutes = [];
  8832. state.ospfInstance = null;
  8833. state.ospfInstances = [];
  8834. state.ospfAreas = [];
  8835. state.ospfAreaRanges = [];
  8836. state.ospfTemplates = [];
  8837. state.ospfLiveInterfaces = [];
  8838. state.ospfStaticNbrs = [];
  8839. state.ospfNeighbors = [];
  8840. state.ospfLSA = [];
  8841. state.ospfRoutes = [];
  8842. state.selectedOspfRow = {
  8843. instances: null,
  8844. areas: null,
  8845. 'area-ranges': null,
  8846. templates: null,
  8847. interfaces: null,
  8848. 'static-nbrs': null,
  8849. neighbors: null,
  8850. lsa: null,
  8851. };
  8852. state.ospfSort = {
  8853. instances: { col: 'name', asc: true },
  8854. areas: { col: 'name', asc: true },
  8855. ranges: { col: 'area', asc: true },
  8856. templates: { col: 'interfaces', asc: true },
  8857. live_ifaces: { col: 'interface', asc: true },
  8858. snbrs: { col: 'address', asc: true },
  8859. neighbors: { col: 'address', asc: true },
  8860. lsa: { col: 'instance', asc: true },
  8861. };
  8862. function switchBgpSubTab(subTab) {
  8863. state.activeBgpSubTab = subTab;
  8864. const tabs = ['bgp-peers', 'bgp-nets', 'bgp-routes'];
  8865. tabs.forEach(t => {
  8866. const el = document.getElementById(`dyn-subtab-${t}`);
  8867. const btn = document.getElementById(`bgp-subtab-btn-${t}`);
  8868. if (el) el.classList.toggle('hidden', t !== subTab);
  8869. if (btn) {
  8870. if (t === subTab) {
  8871. 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';
  8872. } else {
  8873. 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';
  8874. }
  8875. }
  8876. });
  8877. }
  8878. function switchOspfTab(tabName) {
  8879. state.activeOspfTab = tabName;
  8880. const tabs = ['instances', 'areas', 'area-ranges', 'templates', 'interfaces', 'static-nbrs', 'neighbors', 'lsa'];
  8881. tabs.forEach(t => {
  8882. const pane = document.getElementById(`ospf-pane-${t}`);
  8883. const btn = document.getElementById(`ospf-tab-btn-${t}`);
  8884. if (pane) pane.classList.toggle('hidden', t !== tabName);
  8885. if (btn) {
  8886. if (t === tabName) {
  8887. 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';
  8888. } else {
  8889. 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';
  8890. }
  8891. }
  8892. });
  8893. }
  8894. function switchOspfSubTab(tab) {
  8895. // Legacy alias
  8896. if (tab === 'ospf-ifaces') switchOspfTab('templates');
  8897. else if (tab === 'ospf-areas') switchOspfTab('areas');
  8898. else if (tab === 'ospf-nbrs') switchOspfTab('neighbors');
  8899. else switchOspfTab('instances');
  8900. }
  8901. function switchDynSubTab(subTab) {
  8902. if (subTab.startsWith('bgp')) {
  8903. if (state.activeTab !== 'bgp') navigate('bgp');
  8904. switchBgpSubTab(subTab);
  8905. } else if (subTab.startsWith('ospf')) {
  8906. if (state.activeTab !== 'ospf') navigate('ospf');
  8907. switchOspfTab('instances');
  8908. }
  8909. }
  8910. async function loadDynamicRouting(showToastMsg = false) {
  8911. try {
  8912. const fetchSafeJson = async (url) => {
  8913. try {
  8914. const r = await fetch(url);
  8915. return r.ok ? await r.json() : null;
  8916. } catch (e) {
  8917. return null;
  8918. }
  8919. };
  8920. const [
  8921. sum, bgpInst, bgpPeers, bgpNets, bgpRoutes,
  8922. ospfInsts, ospfAreas, ospfRanges, ospfTemplates, ospfLiveIfaces, ospfStaticNbrs, ospfNbrs, ospfLsa, filters,
  8923. commLists, asLists,
  8924. ripInsts, ripIfaces, ripNbrsLive, ripRoutes,
  8925. bfdInst, bfdIfaces, bfdPeers, bfdSessions,
  8926. babelInsts, babelIfaces, babelLiveIfaces, babelNbrs, babelRoutes,
  8927. radvInsts, radvIfaces
  8928. ] = await Promise.all([
  8929. fetchSafeJson(`${API_BASE}/routing/dynamic/summary`),
  8930. fetchSafeJson(`${API_BASE}/routing/bgp/instance`),
  8931. fetchSafeJson(`${API_BASE}/routing/bgp/peers`),
  8932. fetchSafeJson(`${API_BASE}/routing/bgp/networks`),
  8933. fetchSafeJson(`${API_BASE}/routing/bgp/routes`),
  8934. fetchSafeJson(`${API_BASE}/routing/ospf/instances`),
  8935. fetchSafeJson(`${API_BASE}/routing/ospf/areas`),
  8936. fetchSafeJson(`${API_BASE}/routing/ospf/area-ranges`),
  8937. fetchSafeJson(`${API_BASE}/routing/ospf/templates`),
  8938. fetchSafeJson(`${API_BASE}/routing/ospf/interfaces-live`),
  8939. fetchSafeJson(`${API_BASE}/routing/ospf/static-neighbors`),
  8940. fetchSafeJson(`${API_BASE}/routing/ospf/neighbors`),
  8941. fetchSafeJson(`${API_BASE}/routing/ospf/lsa`),
  8942. fetchSafeJson(`${API_BASE}/routing/filters`),
  8943. fetchSafeJson(`${API_BASE}/routing/filters/community-lists`),
  8944. fetchSafeJson(`${API_BASE}/routing/filters/as-lists`),
  8945. fetchSafeJson(`${API_BASE}/routing/rip/instances`),
  8946. fetchSafeJson(`${API_BASE}/routing/rip/interfaces`),
  8947. fetchSafeJson(`${API_BASE}/routing/rip/neighbors-live`),
  8948. fetchSafeJson(`${API_BASE}/routing/rip/routes`),
  8949. fetchSafeJson(`${API_BASE}/routing/bfd/instance`),
  8950. fetchSafeJson(`${API_BASE}/routing/bfd/interfaces`),
  8951. fetchSafeJson(`${API_BASE}/routing/bfd/peers`),
  8952. fetchSafeJson(`${API_BASE}/routing/bfd/sessions`),
  8953. fetchSafeJson(`${API_BASE}/routing/babel/instances`),
  8954. fetchSafeJson(`${API_BASE}/routing/babel/interfaces`),
  8955. fetchSafeJson(`${API_BASE}/routing/babel/interfaces-live`),
  8956. fetchSafeJson(`${API_BASE}/routing/babel/neighbors`),
  8957. fetchSafeJson(`${API_BASE}/routing/babel/routes`),
  8958. fetchSafeJson(`${API_BASE}/routing/radv/instances`),
  8959. fetchSafeJson(`${API_BASE}/routing/radv/interfaces`)
  8960. ]);
  8961. if (sum) state.dynSummary = sum;
  8962. if (bgpInst) state.bgpInstance = bgpInst;
  8963. if (bgpPeers) state.bgpPeers = bgpPeers;
  8964. if (bgpNets) state.bgpNets = bgpNets;
  8965. if (bgpRoutes) state.bgpRoutes = bgpRoutes;
  8966. if (ospfInsts) state.ospfInstances = ospfInsts;
  8967. if (ospfAreas) state.ospfAreas = ospfAreas;
  8968. if (ospfRanges) state.ospfAreaRanges = ospfRanges;
  8969. if (ospfTemplates) state.ospfTemplates = ospfTemplates;
  8970. if (ospfLiveIfaces) state.ospfLiveInterfaces = ospfLiveIfaces;
  8971. if (ospfStaticNbrs) state.ospfStaticNbrs = ospfStaticNbrs;
  8972. if (ospfNbrs) state.ospfNeighbors = ospfNbrs;
  8973. if (ospfLsa) state.ospfLSA = ospfLsa;
  8974. if (filters) state.routingFilters = filters;
  8975. if (commLists) state.routingCommunityLists = commLists;
  8976. if (asLists) state.routingASLists = asLists;
  8977. if (ripInsts) state.ripInstances = ripInsts;
  8978. if (ripIfaces) state.ripInterfaces = ripIfaces;
  8979. if (ripNbrsLive) state.ripNeighborsLive = ripNbrsLive;
  8980. if (ripRoutes) state.ripRoutes = ripRoutes;
  8981. if (bfdInst) state.bfdInstance = bfdInst;
  8982. if (bfdIfaces) state.bfdInterfaces = bfdIfaces;
  8983. if (bfdPeers) state.bfdNeighbors = bfdPeers;
  8984. if (bfdSessions) state.bfdSessions = bfdSessions;
  8985. if (babelInsts) state.babelInstances = babelInsts;
  8986. if (babelIfaces) state.babelInterfaces = babelIfaces;
  8987. if (babelLiveIfaces) state.babelInterfacesLive = babelLiveIfaces;
  8988. if (babelNbrs) state.babelNeighbors = babelNbrs;
  8989. if (babelRoutes) state.babelRoutes = babelRoutes;
  8990. if (radvInsts) state.radvInstances = radvInsts;
  8991. if (radvIfaces) state.radvInterfaces = radvIfaces;
  8992. try { renderBgpStatusPill(); } catch(e) { console.error('renderBgpStatusPill error:', e); }
  8993. try { renderBgpPeers(); } catch(e) { console.error('renderBgpPeers error:', e); }
  8994. try { renderBgpNetworks(); } catch(e) { console.error('renderBgpNetworks error:', e); }
  8995. try { renderBgpRoutes(); } catch(e) { console.error('renderBgpRoutes error:', e); }
  8996. try { renderOspfInstances(); } catch(e) { console.error('renderOspfInstances error:', e); }
  8997. try { renderOspfAreas(); } catch(e) { console.error('renderOspfAreas error:', e); }
  8998. try { renderOspfAreaRanges(); } catch(e) { console.error('renderOspfAreaRanges error:', e); }
  8999. try { renderOspfTemplates(); } catch(e) { console.error('renderOspfTemplates error:', e); }
  9000. try { renderOspfLiveInterfaces(); } catch(e) { console.error('renderOspfLiveInterfaces error:', e); }
  9001. try { renderOspfStaticNbrs(); } catch(e) { console.error('renderOspfStaticNbrs error:', e); }
  9002. try { renderOspfNeighbors(); } catch(e) { console.error('renderOspfNeighbors error:', e); }
  9003. try { renderOspfLSA(); } catch(e) { console.error('renderOspfLSA error:', e); }
  9004. try { renderRipInstances(); } catch(e) { console.error('renderRipInstances error:', e); }
  9005. try { renderRipInterfaces(); } catch(e) { console.error('renderRipInterfaces error:', e); }
  9006. try { renderRipNeighbors(); } catch(e) { console.error('renderRipNeighbors error:', e); }
  9007. try { renderRipRoutes(); } catch(e) { console.error('renderRipRoutes error:', e); }
  9008. try { renderBfdConfig(); } catch(e) { console.error('renderBfdConfig error:', e); }
  9009. try { renderBfdInterfaces(); } catch(e) { console.error('renderBfdInterfaces error:', e); }
  9010. try { renderBfdPeers(); } catch(e) { console.error('renderBfdPeers error:', e); }
  9011. try { renderBfdSessions(); } catch(e) { console.error('renderBfdSessions error:', e); }
  9012. try { renderBabelInstances(); } catch(e) { console.error('renderBabelInstances error:', e); }
  9013. try { renderBabelInterfaces(); } catch(e) { console.error('renderBabelInterfaces error:', e); }
  9014. try { renderBabelLiveInterfaces(); } catch(e) { console.error('renderBabelLiveInterfaces error:', e); }
  9015. try { renderBabelNeighbors(); } catch(e) { console.error('renderBabelNeighbors error:', e); }
  9016. try { renderBabelRoutes(); } catch(e) { console.error('renderBabelRoutes error:', e); }
  9017. try { renderRAdvInstances(); } catch(e) { console.error('renderRAdvInstances error:', e); }
  9018. try { renderRAdvInterfaces(); } catch(e) { console.error('renderRAdvInterfaces error:', e); }
  9019. try { renderRoutingFilters(); } catch(e) { console.error('renderRoutingFilters error:', e); }
  9020. try { updateBadges(); } catch(e) { console.error('updateBadges error:', e); }
  9021. if (showToastMsg) showToast('Refreshed', 'Dynamic routing telemetry updated', 'info');
  9022. } catch (err) {
  9023. console.error('Failed to load dynamic routing:', err);
  9024. if (showToastMsg) showToast('Notice', 'Unable to refresh dynamic routing telemetry', 'warning');
  9025. }
  9026. }
  9027. async function loadOspfAll() {
  9028. await loadDynamicRouting(true);
  9029. }
  9030. function renderBgpStatusPill() {
  9031. const pills = document.querySelectorAll('.bgp-live-status-pill');
  9032. pills.forEach(pill => {
  9033. const inst = state.bgpInstance;
  9034. if (!inst || !inst.enabled) {
  9035. 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';
  9036. pill.innerText = 'BGP DISABLED';
  9037. } else if (inst.running) {
  9038. 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';
  9039. pill.innerText = `BGP ACTIVE (AS ${inst.as})`;
  9040. } else {
  9041. 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';
  9042. pill.innerText = 'BGP STARTING...';
  9043. }
  9044. });
  9045. }
  9046. function renderBgpPeers() {
  9047. const tbody = document.getElementById('bgp-peers-table-body');
  9048. if (!tbody) return;
  9049. const empty = document.getElementById('bgp-peers-empty');
  9050. const countBadge = document.getElementById('bgp-peers-count-badge');
  9051. const navBadge = document.getElementById('dyn-badge-bgp-peers');
  9052. const peers = state.bgpPeers || [];
  9053. if (countBadge) countBadge.innerText = `${peers.length} Peers`;
  9054. if (navBadge) navBadge.innerText = peers.length;
  9055. if (peers.length === 0) {
  9056. tbody.innerHTML = '';
  9057. if (empty) empty.classList.remove('hidden');
  9058. return;
  9059. }
  9060. if (empty) empty.classList.add('hidden');
  9061. const sig = peers.map(p => `${p.name}:${p.state}:${p.uptime}:${p.prefix_received}:${p.prefix_sent}:${p.disabled}`).join(';');
  9062. if (tbody.dataset.sig === sig) return;
  9063. tbody.dataset.sig = sig;
  9064. tbody.innerHTML = peers.map(p => {
  9065. let flagA = !p.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  9066. let flagE = p.state === 'Established' ? '<span class="text-emerald-400 font-bold ml-1" title="Established">E</span>' : '';
  9067. let flagX = p.disabled ? '<span class="text-rose-400 font-bold ml-1" title="Disabled">X</span>' : '';
  9068. let stateBadge = '';
  9069. if (p.disabled) {
  9070. 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>';
  9071. } else if (p.state === 'Established') {
  9072. 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>';
  9073. } else if (p.state === 'Connect' || p.state === 'Active') {
  9074. 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>`;
  9075. } else {
  9076. 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>`;
  9077. }
  9078. return `
  9079. <tr class="hover:bg-slate-800/40 transition">
  9080. <td class="py-2.5 px-3 text-center tracking-wider">${flagA}${flagE}${flagX}</td>
  9081. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(p.name)}</td>
  9082. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(p.remote_address)}</td>
  9083. <td class="py-2.5 px-3">
  9084. <div class="font-bold text-slate-200">AS ${p.remote_as}</div>
  9085. ${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>`}
  9086. </td>
  9087. <td class="py-2.5 px-3">${stateBadge}</td>
  9088. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(p.uptime || '-')}</td>
  9089. <td class="py-2.5 px-3 text-slate-300">
  9090. <span class="text-emerald-400 font-bold">↓ ${p.prefix_received || 0}</span> /
  9091. <span class="text-blue-400 font-bold">↑ ${p.prefix_sent || 0}</span>
  9092. </td>
  9093. <td class="py-2.5 px-3 font-mono text-[11px] whitespace-nowrap">
  9094. ${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> ` : ''}
  9095. ${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>` : ''}
  9096. ${!p.in_filter && !p.out_filter ? '<span class="text-slate-600">-</span>' : ''}
  9097. </td>
  9098. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(p.comment || '')}</td>
  9099. <td class="py-2.5 px-3 text-right space-x-1.5 whitespace-nowrap font-sans">
  9100. <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'}">
  9101. ${p.disabled ? 'Enable' : 'Disable'}
  9102. </button>
  9103. <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">
  9104. Edit
  9105. </button>
  9106. <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">
  9107. Delete
  9108. </button>
  9109. </td>
  9110. </tr>
  9111. `;
  9112. }).join('');
  9113. }
  9114. function renderBgpNetworks() {
  9115. const tbody = document.getElementById('bgp-nets-table-body');
  9116. if (!tbody) return;
  9117. const empty = document.getElementById('bgp-nets-empty');
  9118. const countBadge = document.getElementById('bgp-nets-count-badge');
  9119. const navBadge = document.getElementById('dyn-badge-bgp-nets');
  9120. const nets = state.bgpNets || [];
  9121. if (countBadge) countBadge.innerText = `${nets.length} Networks`;
  9122. if (navBadge) navBadge.innerText = nets.length;
  9123. if (nets.length === 0) {
  9124. tbody.innerHTML = '';
  9125. if (empty) empty.classList.remove('hidden');
  9126. return;
  9127. }
  9128. if (empty) empty.classList.add('hidden');
  9129. const sig = nets.map(n => `${n.network}:${n.disabled}:${n.comment}`).join(';');
  9130. if (tbody.dataset.sig === sig) return;
  9131. tbody.dataset.sig = sig;
  9132. tbody.innerHTML = nets.map(n => `
  9133. <tr class="hover:bg-slate-800/40 transition">
  9134. <td class="py-2.5 px-3 font-semibold text-purple-300 font-mono">${escapeHtml(n.network)}</td>
  9135. <td class="py-2.5 px-3">
  9136. ${n.disabled
  9137. ? '<span class="px-2 py-0.5 rounded-full text-[10px] bg-slate-800 text-slate-400 border border-slate-700">Disabled</span>'
  9138. : '<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>'}
  9139. </td>
  9140. <td class="py-2.5 px-3">
  9141. ${n.disabled
  9142. ? '<span class="text-slate-600 font-mono text-[10px]">-</span>'
  9143. : '<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>'}
  9144. </td>
  9145. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(n.comment || '')}</td>
  9146. <td class="py-2.5 px-3 text-right space-x-1 font-sans">
  9147. <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">
  9148. Delete
  9149. </button>
  9150. </td>
  9151. </tr>
  9152. `).join('');
  9153. }
  9154. function renderBgpRoutes() {
  9155. const tbody = document.getElementById('bgp-routes-table-body');
  9156. if (!tbody) return;
  9157. const empty = document.getElementById('bgp-routes-empty');
  9158. const countBadge = document.getElementById('bgp-routes-count-badge');
  9159. const navBadge = document.getElementById('dyn-badge-bgp-routes');
  9160. const routes = state.bgpRoutes || [];
  9161. if (countBadge) countBadge.innerText = `${routes.length} Routes`;
  9162. if (navBadge) navBadge.innerText = routes.length;
  9163. if (routes.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 = routes.map(r => `${r.prefix}:${r.next_hop}:${r.metric}:${r.path}`).join(';');
  9170. if (tbody.dataset.sig === sig) return;
  9171. tbody.dataset.sig = sig;
  9172. tbody.innerHTML = routes.map(r => `
  9173. <tr class="hover:bg-slate-800/40 transition">
  9174. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.prefix)}</td>
  9175. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(r.next_hop || '-')}</td>
  9176. <td class="py-2.5 px-3 text-slate-300">${r.metric}</td>
  9177. <td class="py-2.5 px-3 text-slate-300">${r.weight}</td>
  9178. <td class="py-2.5 px-3 text-amber-300">${escapeHtml(r.path || 'i')}</td>
  9179. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.origin || 'IGP')}</td>
  9180. </tr>
  9181. `).join('');
  9182. }
  9183. // =========================================================================
  9184. // DEBTIK v7 OSPF TABLE RENDERING & SORTING
  9185. // =========================================================================
  9186. function sortOspfTable(tab, col) {
  9187. if (!state.ospfSort) state.ospfSort = {};
  9188. if (!state.ospfSort[tab]) state.ospfSort[tab] = { col: col, asc: true };
  9189. if (state.ospfSort[tab].col === col) {
  9190. state.ospfSort[tab].asc = !state.ospfSort[tab].asc;
  9191. } else {
  9192. state.ospfSort[tab].col = col;
  9193. state.ospfSort[tab].asc = true;
  9194. }
  9195. const asc = state.ospfSort[tab].asc;
  9196. let list = [];
  9197. if (tab === 'instances') list = state.ospfInstances || [];
  9198. else if (tab === 'areas') list = state.ospfAreas || [];
  9199. else if (tab === 'ranges') list = state.ospfAreaRanges || [];
  9200. else if (tab === 'templates') list = state.ospfTemplates || [];
  9201. else if (tab === 'live_ifaces') list = state.ospfLiveInterfaces || [];
  9202. else if (tab === 'snbrs') list = state.ospfStaticNbrs || [];
  9203. else if (tab === 'neighbors') list = state.ospfNeighbors || [];
  9204. else if (tab === 'lsa') list = state.ospfLSA || [];
  9205. list.sort((a, b) => {
  9206. let valA = a[col] ?? '';
  9207. let valB = b[col] ?? '';
  9208. if (typeof valA === 'number' && typeof valB === 'number') {
  9209. return asc ? valA - valB : valB - valA;
  9210. }
  9211. return asc ? String(valA).localeCompare(String(valB)) : String(valB).localeCompare(String(valA));
  9212. });
  9213. if (tab === 'instances') renderOspfInstances();
  9214. else if (tab === 'areas') renderOspfAreas();
  9215. else if (tab === 'ranges') renderOspfAreaRanges();
  9216. else if (tab === 'templates') renderOspfTemplates();
  9217. else if (tab === 'live_ifaces') renderOspfLiveInterfaces();
  9218. else if (tab === 'snbrs') renderOspfStaticNbrs();
  9219. else if (tab === 'neighbors') renderOspfNeighbors();
  9220. else if (tab === 'lsa') renderOspfLSA();
  9221. }
  9222. function selectOspfRow(tab, id) {
  9223. if (!state.selectedOspfRow) state.selectedOspfRow = {};
  9224. state.selectedOspfRow[tab] = id;
  9225. if (tab === 'instances') {
  9226. renderOspfInstances();
  9227. const btnEn = document.getElementById('btn-ospf-inst-enable');
  9228. const btnDis = document.getElementById('btn-ospf-inst-disable');
  9229. const btnRem = document.getElementById('btn-ospf-inst-remove');
  9230. const btnCom = document.getElementById('btn-ospf-inst-comment');
  9231. if (btnEn) btnEn.disabled = false;
  9232. if (btnDis) btnDis.disabled = false;
  9233. if (btnRem) btnRem.disabled = false;
  9234. if (btnCom) btnCom.disabled = false;
  9235. } else if (tab === 'areas') {
  9236. renderOspfAreas();
  9237. const btnEn = document.getElementById('btn-ospf-area-enable');
  9238. const btnDis = document.getElementById('btn-ospf-area-disable');
  9239. const btnRem = document.getElementById('btn-ospf-area-remove');
  9240. const btnCom = document.getElementById('btn-ospf-area-comment');
  9241. if (btnEn) btnEn.disabled = false;
  9242. if (btnDis) btnDis.disabled = false;
  9243. if (btnRem) btnRem.disabled = false;
  9244. if (btnCom) btnCom.disabled = false;
  9245. } else if (tab === 'ranges') {
  9246. renderOspfAreaRanges();
  9247. const btnEn = document.getElementById('btn-ospf-range-enable');
  9248. const btnDis = document.getElementById('btn-ospf-range-disable');
  9249. const btnRem = document.getElementById('btn-ospf-range-remove');
  9250. const btnCom = document.getElementById('btn-ospf-range-comment');
  9251. if (btnEn) btnEn.disabled = false;
  9252. if (btnDis) btnDis.disabled = false;
  9253. if (btnRem) btnRem.disabled = false;
  9254. if (btnCom) btnCom.disabled = false;
  9255. } else if (tab === 'templates') {
  9256. renderOspfTemplates();
  9257. const btnEn = document.getElementById('btn-ospf-tmpl-enable');
  9258. const btnDis = document.getElementById('btn-ospf-tmpl-disable');
  9259. const btnRem = document.getElementById('btn-ospf-tmpl-remove');
  9260. const btnCom = document.getElementById('btn-ospf-tmpl-comment');
  9261. if (btnEn) btnEn.disabled = false;
  9262. if (btnDis) btnDis.disabled = false;
  9263. if (btnRem) btnRem.disabled = false;
  9264. if (btnCom) btnCom.disabled = false;
  9265. } else if (tab === 'snbrs') {
  9266. renderOspfStaticNbrs();
  9267. const btnEn = document.getElementById('btn-ospf-snbr-enable');
  9268. const btnDis = document.getElementById('btn-ospf-snbr-disable');
  9269. const btnRem = document.getElementById('btn-ospf-snbr-remove');
  9270. const btnCom = document.getElementById('btn-ospf-snbr-comment');
  9271. if (btnEn) btnEn.disabled = false;
  9272. if (btnDis) btnDis.disabled = false;
  9273. if (btnRem) btnRem.disabled = false;
  9274. if (btnCom) btnCom.disabled = false;
  9275. }
  9276. }
  9277. // TAB 1: INSTANCES
  9278. function renderOspfInstances() {
  9279. const tbody = document.getElementById('ospf-instances-table-body');
  9280. if (!tbody) return;
  9281. const countEl = document.getElementById('ospf-instances-footer-count');
  9282. const filter = (document.getElementById('filter-ospf-instances')?.value || '').toLowerCase();
  9283. let list = state.ospfInstances || [];
  9284. if (filter) {
  9285. list = list.filter(i => (i.name || '').toLowerCase().includes(filter) || (i.router_id || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  9286. }
  9287. if (countEl) countEl.innerText = list.length;
  9288. const selId = state.selectedOspfRow?.instances;
  9289. tbody.innerHTML = list.map((inst, idx) => {
  9290. const isSel = inst.id === selId;
  9291. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  9292. const flagD = inst.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  9293. const redist = [];
  9294. if (inst.redistribute_connected) redist.push('conn');
  9295. if (inst.redistribute_static) redist.push('static');
  9296. if (inst.redistribute_bgp) redist.push('bgp');
  9297. if (inst.redistribute_default || (inst.originate_default && inst.originate_default !== 'never')) {
  9298. redist.push('default');
  9299. }
  9300. const origDef = inst.originate_default || (inst.redistribute_default ? 'if-installed' : 'never');
  9301. const origBadge = origDef === 'always'
  9302. ? '<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>'
  9303. : (origDef === 'if-installed'
  9304. ? '<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>'
  9305. : '<span class="text-slate-500 text-[10px]">never</span>');
  9306. return `
  9307. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('instances', '${inst.id}')" ondblclick="openEditOspfInstanceModal('${inst.id}')">
  9308. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  9309. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🔀'}</td>
  9310. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(inst.comment || '')}</td>
  9311. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  9312. <span class="text-sky-400">↳</span> <span>${escapeHtml(inst.name || 'Default')}</span>
  9313. </td>
  9314. <td class="py-1.5 px-3">${inst.version || 2}</td>
  9315. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(inst.vrf || 'main')}</td>
  9316. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(inst.router_id || '192.168.131.56')}</td>
  9317. <td class="py-1.5 px-3 font-mono text-slate-300">${redist.join(', ') || '-'}</td>
  9318. <td class="py-1.5 px-3">${origBadge}</td>
  9319. </tr>
  9320. `;
  9321. }).join('');
  9322. }
  9323. // TAB 2: AREAS
  9324. function renderOspfAreas() {
  9325. const tbody = document.getElementById('ospf-areas-table-body');
  9326. if (!tbody) return;
  9327. const countEl = document.getElementById('ospf-areas-footer-count');
  9328. const filter = (document.getElementById('filter-ospf-areas')?.value || '').toLowerCase();
  9329. let list = state.ospfAreas || [];
  9330. if (filter) {
  9331. list = list.filter(a => (a.name || '').toLowerCase().includes(filter) || (a.area_id || '').toLowerCase().includes(filter) || (a.comment || '').toLowerCase().includes(filter));
  9332. }
  9333. if (countEl) countEl.innerText = list.length;
  9334. const selId = state.selectedOspfRow?.areas;
  9335. tbody.innerHTML = list.map((a, idx) => {
  9336. const isSel = a.id === selId;
  9337. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  9338. const flagD = a.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  9339. return `
  9340. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('areas', '${a.id}')" ondblclick="openEditOspfAreaModal('${a.id}')">
  9341. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  9342. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🌐'}</td>
  9343. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(a.comment || '')}</td>
  9344. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  9345. <span class="text-sky-400">↳</span> <span>${escapeHtml(a.name || 'Default')}</span>
  9346. </td>
  9347. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(a.instance || 'Default')}</td>
  9348. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(a.area_id || '0.0.0.0')}</td>
  9349. <td class="py-1.5 px-3 font-mono text-slate-400">${escapeHtml(a.area_type || 'default')}</td>
  9350. </tr>
  9351. `;
  9352. }).join('');
  9353. }
  9354. // TAB 3: AREA RANGES
  9355. function renderOspfAreaRanges() {
  9356. const tbody = document.getElementById('ospf-ranges-table-body');
  9357. if (!tbody) return;
  9358. const countEl = document.getElementById('ospf-ranges-footer-count');
  9359. const filter = (document.getElementById('filter-ospf-area-ranges')?.value || '').toLowerCase();
  9360. let list = state.ospfAreaRanges || [];
  9361. if (filter) {
  9362. list = list.filter(r => (r.prefix || '').toLowerCase().includes(filter) || (r.area || '').toLowerCase().includes(filter) || (r.comment || '').toLowerCase().includes(filter));
  9363. }
  9364. if (countEl) countEl.innerText = list.length;
  9365. const selId = state.selectedOspfRow?.['area-ranges'];
  9366. tbody.innerHTML = list.map((r, idx) => {
  9367. const isSel = r.id === selId;
  9368. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  9369. const flagD = r.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  9370. return `
  9371. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('ranges', '${r.id}')" ondblclick="openEditOspfAreaRangeModal('${r.id}')">
  9372. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  9373. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🏷'}</td>
  9374. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(r.comment || '')}</td>
  9375. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(r.area || 'Default')}</td>
  9376. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(r.prefix || '')}</td>
  9377. <td class="py-1.5 px-3">${r.cost || 1}</td>
  9378. <td class="py-1.5 px-3">${r.advertise !== false ? 'yes' : 'no'}</td>
  9379. </tr>
  9380. `;
  9381. }).join('');
  9382. }
  9383. // TAB 4: INTERFACE TEMPLATES
  9384. function renderOspfTemplates() {
  9385. const tbody = document.getElementById('ospf-templates-table-body');
  9386. if (!tbody) return;
  9387. const countEl = document.getElementById('ospf-templates-footer-count');
  9388. const filter = (document.getElementById('filter-ospf-templates')?.value || '').toLowerCase();
  9389. let list = state.ospfTemplates || [];
  9390. if (filter) {
  9391. list = list.filter(t => (t.interfaces || t.interface || '').toLowerCase().includes(filter) || (t.networks || t.network || '').toLowerCase().includes(filter) || (t.comment || '').toLowerCase().includes(filter));
  9392. }
  9393. if (countEl) countEl.innerText = list.length;
  9394. const selId = state.selectedOspfRow?.templates;
  9395. tbody.innerHTML = list.map((t, idx) => {
  9396. const isSel = t.id === selId;
  9397. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  9398. const ifaces = t.interfaces || t.interface || 'all';
  9399. const nets = t.networks || t.network || '';
  9400. const flagD = t.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  9401. return `
  9402. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('templates', '${t.id}')" ondblclick="openEditOspfTemplateModal('${t.id}')">
  9403. <td class="py-1.5 px-3 w-8 text-center text-slate-500 font-bold">${idx}</td>
  9404. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🔀'}</td>
  9405. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(t.comment || '')}</td>
  9406. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  9407. <span class="text-sky-400">↳</span> <span>${escapeHtml(ifaces)}</span>
  9408. </td>
  9409. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(t.area || 'Default')}</td>
  9410. <td class="py-1.5 px-3 font-mono text-sky-300">${escapeHtml(nets)}</td>
  9411. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(t.network_type || 'broadcast')}</td>
  9412. <td class="py-1.5 px-3">${t.cost || 1}</td>
  9413. <td class="py-1.5 px-3">${t.priority || 128}</td>
  9414. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(t.auth || t.auth_type || '')}</td>
  9415. </tr>
  9416. `;
  9417. }).join('');
  9418. }
  9419. // TAB 5: LIVE INTERFACES
  9420. function renderOspfLiveInterfaces() {
  9421. const tbody = document.getElementById('ospf-live-interfaces-table-body');
  9422. if (!tbody) return;
  9423. const countEl = document.getElementById('ospf-live-interfaces-footer-count');
  9424. const filter = (document.getElementById('filter-ospf-interfaces')?.value || '').toLowerCase();
  9425. let list = state.ospfLiveInterfaces || [];
  9426. if (filter) {
  9427. list = list.filter(i => (i.interface || '').toLowerCase().includes(filter) || (i.address || '').toLowerCase().includes(filter) || (i.state || '').toLowerCase().includes(filter));
  9428. }
  9429. if (countEl) countEl.innerText = list.length;
  9430. tbody.innerHTML = list.map(i => `
  9431. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  9432. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(i.flags || 'D')}</td>
  9433. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(i.interface || '')}</td>
  9434. <td class="py-1.5 px-3 font-mono text-sky-300 font-medium">${escapeHtml(i.address || '')}</td>
  9435. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(i.area || 'Default')}</td>
  9436. <td class="py-1.5 px-3 text-center text-slate-400">${i.instance_id || 0}</td>
  9437. <td class="py-1.5 px-3 font-mono text-amber-300 lowercase">${escapeHtml(i.state || 'waiting')}</td>
  9438. <td class="py-1.5 px-3">${i.cost || 1}</td>
  9439. <td class="py-1.5 px-3">${i.priority || 128}</td>
  9440. </tr>
  9441. `).join('');
  9442. }
  9443. // TAB 6: STATIC NEIGHBORS
  9444. function renderOspfStaticNbrs() {
  9445. const tbody = document.getElementById('ospf-snbrs-table-body');
  9446. if (!tbody) return;
  9447. const countEl = document.getElementById('ospf-snbrs-footer-count');
  9448. const filter = (document.getElementById('filter-ospf-static-nbrs')?.value || '').toLowerCase();
  9449. let list = state.ospfStaticNbrs || [];
  9450. if (filter) {
  9451. list = list.filter(n => (n.address || '').toLowerCase().includes(filter) || (n.area || '').toLowerCase().includes(filter) || (n.comment || '').toLowerCase().includes(filter));
  9452. }
  9453. if (countEl) countEl.innerText = list.length;
  9454. const selId = state.selectedOspfRow?.['static-nbrs'];
  9455. tbody.innerHTML = list.map((n, idx) => {
  9456. const isSel = n.id === selId;
  9457. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  9458. const flagD = n.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  9459. return `
  9460. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('snbrs', '${n.id}')" ondblclick="openEditOspfStaticNbrModal('${n.id}')">
  9461. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  9462. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '📡'}</td>
  9463. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(n.comment || '')}</td>
  9464. <td class="py-1.5 px-3 font-semibold font-mono text-sky-300">${escapeHtml(n.address || '')}</td>
  9465. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(n.area || 'Default')}</td>
  9466. <td class="py-1.5 px-3">${n.poll_interval || 120}s</td>
  9467. <td class="py-1.5 px-3">${n.cost || 1}</td>
  9468. </tr>
  9469. `;
  9470. }).join('');
  9471. }
  9472. // TAB 7: LIVE NEIGHBORS
  9473. function renderOspfNeighbors() {
  9474. const tbody = document.getElementById('ospf-neighbors-table-body');
  9475. if (!tbody) return;
  9476. const countEl = document.getElementById('ospf-neighbors-footer-count');
  9477. const filter = (document.getElementById('filter-ospf-neighbors')?.value || '').toLowerCase();
  9478. let list = state.ospfNeighbors || [];
  9479. if (filter) {
  9480. list = list.filter(n => (n.address || '').toLowerCase().includes(filter) || (n.state || '').toLowerCase().includes(filter) || (n.instance || '').toLowerCase().includes(filter));
  9481. }
  9482. if (countEl) countEl.innerText = list.length;
  9483. tbody.innerHTML = list.map(n => `
  9484. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  9485. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(n.flags || 'D')}</td>
  9486. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(n.comment || '')}</td>
  9487. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  9488. <span class="text-sky-400">↳</span> <span>${escapeHtml(n.instance || 'Default')}</span>
  9489. </td>
  9490. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(n.area || 'Default')}</td>
  9491. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(n.address || '')}</td>
  9492. <td class="py-1.5 px-3 font-mono font-bold text-emerald-400">${escapeHtml(n.state || 'Full')}</td>
  9493. <td class="py-1.5 px-3 text-slate-400">${n.state_changes ?? 6}</td>
  9494. </tr>
  9495. `).join('');
  9496. }
  9497. // TAB 8: LINK-STATE DATABASE (LSA)
  9498. function renderOspfLSA() {
  9499. const tbody = document.getElementById('ospf-lsa-table-body');
  9500. if (!tbody) return;
  9501. const countEl = document.getElementById('ospf-lsa-footer-count');
  9502. const filter = (document.getElementById('filter-ospf-lsa')?.value || '').toLowerCase();
  9503. let list = state.ospfLSA || [];
  9504. if (filter) {
  9505. list = list.filter(l => (l.type || '').toLowerCase().includes(filter) || (l.originator || '').toLowerCase().includes(filter) || (l.id || '').toLowerCase().includes(filter));
  9506. }
  9507. if (countEl) countEl.innerText = list.length;
  9508. tbody.innerHTML = list.map(l => `
  9509. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  9510. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(l.flags || 'D')}</td>
  9511. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  9512. <span class="text-sky-400">↳</span> <span>${escapeHtml(l.instance || 'Default')}</span>
  9513. </td>
  9514. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(l.area || 'Default')}</td>
  9515. <td class="py-1.5 px-3 font-mono text-amber-300">${escapeHtml(l.type || 'router')}</td>
  9516. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(l.originator || '')}</td>
  9517. <td class="py-1.5 px-3 font-mono text-sky-300 font-medium">${escapeHtml(l.id || '')}</td>
  9518. <td class="py-1.5 px-3 text-slate-500">${escapeHtml(l.link || '')}</td>
  9519. <td class="py-1.5 px-3 text-slate-500">${l.link_index ?? 0}</td>
  9520. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(l.sequence || '')}</td>
  9521. <td class="py-1.5 px-3 text-slate-400">${l.age ?? 0}</td>
  9522. </tr>
  9523. `).join('');
  9524. }
  9525. function renderOspfStatusPill() {
  9526. // Maintained for backward compatibility
  9527. const pill = document.getElementById('ospf-live-status-pill');
  9528. if (!pill) return;
  9529. 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';
  9530. pill.innerText = 'OSPF ACTIVE';
  9531. }
  9532. function renderOspfInterfaces() {
  9533. renderOspfTemplates();
  9534. }
  9535. function renderOspfRoutes() {
  9536. // Routes retained in background
  9537. }
  9538. // BGP Modals & Actions
  9539. function openBgpInstanceModal() {
  9540. const inst = state.bgpInstance || { enabled: false, as: 65001, router_id: '192.168.131.56', hold_time: 180, keepalive_time: 60 };
  9541. document.getElementById('modal-bgp-enabled').checked = !!inst.enabled;
  9542. document.getElementById('modal-bgp-as').value = inst.as || 65001;
  9543. document.getElementById('modal-bgp-router-id').value = inst.router_id || '';
  9544. document.getElementById('modal-bgp-keepalive').value = inst.keepalive_time || 60;
  9545. document.getElementById('modal-bgp-holdtime').value = inst.hold_time || 180;
  9546. document.getElementById('modal-bgp-redist-conn').checked = !!inst.redistribute_connected;
  9547. document.getElementById('modal-bgp-redist-static').checked = !!inst.redistribute_static;
  9548. document.getElementById('modal-bgp-redist-ospf').checked = !!inst.redistribute_ospf;
  9549. document.getElementById('bgp-instance-modal').classList.remove('hidden');
  9550. }
  9551. function closeBgpInstanceModal() {
  9552. document.getElementById('bgp-instance-modal').classList.add('hidden');
  9553. }
  9554. async function submitBgpInstance(e) {
  9555. e.preventDefault();
  9556. const payload = {
  9557. enabled: document.getElementById('modal-bgp-enabled').checked,
  9558. as: parseInt(document.getElementById('modal-bgp-as').value, 10),
  9559. router_id: document.getElementById('modal-bgp-router-id').value.trim(),
  9560. keepalive_time: parseInt(document.getElementById('modal-bgp-keepalive').value, 10),
  9561. hold_time: parseInt(document.getElementById('modal-bgp-holdtime').value, 10),
  9562. redistribute_connected: document.getElementById('modal-bgp-redist-conn').checked,
  9563. redistribute_static: document.getElementById('modal-bgp-redist-static').checked,
  9564. redistribute_ospf: document.getElementById('modal-bgp-redist-ospf').checked
  9565. };
  9566. try {
  9567. const res = await fetch(`${API_BASE}/routing/bgp/instance`, {
  9568. method: 'POST',
  9569. headers: { 'Content-Type': 'application/json' },
  9570. body: JSON.stringify(payload)
  9571. });
  9572. if (res.ok) {
  9573. closeBgpInstanceModal();
  9574. showToast('Success', 'BGP instance configuration updated', 'success');
  9575. loadDynamicRouting();
  9576. } else {
  9577. const err = await res.json();
  9578. showToast('Error', err.error || 'Failed to update BGP instance', 'error');
  9579. }
  9580. } catch (err) {
  9581. showToast('Error', err.message, 'error');
  9582. }
  9583. }
  9584. // ----------------- BGP Peer Connection Modal (DebTik v7) -----------------
  9585. function switchBgpPeerModalTab(tab) {
  9586. // Normalize legacy tab names
  9587. if (tab === 'extra' || tab === 'filter') tab = 'filters';
  9588. if (tab === 'attributes') tab = 'networks';
  9589. const tabs = ['general', 'filters', 'networks'];
  9590. tabs.forEach(t => {
  9591. const pane = document.getElementById(`bgp-peer-tab-${t}`);
  9592. const btn = document.getElementById(`bgp-peer-tab-btn-${t}`);
  9593. if (t === tab) {
  9594. if (pane) pane.classList.remove('hidden');
  9595. if (btn) btn.className = 'px-4 py-2 text-xs font-bold border-b-2 border-cyan-500 text-white transition';
  9596. } else {
  9597. if (pane) pane.classList.add('hidden');
  9598. 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';
  9599. }
  9600. });
  9601. }
  9602. function addOutputNetworkRow(val = '') {
  9603. const container = document.getElementById('modal-bgp-output-networks-container');
  9604. if (!container) return;
  9605. const row = document.createElement('div');
  9606. row.className = 'flex items-center gap-2 output-net-row';
  9607. row.innerHTML = `
  9608. <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">
  9609. <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>
  9610. `;
  9611. container.appendChild(row);
  9612. }
  9613. function parseBgpTime(val) {
  9614. if (!val) return 0;
  9615. val = String(val).trim();
  9616. if (val.includes(':')) {
  9617. const parts = val.split(':').map(x => parseInt(x, 10) || 0);
  9618. if (parts.length === 3) return parts[0] * 3600 + parts[1] * 60 + parts[2];
  9619. if (parts.length === 2) return parts[0] * 60 + parts[1];
  9620. }
  9621. return parseInt(val, 10) || 0;
  9622. }
  9623. function formatBgpTime(secs) {
  9624. if (!secs || secs <= 0) return '30';
  9625. return String(secs);
  9626. }
  9627. function populateBgpRoutingTables() {
  9628. const sel = document.getElementById('modal-bgp-peer-routing-table');
  9629. if (!sel) return;
  9630. const cur = sel.value || 'main';
  9631. sel.innerHTML = '<option value="main">main</option>';
  9632. (state.routingTables || []).forEach(t => {
  9633. if (t.name !== 'main') {
  9634. const opt = document.createElement('option');
  9635. opt.value = t.name;
  9636. opt.innerText = t.name;
  9637. sel.appendChild(opt);
  9638. }
  9639. });
  9640. sel.value = cur;
  9641. }
  9642. function openAddBgpPeerModal() {
  9643. document.getElementById('bgp-peer-form').reset();
  9644. document.getElementById('modal-bgp-peer-id').value = '';
  9645. document.getElementById('bgp-peer-modal-title').innerText = 'New BGP Connection...';
  9646. // General Tab
  9647. document.getElementById('modal-bgp-peer-enabled').checked = true;
  9648. document.getElementById('modal-bgp-peer-name').value = '';
  9649. document.getElementById('modal-bgp-peer-comment').value = '';
  9650. if (document.getElementById('modal-bgp-peer-local-as')) document.getElementById('modal-bgp-peer-local-as').value = '';
  9651. if (document.getElementById('modal-bgp-peer-remote-addr')) document.getElementById('modal-bgp-peer-remote-addr').value = '';
  9652. if (document.getElementById('modal-bgp-peer-remote-port')) document.getElementById('modal-bgp-peer-remote-port').value = '';
  9653. if (document.getElementById('modal-bgp-peer-remote-as')) document.getElementById('modal-bgp-peer-remote-as').value = '';
  9654. if (document.getElementById('modal-bgp-peer-local-addr')) document.getElementById('modal-bgp-peer-local-addr').value = '';
  9655. if (document.getElementById('modal-bgp-peer-local-port')) document.getElementById('modal-bgp-peer-local-port').value = '';
  9656. if (document.getElementById('modal-bgp-peer-local-role')) document.getElementById('modal-bgp-peer-local-role').value = 'ebgp';
  9657. if (document.getElementById('modal-bgp-peer-password')) document.getElementById('modal-bgp-peer-password').value = '';
  9658. if (document.getElementById('modal-bgp-peer-multihop')) document.getElementById('modal-bgp-peer-multihop').checked = false;
  9659. if (document.getElementById('modal-bgp-peer-passive')) document.getElementById('modal-bgp-peer-passive').checked = false;
  9660. if (document.getElementById('modal-bgp-peer-nexthop-self')) document.getElementById('modal-bgp-peer-nexthop-self').checked = false;
  9661. if (document.getElementById('modal-bgp-peer-holdtime')) document.getElementById('modal-bgp-peer-holdtime').value = '30';
  9662. if (document.getElementById('modal-bgp-peer-keepalive')) document.getElementById('modal-bgp-peer-keepalive').value = '10';
  9663. // Filters Tab
  9664. populateFilterChainsDatalist();
  9665. if (document.getElementById('modal-bgp-peer-in-filter')) document.getElementById('modal-bgp-peer-in-filter').value = '';
  9666. if (document.getElementById('modal-bgp-peer-out-filter')) document.getElementById('modal-bgp-peer-out-filter').value = '';
  9667. if (document.getElementById('modal-bgp-peer-redist-conn')) document.getElementById('modal-bgp-peer-redist-conn').checked = false;
  9668. if (document.getElementById('modal-bgp-peer-redist-static')) document.getElementById('modal-bgp-peer-redist-static').checked = true;
  9669. if (document.getElementById('modal-bgp-peer-redist-ospf')) document.getElementById('modal-bgp-peer-redist-ospf').checked = false;
  9670. if (document.getElementById('modal-bgp-peer-default-orig')) document.getElementById('modal-bgp-peer-default-orig').checked = false;
  9671. // Advertised Networks Tab
  9672. const container = document.getElementById('modal-bgp-output-networks-container');
  9673. if (container) {
  9674. container.innerHTML = '';
  9675. addOutputNetworkRow('');
  9676. }
  9677. const removeBtn = document.getElementById('modal-btn-remove-peer');
  9678. if (removeBtn) removeBtn.classList.add('hidden');
  9679. switchBgpPeerModalTab('general');
  9680. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  9681. }
  9682. function populateFilterChainsDatalist() {
  9683. const dl = document.getElementById('filter-chains-list');
  9684. if (!dl) return;
  9685. const chains = new Set();
  9686. (state.routingFilters || []).forEach(f => {
  9687. if (f.chain) chains.add(f.chain);
  9688. });
  9689. if (chains.size === 0) {
  9690. chains.add('awmn');
  9691. chains.add('Internal');
  9692. chains.add('bgp-in');
  9693. chains.add('bgp-out');
  9694. }
  9695. dl.innerHTML = '';
  9696. chains.forEach(c => {
  9697. const opt = document.createElement('option');
  9698. opt.value = c;
  9699. dl.appendChild(opt);
  9700. });
  9701. }
  9702. function openEditBgpPeerModal(id) {
  9703. const p = (state.bgpPeers || []).find(item => item.id === id);
  9704. if (!p) return;
  9705. populateFilterChainsDatalist();
  9706. document.getElementById('modal-bgp-peer-id').value = p.id;
  9707. document.getElementById('bgp-peer-modal-title').innerText = p.name || p.id;
  9708. // General Tab
  9709. document.getElementById('modal-bgp-peer-enabled').checked = p.enabled !== false && !p.disabled;
  9710. document.getElementById('modal-bgp-peer-name').value = p.name || '';
  9711. document.getElementById('modal-bgp-peer-comment').value = p.comment || '';
  9712. if (document.getElementById('modal-bgp-peer-local-as')) document.getElementById('modal-bgp-peer-local-as').value = p.local_as || '';
  9713. if (document.getElementById('modal-bgp-peer-remote-addr')) document.getElementById('modal-bgp-peer-remote-addr').value = p.remote_address || '';
  9714. if (document.getElementById('modal-bgp-peer-remote-port')) document.getElementById('modal-bgp-peer-remote-port').value = p.remote_port || '';
  9715. if (document.getElementById('modal-bgp-peer-remote-as')) document.getElementById('modal-bgp-peer-remote-as').value = p.remote_as || '';
  9716. if (document.getElementById('modal-bgp-peer-local-addr')) document.getElementById('modal-bgp-peer-local-addr').value = p.local_address || '';
  9717. if (document.getElementById('modal-bgp-peer-local-port')) document.getElementById('modal-bgp-peer-local-port').value = p.local_port || '';
  9718. if (document.getElementById('modal-bgp-peer-local-role')) document.getElementById('modal-bgp-peer-local-role').value = p.local_role || 'ebgp';
  9719. if (document.getElementById('modal-bgp-peer-password')) document.getElementById('modal-bgp-peer-password').value = p.password || '';
  9720. if (document.getElementById('modal-bgp-peer-multihop')) document.getElementById('modal-bgp-peer-multihop').checked = !!p.multihop;
  9721. // Passive mode
  9722. const isPassive = !!p.passive || (p.connect === false && p.listen !== false);
  9723. if (document.getElementById('modal-bgp-peer-passive')) document.getElementById('modal-bgp-peer-passive').checked = isPassive;
  9724. // Next-hop self
  9725. const isNexthopSelf = !!p.nexthop_self || p.nexthop_choice === 'force-self';
  9726. if (document.getElementById('modal-bgp-peer-nexthop-self')) document.getElementById('modal-bgp-peer-nexthop-self').checked = isNexthopSelf;
  9727. if (document.getElementById('modal-bgp-peer-holdtime')) document.getElementById('modal-bgp-peer-holdtime').value = p.hold_time ? String(p.hold_time) : '30';
  9728. if (document.getElementById('modal-bgp-peer-keepalive')) document.getElementById('modal-bgp-peer-keepalive').value = p.keepalive_time ? String(p.keepalive_time) : '10';
  9729. // Filters Tab
  9730. if (document.getElementById('modal-bgp-peer-in-filter')) document.getElementById('modal-bgp-peer-in-filter').value = p.in_filter || '';
  9731. if (document.getElementById('modal-bgp-peer-out-filter')) document.getElementById('modal-bgp-peer-out-filter').value = p.out_filter || '';
  9732. if (document.getElementById('modal-bgp-peer-redist-conn')) document.getElementById('modal-bgp-peer-redist-conn').checked = !!p.redist_connected;
  9733. if (document.getElementById('modal-bgp-peer-redist-static')) document.getElementById('modal-bgp-peer-redist-static').checked = p.redist_static !== false;
  9734. if (document.getElementById('modal-bgp-peer-redist-ospf')) document.getElementById('modal-bgp-peer-redist-ospf').checked = !!p.redist_ospf;
  9735. if (document.getElementById('modal-bgp-peer-default-orig')) document.getElementById('modal-bgp-peer-default-orig').checked = !!p.default_originate;
  9736. // Advertised Networks Tab
  9737. const container = document.getElementById('modal-bgp-output-networks-container');
  9738. if (container) {
  9739. container.innerHTML = '';
  9740. if (p.output_networks && p.output_networks.length > 0) {
  9741. p.output_networks.forEach(net => addOutputNetworkRow(net));
  9742. } else {
  9743. addOutputNetworkRow('');
  9744. }
  9745. }
  9746. const removeBtn = document.getElementById('modal-btn-remove-peer');
  9747. if (removeBtn) removeBtn.classList.remove('hidden');
  9748. switchBgpPeerModalTab('general');
  9749. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  9750. }
  9751. function copyCurrentBgpPeer() {
  9752. document.getElementById('modal-bgp-peer-id').value = '';
  9753. const nameEl = document.getElementById('modal-bgp-peer-name');
  9754. if (nameEl) nameEl.value = (nameEl.value || 'peer') + '-copy';
  9755. document.getElementById('bgp-peer-modal-title').innerText = 'New BGP Connection...';
  9756. const removeBtn = document.getElementById('modal-btn-remove-peer');
  9757. if (removeBtn) removeBtn.classList.add('hidden');
  9758. showToast('Cloned', 'BGP connection copied to new draft', 'info');
  9759. }
  9760. function removeCurrentBgpPeer() {
  9761. const id = document.getElementById('modal-bgp-peer-id')?.value;
  9762. if (!id) return;
  9763. deleteBgpPeer(id);
  9764. closeBgpPeerModal();
  9765. }
  9766. function closeBgpPeerModal() {
  9767. document.getElementById('bgp-peer-modal').classList.add('hidden');
  9768. }
  9769. function getBgpPeerFormData() {
  9770. const netInputs = document.querySelectorAll('#modal-bgp-output-networks-container .output-net-row input');
  9771. const outputNetworks = [];
  9772. netInputs.forEach(inp => {
  9773. const v = inp.value.trim();
  9774. if (v) outputNetworks.push(v);
  9775. });
  9776. const enabled = document.getElementById('modal-bgp-peer-enabled').checked;
  9777. const isPassive = document.getElementById('modal-bgp-peer-passive')?.checked || false;
  9778. const isNexthopSelf = document.getElementById('modal-bgp-peer-nexthop-self')?.checked || false;
  9779. return {
  9780. id: document.getElementById('modal-bgp-peer-id').value,
  9781. name: document.getElementById('modal-bgp-peer-name').value.trim(),
  9782. enabled: enabled,
  9783. disabled: !enabled,
  9784. comment: document.getElementById('modal-bgp-peer-comment').value.trim(),
  9785. local_as: parseInt(document.getElementById('modal-bgp-peer-local-as')?.value, 10) || 0,
  9786. remote_address: document.getElementById('modal-bgp-peer-remote-addr').value.trim(),
  9787. remote_port: parseInt(document.getElementById('modal-bgp-peer-remote-port').value, 10) || 0,
  9788. remote_as: parseInt(document.getElementById('modal-bgp-peer-remote-as').value, 10) || 0,
  9789. local_address: document.getElementById('modal-bgp-peer-local-addr')?.value.trim() || '',
  9790. local_port: parseInt(document.getElementById('modal-bgp-peer-local-port')?.value, 10) || 0,
  9791. local_role: document.getElementById('modal-bgp-peer-local-role')?.value || 'ebgp',
  9792. password: document.getElementById('modal-bgp-peer-password')?.value || '',
  9793. multihop: document.getElementById('modal-bgp-peer-multihop')?.checked || false,
  9794. passive: isPassive,
  9795. connect: !isPassive,
  9796. listen: true,
  9797. hold_time: parseBgpTime(document.getElementById('modal-bgp-peer-holdtime')?.value),
  9798. keepalive_time: parseBgpTime(document.getElementById('modal-bgp-peer-keepalive')?.value),
  9799. nexthop_self: isNexthopSelf,
  9800. nexthop_choice: isNexthopSelf ? 'force-self' : 'default',
  9801. in_filter: (document.getElementById('modal-bgp-peer-in-filter')?.value || '').trim(),
  9802. out_filter: (document.getElementById('modal-bgp-peer-out-filter')?.value || '').trim(),
  9803. default_originate: document.getElementById('modal-bgp-peer-default-orig')?.checked || false,
  9804. redist_connected: document.getElementById('modal-bgp-peer-redist-conn')?.checked || false,
  9805. redist_static: document.getElementById('modal-bgp-peer-redist-static')?.checked !== false,
  9806. redist_ospf: document.getElementById('modal-bgp-peer-redist-ospf')?.checked || false,
  9807. output_networks: outputNetworks
  9808. };
  9809. }
  9810. async function submitBgpPeer(e) {
  9811. if (e) e.preventDefault();
  9812. const payload = getBgpPeerFormData();
  9813. try {
  9814. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  9815. method: 'POST',
  9816. headers: { 'Content-Type': 'application/json' },
  9817. body: JSON.stringify(payload)
  9818. });
  9819. if (res.ok) {
  9820. closeBgpPeerModal();
  9821. showToast('Success', 'BGP Connection saved', 'success');
  9822. loadDynamicRouting();
  9823. } else {
  9824. const err = await res.json();
  9825. showToast('Error', err.error || 'Failed to save peer', 'error');
  9826. }
  9827. } catch (err) {
  9828. showToast('Error', err.message, 'error');
  9829. }
  9830. }
  9831. async function applyBgpPeerModal(e) {
  9832. if (e) e.preventDefault();
  9833. const payload = getBgpPeerFormData();
  9834. try {
  9835. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  9836. method: 'POST',
  9837. headers: { 'Content-Type': 'application/json' },
  9838. body: JSON.stringify(payload)
  9839. });
  9840. if (res.ok) {
  9841. const data = await res.json();
  9842. if (data.peer && data.peer.id) {
  9843. document.getElementById('modal-bgp-peer-id').value = data.peer.id;
  9844. document.getElementById('bgp-peer-modal-title').innerText = data.peer.name || data.peer.id;
  9845. document.getElementById('modal-btn-remove-peer')?.classList.remove('hidden');
  9846. }
  9847. showToast('Applied', 'BGP Connection applied', 'success');
  9848. loadDynamicRouting();
  9849. } else {
  9850. const err = await res.json();
  9851. showToast('Error', err.error || 'Failed to apply peer', 'error');
  9852. }
  9853. } catch (err) {
  9854. showToast('Error', err.message, 'error');
  9855. }
  9856. }
  9857. async function deleteBgpPeer(id) {
  9858. if (!confirm('Are you sure you want to delete this BGP peer connection?')) return;
  9859. try {
  9860. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9861. if (res.ok) {
  9862. showToast('Deleted', 'BGP peer removed', 'success');
  9863. loadDynamicRouting();
  9864. }
  9865. } catch (err) {
  9866. showToast('Error', err.message, 'error');
  9867. }
  9868. }
  9869. async function toggleBgpPeerState(id, disabled) {
  9870. try {
  9871. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}/state`, {
  9872. method: 'POST',
  9873. headers: { 'Content-Type': 'application/json' },
  9874. body: JSON.stringify({ disabled })
  9875. });
  9876. if (res.ok) {
  9877. showToast('Updated', `Peer ${disabled ? 'disabled' : 'enabled'}`, 'success');
  9878. loadDynamicRouting();
  9879. }
  9880. } catch (err) {
  9881. showToast('Error', err.message, 'error');
  9882. }
  9883. }
  9884. function openAddBgpNetworkModal() {
  9885. document.getElementById('bgp-network-form').reset();
  9886. document.getElementById('modal-bgp-net-id').value = '';
  9887. document.getElementById('bgp-network-modal').classList.remove('hidden');
  9888. }
  9889. function closeBgpNetworkModal() {
  9890. document.getElementById('bgp-network-modal').classList.add('hidden');
  9891. }
  9892. async function submitBgpNetwork(e) {
  9893. e.preventDefault();
  9894. const payload = {
  9895. id: document.getElementById('modal-bgp-net-id').value,
  9896. network: document.getElementById('modal-bgp-net-cidr').value.trim(),
  9897. comment: document.getElementById('modal-bgp-net-comment').value.trim(),
  9898. disabled: document.getElementById('modal-bgp-net-disabled').checked
  9899. };
  9900. try {
  9901. const res = await fetch(`${API_BASE}/routing/bgp/networks`, {
  9902. method: 'POST',
  9903. headers: { 'Content-Type': 'application/json' },
  9904. body: JSON.stringify(payload)
  9905. });
  9906. if (res.ok) {
  9907. closeBgpNetworkModal();
  9908. showToast('Success', 'BGP network advertisement saved', 'success');
  9909. loadDynamicRouting();
  9910. } else {
  9911. const err = await res.json();
  9912. showToast('Error', err.error || 'Failed to save network', 'error');
  9913. }
  9914. } catch (err) {
  9915. showToast('Error', err.message, 'error');
  9916. }
  9917. }
  9918. async function deleteBgpNetwork(id) {
  9919. if (!confirm('Are you sure you want to stop announcing this network?')) return;
  9920. try {
  9921. const res = await fetch(`${API_BASE}/routing/bgp/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9922. if (res.ok) {
  9923. showToast('Deleted', 'Network advertisement removed', 'success');
  9924. loadDynamicRouting();
  9925. }
  9926. } catch (err) {
  9927. showToast('Error', err.message, 'error');
  9928. }
  9929. }
  9930. // =========================================================================
  9931. // DEBTIK v7 OSPF MODALS & ACTIONS
  9932. // =========================================================================
  9933. // --- 1. OSPF INSTANCE ---
  9934. function openOspfInstanceModal(id = null) {
  9935. const isEdit = !!id;
  9936. const inst = (state.ospfInstances || []).find(i => i.id === id) || {
  9937. id: '',
  9938. name: 'Default',
  9939. version: 2,
  9940. vrf: 'main',
  9941. router_id: '192.168.131.56',
  9942. routing_table: 'main',
  9943. enabled: true,
  9944. redistribute_connected: false,
  9945. redistribute_static: true,
  9946. redistribute_bgp: false,
  9947. comment: ''
  9948. };
  9949. document.getElementById('ospf-instance-modal-title').innerText = isEdit ? inst.name : 'New...';
  9950. document.getElementById('modal-ospf-inst-id').value = isEdit ? inst.id : '';
  9951. document.getElementById('modal-ospf-inst-enabled').checked = !inst.disabled;
  9952. document.getElementById('modal-ospf-inst-comment').value = inst.comment || '';
  9953. document.getElementById('modal-ospf-inst-name').value = inst.name || 'Default';
  9954. document.getElementById('modal-ospf-inst-version').value = inst.version || 2;
  9955. document.getElementById('modal-ospf-inst-vrf').value = inst.vrf || 'main';
  9956. document.getElementById('modal-ospf-inst-router-id').value = inst.router_id || '';
  9957. document.getElementById('modal-ospf-inst-routing-table').value = inst.routing_table || 'main';
  9958. document.getElementById('modal-ospf-inst-redist-conn').checked = !!inst.redistribute_connected;
  9959. document.getElementById('modal-ospf-inst-redist-static').checked = inst.redistribute_static !== false;
  9960. document.getElementById('modal-ospf-inst-redist-bgp').checked = !!inst.redistribute_bgp;
  9961. const isDefaultRedist = !!inst.redistribute_default || (inst.originate_default && inst.originate_default !== 'never');
  9962. const origMode = inst.originate_default || (inst.redistribute_default ? 'if-installed' : 'never');
  9963. document.getElementById('modal-ospf-inst-redist-default').checked = isDefaultRedist;
  9964. document.getElementById('modal-ospf-inst-originate-default').value = origMode;
  9965. document.getElementById('modal-ospf-inst-default-metric').value = inst.default_metric || '';
  9966. const btnRem = document.getElementById('btn-ospf-inst-modal-remove');
  9967. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  9968. document.getElementById('ospf-instance-modal').classList.remove('hidden');
  9969. }
  9970. function toggleOspfDefaultModeUI() {
  9971. const isChecked = document.getElementById('modal-ospf-inst-redist-default')?.checked;
  9972. const select = document.getElementById('modal-ospf-inst-originate-default');
  9973. if (!select) return;
  9974. if (isChecked) {
  9975. if (select.value === 'never') select.value = 'if-installed';
  9976. } else {
  9977. select.value = 'never';
  9978. }
  9979. }
  9980. function onOspfOriginateDefaultChange() {
  9981. const val = document.getElementById('modal-ospf-inst-originate-default')?.value;
  9982. const chk = document.getElementById('modal-ospf-inst-redist-default');
  9983. if (chk) chk.checked = val !== 'never';
  9984. }
  9985. function openEditOspfInstanceModal(id) {
  9986. openOspfInstanceModal(id);
  9987. }
  9988. function closeOspfInstanceModal() {
  9989. document.getElementById('ospf-instance-modal').classList.add('hidden');
  9990. }
  9991. async function submitOspfInstance(e) {
  9992. if (e) e.preventDefault();
  9993. const payload = {
  9994. id: document.getElementById('modal-ospf-inst-id').value,
  9995. name: document.getElementById('modal-ospf-inst-name').value.trim() || 'Default',
  9996. version: parseInt(document.getElementById('modal-ospf-inst-version').value, 10) || 2,
  9997. vrf: document.getElementById('modal-ospf-inst-vrf').value.trim() || 'main',
  9998. router_id: document.getElementById('modal-ospf-inst-router-id').value.trim(),
  9999. routing_table: document.getElementById('modal-ospf-inst-routing-table').value.trim() || 'main',
  10000. enabled: document.getElementById('modal-ospf-inst-enabled').checked,
  10001. disabled: !document.getElementById('modal-ospf-inst-enabled').checked,
  10002. comment: document.getElementById('modal-ospf-inst-comment').value.trim(),
  10003. redistribute_connected: document.getElementById('modal-ospf-inst-redist-conn').checked,
  10004. redistribute_static: document.getElementById('modal-ospf-inst-redist-static').checked,
  10005. redistribute_bgp: document.getElementById('modal-ospf-inst-redist-bgp').checked,
  10006. redistribute_default: document.getElementById('modal-ospf-inst-redist-default').checked,
  10007. originate_default: document.getElementById('modal-ospf-inst-originate-default').value,
  10008. default_metric: parseInt(document.getElementById('modal-ospf-inst-default-metric').value, 10) || 0
  10009. };
  10010. try {
  10011. const res = await fetch(`${API_BASE}/routing/ospf/instances`, {
  10012. method: 'POST',
  10013. headers: { 'Content-Type': 'application/json' },
  10014. body: JSON.stringify(payload)
  10015. });
  10016. if (res.ok) {
  10017. closeOspfInstanceModal();
  10018. showToast('Saved', 'OSPF instance updated', 'success');
  10019. loadDynamicRouting();
  10020. } else {
  10021. const err = await res.json();
  10022. showToast('Error', err.error || 'Failed to save OSPF instance', 'error');
  10023. }
  10024. } catch (err) {
  10025. showToast('Error', err.message, 'error');
  10026. }
  10027. }
  10028. function applyOspfInstanceForm() {
  10029. submitOspfInstance(null);
  10030. }
  10031. function copyOspfInstance() {
  10032. document.getElementById('modal-ospf-inst-id').value = '';
  10033. document.getElementById('modal-ospf-inst-name').value += '-copy';
  10034. document.getElementById('ospf-instance-modal-title').innerText = 'New...';
  10035. showToast('Copied', 'Duplicated as new OSPF instance', 'info');
  10036. }
  10037. async function deleteCurrentOspfInstance() {
  10038. const id = document.getElementById('modal-ospf-inst-id').value;
  10039. if (!id) return;
  10040. if (!confirm('Are you sure you want to remove this OSPF instance?')) return;
  10041. try {
  10042. const res = await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10043. if (res.ok) {
  10044. closeOspfInstanceModal();
  10045. showToast('Removed', 'OSPF instance deleted', 'success');
  10046. loadDynamicRouting();
  10047. }
  10048. } catch (err) {
  10049. showToast('Error', err.message, 'error');
  10050. }
  10051. }
  10052. async function enableSelectedOspfInstance() {
  10053. const id = state.selectedOspfRow?.instances;
  10054. if (!id) return;
  10055. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}/state`, {
  10056. method: 'POST',
  10057. headers: { 'Content-Type': 'application/json' },
  10058. body: JSON.stringify({ disabled: false })
  10059. });
  10060. loadDynamicRouting();
  10061. }
  10062. async function disableSelectedOspfInstance() {
  10063. const id = state.selectedOspfRow?.instances;
  10064. if (!id) return;
  10065. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}/state`, {
  10066. method: 'POST',
  10067. headers: { 'Content-Type': 'application/json' },
  10068. body: JSON.stringify({ disabled: true })
  10069. });
  10070. loadDynamicRouting();
  10071. }
  10072. async function removeSelectedOspfInstance() {
  10073. const id = state.selectedOspfRow?.instances;
  10074. if (!id) return;
  10075. if (!confirm('Delete selected OSPF instance?')) return;
  10076. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10077. loadDynamicRouting();
  10078. }
  10079. async function promptCommentOspfInstance() {
  10080. const id = state.selectedOspfRow?.instances;
  10081. if (!id) return;
  10082. const inst = (state.ospfInstances || []).find(i => i.id === id);
  10083. if (!inst) return;
  10084. const comment = prompt('Enter comment for OSPF instance:', inst.comment || '');
  10085. if (comment === null) return;
  10086. inst.comment = comment;
  10087. await fetch(`${API_BASE}/routing/ospf/instances`, {
  10088. method: 'POST',
  10089. headers: { 'Content-Type': 'application/json' },
  10090. body: JSON.stringify(inst)
  10091. });
  10092. loadDynamicRouting();
  10093. }
  10094. // --- 2. OSPF AREA ---
  10095. function populateOspfAreaDropdowns() {
  10096. const instSelect = document.getElementById('modal-ospf-area-instance');
  10097. if (instSelect) {
  10098. const cur = instSelect.value;
  10099. instSelect.innerHTML = (state.ospfInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)}</option>`).join('');
  10100. if (instSelect.innerHTML === '') instSelect.innerHTML = '<option value="Default">Default</option>';
  10101. if (cur) instSelect.value = cur;
  10102. }
  10103. }
  10104. function openOspfAreaModal(id = null) {
  10105. const isEdit = !!id;
  10106. populateOspfAreaDropdowns();
  10107. const area = (state.ospfAreas || []).find(a => a.id === id) || {
  10108. id: '',
  10109. name: 'Default',
  10110. instance: 'Default',
  10111. area_id: '0.0.0.0',
  10112. area_type: 'default',
  10113. default_cost: 1,
  10114. no_summaries: false,
  10115. disabled: false,
  10116. comment: ''
  10117. };
  10118. document.getElementById('ospf-area-modal-title').innerText = isEdit ? area.name : 'New...';
  10119. document.getElementById('modal-ospf-area-id').value = isEdit ? area.id : '';
  10120. document.getElementById('modal-ospf-area-enabled').checked = !area.disabled;
  10121. document.getElementById('modal-ospf-area-comment').value = area.comment || '';
  10122. document.getElementById('modal-ospf-area-name').value = area.name || 'Default';
  10123. document.getElementById('modal-ospf-area-instance').value = area.instance || 'Default';
  10124. document.getElementById('modal-ospf-area-areaid').value = area.area_id || '0.0.0.0';
  10125. document.getElementById('modal-ospf-area-type').value = area.area_type || 'default';
  10126. document.getElementById('modal-ospf-area-default-cost').value = area.default_cost || 1;
  10127. document.getElementById('modal-ospf-area-no-summaries').checked = !!area.no_summaries;
  10128. const btnRem = document.getElementById('btn-ospf-area-modal-remove');
  10129. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  10130. document.getElementById('ospf-area-modal').classList.remove('hidden');
  10131. }
  10132. function openEditOspfAreaModal(id) {
  10133. openOspfAreaModal(id);
  10134. }
  10135. function closeOspfAreaModal() {
  10136. document.getElementById('ospf-area-modal').classList.add('hidden');
  10137. }
  10138. async function submitOspfArea(e) {
  10139. if (e) e.preventDefault();
  10140. const payload = {
  10141. id: document.getElementById('modal-ospf-area-id').value,
  10142. name: document.getElementById('modal-ospf-area-name').value.trim() || 'Default',
  10143. instance: document.getElementById('modal-ospf-area-instance').value.trim() || 'Default',
  10144. area_id: document.getElementById('modal-ospf-area-areaid').value.trim() || '0.0.0.0',
  10145. area_type: document.getElementById('modal-ospf-area-type').value,
  10146. default_cost: parseInt(document.getElementById('modal-ospf-area-default-cost').value, 10) || 1,
  10147. no_summaries: document.getElementById('modal-ospf-area-no-summaries').checked,
  10148. disabled: !document.getElementById('modal-ospf-area-enabled').checked,
  10149. comment: document.getElementById('modal-ospf-area-comment').value.trim()
  10150. };
  10151. try {
  10152. const res = await fetch(`${API_BASE}/routing/ospf/areas`, {
  10153. method: 'POST',
  10154. headers: { 'Content-Type': 'application/json' },
  10155. body: JSON.stringify(payload)
  10156. });
  10157. if (res.ok) {
  10158. closeOspfAreaModal();
  10159. showToast('Saved', 'OSPF area saved', 'success');
  10160. loadDynamicRouting();
  10161. } else {
  10162. const err = await res.json();
  10163. showToast('Error', err.error || 'Failed to save area', 'error');
  10164. }
  10165. } catch (err) {
  10166. showToast('Error', err.message, 'error');
  10167. }
  10168. }
  10169. function applyOspfAreaForm() {
  10170. submitOspfArea(null);
  10171. }
  10172. function copyOspfArea() {
  10173. document.getElementById('modal-ospf-area-id').value = '';
  10174. document.getElementById('modal-ospf-area-name').value += '-copy';
  10175. document.getElementById('ospf-area-modal-title').innerText = 'New...';
  10176. showToast('Copied', 'Duplicated as new OSPF area', 'info');
  10177. }
  10178. async function deleteCurrentOspfArea() {
  10179. const id = document.getElementById('modal-ospf-area-id').value;
  10180. if (!id) return;
  10181. if (!confirm('Are you sure you want to remove this OSPF area?')) return;
  10182. try {
  10183. const res = await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10184. if (res.ok) {
  10185. closeOspfAreaModal();
  10186. showToast('Removed', 'OSPF area deleted', 'success');
  10187. loadDynamicRouting();
  10188. }
  10189. } catch (err) {
  10190. showToast('Error', err.message, 'error');
  10191. }
  10192. }
  10193. async function enableSelectedOspfArea() {
  10194. const id = state.selectedOspfRow?.areas;
  10195. if (!id) return;
  10196. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}/state`, {
  10197. method: 'POST',
  10198. headers: { 'Content-Type': 'application/json' },
  10199. body: JSON.stringify({ disabled: false })
  10200. });
  10201. loadDynamicRouting();
  10202. }
  10203. async function disableSelectedOspfArea() {
  10204. const id = state.selectedOspfRow?.areas;
  10205. if (!id) return;
  10206. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}/state`, {
  10207. method: 'POST',
  10208. headers: { 'Content-Type': 'application/json' },
  10209. body: JSON.stringify({ disabled: true })
  10210. });
  10211. loadDynamicRouting();
  10212. }
  10213. async function removeSelectedOspfArea() {
  10214. const id = state.selectedOspfRow?.areas;
  10215. if (!id) return;
  10216. if (!confirm('Delete selected OSPF area?')) return;
  10217. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10218. loadDynamicRouting();
  10219. }
  10220. async function promptCommentOspfArea() {
  10221. const id = state.selectedOspfRow?.areas;
  10222. if (!id) return;
  10223. const area = (state.ospfAreas || []).find(a => a.id === id);
  10224. if (!area) return;
  10225. const comment = prompt('Enter comment for OSPF area:', area.comment || '');
  10226. if (comment === null) return;
  10227. area.comment = comment;
  10228. await fetch(`${API_BASE}/routing/ospf/areas`, {
  10229. method: 'POST',
  10230. headers: { 'Content-Type': 'application/json' },
  10231. body: JSON.stringify(area)
  10232. });
  10233. loadDynamicRouting();
  10234. }
  10235. // --- 3. OSPF AREA RANGE ---
  10236. function populateAreaRangeDropdowns() {
  10237. const select = document.getElementById('modal-ospf-range-area');
  10238. if (select) {
  10239. const cur = select.value;
  10240. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  10241. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  10242. if (cur) select.value = cur;
  10243. }
  10244. }
  10245. function openOspfAreaRangeModal(id = null) {
  10246. const isEdit = !!id;
  10247. populateAreaRangeDropdowns();
  10248. const r = (state.ospfAreaRanges || []).find(it => it.id === id) || {
  10249. id: '',
  10250. area: 'Default',
  10251. prefix: '',
  10252. cost: 1,
  10253. advertise: true,
  10254. disabled: false,
  10255. comment: ''
  10256. };
  10257. document.getElementById('ospf-area-range-modal-title').innerText = isEdit ? r.prefix : 'New...';
  10258. document.getElementById('modal-ospf-range-id').value = isEdit ? r.id : '';
  10259. document.getElementById('modal-ospf-range-enabled').checked = !r.disabled;
  10260. document.getElementById('modal-ospf-range-comment').value = r.comment || '';
  10261. document.getElementById('modal-ospf-range-area').value = r.area || 'Default';
  10262. document.getElementById('modal-ospf-range-prefix').value = r.prefix || '';
  10263. document.getElementById('modal-ospf-range-cost').value = r.cost || 1;
  10264. document.getElementById('modal-ospf-range-advertise').checked = r.advertise !== false;
  10265. const btnRem = document.getElementById('btn-ospf-range-modal-remove');
  10266. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  10267. document.getElementById('ospf-area-range-modal').classList.remove('hidden');
  10268. }
  10269. function openEditOspfAreaRangeModal(id) {
  10270. openOspfAreaRangeModal(id);
  10271. }
  10272. function closeOspfAreaRangeModal() {
  10273. document.getElementById('ospf-area-range-modal').classList.add('hidden');
  10274. }
  10275. async function submitOspfAreaRange(e) {
  10276. if (e) e.preventDefault();
  10277. const payload = {
  10278. id: document.getElementById('modal-ospf-range-id').value,
  10279. area: document.getElementById('modal-ospf-range-area').value,
  10280. prefix: document.getElementById('modal-ospf-range-prefix').value.trim(),
  10281. cost: parseInt(document.getElementById('modal-ospf-range-cost').value, 10) || 1,
  10282. advertise: document.getElementById('modal-ospf-range-advertise').checked,
  10283. disabled: !document.getElementById('modal-ospf-range-enabled').checked,
  10284. comment: document.getElementById('modal-ospf-range-comment').value.trim()
  10285. };
  10286. try {
  10287. const res = await fetch(`${API_BASE}/routing/ospf/area-ranges`, {
  10288. method: 'POST',
  10289. headers: { 'Content-Type': 'application/json' },
  10290. body: JSON.stringify(payload)
  10291. });
  10292. if (res.ok) {
  10293. closeOspfAreaRangeModal();
  10294. showToast('Saved', 'Area range saved', 'success');
  10295. loadDynamicRouting();
  10296. } else {
  10297. const err = await res.json();
  10298. showToast('Error', err.error || 'Failed to save area range', 'error');
  10299. }
  10300. } catch (err) {
  10301. showToast('Error', err.message, 'error');
  10302. }
  10303. }
  10304. function applyOspfAreaRangeForm() {
  10305. submitOspfAreaRange(null);
  10306. }
  10307. async function deleteCurrentOspfAreaRange() {
  10308. const id = document.getElementById('modal-ospf-range-id').value;
  10309. if (!id) return;
  10310. if (!confirm('Delete this area range?')) return;
  10311. try {
  10312. await fetch(`${API_BASE}/routing/ospf/area-ranges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10313. closeOspfAreaRangeModal();
  10314. showToast('Removed', 'Area range removed', 'success');
  10315. loadDynamicRouting();
  10316. } catch (err) {
  10317. showToast('Error', err.message, 'error');
  10318. }
  10319. }
  10320. async function enableSelectedOspfAreaRange() {
  10321. const id = state.selectedOspfRow?.['area-ranges'];
  10322. if (!id) return;
  10323. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  10324. if (!r) return;
  10325. r.disabled = false;
  10326. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  10327. loadDynamicRouting();
  10328. }
  10329. async function disableSelectedOspfAreaRange() {
  10330. const id = state.selectedOspfRow?.['area-ranges'];
  10331. if (!id) return;
  10332. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  10333. if (!r) return;
  10334. r.disabled = true;
  10335. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  10336. loadDynamicRouting();
  10337. }
  10338. async function removeSelectedOspfAreaRange() {
  10339. const id = state.selectedOspfRow?.['area-ranges'];
  10340. if (!id) return;
  10341. if (!confirm('Delete selected area range?')) return;
  10342. await fetch(`${API_BASE}/routing/ospf/area-ranges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10343. loadDynamicRouting();
  10344. }
  10345. async function promptCommentOspfAreaRange() {
  10346. const id = state.selectedOspfRow?.['area-ranges'];
  10347. if (!id) return;
  10348. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  10349. if (!r) return;
  10350. const comment = prompt('Enter comment for area range:', r.comment || '');
  10351. if (comment === null) return;
  10352. r.comment = comment;
  10353. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  10354. loadDynamicRouting();
  10355. }
  10356. // --- 4. OSPF INTERFACE TEMPLATE ---
  10357. function switchOspfTemplateTab(tab) {
  10358. const tabGen = document.getElementById('ospf-tmpl-tab-general');
  10359. const tabAuth = document.getElementById('ospf-tmpl-tab-auth');
  10360. const btnGen = document.getElementById('ospf-tmpl-tab-btn-general');
  10361. const btnAuth = document.getElementById('ospf-tmpl-tab-btn-auth');
  10362. if (tab === 'general') {
  10363. if (tabGen) tabGen.classList.remove('hidden');
  10364. if (tabAuth) tabAuth.classList.add('hidden');
  10365. if (btnGen) btnGen.className = 'px-4 py-2 text-xs font-bold border-b-2 border-sky-500 text-white transition';
  10366. 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';
  10367. } else {
  10368. if (tabGen) tabGen.classList.add('hidden');
  10369. if (tabAuth) tabAuth.classList.remove('hidden');
  10370. 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';
  10371. if (btnAuth) btnAuth.className = 'px-4 py-2 text-xs font-bold border-b-2 border-sky-500 text-white transition';
  10372. }
  10373. }
  10374. function populateTemplateAreaDropdowns() {
  10375. const select = document.getElementById('modal-ospf-tmpl-area');
  10376. if (select) {
  10377. const cur = select.value;
  10378. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  10379. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  10380. if (cur) select.value = cur;
  10381. }
  10382. }
  10383. function openOspfTemplateModal(id = null) {
  10384. const isEdit = !!id;
  10385. populateTemplateAreaDropdowns();
  10386. switchOspfTemplateTab('general');
  10387. const tmpl = (state.ospfTemplates || []).find(t => t.id === id) || {
  10388. id: '',
  10389. interfaces: '',
  10390. area: 'Default',
  10391. networks: '',
  10392. network_type: 'broadcast',
  10393. cost: 1,
  10394. priority: 128,
  10395. passive: false,
  10396. hello_interval: 10,
  10397. dead_interval: 40,
  10398. auth: 'none',
  10399. auth_key: '',
  10400. disabled: false,
  10401. comment: ''
  10402. };
  10403. document.getElementById('ospf-template-modal-title').innerText = isEdit ? (tmpl.interfaces || tmpl.networks || 'Template') : 'New...';
  10404. document.getElementById('modal-ospf-tmpl-id').value = isEdit ? tmpl.id : '';
  10405. document.getElementById('modal-ospf-tmpl-enabled').checked = !tmpl.disabled;
  10406. document.getElementById('modal-ospf-tmpl-comment').value = tmpl.comment || '';
  10407. document.getElementById('modal-ospf-tmpl-interfaces').value = tmpl.interfaces || tmpl.interface || '';
  10408. document.getElementById('modal-ospf-tmpl-area').value = tmpl.area || 'Default';
  10409. document.getElementById('modal-ospf-tmpl-networks').value = tmpl.networks || tmpl.network || '';
  10410. document.getElementById('modal-ospf-tmpl-net-type').value = tmpl.network_type || 'broadcast';
  10411. document.getElementById('modal-ospf-tmpl-cost').value = tmpl.cost || 1;
  10412. document.getElementById('modal-ospf-tmpl-priority').value = tmpl.priority || 128;
  10413. document.getElementById('modal-ospf-tmpl-passive').checked = !!tmpl.passive;
  10414. document.getElementById('modal-ospf-tmpl-hello').value = tmpl.hello_interval || 10;
  10415. document.getElementById('modal-ospf-tmpl-dead').value = tmpl.dead_interval || 40;
  10416. document.getElementById('modal-ospf-tmpl-auth').value = tmpl.auth || tmpl.auth_type || 'none';
  10417. document.getElementById('modal-ospf-tmpl-auth-key').value = tmpl.auth_key || '';
  10418. const btnRem = document.getElementById('btn-ospf-tmpl-modal-remove');
  10419. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  10420. document.getElementById('ospf-template-modal').classList.remove('hidden');
  10421. }
  10422. function openEditOspfTemplateModal(id) {
  10423. openOspfTemplateModal(id);
  10424. }
  10425. function closeOspfTemplateModal() {
  10426. document.getElementById('ospf-template-modal').classList.add('hidden');
  10427. }
  10428. async function submitOspfTemplate(e) {
  10429. if (e) e.preventDefault();
  10430. const payload = {
  10431. id: document.getElementById('modal-ospf-tmpl-id').value,
  10432. interfaces: document.getElementById('modal-ospf-tmpl-interfaces').value.trim(),
  10433. interface: document.getElementById('modal-ospf-tmpl-interfaces').value.trim(),
  10434. area: document.getElementById('modal-ospf-tmpl-area').value,
  10435. networks: document.getElementById('modal-ospf-tmpl-networks').value.trim(),
  10436. network: document.getElementById('modal-ospf-tmpl-networks').value.trim(),
  10437. network_type: document.getElementById('modal-ospf-tmpl-net-type').value,
  10438. cost: parseInt(document.getElementById('modal-ospf-tmpl-cost').value, 10) || 1,
  10439. priority: parseInt(document.getElementById('modal-ospf-tmpl-priority').value, 10) || 128,
  10440. passive: document.getElementById('modal-ospf-tmpl-passive').checked,
  10441. hello_interval: parseInt(document.getElementById('modal-ospf-tmpl-hello').value, 10) || 10,
  10442. dead_interval: parseInt(document.getElementById('modal-ospf-tmpl-dead').value, 10) || 40,
  10443. auth: document.getElementById('modal-ospf-tmpl-auth').value,
  10444. auth_type: document.getElementById('modal-ospf-tmpl-auth').value,
  10445. auth_key: document.getElementById('modal-ospf-tmpl-auth-key').value,
  10446. disabled: !document.getElementById('modal-ospf-tmpl-enabled').checked,
  10447. comment: document.getElementById('modal-ospf-tmpl-comment').value.trim()
  10448. };
  10449. try {
  10450. const res = await fetch(`${API_BASE}/routing/ospf/templates`, {
  10451. method: 'POST',
  10452. headers: { 'Content-Type': 'application/json' },
  10453. body: JSON.stringify(payload)
  10454. });
  10455. if (res.ok) {
  10456. closeOspfTemplateModal();
  10457. showToast('Saved', 'Interface template saved', 'success');
  10458. loadDynamicRouting();
  10459. } else {
  10460. const err = await res.json();
  10461. showToast('Error', err.error || 'Failed to save interface template', 'error');
  10462. }
  10463. } catch (err) {
  10464. showToast('Error', err.message, 'error');
  10465. }
  10466. }
  10467. function applyOspfTemplateForm() {
  10468. submitOspfTemplate(null);
  10469. }
  10470. function copyOspfTemplate() {
  10471. document.getElementById('modal-ospf-tmpl-id').value = '';
  10472. document.getElementById('ospf-template-modal-title').innerText = 'New...';
  10473. showToast('Copied', 'Duplicated as new template', 'info');
  10474. }
  10475. async function deleteCurrentOspfTemplate() {
  10476. const id = document.getElementById('modal-ospf-tmpl-id').value;
  10477. if (!id) return;
  10478. if (!confirm('Delete this interface template?')) return;
  10479. try {
  10480. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10481. closeOspfTemplateModal();
  10482. showToast('Removed', 'Interface template deleted', 'success');
  10483. loadDynamicRouting();
  10484. } catch (err) {
  10485. showToast('Error', err.message, 'error');
  10486. }
  10487. }
  10488. async function enableSelectedOspfTemplate() {
  10489. const id = state.selectedOspfRow?.templates;
  10490. if (!id) return;
  10491. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  10492. method: 'POST',
  10493. headers: { 'Content-Type': 'application/json' },
  10494. body: JSON.stringify({ disabled: false })
  10495. });
  10496. loadDynamicRouting();
  10497. }
  10498. async function disableSelectedOspfTemplate() {
  10499. const id = state.selectedOspfRow?.templates;
  10500. if (!id) return;
  10501. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  10502. method: 'POST',
  10503. headers: { 'Content-Type': 'application/json' },
  10504. body: JSON.stringify({ disabled: true })
  10505. });
  10506. loadDynamicRouting();
  10507. }
  10508. async function removeSelectedOspfTemplate() {
  10509. const id = state.selectedOspfRow?.templates;
  10510. if (!id) return;
  10511. if (!confirm('Delete selected interface template?')) return;
  10512. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10513. loadDynamicRouting();
  10514. }
  10515. async function promptCommentOspfTemplate() {
  10516. const id = state.selectedOspfRow?.templates;
  10517. if (!id) return;
  10518. const tmpl = (state.ospfTemplates || []).find(t => t.id === id);
  10519. if (!tmpl) return;
  10520. const comment = prompt('Enter comment for template:', tmpl.comment || '');
  10521. if (comment === null) return;
  10522. tmpl.comment = comment;
  10523. await fetch(`${API_BASE}/routing/ospf/templates`, {
  10524. method: 'POST',
  10525. headers: { 'Content-Type': 'application/json' },
  10526. body: JSON.stringify(tmpl)
  10527. });
  10528. loadDynamicRouting();
  10529. }
  10530. // --- 5. OSPF STATIC NEIGHBOR ---
  10531. function populateStaticNbrAreaDropdowns() {
  10532. const select = document.getElementById('modal-ospf-snbr-area');
  10533. if (select) {
  10534. const cur = select.value;
  10535. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  10536. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  10537. if (cur) select.value = cur;
  10538. }
  10539. }
  10540. function openOspfStaticNbrModal(id = null) {
  10541. const isEdit = !!id;
  10542. populateStaticNbrAreaDropdowns();
  10543. const nbr = (state.ospfStaticNbrs || []).find(n => n.id === id) || {
  10544. id: '',
  10545. address: '',
  10546. area: 'Default',
  10547. poll_interval: 120,
  10548. cost: 1,
  10549. disabled: false,
  10550. comment: ''
  10551. };
  10552. document.getElementById('ospf-static-nbr-modal-title').innerText = isEdit ? nbr.address : 'New...';
  10553. document.getElementById('modal-ospf-snbr-id').value = isEdit ? nbr.id : '';
  10554. document.getElementById('modal-ospf-snbr-enabled').checked = !nbr.disabled;
  10555. document.getElementById('modal-ospf-snbr-comment').value = nbr.comment || '';
  10556. document.getElementById('modal-ospf-snbr-address').value = nbr.address || '';
  10557. document.getElementById('modal-ospf-snbr-area').value = nbr.area || 'Default';
  10558. document.getElementById('modal-ospf-snbr-poll').value = nbr.poll_interval || 120;
  10559. document.getElementById('modal-ospf-snbr-cost').value = nbr.cost || 1;
  10560. const btnRem = document.getElementById('btn-ospf-snbr-modal-remove');
  10561. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  10562. document.getElementById('ospf-static-nbr-modal').classList.remove('hidden');
  10563. }
  10564. function openEditOspfStaticNbrModal(id) {
  10565. openOspfStaticNbrModal(id);
  10566. }
  10567. function closeOspfStaticNbrModal() {
  10568. document.getElementById('ospf-static-nbr-modal').classList.add('hidden');
  10569. }
  10570. async function submitOspfStaticNbr(e) {
  10571. if (e) e.preventDefault();
  10572. const payload = {
  10573. id: document.getElementById('modal-ospf-snbr-id').value,
  10574. address: document.getElementById('modal-ospf-snbr-address').value.trim(),
  10575. area: document.getElementById('modal-ospf-snbr-area').value,
  10576. poll_interval: parseInt(document.getElementById('modal-ospf-snbr-poll').value, 10) || 120,
  10577. cost: parseInt(document.getElementById('modal-ospf-snbr-cost').value, 10) || 1,
  10578. disabled: !document.getElementById('modal-ospf-snbr-enabled').checked,
  10579. comment: document.getElementById('modal-ospf-snbr-comment').value.trim()
  10580. };
  10581. try {
  10582. const res = await fetch(`${API_BASE}/routing/ospf/static-neighbors`, {
  10583. method: 'POST',
  10584. headers: { 'Content-Type': 'application/json' },
  10585. body: JSON.stringify(payload)
  10586. });
  10587. if (res.ok) {
  10588. closeOspfStaticNbrModal();
  10589. showToast('Saved', 'Static neighbor saved', 'success');
  10590. loadDynamicRouting();
  10591. } else {
  10592. const err = await res.json();
  10593. showToast('Error', err.error || 'Failed to save static neighbor', 'error');
  10594. }
  10595. } catch (err) {
  10596. showToast('Error', err.message, 'error');
  10597. }
  10598. }
  10599. function applyOspfStaticNbrForm() {
  10600. submitOspfStaticNbr(null);
  10601. }
  10602. async function deleteCurrentOspfStaticNbr() {
  10603. const id = document.getElementById('modal-ospf-snbr-id').value;
  10604. if (!id) return;
  10605. if (!confirm('Delete this static neighbor?')) return;
  10606. try {
  10607. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10608. closeOspfStaticNbrModal();
  10609. showToast('Removed', 'Static neighbor removed', 'success');
  10610. loadDynamicRouting();
  10611. } catch (err) {
  10612. showToast('Error', err.message, 'error');
  10613. }
  10614. }
  10615. async function enableSelectedOspfStaticNbr() {
  10616. const id = state.selectedOspfRow?.['static-nbrs'];
  10617. if (!id) return;
  10618. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: false }) });
  10619. loadDynamicRouting();
  10620. }
  10621. async function disableSelectedOspfStaticNbr() {
  10622. const id = state.selectedOspfRow?.['static-nbrs'];
  10623. if (!id) return;
  10624. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: true }) });
  10625. loadDynamicRouting();
  10626. }
  10627. async function removeSelectedOspfStaticNbr() {
  10628. const id = state.selectedOspfRow?.['static-nbrs'];
  10629. if (!id) return;
  10630. if (!confirm('Delete selected static neighbor?')) return;
  10631. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10632. loadDynamicRouting();
  10633. }
  10634. async function promptCommentOspfStaticNbr() {
  10635. const id = state.selectedOspfRow?.['static-nbrs'];
  10636. if (!id) return;
  10637. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  10638. if (!n) return;
  10639. const comment = prompt('Enter comment for static neighbor:', n.comment || '');
  10640. if (comment === null) return;
  10641. n.comment = comment;
  10642. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  10643. loadDynamicRouting();
  10644. }
  10645. // Backward-compat aliases
  10646. function openAddOspfInterfaceModal() { openOspfTemplateModal(); }
  10647. function openEditOspfInterfaceModal(id) { openEditOspfTemplateModal(id); }
  10648. function closeOspfInterfaceModal() { closeOspfTemplateModal(); }
  10649. function submitOspfInterface(e) { submitOspfTemplate(e); }
  10650. function deleteOspfInterface(id) {
  10651. fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' }).then(() => loadDynamicRouting());
  10652. }
  10653. function toggleOspfInterfaceState(id, disabled) {
  10654. fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  10655. method: 'POST',
  10656. headers: { 'Content-Type': 'application/json' },
  10657. body: JSON.stringify({ disabled })
  10658. }).then(() => loadDynamicRouting());
  10659. }
  10660. function openAddOspfAreaModal() { openOspfAreaModal(); }
  10661. function deleteOspfArea(id) {
  10662. fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' }).then(() => loadDynamicRouting());
  10663. }
  10664. // ============================================================================
  10665. // ==================== MIKROTIK BRIDGE SUBSYSTEM ==============================
  10666. // ============================================================================
  10667. function switchBridgeSubTab(tab) {
  10668. state.bridgeSubTab = tab;
  10669. const tabs = ['bridges', 'ports', 'vlans', 'hosts'];
  10670. tabs.forEach(t => {
  10671. const panel = document.getElementById(`bridge-subtab-${t}`);
  10672. const btn = document.getElementById(`bridge-subtab-btn-${t}`);
  10673. if (panel) {
  10674. if (t === tab) panel.classList.remove('hidden');
  10675. else panel.classList.add('hidden');
  10676. }
  10677. if (btn) {
  10678. if (t === tab) {
  10679. 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';
  10680. } else {
  10681. 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';
  10682. }
  10683. }
  10684. });
  10685. const addBtn = document.getElementById('bridge-top-action-btn');
  10686. if (addBtn) {
  10687. if (tab === 'bridges') addBtn.innerHTML = '<span>+ Add Bridge</span>';
  10688. else if (tab === 'ports') addBtn.innerHTML = '<span>+ Add Port</span>';
  10689. else if (tab === 'vlans') addBtn.innerHTML = '<span>+ Add VLAN Entry</span>';
  10690. else if (tab === 'hosts') addBtn.innerHTML = '<span>🔄 Refresh MACs</span>';
  10691. }
  10692. if (tab === 'hosts') loadBridgeHosts();
  10693. setTimeout(initTableSorting, 50);
  10694. }
  10695. function openCurrentBridgeModal() {
  10696. if (state.bridgeSubTab === 'bridges') openAddBridgeModal();
  10697. else if (state.bridgeSubTab === 'ports') openAddBridgePortModal();
  10698. else if (state.bridgeSubTab === 'vlans') openAddBridgeVLANModal();
  10699. else if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  10700. }
  10701. async function loadBridge() {
  10702. try {
  10703. const [bridgesRes, portsRes, vlansRes, summaryRes, eoipRes, vxlanRes, vlanIfacesRes] = await Promise.all([
  10704. fetch(`${API_BASE}/bridge/bridges`),
  10705. fetch(`${API_BASE}/bridge/ports`),
  10706. fetch(`${API_BASE}/bridge/vlans`),
  10707. fetch(`${API_BASE}/bridge/summary`),
  10708. fetch(`${API_BASE}/vpn/eoip`),
  10709. fetch(`${API_BASE}/vpn/vxlan`),
  10710. fetch(`${API_BASE}/vlans`)
  10711. ]);
  10712. if (bridgesRes.ok) state.bridges = await bridgesRes.json();
  10713. if (portsRes.ok) state.bridgePorts = await portsRes.json();
  10714. if (vlansRes.ok) state.bridgeVLANs = await vlansRes.json();
  10715. if (summaryRes.ok) state.bridgeSummary = await summaryRes.json();
  10716. if (eoipRes && eoipRes.ok) state.eoipTunnels = await eoipRes.json();
  10717. if (vxlanRes && vxlanRes.ok) state.vxlanTunnels = await vxlanRes.json();
  10718. if (vlanIfacesRes && vlanIfacesRes.ok) state.vlans = await vlanIfacesRes.json();
  10719. // Badges & Stats
  10720. const bBridges = document.getElementById('bridge-badge-bridges');
  10721. if (bBridges) bBridges.innerText = (state.bridges || []).length;
  10722. const bPorts = document.getElementById('bridge-badge-ports');
  10723. if (bPorts) bPorts.innerText = (state.bridgePorts || []).length;
  10724. const bVlans = document.getElementById('bridge-badge-vlans');
  10725. if (bVlans) bVlans.innerText = (state.bridgeVLANs || []).length;
  10726. const bHosts = document.getElementById('bridge-badge-hosts');
  10727. if (bHosts) bHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  10728. const sBr = document.getElementById('bridge-stat-bridges');
  10729. if (sBr) sBr.innerText = (state.bridges || []).length;
  10730. const sPorts = document.getElementById('bridge-stat-ports');
  10731. if (sPorts) sPorts.innerText = (state.bridgePorts || []).length;
  10732. const sHosts = document.getElementById('bridge-stat-hosts');
  10733. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  10734. renderBridges();
  10735. renderBridgePorts();
  10736. renderBridgeVLANs();
  10737. if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  10738. } catch (err) {
  10739. console.error('Failed to load bridge subsystem:', err);
  10740. }
  10741. }
  10742. // ----------------- Bridges -----------------
  10743. function renderBridges() {
  10744. const tbody = document.getElementById('bridge-table-body');
  10745. const empty = document.getElementById('bridge-empty-bridges');
  10746. const countBadge = document.getElementById('bridge-count-badge');
  10747. if (!tbody) return;
  10748. tbody.innerHTML = '';
  10749. const bridges = state.bridges || [];
  10750. if (countBadge) countBadge.innerText = `${bridges.length} Bridges`;
  10751. if (bridges.length === 0) {
  10752. empty?.classList.remove('hidden');
  10753. return;
  10754. }
  10755. empty?.classList.add('hidden');
  10756. bridges.forEach((b, idx) => {
  10757. const tr = document.createElement('tr');
  10758. tr.className = `hover:bg-slate-800/40 transition text-xs ${b.disabled ? 'opacity-50' : ''}`;
  10759. // Format IP addresses pill list
  10760. let ipsHtml = '<span class="text-slate-600 font-sans">None</span>';
  10761. if (b.ip_addresses && b.ip_addresses.length > 0) {
  10762. ipsHtml = b.ip_addresses.map(ip => `
  10763. <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">
  10764. <span>${ip}</span>
  10765. <button onclick="deleteBridgeIP('${b.id}', '${ip}')" class="text-slate-500 hover:text-rose-400 font-bold ml-0.5">×</button>
  10766. </span>
  10767. `).join(' ');
  10768. }
  10769. const runningFlag = b.running ? '<span class="text-emerald-400 font-bold" title="Running (R)">R</span>' : '<span class="text-slate-600">-</span>';
  10770. const disabledFlag = b.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '';
  10771. const flagDisplay = `${runningFlag}${disabledFlag ? ' ' + disabledFlag : ''}`;
  10772. tr.innerHTML = `
  10773. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  10774. <td class="py-2.5 px-3 text-center font-mono">${flagDisplay}</td>
  10775. <td class="py-2.5 px-3 font-bold text-white text-sm">
  10776. <span class="text-sky-400 mr-1.5">🌉</span>${b.name}
  10777. </td>
  10778. <td class="py-2.5 px-3 text-slate-300">${b.mtu}</td>
  10779. <td class="py-2.5 px-3 font-mono text-slate-300 text-[11px]">${b.mac_address || '-'}</td>
  10780. <td class="py-2.5 px-3">
  10781. <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>
  10782. </td>
  10783. <td class="py-2.5 px-3 text-center">
  10784. ${b.vlan_filtering ? '<span class="text-emerald-400 font-bold">yes</span>' : '<span class="text-slate-500">no</span>'}
  10785. </td>
  10786. <td class="py-2.5 px-3 font-mono">${b.pvid || 1}</td>
  10787. <td class="py-2.5 px-3">
  10788. <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>
  10789. </td>
  10790. <td class="py-2.5 px-3">
  10791. <div class="flex items-center gap-1.5 flex-wrap">
  10792. ${ipsHtml}
  10793. <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>
  10794. </div>
  10795. </td>
  10796. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  10797. <span class="text-emerald-400">↓ ${b.rx_human || '0 B'}</span> / <span class="text-cyan-400">↑ ${b.tx_human || '0 B'}</span>
  10798. </td>
  10799. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${b.comment || ''}">${b.comment || '-'}</td>
  10800. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  10801. <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>
  10802. <button onclick="openEditBridgeModal('${b.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  10803. <button onclick="deleteBridge('${b.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  10804. </td>
  10805. `;
  10806. tbody.appendChild(tr);
  10807. });
  10808. }
  10809. function openAddBridgeModal() {
  10810. document.getElementById('bridge-modal-title').innerText = 'Add Bridge Interface';
  10811. document.getElementById('bridge-modal-id').value = '';
  10812. document.getElementById('bridge-modal-name').value = 'bridge1';
  10813. document.getElementById('bridge-modal-name').disabled = false;
  10814. document.getElementById('bridge-modal-mtu').value = '1500';
  10815. document.getElementById('bridge-modal-mac').value = '';
  10816. document.getElementById('bridge-modal-stp').value = 'stp';
  10817. document.getElementById('bridge-modal-priority').value = '32768';
  10818. document.getElementById('bridge-modal-vlanfiltering').checked = false;
  10819. document.getElementById('bridge-modal-pvid').value = '1';
  10820. document.getElementById('bridge-modal-fastforward').checked = true;
  10821. document.getElementById('bridge-modal-comment').value = '';
  10822. document.getElementById('bridge-modal-disabled').checked = false;
  10823. toggleBridgeModalVlanFiltering();
  10824. document.getElementById('bridge-modal').classList.remove('hidden');
  10825. }
  10826. function openEditBridgeModal(id) {
  10827. const b = (state.bridges || []).find(x => x.id === id);
  10828. if (!b) return;
  10829. document.getElementById('bridge-modal-title').innerText = `Edit Bridge (${b.name})`;
  10830. document.getElementById('bridge-modal-id').value = b.id;
  10831. document.getElementById('bridge-modal-name').value = b.name;
  10832. document.getElementById('bridge-modal-name').disabled = true;
  10833. document.getElementById('bridge-modal-mtu').value = b.mtu || 1500;
  10834. document.getElementById('bridge-modal-mac').value = b.mac_address || '';
  10835. document.getElementById('bridge-modal-stp').value = b.stp || 'stp';
  10836. document.getElementById('bridge-modal-priority').value = b.priority || 32768;
  10837. document.getElementById('bridge-modal-vlanfiltering').checked = !!b.vlan_filtering;
  10838. document.getElementById('bridge-modal-pvid').value = b.pvid || 1;
  10839. document.getElementById('bridge-modal-fastforward').checked = b.fast_forward !== false;
  10840. document.getElementById('bridge-modal-comment').value = b.comment || '';
  10841. document.getElementById('bridge-modal-disabled').checked = !!b.disabled;
  10842. toggleBridgeModalVlanFiltering();
  10843. document.getElementById('bridge-modal').classList.remove('hidden');
  10844. }
  10845. function closeBridgeModal() {
  10846. document.getElementById('bridge-modal').classList.add('hidden');
  10847. }
  10848. function toggleBridgeModalVlanFiltering() {
  10849. const chk = document.getElementById('bridge-modal-vlanfiltering').checked;
  10850. const pvidBox = document.getElementById('bridge-modal-pvid-box');
  10851. if (pvidBox) {
  10852. if (chk) pvidBox.classList.remove('opacity-40');
  10853. else pvidBox.classList.add('opacity-40');
  10854. }
  10855. }
  10856. async function submitSaveBridge(e) {
  10857. e.preventDefault();
  10858. const id = document.getElementById('bridge-modal-id').value;
  10859. const name = document.getElementById('bridge-modal-name').value.trim();
  10860. const mtu = parseInt(document.getElementById('bridge-modal-mtu').value, 10) || 1500;
  10861. const mac = document.getElementById('bridge-modal-mac').value.trim();
  10862. const stp = document.getElementById('bridge-modal-stp').value;
  10863. const priority = parseInt(document.getElementById('bridge-modal-priority').value, 10) || 32768;
  10864. const vlanFiltering = document.getElementById('bridge-modal-vlanfiltering').checked;
  10865. const pvid = parseInt(document.getElementById('bridge-modal-pvid').value, 10) || 1;
  10866. const fastForward = document.getElementById('bridge-modal-fastforward').checked;
  10867. const comment = document.getElementById('bridge-modal-comment').value.trim();
  10868. const disabled = document.getElementById('bridge-modal-disabled').checked;
  10869. try {
  10870. const res = await fetch(`${API_BASE}/bridge/bridges`, {
  10871. method: 'POST',
  10872. headers: { 'Content-Type': 'application/json' },
  10873. body: JSON.stringify({
  10874. id,
  10875. name,
  10876. mtu,
  10877. mac_address: mac,
  10878. stp,
  10879. priority,
  10880. vlan_filtering: vlanFiltering,
  10881. pvid,
  10882. fast_forward: fastForward,
  10883. comment,
  10884. disabled
  10885. })
  10886. });
  10887. if (res.ok) {
  10888. showToast('Bridge Saved', `Bridge ${name} configured`, 'success');
  10889. closeBridgeModal();
  10890. loadBridge();
  10891. fetchData(false);
  10892. } else {
  10893. const err = await res.json();
  10894. showToast('Error', err.error || err.message || 'Failed to save bridge', 'error');
  10895. }
  10896. } catch (err) {
  10897. showToast('Error', err.message, 'error');
  10898. }
  10899. }
  10900. async function toggleBridgeState(id, disabled) {
  10901. try {
  10902. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/state`, {
  10903. method: 'POST',
  10904. headers: { 'Content-Type': 'application/json' },
  10905. body: JSON.stringify({ disabled })
  10906. });
  10907. if (res.ok) {
  10908. loadBridge();
  10909. fetchData(false);
  10910. }
  10911. } catch (err) {
  10912. showToast('Error', err.message, 'error');
  10913. }
  10914. }
  10915. async function deleteBridge(id) {
  10916. const b = (state.bridges || []).find(x => x.id === id);
  10917. const name = b ? b.name : id;
  10918. if (!confirm(`Are you sure you want to delete bridge '${name}'? All member ports will be detached.`)) return;
  10919. try {
  10920. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10921. if (res.ok) {
  10922. showToast('Deleted', `Bridge ${name} deleted`, 'success');
  10923. loadBridge();
  10924. fetchData(false);
  10925. } else {
  10926. const err = await res.json();
  10927. showToast('Error', err.error || err.message || 'Failed to delete bridge', 'error');
  10928. }
  10929. } catch (err) {
  10930. showToast('Error', err.message, 'error');
  10931. }
  10932. }
  10933. // ----------------- Bridge IP Assignments -----------------
  10934. function openAddBridgeIPModal(id, name) {
  10935. document.getElementById('bridge-ip-modal-id').value = id;
  10936. document.getElementById('bridge-ip-modal-sub').innerText = name;
  10937. document.getElementById('bridge-ip-modal-cidr').value = '';
  10938. document.getElementById('bridge-ip-modal').classList.remove('hidden');
  10939. }
  10940. function closeBridgeIPModal() {
  10941. document.getElementById('bridge-ip-modal').classList.add('hidden');
  10942. }
  10943. async function submitAddBridgeIP(e) {
  10944. e.preventDefault();
  10945. const id = document.getElementById('bridge-ip-modal-id').value;
  10946. const ip = document.getElementById('bridge-ip-modal-cidr').value.trim();
  10947. try {
  10948. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  10949. method: 'POST',
  10950. headers: { 'Content-Type': 'application/json' },
  10951. body: JSON.stringify({ ip })
  10952. });
  10953. if (res.ok) {
  10954. showToast('IP Assigned', `${ip} assigned to bridge`, 'success');
  10955. closeBridgeIPModal();
  10956. loadBridge();
  10957. fetchData(false);
  10958. } else {
  10959. const err = await res.json();
  10960. showToast('Error', err.error || err.message || 'Failed to add IP', 'error');
  10961. }
  10962. } catch (err) {
  10963. showToast('Error', err.message, 'error');
  10964. }
  10965. }
  10966. async function deleteBridgeIP(id, ip) {
  10967. if (!confirm(`Remove IP address ${ip} from bridge?`)) return;
  10968. try {
  10969. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  10970. method: 'DELETE',
  10971. headers: { 'Content-Type': 'application/json' },
  10972. body: JSON.stringify({ ip })
  10973. });
  10974. if (res.ok) {
  10975. showToast('IP Removed', `${ip} removed from bridge`, 'success');
  10976. loadBridge();
  10977. fetchData(false);
  10978. }
  10979. } catch (err) {
  10980. showToast('Error', err.message, 'error');
  10981. }
  10982. }
  10983. // ----------------- Bridge Ports -----------------
  10984. function renderBridgePorts() {
  10985. const tbody = document.getElementById('bridge-ports-table-body');
  10986. const empty = document.getElementById('bridge-empty-ports');
  10987. const countBadge = document.getElementById('bridge-ports-count-badge');
  10988. const filterBridge = document.getElementById('bridge-ports-filter-bridge')?.value || '';
  10989. if (!tbody) return;
  10990. tbody.innerHTML = '';
  10991. // Update filter select
  10992. populateBridgeSelect('bridge-ports-filter-bridge', filterBridge, true);
  10993. const ports = (state.bridgePorts || []).filter(p => !filterBridge || p.bridge === filterBridge);
  10994. if (countBadge) countBadge.innerText = `${ports.length} Ports`;
  10995. if (ports.length === 0) {
  10996. empty?.classList.remove('hidden');
  10997. return;
  10998. }
  10999. empty?.classList.add('hidden');
  11000. ports.forEach((p, idx) => {
  11001. const tr = document.createElement('tr');
  11002. tr.className = `hover:bg-slate-800/40 transition text-xs ${p.disabled ? 'opacity-50' : ''}`;
  11003. const disabledFlag = p.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  11004. tr.innerHTML = `
  11005. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  11006. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  11007. <td class="py-2.5 px-3 font-bold text-white text-sm">
  11008. <span class="text-emerald-400 mr-1.5">🔌</span>${p.interface}
  11009. </td>
  11010. <td class="py-2.5 px-3 font-semibold text-sky-400">${p.bridge}</td>
  11011. <td class="py-2.5 px-3 font-mono">${p.pvid || 1}</td>
  11012. <td class="py-2.5 px-3 text-slate-300">${p.frame_types}</td>
  11013. <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>
  11014. <td class="py-2.5 px-3">
  11015. ${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>'}
  11016. </td>
  11017. <td class="py-2.5 px-3">
  11018. <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>
  11019. </td>
  11020. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${p.comment || ''}">${p.comment || '-'}</td>
  11021. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  11022. <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>
  11023. <button onclick="openEditBridgePortModal('${p.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  11024. <button onclick="deleteBridgePort('${p.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  11025. </td>
  11026. `;
  11027. tbody.appendChild(tr);
  11028. });
  11029. }
  11030. function openAddBridgePortModal() {
  11031. document.getElementById('bridge-port-modal-title').innerText = 'Add Port to Bridge';
  11032. document.getElementById('bridge-port-modal-id').value = '';
  11033. populateBridgeSelect('bridge-port-modal-bridge');
  11034. populateBridgePortCandidateSelect('bridge-port-modal-interface');
  11035. document.getElementById('bridge-port-modal-pvid').value = '1';
  11036. document.getElementById('bridge-port-modal-frametypes').value = 'admit-all';
  11037. document.getElementById('bridge-port-modal-ingressfiltering').checked = false;
  11038. document.getElementById('bridge-port-modal-horizon').value = '0';
  11039. document.getElementById('bridge-port-modal-pathcost').value = '10';
  11040. document.getElementById('bridge-port-modal-priority').value = '128';
  11041. document.getElementById('bridge-port-modal-learn').checked = true;
  11042. document.getElementById('bridge-port-modal-comment').value = '';
  11043. document.getElementById('bridge-port-modal-disabled').checked = false;
  11044. document.getElementById('bridge-port-modal').classList.remove('hidden');
  11045. }
  11046. function openEditBridgePortModal(id) {
  11047. const p = (state.bridgePorts || []).find(x => x.id === id);
  11048. if (!p) return;
  11049. document.getElementById('bridge-port-modal-title').innerText = `Edit Bridge Port (${p.interface})`;
  11050. document.getElementById('bridge-port-modal-id').value = p.id;
  11051. populateBridgeSelect('bridge-port-modal-bridge', p.bridge);
  11052. populateBridgePortCandidateSelect('bridge-port-modal-interface', p.interface);
  11053. document.getElementById('bridge-port-modal-pvid').value = p.pvid || 1;
  11054. document.getElementById('bridge-port-modal-frametypes').value = p.frame_types || 'admit-all';
  11055. document.getElementById('bridge-port-modal-ingressfiltering').checked = !!p.ingress_filtering;
  11056. document.getElementById('bridge-port-modal-horizon').value = p.horizon || 0;
  11057. document.getElementById('bridge-port-modal-pathcost').value = p.path_cost || 10;
  11058. document.getElementById('bridge-port-modal-priority').value = p.priority || 128;
  11059. document.getElementById('bridge-port-modal-learn').checked = p.learn !== false;
  11060. document.getElementById('bridge-port-modal-comment').value = p.comment || '';
  11061. document.getElementById('bridge-port-modal-disabled').checked = !!p.disabled;
  11062. document.getElementById('bridge-port-modal').classList.remove('hidden');
  11063. }
  11064. function closeBridgePortModal() {
  11065. document.getElementById('bridge-port-modal').classList.add('hidden');
  11066. }
  11067. async function submitSaveBridgePort(e) {
  11068. e.preventDefault();
  11069. const id = document.getElementById('bridge-port-modal-id').value;
  11070. const bridge = document.getElementById('bridge-port-modal-bridge').value;
  11071. const iface = document.getElementById('bridge-port-modal-interface').value;
  11072. const pvid = parseInt(document.getElementById('bridge-port-modal-pvid').value, 10) || 1;
  11073. const frameTypes = document.getElementById('bridge-port-modal-frametypes').value;
  11074. const ingressFiltering = document.getElementById('bridge-port-modal-ingressfiltering').checked;
  11075. const horizon = parseInt(document.getElementById('bridge-port-modal-horizon').value, 10) || 0;
  11076. const pathCost = parseInt(document.getElementById('bridge-port-modal-pathcost').value, 10) || 10;
  11077. const priority = parseInt(document.getElementById('bridge-port-modal-priority').value, 10) || 128;
  11078. const learn = document.getElementById('bridge-port-modal-learn').checked;
  11079. const comment = document.getElementById('bridge-port-modal-comment').value.trim();
  11080. const disabled = document.getElementById('bridge-port-modal-disabled').checked;
  11081. try {
  11082. const res = await fetch(`${API_BASE}/bridge/ports`, {
  11083. method: 'POST',
  11084. headers: { 'Content-Type': 'application/json' },
  11085. body: JSON.stringify({
  11086. id,
  11087. bridge,
  11088. interface: iface,
  11089. pvid,
  11090. frame_types: frameTypes,
  11091. ingress_filtering: ingressFiltering,
  11092. horizon,
  11093. path_cost: pathCost,
  11094. priority,
  11095. learn,
  11096. comment,
  11097. disabled
  11098. })
  11099. });
  11100. if (res.ok) {
  11101. showToast('Port Attached', `${iface} added to ${bridge}`, 'success');
  11102. closeBridgePortModal();
  11103. loadBridge();
  11104. fetchData(false);
  11105. } else {
  11106. const err = await res.json();
  11107. showToast('Error', err.error || err.message || 'Failed to save port', 'error');
  11108. }
  11109. } catch (err) {
  11110. showToast('Error', err.message, 'error');
  11111. }
  11112. }
  11113. async function toggleBridgePortState(id, disabled) {
  11114. try {
  11115. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}/state`, {
  11116. method: 'POST',
  11117. headers: { 'Content-Type': 'application/json' },
  11118. body: JSON.stringify({ disabled })
  11119. });
  11120. if (res.ok) {
  11121. loadBridge();
  11122. fetchData(false);
  11123. }
  11124. } catch (err) {
  11125. showToast('Error', err.message, 'error');
  11126. }
  11127. }
  11128. async function deleteBridgePort(id) {
  11129. const p = (state.bridgePorts || []).find(x => x.id === id);
  11130. const iface = p ? p.interface : id;
  11131. if (!confirm(`Detach interface '${iface}' from bridge?`)) return;
  11132. try {
  11133. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11134. if (res.ok) {
  11135. showToast('Port Detached', `${iface} removed from bridge`, 'success');
  11136. loadBridge();
  11137. fetchData(false);
  11138. }
  11139. } catch (err) {
  11140. showToast('Error', err.message, 'error');
  11141. }
  11142. }
  11143. // ----------------- Bridge VLANs -----------------
  11144. function renderBridgeVLANs() {
  11145. const tbody = document.getElementById('bridge-vlans-table-body');
  11146. const empty = document.getElementById('bridge-empty-vlans');
  11147. const countBadge = document.getElementById('bridge-vlans-count-badge');
  11148. const filterBridge = document.getElementById('bridge-vlans-filter-bridge')?.value || '';
  11149. if (!tbody) return;
  11150. tbody.innerHTML = '';
  11151. populateBridgeSelect('bridge-vlans-filter-bridge', filterBridge, true);
  11152. const vlans = (state.bridgeVLANs || []).filter(v => !filterBridge || v.bridge === filterBridge);
  11153. if (countBadge) countBadge.innerText = `${vlans.length} Entries`;
  11154. if (vlans.length === 0) {
  11155. empty?.classList.remove('hidden');
  11156. return;
  11157. }
  11158. empty?.classList.add('hidden');
  11159. vlans.forEach((v, idx) => {
  11160. const tr = document.createElement('tr');
  11161. tr.className = `hover:bg-slate-800/40 transition text-xs ${v.disabled ? 'opacity-50' : ''}`;
  11162. const taggedHtml = (v.tagged && v.tagged.length > 0)
  11163. ? 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(' ')
  11164. : '<span class="text-slate-600">none</span>';
  11165. const untaggedHtml = (v.untagged && v.untagged.length > 0)
  11166. ? 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(' ')
  11167. : '<span class="text-slate-600">none</span>';
  11168. const disabledFlag = v.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  11169. tr.innerHTML = `
  11170. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  11171. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  11172. <td class="py-2.5 px-3 font-semibold text-sky-400">${v.bridge}</td>
  11173. <td class="py-2.5 px-3 font-bold text-white font-mono text-sm">${v.vlan_ids}</td>
  11174. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${taggedHtml}</div></td>
  11175. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${untaggedHtml}</div></td>
  11176. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${v.comment || ''}">${v.comment || '-'}</td>
  11177. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  11178. <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>
  11179. <button onclick="openEditBridgeVLANModal('${v.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  11180. <button onclick="deleteBridgeVLAN('${v.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  11181. </td>
  11182. `;
  11183. tbody.appendChild(tr);
  11184. });
  11185. }
  11186. function openAddBridgeVLANModal() {
  11187. document.getElementById('bridge-vlan-modal-title').innerText = 'Add Bridge VLAN Entry';
  11188. document.getElementById('bridge-vlan-modal-id').value = '';
  11189. populateBridgeSelect('bridge-vlan-modal-bridge');
  11190. document.getElementById('bridge-vlan-modal-vlanids').value = '';
  11191. document.getElementById('bridge-vlan-modal-comment').value = '';
  11192. document.getElementById('bridge-vlan-modal-disabled').checked = false;
  11193. updateBridgeVlanPortCheckboxes();
  11194. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  11195. }
  11196. function openEditBridgeVLANModal(id) {
  11197. const v = (state.bridgeVLANs || []).find(x => x.id === id);
  11198. if (!v) return;
  11199. document.getElementById('bridge-vlan-modal-title').innerText = `Edit Bridge VLAN (${v.vlan_ids})`;
  11200. document.getElementById('bridge-vlan-modal-id').value = v.id;
  11201. populateBridgeSelect('bridge-vlan-modal-bridge', v.bridge);
  11202. document.getElementById('bridge-vlan-modal-vlanids').value = v.vlan_ids;
  11203. document.getElementById('bridge-vlan-modal-comment').value = v.comment || '';
  11204. document.getElementById('bridge-vlan-modal-disabled').checked = !!v.disabled;
  11205. updateBridgeVlanPortCheckboxes(v.tagged || [], v.untagged || []);
  11206. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  11207. }
  11208. function closeBridgeVlanModal() {
  11209. document.getElementById('bridge-vlan-modal').classList.add('hidden');
  11210. }
  11211. function updateBridgeVlanPortCheckboxes(taggedSelected = [], untaggedSelected = []) {
  11212. const selBridge = document.getElementById('bridge-vlan-modal-bridge')?.value || '';
  11213. const taggedBox = document.getElementById('bridge-vlan-tagged-ports');
  11214. const untaggedBox = document.getElementById('bridge-vlan-untagged-ports');
  11215. if (!taggedBox || !untaggedBox) return;
  11216. // Ports belonging to the selected bridge
  11217. const memberPorts = (state.bridgePorts || []).filter(p => !selBridge || p.bridge === selBridge);
  11218. if (memberPorts.length === 0) {
  11219. taggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  11220. untaggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  11221. return;
  11222. }
  11223. taggedBox.innerHTML = memberPorts.map(p => `
  11224. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  11225. <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">
  11226. <span>${p.interface}</span>
  11227. </label>
  11228. `).join('');
  11229. untaggedBox.innerHTML = memberPorts.map(p => `
  11230. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  11231. <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">
  11232. <span>${p.interface}</span>
  11233. </label>
  11234. `).join('');
  11235. }
  11236. async function submitSaveBridgeVLAN(e) {
  11237. e.preventDefault();
  11238. const id = document.getElementById('bridge-vlan-modal-id').value;
  11239. const bridge = document.getElementById('bridge-vlan-modal-bridge').value;
  11240. const vlanIDs = document.getElementById('bridge-vlan-modal-vlanids').value.trim();
  11241. const comment = document.getElementById('bridge-vlan-modal-comment').value.trim();
  11242. const disabled = document.getElementById('bridge-vlan-modal-disabled').checked;
  11243. const tagged = Array.from(document.querySelectorAll('input[name="bvlan-tagged"]:checked')).map(x => x.value);
  11244. const untagged = Array.from(document.querySelectorAll('input[name="bvlan-untagged"]:checked')).map(x => x.value);
  11245. try {
  11246. const res = await fetch(`${API_BASE}/bridge/vlans`, {
  11247. method: 'POST',
  11248. headers: { 'Content-Type': 'application/json' },
  11249. body: JSON.stringify({
  11250. id,
  11251. bridge,
  11252. vlan_ids: vlanIDs,
  11253. tagged,
  11254. untagged,
  11255. comment,
  11256. disabled
  11257. })
  11258. });
  11259. if (res.ok) {
  11260. showToast('VLAN Entry Saved', `VLAN ${vlanIDs} configured on ${bridge}`, 'success');
  11261. closeBridgeVlanModal();
  11262. loadBridge();
  11263. } else {
  11264. const err = await res.json();
  11265. showToast('Error', err.error || err.message || 'Failed to save VLAN entry', 'error');
  11266. }
  11267. } catch (err) {
  11268. showToast('Error', err.message, 'error');
  11269. }
  11270. }
  11271. async function toggleBridgeVLANState(id, disabled) {
  11272. try {
  11273. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}/state`, {
  11274. method: 'POST',
  11275. headers: { 'Content-Type': 'application/json' },
  11276. body: JSON.stringify({ disabled })
  11277. });
  11278. if (res.ok) loadBridge();
  11279. } catch (err) {
  11280. showToast('Error', err.message, 'error');
  11281. }
  11282. }
  11283. async function deleteBridgeVLAN(id) {
  11284. if (!confirm('Delete this bridge VLAN entry?')) return;
  11285. try {
  11286. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11287. if (res.ok) {
  11288. showToast('Deleted', 'VLAN entry removed from bridge', 'success');
  11289. loadBridge();
  11290. }
  11291. } catch (err) {
  11292. showToast('Error', err.message, 'error');
  11293. }
  11294. }
  11295. // ----------------- Hosts / MAC Table -----------------
  11296. async function loadBridgeHosts() {
  11297. const filterBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || '';
  11298. populateBridgeSelect('bridge-hosts-filter-bridge', filterBridge, true);
  11299. try {
  11300. const url = filterBridge ? `${API_BASE}/bridge/hosts?bridge=${encodeURIComponent(filterBridge)}` : `${API_BASE}/bridge/hosts`;
  11301. const res = await fetch(url);
  11302. if (res.ok) {
  11303. state.bridgeHosts = await res.json();
  11304. renderBridgeHosts();
  11305. }
  11306. } catch (err) {
  11307. console.error('Failed to load bridge hosts:', err);
  11308. }
  11309. }
  11310. function renderBridgeHosts() {
  11311. const tbody = document.getElementById('bridge-hosts-table-body');
  11312. const empty = document.getElementById('bridge-empty-hosts');
  11313. const countBadge = document.getElementById('bridge-hosts-count-badge');
  11314. const search = (document.getElementById('bridge-hosts-search')?.value || '').toLowerCase().trim();
  11315. if (!tbody) return;
  11316. tbody.innerHTML = '';
  11317. const hosts = (state.bridgeHosts || []).filter(h => {
  11318. if (!search) return true;
  11319. return (h.mac || '').toLowerCase().includes(search) || (h.interface || '').toLowerCase().includes(search) || (h.bridge || '').toLowerCase().includes(search);
  11320. });
  11321. if (countBadge) countBadge.innerText = `${hosts.length} Hosts`;
  11322. if (hosts.length === 0) {
  11323. empty?.classList.remove('hidden');
  11324. return;
  11325. }
  11326. empty?.classList.add('hidden');
  11327. hosts.forEach(h => {
  11328. const tr = document.createElement('tr');
  11329. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  11330. let flagBadges = '';
  11331. 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>';
  11332. 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>';
  11333. 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>';
  11334. tr.innerHTML = `
  11335. <td class="py-2.5 px-3 font-mono font-bold text-white text-sm">${h.mac}</td>
  11336. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${h.interface || '-'}</td>
  11337. <td class="py-2.5 px-3 font-mono text-sky-400">${h.bridge || '-'}</td>
  11338. <td class="py-2.5 px-3 font-mono">${h.vlan_id || 1}</td>
  11339. <td class="py-2.5 px-3 font-mono text-slate-400">${h.age ? h.age.toFixed(1) + 's' : '-'}</td>
  11340. <td class="py-2.5 px-3">${flagBadges}</td>
  11341. `;
  11342. tbody.appendChild(tr);
  11343. });
  11344. }
  11345. async function flushBridgeHosts() {
  11346. const selBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || (state.bridges[0] ? state.bridges[0].name : '');
  11347. if (!selBridge) {
  11348. showToast('Notice', 'Please select a bridge to flush dynamic MACs', 'info');
  11349. return;
  11350. }
  11351. if (!confirm(`Flush all dynamic learned MAC addresses on bridge '${selBridge}'?`)) return;
  11352. try {
  11353. const res = await fetch(`${API_BASE}/bridge/hosts/flush`, {
  11354. method: 'POST',
  11355. headers: { 'Content-Type': 'application/json' },
  11356. body: JSON.stringify({ bridge: selBridge })
  11357. });
  11358. if (res.ok) {
  11359. showToast('FDB Flushed', `Dynamic MACs flushed on ${selBridge}`, 'success');
  11360. loadBridgeHosts();
  11361. }
  11362. } catch (err) {
  11363. showToast('Error', err.message, 'error');
  11364. }
  11365. }
  11366. // ----------------- Helpers -----------------
  11367. function populateBridgeSelect(selectId, currentVal = '', includeAll = false) {
  11368. const sel = document.getElementById(selectId);
  11369. if (!sel) return;
  11370. const prevVal = currentVal || sel.value;
  11371. sel.innerHTML = includeAll ? '<option value="">All Bridges</option>' : '';
  11372. (state.bridges || []).forEach(b => {
  11373. const opt = document.createElement('option');
  11374. opt.value = b.name;
  11375. opt.innerText = `${b.name} (${b.ports_count} ports)`;
  11376. if (b.name === prevVal) opt.selected = true;
  11377. sel.appendChild(opt);
  11378. });
  11379. }
  11380. function populateBridgePortCandidateSelect(selectId, currentVal = '') {
  11381. const sel = document.getElementById(selectId);
  11382. if (!sel) return;
  11383. sel.innerHTML = '<option value="">(Select Interface...)</option>';
  11384. // 1. Physical Interfaces
  11385. const grpPhys = document.createElement('optgroup');
  11386. grpPhys.label = 'Physical Interfaces';
  11387. (state.interfaces || []).filter(i => i.type !== 'bridge' && i.type !== 'vlan' && i.type !== 'loopback').forEach(i => {
  11388. const opt = document.createElement('option');
  11389. opt.value = i.name;
  11390. opt.innerText = `${i.name} (${i.role || i.type})`;
  11391. if (i.name === currentVal) opt.selected = true;
  11392. grpPhys.appendChild(opt);
  11393. });
  11394. if (grpPhys.children.length > 0) sel.appendChild(grpPhys);
  11395. // 2. VLAN Sub-interfaces
  11396. const grpVlans = document.createElement('optgroup');
  11397. grpVlans.label = 'VLAN Sub-interfaces (802.1Q)';
  11398. (state.vlans || []).forEach(v => {
  11399. const opt = document.createElement('option');
  11400. opt.value = v.name;
  11401. opt.innerText = `${v.name} (VLAN ${v.vlan_id})`;
  11402. if (v.name === currentVal) opt.selected = true;
  11403. grpVlans.appendChild(opt);
  11404. });
  11405. if (grpVlans.children.length > 0) sel.appendChild(grpVlans);
  11406. // 3. EoIP Tunnels (MikroTik EoIP bridging!)
  11407. const grpEoip = document.createElement('optgroup');
  11408. grpEoip.label = 'EoIP Tunnels (Layer 2 VPN)';
  11409. (state.eoipTunnels || []).forEach(t => {
  11410. const opt = document.createElement('option');
  11411. opt.value = t.name;
  11412. opt.innerText = `${t.name} (Tunnel ID: ${t.tunnel_id} -> ${t.remote_address})`;
  11413. if (t.name === currentVal) opt.selected = true;
  11414. grpEoip.appendChild(opt);
  11415. });
  11416. if (grpEoip.children.length > 0) sel.appendChild(grpEoip);
  11417. // 4. VXLAN Tunnels (MikroTik VXLAN bridging!)
  11418. const grpVxlan = document.createElement('optgroup');
  11419. grpVxlan.label = 'VXLAN Tunnels (Layer 2 Overlay)';
  11420. (state.vxlanTunnels || []).forEach(t => {
  11421. const opt = document.createElement('option');
  11422. opt.value = t.name;
  11423. opt.innerText = `${t.name} (VNI: ${t.vni}, Port: ${t.port})`;
  11424. if (t.name === currentVal) opt.selected = true;
  11425. grpVxlan.appendChild(opt);
  11426. });
  11427. if (grpVxlan.children.length > 0) sel.appendChild(grpVxlan);
  11428. }
  11429. // -------------------------------------------------------------
  11430. // DebTik Routing Filters Management (/routing filter)
  11431. // -------------------------------------------------------------
  11432. if (!state.activeRoutingFilterTab) state.activeRoutingFilterTab = 'rules';
  11433. if (!state.selectedFilterRow) state.selectedFilterRow = {};
  11434. if (!state.rfSort) state.rfSort = {};
  11435. function switchRoutingFilterTab(tab) {
  11436. state.activeRoutingFilterTab = tab;
  11437. const tabs = ['rules', 'community-lists', 'as-lists'];
  11438. tabs.forEach(t => {
  11439. const btn = document.getElementById(`tab-rf-${t}`);
  11440. const content = document.getElementById(`tab-content-rf-${t}`);
  11441. if (btn) {
  11442. if (t === tab) {
  11443. 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';
  11444. } else {
  11445. btn.className = 'px-3 py-1 text-xs font-semibold rounded text-slate-400 hover:text-white hover:bg-slate-800 transition';
  11446. }
  11447. }
  11448. if (content) {
  11449. if (t === tab) content.classList.remove('hidden');
  11450. else content.classList.add('hidden');
  11451. }
  11452. });
  11453. const chainContainer = document.getElementById('rf-chain-filter-container');
  11454. if (chainContainer) {
  11455. if (tab === 'rules') chainContainer.classList.remove('hidden');
  11456. else chainContainer.classList.add('hidden');
  11457. }
  11458. renderRoutingFilters();
  11459. }
  11460. function selectFilterRow(tab, id) {
  11461. if (state.selectedFilterRow[tab] === id) {
  11462. delete state.selectedFilterRow[tab];
  11463. } else {
  11464. state.selectedFilterRow[tab] = id;
  11465. }
  11466. if (tab === 'rules') renderRoutingFilterRules();
  11467. else if (tab === 'community-lists') renderRoutingFilterCommunityLists();
  11468. else if (tab === 'as-lists') renderRoutingFilterASLists();
  11469. }
  11470. function openRoutingFilterNewModal() {
  11471. const tab = state.activeRoutingFilterTab || 'rules';
  11472. if (tab === 'rules') openAddRoutingFilterModal();
  11473. else if (tab === 'community-lists') openAddCommunityListModal();
  11474. else if (tab === 'as-lists') openAddASListModal();
  11475. }
  11476. function toggleSelectedRoutingFilter(disabled) {
  11477. const tab = state.activeRoutingFilterTab || 'rules';
  11478. const id = state.selectedFilterRow[tab];
  11479. if (!id) {
  11480. showToast('Select Row', 'Please click on a row to select it first', 'info');
  11481. return;
  11482. }
  11483. if (tab === 'rules') toggleRoutingFilterState(id, disabled);
  11484. else if (tab === 'community-lists') toggleCommunityListState(id, disabled);
  11485. else if (tab === 'as-lists') toggleASListState(id, disabled);
  11486. }
  11487. function removeSelectedRoutingFilter() {
  11488. const tab = state.activeRoutingFilterTab || 'rules';
  11489. const id = state.selectedFilterRow[tab];
  11490. if (!id) {
  11491. showToast('Select Row', 'Please click on a row to select it first', 'info');
  11492. return;
  11493. }
  11494. if (tab === 'rules') deleteRoutingFilter(id);
  11495. else if (tab === 'community-lists') deleteCommunityList(id);
  11496. else if (tab === 'as-lists') deleteASList(id);
  11497. }
  11498. function searchRoutingFilters(q) {
  11499. state.rfSearchQuery = (q || '').trim().toLowerCase();
  11500. renderRoutingFilters();
  11501. }
  11502. function sortFilterTable(tab, col) {
  11503. if (!state.rfSort) state.rfSort = {};
  11504. if (!state.rfSort[tab]) state.rfSort[tab] = { col: col, asc: true };
  11505. if (state.rfSort[tab].col === col) {
  11506. state.rfSort[tab].asc = !state.rfSort[tab].asc;
  11507. } else {
  11508. state.rfSort[tab].col = col;
  11509. state.rfSort[tab].asc = true;
  11510. }
  11511. const asc = state.rfSort[tab].asc;
  11512. let list = [];
  11513. if (tab === 'rules') list = state.routingFilters || [];
  11514. else if (tab === 'community-lists') list = state.routingCommunityLists || [];
  11515. else if (tab === 'as-lists') list = state.routingASLists || [];
  11516. list.sort((a, b) => {
  11517. let valA = a[col] ?? '';
  11518. let valB = b[col] ?? '';
  11519. if (col === 'flags') {
  11520. valA = a.disabled ? 'X' : 'A';
  11521. valB = b.disabled ? 'X' : 'A';
  11522. }
  11523. if (typeof valA === 'number' && typeof valB === 'number') {
  11524. return asc ? valA - valB : valB - valA;
  11525. }
  11526. return asc ? String(valA).localeCompare(String(valB)) : String(valB).localeCompare(String(valA));
  11527. });
  11528. const allCols = ['flags', 'rule_order', 'chain', 'rule', 'name', 'communities', 'range', 'regexp', 'comment'];
  11529. allCols.forEach(c => {
  11530. const el = document.getElementById(`sort-icon-${tab}-${c}`);
  11531. if (el) el.innerText = (c === col) ? (asc ? '▲' : '▼') : '';
  11532. });
  11533. if (tab === 'rules') renderRoutingFilterRules();
  11534. else if (tab === 'community-lists') renderRoutingFilterCommunityLists();
  11535. else if (tab === 'as-lists') renderRoutingFilterASLists();
  11536. }
  11537. function renderRoutingFilters() {
  11538. const navBadge = document.getElementById('badge-filters-count');
  11539. const allRules = state.routingFilters || [];
  11540. if (navBadge) navBadge.innerText = allRules.length;
  11541. // Populate chain filter select options and datalist
  11542. const chainSelect = document.getElementById('routing-filter-chain-select');
  11543. const chainDatalist = document.getElementById('dl-routing-chains');
  11544. const uniqueChains = Array.from(new Set(allRules.map(r => r.chain).filter(Boolean))).sort();
  11545. if (chainSelect) {
  11546. const currentVal = state.filterChainSelected || 'all';
  11547. chainSelect.innerHTML = `<option value="all">All Chains (${allRules.length})</option>` +
  11548. uniqueChains.map(ch => {
  11549. const count = allRules.filter(r => r.chain === ch).length;
  11550. return `<option value="${escapeHtml(ch)}"${currentVal === ch ? ' selected' : ''}>${escapeHtml(ch)} (${count})</option>`;
  11551. }).join('');
  11552. chainSelect.value = currentVal;
  11553. }
  11554. if (chainDatalist) {
  11555. chainDatalist.innerHTML = uniqueChains.map(ch => `<option value="${escapeHtml(ch)}">`).join('');
  11556. }
  11557. renderRoutingFilterRules();
  11558. renderRoutingFilterCommunityLists();
  11559. renderRoutingFilterASLists();
  11560. }
  11561. function filterRoutingFiltersByChain(chain) {
  11562. state.filterChainSelected = chain;
  11563. renderRoutingFilters();
  11564. }
  11565. // -------------------------------------------------------------
  11566. // TAB 1: RULES (/routing filter rule)
  11567. // -------------------------------------------------------------
  11568. function renderRoutingFilterRules() {
  11569. const tbody = document.getElementById('routing-filter-rules-tbody');
  11570. if (!tbody) return;
  11571. const empty = document.getElementById('rf-rules-empty');
  11572. const statusCount = document.getElementById('rf-status-count');
  11573. let list = (state.routingFilters || []).slice();
  11574. if (state.filterChainSelected && state.filterChainSelected !== 'all') {
  11575. list = list.filter(r => r.chain === state.filterChainSelected);
  11576. }
  11577. const q = state.rfSearchQuery;
  11578. if (q) {
  11579. list = list.filter(r =>
  11580. (r.chain && r.chain.toLowerCase().includes(q)) ||
  11581. (r.rule && r.rule.toLowerCase().includes(q)) ||
  11582. (r.prefix && r.prefix.toLowerCase().includes(q)) ||
  11583. (r.comment && r.comment.toLowerCase().includes(q))
  11584. );
  11585. }
  11586. if (!state.rfSort?.['rules']) {
  11587. list.sort((a, b) => {
  11588. if (a.chain !== b.chain) return (a.chain || '').localeCompare(b.chain || '');
  11589. return (a.rule_order || 0) - (b.rule_order || 0);
  11590. });
  11591. }
  11592. if (statusCount && (state.activeRoutingFilterTab === 'rules' || !state.activeRoutingFilterTab)) {
  11593. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  11594. }
  11595. if (list.length === 0) {
  11596. tbody.innerHTML = '';
  11597. if (empty) empty.classList.remove('hidden');
  11598. return;
  11599. }
  11600. if (empty) empty.classList.add('hidden');
  11601. tbody.innerHTML = list.map(r => {
  11602. const isSelected = state.selectedFilterRow?.['rules'] === r.id;
  11603. const flagA = !r.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  11604. const flagX = r.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  11605. const flagC = r.comment ? '<span class="text-amber-400 font-bold ml-1" title="Comment">C</span>' : '';
  11606. let ruleDisplay = '';
  11607. if (r.rule && r.rule.trim() !== '') {
  11608. ruleDisplay = `<span class="text-emerald-400 font-mono font-medium">${escapeHtml(r.rule)}</span>`;
  11609. } else {
  11610. let conds = [];
  11611. if (r.prefix) conds.push(`dst in ${escapeHtml(r.prefix)}`);
  11612. if (r.match_protocol && r.match_protocol !== 'any') conds.push(`protocol ${escapeHtml(r.match_protocol)}`);
  11613. let act = r.action || 'accept';
  11614. ruleDisplay = `<span class="text-slate-300 font-mono">if (${conds.length ? conds.join(' && ') : 'true'}) { ${escapeHtml(act)}; }</span>`;
  11615. }
  11616. return `
  11617. <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'}">
  11618. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}${flagC}</td>
  11619. <td class="py-2 px-2 font-mono text-slate-400 font-bold">${r.rule_order || 10}</td>
  11620. <td class="py-2 px-3">
  11621. <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>
  11622. </td>
  11623. <td class="py-2 px-3 break-all max-w-xl">${ruleDisplay}</td>
  11624. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(r.comment || '')}</td>
  11625. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  11626. <button onclick="moveRoutingFilterOrder('${r.id}', -1)" title="Move Up" class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 hover:bg-slate-700 text-slate-300 border border-slate-700">▲</button>
  11627. <button onclick="moveRoutingFilterOrder('${r.id}', 1)" title="Move Down" class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 hover:bg-slate-700 text-slate-300 border border-slate-700">▼</button>
  11628. <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'}">
  11629. ${r.disabled ? 'Enable' : 'Disable'}
  11630. </button>
  11631. <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">
  11632. Edit
  11633. </button>
  11634. <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">
  11635. ✕
  11636. </button>
  11637. </td>
  11638. </tr>
  11639. `;
  11640. }).join('');
  11641. }
  11642. // -------------------------------------------------------------
  11643. // TAB 2: COMMUNITY LISTS (/routing filter community-list)
  11644. // -------------------------------------------------------------
  11645. function renderRoutingFilterCommunityLists() {
  11646. const tbody = document.getElementById('routing-filter-comm-lists-tbody');
  11647. if (!tbody) return;
  11648. const empty = document.getElementById('rf-comm-lists-empty');
  11649. const statusCount = document.getElementById('rf-status-count');
  11650. let list = (state.routingCommunityLists || []).slice();
  11651. const q = state.rfSearchQuery;
  11652. if (q) {
  11653. list = list.filter(cl =>
  11654. (cl.name && cl.name.toLowerCase().includes(q)) ||
  11655. (cl.comment && cl.comment.toLowerCase().includes(q)) ||
  11656. (cl.communities && cl.communities.some(c => c.toLowerCase().includes(q)))
  11657. );
  11658. }
  11659. if (statusCount && state.activeRoutingFilterTab === 'community-lists') {
  11660. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  11661. }
  11662. if (list.length === 0) {
  11663. tbody.innerHTML = '';
  11664. if (empty) empty.classList.remove('hidden');
  11665. return;
  11666. }
  11667. if (empty) empty.classList.add('hidden');
  11668. tbody.innerHTML = list.map(cl => {
  11669. const isSelected = state.selectedFilterRow?.['community-lists'] === cl.id;
  11670. const flagA = !cl.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  11671. const flagX = cl.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  11672. const commBadges = (cl.communities || []).map(c =>
  11673. `<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>`
  11674. ).join(' ');
  11675. return `
  11676. <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'}">
  11677. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  11678. <td class="py-2 px-3 font-mono font-bold text-white">${escapeHtml(cl.name)}</td>
  11679. <td class="py-2 px-3 space-x-1">${commBadges || '<span class="text-slate-600">-</span>'}</td>
  11680. <td class="py-2 px-3 font-mono text-slate-400">${escapeHtml(cl.regexp || '-')}</td>
  11681. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(cl.comment || '')}</td>
  11682. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  11683. <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'}">
  11684. ${cl.disabled ? 'Enable' : 'Disable'}
  11685. </button>
  11686. <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">
  11687. Edit
  11688. </button>
  11689. <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">
  11690. ✕
  11691. </button>
  11692. </td>
  11693. </tr>
  11694. `;
  11695. }).join('');
  11696. }
  11697. // -------------------------------------------------------------
  11698. // TAB 4: AS LISTS (/routing filter num-list)
  11699. // -------------------------------------------------------------
  11700. function renderRoutingFilterASLists() {
  11701. const tbody = document.getElementById('routing-filter-as-lists-tbody');
  11702. if (!tbody) return;
  11703. const empty = document.getElementById('rf-as-lists-empty');
  11704. const statusCount = document.getElementById('rf-status-count');
  11705. let list = (state.routingASLists || []).slice();
  11706. const q = state.rfSearchQuery;
  11707. if (q) {
  11708. list = list.filter(al =>
  11709. (al.name && al.name.toLowerCase().includes(q)) ||
  11710. (al.range && al.range.toLowerCase().includes(q)) ||
  11711. (al.comment && al.comment.toLowerCase().includes(q))
  11712. );
  11713. }
  11714. if (statusCount && state.activeRoutingFilterTab === 'as-lists') {
  11715. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  11716. }
  11717. if (list.length === 0) {
  11718. tbody.innerHTML = '';
  11719. if (empty) empty.classList.remove('hidden');
  11720. return;
  11721. }
  11722. if (empty) empty.classList.add('hidden');
  11723. tbody.innerHTML = list.map(al => {
  11724. const isSelected = state.selectedFilterRow?.['as-lists'] === al.id;
  11725. const flagA = !al.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  11726. const flagX = al.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  11727. return `
  11728. <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'}">
  11729. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  11730. <td class="py-2 px-3 font-mono font-bold text-white">${escapeHtml(al.name)}</td>
  11731. <td class="py-2 px-3 font-mono text-purple-300">${escapeHtml(al.range)}</td>
  11732. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(al.comment || '')}</td>
  11733. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  11734. <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'}">
  11735. ${al.disabled ? 'Enable' : 'Disable'}
  11736. </button>
  11737. <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">
  11738. Edit
  11739. </button>
  11740. <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">
  11741. ✕
  11742. </button>
  11743. </td>
  11744. </tr>
  11745. `;
  11746. }).join('');
  11747. }
  11748. // -------------------------------------------------------------
  11749. // SNIPPETS & WIZARD HELPERS
  11750. // -------------------------------------------------------------
  11751. function insertRuleSnippet(type) {
  11752. const textarea = document.getElementById('modal-rf-rule');
  11753. if (!textarea) return;
  11754. let snippet = '';
  11755. switch (type) {
  11756. case 'accept-default':
  11757. snippet = 'if (dst in 0.0.0.0/0) { accept; }';
  11758. break;
  11759. case 'drop-rfc1918':
  11760. snippet = 'if (dst in 10.0.0.0/8 || dst in 172.16.0.0/12 || dst in 192.168.0.0/16) { reject; }';
  11761. break;
  11762. case 'len-24':
  11763. snippet = 'if (dst-len > 24) { reject; }';
  11764. break;
  11765. case 'local-pref-150':
  11766. snippet = 'if (dst in 10.0.0.0/8) { set bgp-local-pref 150; accept; }';
  11767. break;
  11768. case 'as-prepend-2':
  11769. snippet = 'set bgp-path-prepend 2; accept;';
  11770. break;
  11771. case 'set-comm':
  11772. snippet = 'set bgp-communities.add 65000:100; accept;';
  11773. break;
  11774. case 'match-comm':
  11775. snippet = 'if (bgp-communities includes 65000:100) { accept; }';
  11776. break;
  11777. case 'reject-all':
  11778. snippet = 'reject;';
  11779. break;
  11780. }
  11781. if (!snippet) return;
  11782. if (!textarea.value.trim()) {
  11783. textarea.value = snippet;
  11784. } else {
  11785. textarea.value = textarea.value.trim() + '\n' + snippet;
  11786. }
  11787. }
  11788. function generateScriptFromWizard() {
  11789. const pfx = (document.getElementById('modal-rf-prefix')?.value || '').trim();
  11790. const pfxLen = (document.getElementById('modal-rf-prefix-len')?.value || '').trim();
  11791. const proto = document.getElementById('modal-rf-protocol')?.value || 'any';
  11792. const asp = (document.getElementById('modal-rf-as-path')?.value || '').trim();
  11793. const comm = (document.getElementById('modal-rf-community')?.value || '').trim();
  11794. const act = document.getElementById('modal-rf-action')?.value || 'accept';
  11795. const lp = parseInt(document.getElementById('modal-rf-set-local-pref')?.value, 10) || 0;
  11796. const prep = parseInt(document.getElementById('modal-rf-set-as-prepend')?.value, 10) || 0;
  11797. const conds = [];
  11798. if (pfx) {
  11799. if (pfxLen) {
  11800. if (pfxLen.includes('-')) {
  11801. const parts = pfxLen.split('-');
  11802. conds.push(`dst in ${pfx}{${parts[0].trim()},${parts[1].trim()}}`);
  11803. } else {
  11804. conds.push(`dst in ${pfx} && dst-len >= ${pfxLen}`);
  11805. }
  11806. } else {
  11807. conds.push(`dst in ${pfx}`);
  11808. }
  11809. }
  11810. if (proto && proto !== 'any') {
  11811. conds.push(`protocol ${proto}`);
  11812. }
  11813. if (asp) {
  11814. conds.push(`bgp-as-path "${asp}"`);
  11815. }
  11816. if (comm) {
  11817. conds.push(`bgp-communities includes ${comm}`);
  11818. }
  11819. const actions = [];
  11820. if (lp > 0) actions.push(`set bgp-local-pref ${lp};`);
  11821. if (prep > 0) actions.push(`set bgp-path-prepend ${prep};`);
  11822. if (act && act !== 'passthrough') {
  11823. actions.push(`${act};`);
  11824. }
  11825. let code = '';
  11826. if (conds.length > 0) {
  11827. code = `if (${conds.join(' && ')}) {\n ${actions.join(' ')}\n}`;
  11828. } else {
  11829. code = actions.join(' ');
  11830. }
  11831. const textarea = document.getElementById('modal-rf-rule');
  11832. if (textarea) textarea.value = code;
  11833. }
  11834. // -------------------------------------------------------------
  11835. // MODAL CRUD: RULES (/routing filter rule)
  11836. // -------------------------------------------------------------
  11837. function openAddRoutingFilterModal(defaultChain = '') {
  11838. const form = document.getElementById('routing-filter-form');
  11839. if (form) form.reset();
  11840. const idEl = document.getElementById('modal-rf-id');
  11841. if (idEl) idEl.value = '';
  11842. const titleEl = document.getElementById('modal-rf-title');
  11843. if (titleEl) titleEl.innerText = 'Add Routing Filter Rule';
  11844. const chainEl = document.getElementById('modal-rf-chain');
  11845. if (chainEl) chainEl.value = defaultChain || (state.filterChainSelected && state.filterChainSelected !== 'all' ? state.filterChainSelected : 'bgp-in');
  11846. const orderEl = document.getElementById('modal-rf-order');
  11847. if (orderEl) orderEl.value = ((state.routingFilters || []).length + 1) * 10;
  11848. const ruleEl = document.getElementById('modal-rf-rule');
  11849. if (ruleEl) ruleEl.value = 'if (dst in 10.0.0.0/8) { set bgp-local-pref 150; accept; }';
  11850. const disEl = document.getElementById('modal-rf-disabled');
  11851. if (disEl) disEl.checked = false;
  11852. const modal = document.getElementById('modal-routing-filter');
  11853. if (modal) modal.classList.remove('hidden');
  11854. }
  11855. function openEditRoutingFilterModal(id) {
  11856. const r = (state.routingFilters || []).find(item => item.id === id);
  11857. if (!r) return;
  11858. const idEl = document.getElementById('modal-rf-id');
  11859. if (idEl) idEl.value = r.id;
  11860. const titleEl = document.getElementById('modal-rf-title');
  11861. if (titleEl) titleEl.innerText = 'Edit Routing Filter Rule';
  11862. const chainEl = document.getElementById('modal-rf-chain');
  11863. if (chainEl) chainEl.value = r.chain || '';
  11864. const orderEl = document.getElementById('modal-rf-order');
  11865. if (orderEl) orderEl.value = r.rule_order || 10;
  11866. const ruleEl = document.getElementById('modal-rf-rule');
  11867. if (ruleEl) {
  11868. if (r.rule) {
  11869. ruleEl.value = r.rule;
  11870. } else {
  11871. let conds = [];
  11872. if (r.prefix) conds.push(`dst in ${r.prefix}`);
  11873. if (r.match_protocol && r.match_protocol !== 'any') conds.push(`protocol ${r.match_protocol}`);
  11874. let act = r.action || 'accept';
  11875. ruleEl.value = `if (${conds.length ? conds.join(' && ') : 'true'}) { ${act}; }`;
  11876. }
  11877. }
  11878. const comEl = document.getElementById('modal-rf-comment');
  11879. if (comEl) comEl.value = r.comment || '';
  11880. const disEl = document.getElementById('modal-rf-disabled');
  11881. if (disEl) disEl.checked = !!r.disabled;
  11882. const modal = document.getElementById('modal-routing-filter');
  11883. if (modal) modal.classList.remove('hidden');
  11884. }
  11885. function closeRoutingFilterModal() {
  11886. const modal = document.getElementById('modal-routing-filter');
  11887. if (modal) modal.classList.add('hidden');
  11888. }
  11889. async function submitRoutingFilter(e) {
  11890. if (e) e.preventDefault();
  11891. const payload = {
  11892. id: document.getElementById('modal-rf-id').value,
  11893. chain: document.getElementById('modal-rf-chain').value.trim(),
  11894. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  11895. rule: document.getElementById('modal-rf-rule').value.trim(),
  11896. comment: document.getElementById('modal-rf-comment').value.trim(),
  11897. disabled: document.getElementById('modal-rf-disabled').checked
  11898. };
  11899. try {
  11900. const res = await fetch(`${API_BASE}/routing/filters`, {
  11901. method: 'POST',
  11902. headers: { 'Content-Type': 'application/json' },
  11903. body: JSON.stringify(payload)
  11904. });
  11905. if (res.ok) {
  11906. closeRoutingFilterModal();
  11907. showToast('Success', 'Routing filter rule saved', 'success');
  11908. loadDynamicRouting();
  11909. } else {
  11910. const err = await res.json();
  11911. showToast('Error', err.error || 'Failed to save filter rule', 'error');
  11912. }
  11913. } catch (err) {
  11914. showToast('Error', err.message, 'error');
  11915. }
  11916. }
  11917. async function applyRoutingFilterForm() {
  11918. const payload = {
  11919. id: document.getElementById('modal-rf-id').value,
  11920. chain: document.getElementById('modal-rf-chain').value.trim(),
  11921. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  11922. rule: document.getElementById('modal-rf-rule').value.trim(),
  11923. comment: document.getElementById('modal-rf-comment').value.trim(),
  11924. disabled: document.getElementById('modal-rf-disabled').checked
  11925. };
  11926. try {
  11927. const res = await fetch(`${API_BASE}/routing/filters`, {
  11928. method: 'POST',
  11929. headers: { 'Content-Type': 'application/json' },
  11930. body: JSON.stringify(payload)
  11931. });
  11932. if (res.ok) {
  11933. const data = await res.json();
  11934. if (data.id) document.getElementById('modal-rf-id').value = data.id;
  11935. showToast('Applied', 'Routing filter configuration applied', 'success');
  11936. loadDynamicRouting();
  11937. } else {
  11938. const err = await res.json();
  11939. showToast('Error', err.error || 'Failed to apply filter rule', 'error');
  11940. }
  11941. } catch (err) {
  11942. showToast('Error', err.message, 'error');
  11943. }
  11944. }
  11945. async function moveRoutingFilterOrder(id, delta) {
  11946. const list = state.routingFilters || [];
  11947. const idx = list.findIndex(r => r.id === id);
  11948. if (idx < 0) return;
  11949. const targetIdx = idx + delta;
  11950. if (targetIdx < 0 || targetIdx >= list.length) return;
  11951. const currentOrder = list[idx].rule_order || 10;
  11952. const targetOrder = list[targetIdx].rule_order || 20;
  11953. list[idx].rule_order = targetOrder;
  11954. list[targetIdx].rule_order = currentOrder;
  11955. try {
  11956. await fetch(`${API_BASE}/routing/filters`, {
  11957. method: 'POST',
  11958. headers: { 'Content-Type': 'application/json' },
  11959. body: JSON.stringify(list[idx])
  11960. });
  11961. await fetch(`${API_BASE}/routing/filters`, {
  11962. method: 'POST',
  11963. headers: { 'Content-Type': 'application/json' },
  11964. body: JSON.stringify(list[targetIdx])
  11965. });
  11966. loadDynamicRouting();
  11967. } catch (e) {
  11968. console.error('Reorder error:', e);
  11969. }
  11970. }
  11971. async function deleteRoutingFilter(id) {
  11972. if (!confirm('Are you sure you want to delete this routing filter rule?')) return;
  11973. try {
  11974. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11975. if (res.ok) {
  11976. showToast('Deleted', 'Routing filter rule removed', 'info');
  11977. loadDynamicRouting();
  11978. } else {
  11979. const err = await res.json();
  11980. showToast('Error', err.error || 'Failed to delete rule', 'error');
  11981. }
  11982. } catch (err) {
  11983. showToast('Error', err.message, 'error');
  11984. }
  11985. }
  11986. async function toggleRoutingFilterState(id, disabled) {
  11987. try {
  11988. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}/state`, {
  11989. method: 'POST',
  11990. headers: { 'Content-Type': 'application/json' },
  11991. body: JSON.stringify({ disabled })
  11992. });
  11993. if (res.ok) {
  11994. showToast('Status Updated', `Rule ${disabled ? 'disabled' : 'enabled'}`, 'info');
  11995. loadDynamicRouting();
  11996. } else {
  11997. const err = await res.json();
  11998. showToast('Error', err.error || 'Failed to toggle rule state', 'error');
  11999. }
  12000. } catch (err) {
  12001. showToast('Error', err.message, 'error');
  12002. }
  12003. }
  12004. // -------------------------------------------------------------
  12005. // MODAL CRUD: COMMUNITY LISTS (/routing filter community-list)
  12006. // -------------------------------------------------------------
  12007. function openAddCommunityListModal() {
  12008. document.getElementById('modal-rf-cl-id').value = '';
  12009. document.getElementById('modal-rf-cl-title').innerText = 'Add BGP Community List';
  12010. document.getElementById('modal-rf-cl-name').value = '';
  12011. document.getElementById('modal-rf-cl-communities').value = '';
  12012. document.getElementById('modal-rf-cl-regexp').value = '';
  12013. document.getElementById('modal-rf-cl-comment').value = '';
  12014. document.getElementById('modal-rf-cl-disabled').checked = false;
  12015. document.getElementById('modal-rf-community-list').classList.remove('hidden');
  12016. }
  12017. function openEditCommunityListModal(id) {
  12018. const cl = (state.routingCommunityLists || []).find(item => item.id === id);
  12019. if (!cl) return;
  12020. document.getElementById('modal-rf-cl-id').value = cl.id;
  12021. document.getElementById('modal-rf-cl-title').innerText = 'Edit BGP Community List';
  12022. document.getElementById('modal-rf-cl-name').value = cl.name || '';
  12023. document.getElementById('modal-rf-cl-communities').value = (cl.communities || []).join(', ');
  12024. document.getElementById('modal-rf-cl-regexp').value = cl.regexp || '';
  12025. document.getElementById('modal-rf-cl-comment').value = cl.comment || '';
  12026. document.getElementById('modal-rf-cl-disabled').checked = !!cl.disabled;
  12027. document.getElementById('modal-rf-community-list').classList.remove('hidden');
  12028. }
  12029. function closeCommunityListModal() {
  12030. document.getElementById('modal-rf-community-list').classList.add('hidden');
  12031. }
  12032. async function submitCommunityList(e) {
  12033. e.preventDefault();
  12034. const rawComms = document.getElementById('modal-rf-cl-communities').value;
  12035. const comms = rawComms.split(',').map(c => c.trim()).filter(Boolean);
  12036. const payload = {
  12037. id: document.getElementById('modal-rf-cl-id').value,
  12038. name: document.getElementById('modal-rf-cl-name').value.trim(),
  12039. communities: comms,
  12040. regexp: document.getElementById('modal-rf-cl-regexp').value.trim(),
  12041. comment: document.getElementById('modal-rf-cl-comment').value.trim(),
  12042. disabled: document.getElementById('modal-rf-cl-disabled').checked
  12043. };
  12044. try {
  12045. const res = await fetch(`${API_BASE}/routing/filters/community-lists`, {
  12046. method: 'POST',
  12047. headers: { 'Content-Type': 'application/json' },
  12048. body: JSON.stringify(payload)
  12049. });
  12050. if (res.ok) {
  12051. closeCommunityListModal();
  12052. showToast('Success', 'Community list saved', 'success');
  12053. loadDynamicRouting();
  12054. } else {
  12055. const err = await res.json();
  12056. showToast('Error', err.error || 'Failed to save community list', 'error');
  12057. }
  12058. } catch (err) {
  12059. showToast('Error', err.message, 'error');
  12060. }
  12061. }
  12062. async function deleteCommunityList(id) {
  12063. if (!confirm('Are you sure you want to delete this community list?')) return;
  12064. try {
  12065. const res = await fetch(`${API_BASE}/routing/filters/community-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12066. if (res.ok) {
  12067. showToast('Deleted', 'Community list removed', 'info');
  12068. loadDynamicRouting();
  12069. } else {
  12070. const err = await res.json();
  12071. showToast('Error', err.error || 'Failed to delete community list', 'error');
  12072. }
  12073. } catch (err) {
  12074. showToast('Error', err.message, 'error');
  12075. }
  12076. }
  12077. async function toggleCommunityListState(id, disabled) {
  12078. try {
  12079. const res = await fetch(`${API_BASE}/routing/filters/community-lists/${encodeURIComponent(id)}/state`, {
  12080. method: 'POST',
  12081. headers: { 'Content-Type': 'application/json' },
  12082. body: JSON.stringify({ disabled })
  12083. });
  12084. if (res.ok) {
  12085. showToast('Status Updated', `Community list ${disabled ? 'disabled' : 'enabled'}`, 'info');
  12086. loadDynamicRouting();
  12087. } else {
  12088. const err = await res.json();
  12089. showToast('Error', err.error || 'Failed to update community list state', 'error');
  12090. }
  12091. } catch (err) {
  12092. showToast('Error', err.message, 'error');
  12093. }
  12094. }
  12095. // -------------------------------------------------------------
  12096. // MODAL CRUD: AS LISTS (/routing filter num-list)
  12097. // -------------------------------------------------------------
  12098. function openAddASListModal() {
  12099. document.getElementById('modal-rf-al-id').value = '';
  12100. document.getElementById('modal-rf-al-title').innerText = 'Add AS Number List';
  12101. document.getElementById('modal-rf-al-name').value = '';
  12102. document.getElementById('modal-rf-al-range').value = '';
  12103. document.getElementById('modal-rf-al-comment').value = '';
  12104. document.getElementById('modal-rf-al-disabled').checked = false;
  12105. document.getElementById('modal-rf-as-list').classList.remove('hidden');
  12106. }
  12107. function openEditASListModal(id) {
  12108. const al = (state.routingASLists || []).find(item => item.id === id);
  12109. if (!al) return;
  12110. document.getElementById('modal-rf-al-id').value = al.id;
  12111. document.getElementById('modal-rf-al-title').innerText = 'Edit AS Number List';
  12112. document.getElementById('modal-rf-al-name').value = al.name || '';
  12113. document.getElementById('modal-rf-al-range').value = al.range || '';
  12114. document.getElementById('modal-rf-al-comment').value = al.comment || '';
  12115. document.getElementById('modal-rf-al-disabled').checked = !!al.disabled;
  12116. document.getElementById('modal-rf-as-list').classList.remove('hidden');
  12117. }
  12118. function closeASListModal() {
  12119. document.getElementById('modal-rf-as-list').classList.add('hidden');
  12120. }
  12121. async function submitASList(e) {
  12122. e.preventDefault();
  12123. const payload = {
  12124. id: document.getElementById('modal-rf-al-id').value,
  12125. name: document.getElementById('modal-rf-al-name').value.trim(),
  12126. range: document.getElementById('modal-rf-al-range').value.trim(),
  12127. comment: document.getElementById('modal-rf-al-comment').value.trim(),
  12128. disabled: document.getElementById('modal-rf-al-disabled').checked
  12129. };
  12130. try {
  12131. const res = await fetch(`${API_BASE}/routing/filters/as-lists`, {
  12132. method: 'POST',
  12133. headers: { 'Content-Type': 'application/json' },
  12134. body: JSON.stringify(payload)
  12135. });
  12136. if (res.ok) {
  12137. closeASListModal();
  12138. showToast('Success', 'AS number list saved', 'success');
  12139. loadDynamicRouting();
  12140. } else {
  12141. const err = await res.json();
  12142. showToast('Error', err.error || 'Failed to save AS list', 'error');
  12143. }
  12144. } catch (err) {
  12145. showToast('Error', err.message, 'error');
  12146. }
  12147. }
  12148. async function deleteASList(id) {
  12149. if (!confirm('Are you sure you want to delete this AS list?')) return;
  12150. try {
  12151. const res = await fetch(`${API_BASE}/routing/filters/as-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12152. if (res.ok) {
  12153. showToast('Deleted', 'AS list removed', 'info');
  12154. loadDynamicRouting();
  12155. } else {
  12156. const err = await res.json();
  12157. showToast('Error', err.error || 'Failed to delete AS list', 'error');
  12158. }
  12159. } catch (err) {
  12160. showToast('Error', err.message, 'error');
  12161. }
  12162. }
  12163. async function toggleASListState(id, disabled) {
  12164. try {
  12165. const res = await fetch(`${API_BASE}/routing/filters/as-lists/${encodeURIComponent(id)}/state`, {
  12166. method: 'POST',
  12167. headers: { 'Content-Type': 'application/json' },
  12168. body: JSON.stringify({ disabled })
  12169. });
  12170. if (res.ok) {
  12171. showToast('Status Updated', `AS list ${disabled ? 'disabled' : 'enabled'}`, 'info');
  12172. loadDynamicRouting();
  12173. } else {
  12174. const err = await res.json();
  12175. showToast('Error', err.error || 'Failed to update AS list state', 'error');
  12176. }
  12177. } catch (err) {
  12178. showToast('Error', err.message, 'error');
  12179. }
  12180. }
  12181. // ==========================================
  12182. // TROUBLESHOOT & DIAGNOSTIC TOOLS (/tool)
  12183. // ==========================================
  12184. function loadToolsView() {
  12185. populateToolsInterfaces();
  12186. switchToolsSubTab(state.activeToolsSubTab || 'ping');
  12187. }
  12188. function populateToolsInterfaces() {
  12189. const pingSel = document.getElementById('tools-ping-iface');
  12190. const traceSel = document.getElementById('tools-tr-iface');
  12191. let opts = '<option value="">Auto (Default Route)</option>';
  12192. if (Array.isArray(state.interfaces)) {
  12193. state.interfaces.forEach(iface => {
  12194. if (iface.name) {
  12195. opts += `<option value="${escapeHtml(iface.name)}">${escapeHtml(iface.name)}${iface.ip_address ? ' (' + escapeHtml(iface.ip_address) + ')' : ''}</option>`;
  12196. }
  12197. });
  12198. }
  12199. if (pingSel) {
  12200. const cur = pingSel.value;
  12201. pingSel.innerHTML = opts;
  12202. if (cur) pingSel.value = cur;
  12203. }
  12204. if (traceSel) {
  12205. const cur = traceSel.value;
  12206. traceSel.innerHTML = opts;
  12207. if (cur) traceSel.value = cur;
  12208. }
  12209. }
  12210. function switchToolsSubTab(subTab) {
  12211. state.activeToolsSubTab = subTab;
  12212. const tabs = ['ping', 'traceroute', 'mtr', 'dns', 'port'];
  12213. tabs.forEach(t => {
  12214. const btn = document.getElementById(`tools-subtab-btn-${t}`);
  12215. const view = document.getElementById(`tools-view-${t}`);
  12216. if (btn) {
  12217. if (t === subTab) {
  12218. 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';
  12219. } else {
  12220. 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';
  12221. }
  12222. }
  12223. if (view) {
  12224. if (t === subTab) {
  12225. view.classList.remove('hidden');
  12226. } else {
  12227. view.classList.add('hidden');
  12228. }
  12229. }
  12230. });
  12231. }
  12232. function setPortPreset(port) {
  12233. const input = document.getElementById('tools-port-num');
  12234. if (input) input.value = port;
  12235. }
  12236. let pingAbortController = null;
  12237. let tracerouteAbortController = null;
  12238. function clearPingTable() {
  12239. const tbody = document.getElementById('tools-ping-tbody');
  12240. if (tbody) tbody.innerHTML = '';
  12241. const rawEl = document.getElementById('tools-ping-raw');
  12242. if (rawEl) rawEl.innerText = '';
  12243. const sentEl = document.getElementById('tools-ping-stat-sent');
  12244. if (sentEl) sentEl.innerText = '0';
  12245. const recvEl = document.getElementById('tools-ping-stat-recv');
  12246. if (recvEl) recvEl.innerText = '0';
  12247. const lossEl = document.getElementById('tools-ping-stat-loss');
  12248. if (lossEl) lossEl.innerText = '0%';
  12249. const avgEl = document.getElementById('tools-ping-stat-avg');
  12250. if (avgEl) avgEl.innerText = '0 ms';
  12251. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  12252. if (minMaxEl) minMaxEl.innerText = '-';
  12253. const badge = document.getElementById('tools-ping-status-badge');
  12254. if (badge) {
  12255. badge.className = '';
  12256. badge.innerText = '';
  12257. }
  12258. }
  12259. function clearTracerouteTable() {
  12260. const tbody = document.getElementById('tools-tr-tbody');
  12261. if (tbody) tbody.innerHTML = '';
  12262. const rawEl = document.getElementById('tools-tr-raw');
  12263. if (rawEl) rawEl.innerText = '';
  12264. const statHops = document.getElementById('tools-tr-hops-count');
  12265. if (statHops) statHops.innerText = '0 Hops';
  12266. }
  12267. function resetPingButton() {
  12268. const btn = document.getElementById('tools-ping-btn');
  12269. const btnText = document.getElementById('tools-ping-btn-text');
  12270. const spinner = document.getElementById('tools-ping-spinner');
  12271. if (btn) {
  12272. btn.disabled = false;
  12273. 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';
  12274. }
  12275. if (btnText) btnText.innerText = 'Start Ping';
  12276. if (spinner) spinner.classList.add('hidden');
  12277. }
  12278. function setPingRunningButton() {
  12279. const btn = document.getElementById('tools-ping-btn');
  12280. const btnText = document.getElementById('tools-ping-btn-text');
  12281. const spinner = document.getElementById('tools-ping-spinner');
  12282. if (btn) {
  12283. btn.disabled = false;
  12284. 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';
  12285. }
  12286. if (btnText) btnText.innerText = 'Stop Ping';
  12287. if (spinner) spinner.classList.remove('hidden');
  12288. }
  12289. function resetTracerouteButton() {
  12290. const btn = document.getElementById('tools-tr-btn');
  12291. const btnText = document.getElementById('tools-tr-btn-text');
  12292. const spinner = document.getElementById('tools-tr-spinner');
  12293. if (btn) {
  12294. btn.disabled = false;
  12295. 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';
  12296. }
  12297. if (btnText) btnText.innerText = 'Start Traceroute';
  12298. if (spinner) spinner.classList.add('hidden');
  12299. }
  12300. function setTracerouteRunningButton() {
  12301. const btn = document.getElementById('tools-tr-btn');
  12302. const btnText = document.getElementById('tools-tr-btn-text');
  12303. const spinner = document.getElementById('tools-tr-spinner');
  12304. if (btn) {
  12305. btn.disabled = false;
  12306. 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';
  12307. }
  12308. if (btnText) btnText.innerText = 'Stop Traceroute';
  12309. if (spinner) spinner.classList.remove('hidden');
  12310. }
  12311. async function executePing(e) {
  12312. if (e) e.preventDefault();
  12313. // If already running, clicking the button stops the stream!
  12314. if (pingAbortController) {
  12315. pingAbortController.abort();
  12316. pingAbortController = null;
  12317. resetPingButton();
  12318. showToast('Ping Stopped', 'Live ping stopped by user', 'info');
  12319. return;
  12320. }
  12321. const target = document.getElementById('tools-ping-target')?.value?.trim();
  12322. const count = parseInt(document.getElementById('tools-ping-count')?.value || '4', 10);
  12323. const size = parseInt(document.getElementById('tools-ping-size')?.value || '56', 10);
  12324. const timeout = parseInt(document.getElementById('tools-ping-timeout')?.value || '3', 10);
  12325. const iface = document.getElementById('tools-ping-iface')?.value || '';
  12326. const dontFrag = document.getElementById('tools-ping-df')?.checked || false;
  12327. if (!target) {
  12328. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  12329. return;
  12330. }
  12331. clearPingTable();
  12332. const resCard = document.getElementById('tools-ping-results');
  12333. if (resCard) resCard.classList.remove('hidden');
  12334. pingAbortController = new AbortController();
  12335. setPingRunningButton();
  12336. try {
  12337. const res = await fetch(`${API_BASE}/tools/ping/stream`, {
  12338. method: 'POST',
  12339. headers: { 'Content-Type': 'application/json' },
  12340. body: JSON.stringify({
  12341. target,
  12342. count,
  12343. size,
  12344. timeout,
  12345. interface: iface,
  12346. dont_frag: dontFrag
  12347. }),
  12348. signal: pingAbortController.signal
  12349. });
  12350. if (!res.ok) {
  12351. const errText = await res.text();
  12352. showToast('Ping Error', errText || 'Failed to start live ping', 'error');
  12353. resetPingButton();
  12354. pingAbortController = null;
  12355. return;
  12356. }
  12357. const reader = res.body.getReader();
  12358. const decoder = new TextDecoder('utf-8');
  12359. let buffer = '';
  12360. while (true) {
  12361. const { done, value } = await reader.read();
  12362. if (done) break;
  12363. buffer += decoder.decode(value, { stream: true });
  12364. const blocks = buffer.split('\n\n');
  12365. buffer = blocks.pop() || '';
  12366. for (const block of blocks) {
  12367. const trimmed = block.trim();
  12368. if (!trimmed) continue;
  12369. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  12370. try {
  12371. const evt = JSON.parse(line);
  12372. handleLivePingEvent(evt);
  12373. } catch (parseErr) {
  12374. console.warn('Ping SSE parse error:', parseErr, line);
  12375. }
  12376. }
  12377. }
  12378. } catch (err) {
  12379. if (err.name === 'AbortError') {
  12380. // User aborted normally
  12381. } else {
  12382. showToast('Ping Error', err.message, 'error');
  12383. }
  12384. } finally {
  12385. pingAbortController = null;
  12386. resetPingButton();
  12387. }
  12388. }
  12389. function handleLivePingEvent(evt) {
  12390. const sentEl = document.getElementById('tools-ping-stat-sent');
  12391. const recvEl = document.getElementById('tools-ping-stat-recv');
  12392. const lossEl = document.getElementById('tools-ping-stat-loss');
  12393. const avgEl = document.getElementById('tools-ping-stat-avg');
  12394. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  12395. const badge = document.getElementById('tools-ping-status-badge');
  12396. const tbody = document.getElementById('tools-ping-tbody');
  12397. const rawEl = document.getElementById('tools-ping-raw');
  12398. if (evt.raw && rawEl) {
  12399. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  12400. rawEl.scrollTop = rawEl.scrollHeight;
  12401. }
  12402. if (evt.type === 'reply') {
  12403. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  12404. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  12405. if (lossEl && evt.packet_loss_pct !== undefined) {
  12406. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  12407. lossEl.className = evt.packet_loss_pct === 0
  12408. ? 'text-base font-bold font-mono text-emerald-400 mt-1'
  12409. : (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');
  12410. }
  12411. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  12412. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  12413. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  12414. }
  12415. if (badge) {
  12416. if (evt.packet_loss_pct === 0) {
  12417. 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';
  12418. badge.innerText = '100% OK';
  12419. } else {
  12420. 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';
  12421. badge.innerText = `${evt.packet_loss_pct.toFixed(0)}% LOSS`;
  12422. }
  12423. }
  12424. if (tbody) {
  12425. const tr = document.createElement('tr');
  12426. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  12427. tr.innerHTML = `
  12428. <td class="py-2 px-3 text-slate-300">#${evt.seq}</td>
  12429. <td class="py-2 px-3 font-semibold text-white">${escapeHtml(evt.from)}</td>
  12430. <td class="py-2 px-3 text-slate-400">${evt.bytes} bytes</td>
  12431. <td class="py-2 px-3 text-slate-300">${evt.ttl}</td>
  12432. <td class="py-2 px-3 font-bold text-amber-300">${evt.time_ms.toFixed(2)} ms</td>
  12433. <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>
  12434. `;
  12435. tbody.appendChild(tr);
  12436. }
  12437. } else if (evt.type === 'timeout') {
  12438. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  12439. if (lossEl && evt.packet_loss_pct !== undefined) {
  12440. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  12441. 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';
  12442. }
  12443. if (badge) {
  12444. 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';
  12445. badge.innerText = `${evt.packet_loss_pct?.toFixed(0) || 100}% LOSS`;
  12446. }
  12447. if (tbody) {
  12448. const tr = document.createElement('tr');
  12449. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs opacity-75';
  12450. tr.innerHTML = `
  12451. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  12452. <td class="py-2 px-3 font-semibold text-slate-500 italic">Request timed out</td>
  12453. <td class="py-2 px-3 text-slate-600">--</td>
  12454. <td class="py-2 px-3 text-slate-600">--</td>
  12455. <td class="py-2 px-3 font-bold text-slate-500">* * *</td>
  12456. <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>
  12457. `;
  12458. tbody.appendChild(tr);
  12459. }
  12460. } else if (evt.type === 'unreach') {
  12461. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  12462. if (lossEl && evt.packet_loss_pct !== undefined) {
  12463. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  12464. lossEl.className = 'text-base font-bold font-mono text-rose-400 mt-1';
  12465. }
  12466. if (badge) {
  12467. 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';
  12468. badge.innerText = 'UNREACHABLE';
  12469. }
  12470. if (tbody) {
  12471. const tr = document.createElement('tr');
  12472. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  12473. tr.innerHTML = `
  12474. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  12475. <td class="py-2 px-3 font-semibold text-rose-400">${escapeHtml(evt.from || 'Gateway')}</td>
  12476. <td class="py-2 px-3 text-slate-600">--</td>
  12477. <td class="py-2 px-3 text-slate-600">--</td>
  12478. <td class="py-2 px-3 font-bold text-rose-400 text-xs">${escapeHtml(evt.message || 'Unreachable')}</td>
  12479. <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>
  12480. `;
  12481. tbody.appendChild(tr);
  12482. }
  12483. } else if (evt.type === 'stats') {
  12484. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  12485. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  12486. if (lossEl && evt.packet_loss_pct !== undefined) lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  12487. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  12488. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  12489. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  12490. }
  12491. } else if (evt.type === 'done') {
  12492. 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');
  12493. }
  12494. }
  12495. async function executeTraceroute(e) {
  12496. if (e) e.preventDefault();
  12497. if (tracerouteAbortController) {
  12498. tracerouteAbortController.abort();
  12499. tracerouteAbortController = null;
  12500. resetTracerouteButton();
  12501. showToast('Traceroute Stopped', 'Traceroute stopped by user', 'info');
  12502. return;
  12503. }
  12504. const target = document.getElementById('tools-tr-target')?.value?.trim();
  12505. const maxHops = parseInt(document.getElementById('tools-tr-maxhops')?.value || '15', 10);
  12506. const protocol = document.getElementById('tools-tr-proto')?.value || 'icmp';
  12507. const iface = document.getElementById('tools-tr-iface')?.value || '';
  12508. const resolve = document.getElementById('tools-tr-resolve')?.checked || false;
  12509. if (!target) {
  12510. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  12511. return;
  12512. }
  12513. clearTracerouteTable();
  12514. const resCard = document.getElementById('tools-tr-results');
  12515. if (resCard) resCard.classList.remove('hidden');
  12516. tracerouteAbortController = new AbortController();
  12517. setTracerouteRunningButton();
  12518. try {
  12519. const res = await fetch(`${API_BASE}/tools/traceroute/stream`, {
  12520. method: 'POST',
  12521. headers: { 'Content-Type': 'application/json' },
  12522. body: JSON.stringify({
  12523. target,
  12524. max_hops: maxHops,
  12525. protocol,
  12526. interface: iface,
  12527. resolve
  12528. }),
  12529. signal: tracerouteAbortController.signal
  12530. });
  12531. if (!res.ok) {
  12532. const errText = await res.text();
  12533. showToast('Traceroute Error', errText || 'Failed to start traceroute', 'error');
  12534. resetTracerouteButton();
  12535. tracerouteAbortController = null;
  12536. return;
  12537. }
  12538. const reader = res.body.getReader();
  12539. const decoder = new TextDecoder('utf-8');
  12540. let buffer = '';
  12541. while (true) {
  12542. const { done, value } = await reader.read();
  12543. if (done) break;
  12544. buffer += decoder.decode(value, { stream: true });
  12545. const blocks = buffer.split('\n\n');
  12546. buffer = blocks.pop() || '';
  12547. for (const block of blocks) {
  12548. const trimmed = block.trim();
  12549. if (!trimmed) continue;
  12550. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  12551. try {
  12552. const evt = JSON.parse(line);
  12553. handleLiveTracerouteEvent(evt);
  12554. } catch (parseErr) {
  12555. console.warn('Traceroute SSE parse error:', parseErr, line);
  12556. }
  12557. }
  12558. }
  12559. } catch (err) {
  12560. if (err.name === 'AbortError') {
  12561. // User aborted normally
  12562. } else {
  12563. showToast('Traceroute Error', err.message, 'error');
  12564. }
  12565. } finally {
  12566. tracerouteAbortController = null;
  12567. resetTracerouteButton();
  12568. }
  12569. }
  12570. function handleLiveTracerouteEvent(evt) {
  12571. const statHops = document.getElementById('tools-tr-hops-count');
  12572. const tbody = document.getElementById('tools-tr-tbody');
  12573. const rawEl = document.getElementById('tools-tr-raw');
  12574. if (evt.raw && rawEl) {
  12575. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  12576. rawEl.scrollTop = rawEl.scrollHeight;
  12577. }
  12578. if (evt.hops_count !== undefined && statHops) {
  12579. statHops.innerText = `${evt.hops_count} Hops`;
  12580. }
  12581. if (evt.type === 'hop' && evt.hop && tbody) {
  12582. const h = evt.hop;
  12583. const isTimeout = h.status === 'timeout' || (!h.ip && !h.host);
  12584. const rtt1 = Array.isArray(h.times_ms) && h.times_ms[0] ? `${h.times_ms[0]} ms` : (isTimeout ? '*' : '--');
  12585. const rtt2 = Array.isArray(h.times_ms) && h.times_ms[1] ? `${h.times_ms[1]} ms` : (isTimeout ? '*' : '--');
  12586. const displayHost = h.host && h.host !== h.ip ? `${escapeHtml(h.host)} (${escapeHtml(h.ip || '')})` : escapeHtml(h.ip || (isTimeout ? 'Request timed out' : '--'));
  12587. const tr = document.createElement('tr');
  12588. tr.className = `hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs ${isTimeout ? 'opacity-60' : ''}`;
  12589. tr.innerHTML = `
  12590. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  12591. <td class="py-2.5 px-3 font-semibold ${isTimeout ? 'text-slate-500 italic' : 'text-cyan-300'}">${displayHost}</td>
  12592. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt1)}</td>
  12593. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt2)}</td>
  12594. <td class="py-2.5 px-3 text-right">
  12595. ${isTimeout
  12596. ? '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-slate-800 text-slate-400 border border-slate-700">TIMEOUT</span>'
  12597. : '<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>'}
  12598. </td>
  12599. `;
  12600. tbody.appendChild(tr);
  12601. } else if (evt.type === 'done') {
  12602. showToast('Traceroute Finished', `Traced ${evt.hops_count || 0} hops`, 'info');
  12603. }
  12604. }
  12605. async function executeMTR(e) {
  12606. if (e) e.preventDefault();
  12607. const target = document.getElementById('tools-mtr-target')?.value?.trim();
  12608. const cycles = parseInt(document.getElementById('tools-mtr-count')?.value || '3', 10);
  12609. if (!target) {
  12610. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  12611. return;
  12612. }
  12613. const btn = document.getElementById('tools-mtr-btn');
  12614. const spinner = document.getElementById('tools-mtr-spinner');
  12615. if (btn) btn.disabled = true;
  12616. if (spinner) spinner.classList.remove('hidden');
  12617. try {
  12618. const res = await fetch(`${API_BASE}/tools/mtr`, {
  12619. method: 'POST',
  12620. headers: { 'Content-Type': 'application/json' },
  12621. body: JSON.stringify({ target, count: cycles })
  12622. });
  12623. const data = await res.json();
  12624. if (!res.ok) {
  12625. showToast('MTR Error', data.error || 'Failed to execute MTR', 'error');
  12626. return;
  12627. }
  12628. const resCard = document.getElementById('tools-mtr-results');
  12629. if (resCard) resCard.classList.remove('hidden');
  12630. const hopsCount = Array.isArray(data.hops) ? data.hops.length : 0;
  12631. const statHops = document.getElementById('tools-mtr-hops-count');
  12632. if (statHops) statHops.innerText = `${hopsCount} Hops`;
  12633. const tbody = document.getElementById('tools-mtr-tbody');
  12634. if (tbody) {
  12635. if (hopsCount > 0) {
  12636. tbody.innerHTML = data.hops.map(h => {
  12637. 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');
  12638. return `
  12639. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  12640. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  12641. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(h.host || '--')}</td>
  12642. <td class="py-2.5 px-3 ${lossClass}">${h.loss_pct.toFixed(1)}%</td>
  12643. <td class="py-2.5 px-3 text-slate-300">${h.sent}</td>
  12644. <td class="py-2.5 px-3 text-slate-300">${h.last_ms.toFixed(1)}</td>
  12645. <td class="py-2.5 px-3 font-bold text-amber-300">${h.avg_ms.toFixed(1)}</td>
  12646. <td class="py-2.5 px-3 text-emerald-400">${h.best_ms.toFixed(1)}</td>
  12647. <td class="py-2.5 px-3 text-rose-400">${h.wrst_ms.toFixed(1)}</td>
  12648. <td class="py-2.5 px-3 text-slate-400">${h.stdev_ms.toFixed(1)}</td>
  12649. </tr>
  12650. `;
  12651. }).join('');
  12652. } else {
  12653. tbody.innerHTML = `<tr><td colspan="9" class="p-4 text-center text-xs text-rose-400 font-mono">No MTR data collected</td></tr>`;
  12654. }
  12655. }
  12656. const rawEl = document.getElementById('tools-mtr-raw');
  12657. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  12658. showToast('MTR Finished', `Report completed (${hopsCount} hops discovered)`, 'info');
  12659. } catch (err) {
  12660. showToast('MTR Error', err.message, 'error');
  12661. } finally {
  12662. if (btn) btn.disabled = false;
  12663. if (spinner) spinner.classList.add('hidden');
  12664. }
  12665. }
  12666. async function executeDNS(e) {
  12667. if (e) e.preventDefault();
  12668. const domain = document.getElementById('tools-dns-domain')?.value?.trim();
  12669. const type = document.getElementById('tools-dns-type')?.value || 'A';
  12670. const server = document.getElementById('tools-dns-server')?.value?.trim() || '';
  12671. if (!domain) {
  12672. showToast('Input Required', 'Please enter a hostname or domain', 'warning');
  12673. return;
  12674. }
  12675. const btn = document.getElementById('tools-dns-btn');
  12676. const spinner = document.getElementById('tools-dns-spinner');
  12677. if (btn) btn.disabled = true;
  12678. if (spinner) spinner.classList.remove('hidden');
  12679. try {
  12680. const res = await fetch(`${API_BASE}/tools/dns`, {
  12681. method: 'POST',
  12682. headers: { 'Content-Type': 'application/json' },
  12683. body: JSON.stringify({ domain, type, server })
  12684. });
  12685. const data = await res.json();
  12686. if (!res.ok) {
  12687. showToast('DNS Error', data.error || 'Failed to resolve DNS query', 'error');
  12688. return;
  12689. }
  12690. const resCard = document.getElementById('tools-dns-results');
  12691. if (resCard) resCard.classList.remove('hidden');
  12692. const metaEl = document.getElementById('tools-dns-meta');
  12693. if (metaEl) metaEl.innerText = `Resolved in ${data.query_time_ms ?? 0} ms via ${escapeHtml(data.server || 'System DNS')}`;
  12694. const tbody = document.getElementById('tools-dns-tbody');
  12695. if (tbody) {
  12696. if (Array.isArray(data.records) && data.records.length > 0) {
  12697. tbody.innerHTML = data.records.map(r => `
  12698. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  12699. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.name)}</td>
  12700. <td class="py-2.5 px-3 text-slate-400">${r.ttl}s</td>
  12701. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.class || 'IN')}</td>
  12702. <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>
  12703. <td class="py-2.5 px-3 font-bold text-amber-300 break-all">${escapeHtml(r.value)}</td>
  12704. </tr>
  12705. `).join('');
  12706. } else {
  12707. 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>`;
  12708. }
  12709. }
  12710. const rawEl = document.getElementById('tools-dns-raw');
  12711. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  12712. showToast('DNS Lookup Done', `Resolved ${domain} in ${data.query_time_ms} ms`, 'success');
  12713. } catch (err) {
  12714. showToast('DNS Error', err.message, 'error');
  12715. } finally {
  12716. if (btn) btn.disabled = false;
  12717. if (spinner) spinner.classList.add('hidden');
  12718. }
  12719. }
  12720. async function executePortProbe(e) {
  12721. if (e) e.preventDefault();
  12722. const target = document.getElementById('tools-port-target')?.value?.trim();
  12723. const port = parseInt(document.getElementById('tools-port-num')?.value || '80', 10);
  12724. const timeout = parseInt(document.getElementById('tools-port-timeout')?.value || '3', 10);
  12725. if (!target || !port) {
  12726. showToast('Input Required', 'Please enter a target host and TCP port', 'warning');
  12727. return;
  12728. }
  12729. const btn = document.getElementById('tools-port-btn');
  12730. const spinner = document.getElementById('tools-port-spinner');
  12731. if (btn) btn.disabled = true;
  12732. if (spinner) spinner.classList.remove('hidden');
  12733. try {
  12734. const res = await fetch(`${API_BASE}/tools/port-probe`, {
  12735. method: 'POST',
  12736. headers: { 'Content-Type': 'application/json' },
  12737. body: JSON.stringify({ target, port, timeout })
  12738. });
  12739. const data = await res.json();
  12740. if (!res.ok) {
  12741. showToast('Probe Error', data.error || 'Failed to probe TCP port', 'error');
  12742. return;
  12743. }
  12744. const resCard = document.getElementById('tools-port-results');
  12745. if (resCard) resCard.classList.remove('hidden');
  12746. const banner = document.getElementById('tools-port-banner');
  12747. const icon = document.getElementById('tools-port-icon');
  12748. const title = document.getElementById('tools-port-title');
  12749. const sub = document.getElementById('tools-port-sub');
  12750. const latency = document.getElementById('tools-port-latency');
  12751. if (data.open) {
  12752. if (banner) banner.className = 'rounded-xl p-5 border bg-emerald-950/30 border-emerald-800/50 flex items-center justify-between';
  12753. if (icon) {
  12754. 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';
  12755. icon.innerText = '✓';
  12756. }
  12757. if (title) {
  12758. title.className = 'text-sm font-bold text-emerald-300';
  12759. title.innerText = `PORT ${port} OPEN / LISTENING`;
  12760. }
  12761. if (sub) {
  12762. sub.className = 'text-xs mt-0.5 font-mono text-emerald-400/80';
  12763. sub.innerText = `TCP 3-way handshake established with ${escapeHtml(target)}:${port}${data.service ? ' (' + escapeHtml(data.service) + ')' : ''}`;
  12764. }
  12765. if (latency) {
  12766. latency.className = 'text-base font-bold font-mono text-emerald-300';
  12767. latency.innerText = `${data.latency_ms.toFixed(2)} ms`;
  12768. }
  12769. } else {
  12770. if (banner) banner.className = 'rounded-xl p-5 border bg-rose-950/30 border-rose-800/50 flex items-center justify-between';
  12771. if (icon) {
  12772. 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';
  12773. icon.innerText = '✕';
  12774. }
  12775. if (title) {
  12776. title.className = 'text-sm font-bold text-rose-300';
  12777. title.innerText = `PORT ${port} CLOSED / FILTERED`;
  12778. }
  12779. if (sub) {
  12780. sub.className = 'text-xs mt-0.5 font-mono text-rose-400/80';
  12781. sub.innerText = `Connection failed or timed out to ${escapeHtml(target)}:${port}`;
  12782. }
  12783. if (latency) {
  12784. latency.className = 'text-base font-bold font-mono text-slate-500';
  12785. latency.innerText = '--';
  12786. }
  12787. }
  12788. const rawEl = document.getElementById('tools-port-raw');
  12789. 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'}`);
  12790. showToast('Probe Complete', `Port ${port} is ${data.open ? 'OPEN' : 'CLOSED'}`, data.open ? 'success' : 'warning');
  12791. } catch (err) {
  12792. showToast('Probe Error', err.message, 'error');
  12793. } finally {
  12794. if (btn) btn.disabled = false;
  12795. if (spinner) spinner.classList.add('hidden');
  12796. }
  12797. }
  12798. // ==========================================
  12799. // DHCP CLIENT (/ip dhcp-client) CONTROLLER
  12800. // ==========================================
  12801. async function loadDHCPClients(showToastMsg = false) {
  12802. try {
  12803. const [clientsRes, sumRes] = await Promise.all([
  12804. fetch(`${API_BASE}/dhcp/clients`),
  12805. fetch(`${API_BASE}/dhcp/clients/summary`)
  12806. ]);
  12807. if (clientsRes.ok) {
  12808. state.dhcpClients = await clientsRes.json();
  12809. }
  12810. if (sumRes.ok) {
  12811. state.dhcpSummary = await sumRes.json();
  12812. }
  12813. renderDHCPClients();
  12814. updateDHCPSummaryCards();
  12815. const bDhcp = document.getElementById('badge-dhcp-client-count');
  12816. if (bDhcp && state.dhcpSummary) {
  12817. bDhcp.innerText = state.dhcpSummary.total_clients || 0;
  12818. }
  12819. if (showToastMsg) {
  12820. showToast('Refreshed', 'DHCP Client telemetry updated', 'info');
  12821. }
  12822. } catch (err) {
  12823. console.error('Failed to load DHCP clients:', err);
  12824. if (showToastMsg) {
  12825. showToast('Notice', 'Unable to fetch DHCP client status', 'warning');
  12826. }
  12827. }
  12828. }
  12829. function updateDHCPSummaryCards() {
  12830. const sum = state.dhcpSummary || {
  12831. total_clients: (state.dhcpClients || []).length,
  12832. bound_clients: (state.dhcpClients || []).filter(c => c.status === 'bound').length,
  12833. searching_clients: (state.dhcpClients || []).filter(c => c.status === 'searching').length,
  12834. disabled_clients: (state.dhcpClients || []).filter(c => !c.enabled).length
  12835. };
  12836. const totalEl = document.getElementById('dhcp-stat-total');
  12837. const boundEl = document.getElementById('dhcp-stat-bound');
  12838. const searchEl = document.getElementById('dhcp-stat-searching');
  12839. const disEl = document.getElementById('dhcp-stat-disabled');
  12840. if (totalEl) totalEl.innerText = sum.total_clients ?? 0;
  12841. if (boundEl) boundEl.innerText = sum.bound_clients ?? 0;
  12842. if (searchEl) searchEl.innerText = sum.searching_clients ?? 0;
  12843. if (disEl) disEl.innerText = sum.disabled_clients ?? 0;
  12844. }
  12845. function renderDHCPClients() {
  12846. const tbody = document.getElementById('dhcp-clients-tbody');
  12847. const emptyState = document.getElementById('dhcp-clients-empty');
  12848. if (!tbody) return;
  12849. const clients = Array.isArray(state.dhcpClients) ? state.dhcpClients : [];
  12850. if (clients.length === 0) {
  12851. tbody.innerHTML = '';
  12852. if (emptyState) emptyState.classList.remove('hidden');
  12853. return;
  12854. }
  12855. if (emptyState) emptyState.classList.add('hidden');
  12856. const sig = clients.map(c => `${c.id}:${c.status}:${c.ip_address}:${c.gateway}:${c.enabled}`).join(';');
  12857. if (tbody.dataset.sig === sig) return;
  12858. tbody.dataset.sig = sig;
  12859. tbody.innerHTML = clients.map(c => {
  12860. let statusBadge = '';
  12861. if (!c.enabled) {
  12862. 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>';
  12863. } else if (c.status === 'bound') {
  12864. 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>';
  12865. } else if (c.status === 'searching') {
  12866. 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>';
  12867. } else if (c.status === 'stopped') {
  12868. 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>';
  12869. } else {
  12870. 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>`;
  12871. }
  12872. 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>';
  12873. const gwDisplay = c.gateway ? `<span class="text-slate-300">${escapeHtml(c.gateway)}</span>` : '<span class="text-slate-600">--</span>';
  12874. const srvDisplay = c.dhcp_server ? `<span class="text-slate-300">${escapeHtml(c.dhcp_server)}</span>` : '<span class="text-slate-600">--</span>';
  12875. 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>';
  12876. const expDisplay = c.expires_in ? `<span class="text-purple-300">${escapeHtml(c.expires_in)}</span>` : '<span class="text-slate-600">--</span>';
  12877. // Option flags
  12878. const flags = [];
  12879. 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>');
  12880. 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>');
  12881. 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>');
  12882. 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>`);
  12883. return `
  12884. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 text-xs transition">
  12885. <td class="py-3 px-4">
  12886. <div class="flex items-center gap-2">
  12887. <span class="font-bold text-white text-sm">${escapeHtml(c.interface)}</span>
  12888. ${c.comment ? `<span class="text-[11px] text-slate-400 font-sans italic">(${escapeHtml(c.comment)})</span>` : ''}
  12889. </div>
  12890. </td>
  12891. <td class="py-3 px-4">${statusBadge}</td>
  12892. <td class="py-3 px-4 font-mono">${ipDisplay}</td>
  12893. <td class="py-3 px-4 font-mono">${gwDisplay}</td>
  12894. <td class="py-3 px-4 font-mono">${srvDisplay}</td>
  12895. <td class="py-3 px-4 font-mono text-[11px]">${dnsDisplay}</td>
  12896. <td class="py-3 px-4 font-mono text-[11px]">${expDisplay}</td>
  12897. <td class="py-3 px-4">
  12898. <div class="flex flex-wrap gap-1 font-mono">${flags.join('')}</div>
  12899. </td>
  12900. <td class="py-3 px-4 text-right space-x-1.5 font-sans whitespace-nowrap">
  12901. ${c.enabled ? `
  12902. <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>
  12903. <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>
  12904. <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>
  12905. ` : `
  12906. <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>
  12907. `}
  12908. <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>
  12909. <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>
  12910. </td>
  12911. </tr>
  12912. `;
  12913. }).join('');
  12914. }
  12915. function openDHCPClientModal(clientId = null) {
  12916. const modal = document.getElementById('modal-dhcp-client');
  12917. if (!modal) return;
  12918. const title = document.getElementById('modal-dhcp-title');
  12919. const idInput = document.getElementById('modal-dhcp-id');
  12920. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  12921. const distInput = document.getElementById('modal-dhcp-distance');
  12922. const commentInput = document.getElementById('modal-dhcp-comment');
  12923. const defRouteCheck = document.getElementById('modal-dhcp-def-route');
  12924. const peerDnsCheck = document.getElementById('modal-dhcp-peer-dns');
  12925. const peerNtpCheck = document.getElementById('modal-dhcp-peer-ntp');
  12926. const enabledCheck = document.getElementById('modal-dhcp-enabled');
  12927. // Populate interfaces
  12928. if (ifaceSelect) {
  12929. let opts = '<option value="">Select interface...</option>';
  12930. const allIfaces = state.interfaces || [];
  12931. const allVlans = state.vlans || [];
  12932. const usedIfaces = new Set((state.dhcpClients || []).map(c => c.interface));
  12933. // Group 1: Physical & Bridge Interfaces
  12934. opts += '<optgroup label="Physical & Bridge Interfaces">';
  12935. allIfaces.filter(i => supportsDHCPClient(i)).forEach(i => {
  12936. const isConfigured = usedIfaces.has(i.name) ? ' (Configured)' : '';
  12937. opts += `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)} [${escapeHtml(i.role || i.type)}]${isConfigured}</option>`;
  12938. });
  12939. opts += '</optgroup>';
  12940. // Group 2: VLAN Interfaces
  12941. if (allVlans.length > 0) {
  12942. opts += '<optgroup label="802.1Q VLAN Sub-interfaces">';
  12943. allVlans.forEach(v => {
  12944. const isConfigured = usedIfaces.has(v.name) ? ' (Configured)' : '';
  12945. opts += `<option value="${escapeHtml(v.name)}">${escapeHtml(v.name)} (VLAN ${v.vlan_id})${isConfigured}</option>`;
  12946. });
  12947. opts += '</optgroup>';
  12948. }
  12949. ifaceSelect.innerHTML = opts;
  12950. }
  12951. if (clientId) {
  12952. const client = (state.dhcpClients || []).find(c => c.id === clientId);
  12953. if (client) {
  12954. if (title) title.innerText = `Edit DHCP Client: ${client.interface}`;
  12955. if (idInput) idInput.value = client.id;
  12956. if (ifaceSelect) {
  12957. ifaceSelect.value = client.interface;
  12958. ifaceSelect.disabled = true; // interface cannot be changed on edit
  12959. }
  12960. if (distInput) distInput.value = client.default_route_distance || 1;
  12961. if (commentInput) commentInput.value = client.comment || '';
  12962. if (defRouteCheck) defRouteCheck.checked = client.add_default_route !== false;
  12963. if (peerDnsCheck) peerDnsCheck.checked = client.use_peer_dns !== false;
  12964. if (peerNtpCheck) peerNtpCheck.checked = client.use_peer_ntp !== false;
  12965. if (enabledCheck) enabledCheck.checked = client.enabled !== false;
  12966. }
  12967. } else {
  12968. if (title) title.innerText = 'Add DHCP Client';
  12969. if (idInput) idInput.value = '';
  12970. if (ifaceSelect) {
  12971. ifaceSelect.value = '';
  12972. ifaceSelect.disabled = false;
  12973. }
  12974. if (distInput) distInput.value = 1;
  12975. if (commentInput) commentInput.value = '';
  12976. if (defRouteCheck) defRouteCheck.checked = true;
  12977. if (peerDnsCheck) peerDnsCheck.checked = true;
  12978. if (peerNtpCheck) peerNtpCheck.checked = true;
  12979. if (enabledCheck) enabledCheck.checked = true;
  12980. }
  12981. modal.classList.remove('hidden');
  12982. }
  12983. function openDHCPClientModalForIface(ifaceName) {
  12984. openDHCPClientModal();
  12985. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  12986. if (ifaceSelect && ifaceName) {
  12987. ifaceSelect.value = ifaceName;
  12988. }
  12989. }
  12990. function closeDHCPClientModal() {
  12991. const modal = document.getElementById('modal-dhcp-client');
  12992. if (modal) modal.classList.add('hidden');
  12993. }
  12994. async function submitSaveDHCPClient(e) {
  12995. if (e) e.preventDefault();
  12996. const id = document.getElementById('modal-dhcp-id')?.value;
  12997. const iface = document.getElementById('modal-dhcp-iface')?.value?.trim();
  12998. const distance = parseInt(document.getElementById('modal-dhcp-distance')?.value || '1', 10);
  12999. const comment = document.getElementById('modal-dhcp-comment')?.value?.trim() || '';
  13000. const defRoute = document.getElementById('modal-dhcp-def-route')?.checked ?? true;
  13001. const peerDns = document.getElementById('modal-dhcp-peer-dns')?.checked ?? true;
  13002. const peerNtp = document.getElementById('modal-dhcp-peer-ntp')?.checked ?? true;
  13003. const enabled = document.getElementById('modal-dhcp-enabled')?.checked ?? true;
  13004. if (!id && !iface) {
  13005. showToast('Input Required', 'Please select an interface for the DHCP client', 'warning');
  13006. return;
  13007. }
  13008. try {
  13009. let res;
  13010. if (id) {
  13011. // PUT update
  13012. res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  13013. method: 'PUT',
  13014. headers: { 'Content-Type': 'application/json' },
  13015. body: JSON.stringify({
  13016. enabled,
  13017. add_default_route: defRoute,
  13018. default_route_distance: distance,
  13019. use_peer_dns: peerDns,
  13020. use_peer_ntp: peerNtp,
  13021. comment
  13022. })
  13023. });
  13024. } else {
  13025. // POST create
  13026. res = await fetch(`${API_BASE}/dhcp/clients`, {
  13027. method: 'POST',
  13028. headers: { 'Content-Type': 'application/json' },
  13029. body: JSON.stringify({
  13030. interface: iface,
  13031. enabled,
  13032. add_default_route: defRoute,
  13033. default_route_distance: distance,
  13034. use_peer_dns: peerDns,
  13035. use_peer_ntp: peerNtp,
  13036. comment
  13037. })
  13038. });
  13039. }
  13040. const data = await res.json();
  13041. if (!res.ok) {
  13042. showToast('Error', data.error || 'Failed to save DHCP client', 'error');
  13043. return;
  13044. }
  13045. closeDHCPClientModal();
  13046. showToast('Success', id ? 'DHCP Client updated successfully' : `DHCP Client activated on ${iface}`, 'success');
  13047. await loadDHCPClients();
  13048. fetchData(); // refresh interfaces list with new lease/status
  13049. } catch (err) {
  13050. showToast('Error', err.message, 'error');
  13051. }
  13052. }
  13053. async function toggleDHCPClientState(id, enabled) {
  13054. try {
  13055. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/state`, {
  13056. method: 'POST',
  13057. headers: { 'Content-Type': 'application/json' },
  13058. body: JSON.stringify({ enabled })
  13059. });
  13060. const data = await res.json();
  13061. if (!res.ok) {
  13062. showToast('Error', data.error || 'Failed to toggle client state', 'error');
  13063. return;
  13064. }
  13065. showToast('Updated', `DHCP client ${enabled ? 'enabled' : 'disabled'}`, 'info');
  13066. await loadDHCPClients();
  13067. fetchData();
  13068. } catch (err) {
  13069. showToast('Error', err.message, 'error');
  13070. }
  13071. }
  13072. async function renewDHCPClient(id) {
  13073. try {
  13074. showToast('Renewing...', 'Requesting DHCP lease renewal from upstream server', 'info');
  13075. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/renew`, {
  13076. method: 'POST'
  13077. });
  13078. const data = await res.json();
  13079. if (!res.ok) {
  13080. showToast('Error', data.error || 'Failed to renew lease', 'error');
  13081. return;
  13082. }
  13083. showToast('Lease Renewed', 'DHCP renewal signal sent successfully', 'success');
  13084. setTimeout(() => {
  13085. loadDHCPClients();
  13086. fetchData();
  13087. }, 1500);
  13088. } catch (err) {
  13089. showToast('Error', err.message, 'error');
  13090. }
  13091. }
  13092. async function releaseDHCPClient(id) {
  13093. try {
  13094. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/release`, {
  13095. method: 'POST'
  13096. });
  13097. const data = await res.json();
  13098. if (!res.ok) {
  13099. showToast('Error', data.error || 'Failed to release lease', 'error');
  13100. return;
  13101. }
  13102. showToast('Lease Released', 'DHCP lease released from upstream server', 'info');
  13103. await loadDHCPClients();
  13104. fetchData();
  13105. } catch (err) {
  13106. showToast('Error', err.message, 'error');
  13107. }
  13108. }
  13109. async function deleteDHCPClient(id, ifaceName) {
  13110. if (!confirm(`Are you sure you want to remove the DHCP Client on ${ifaceName}? The interface will release its dynamic IP.`)) {
  13111. return;
  13112. }
  13113. try {
  13114. const res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  13115. method: 'DELETE'
  13116. });
  13117. const data = await res.json();
  13118. if (!res.ok) {
  13119. showToast('Error', data.error || 'Failed to delete DHCP client', 'error');
  13120. return;
  13121. }
  13122. showToast('Deleted', `DHCP client removed from ${ifaceName}`, 'info');
  13123. await loadDHCPClients();
  13124. fetchData();
  13125. } catch (err) {
  13126. showToast('Error', err.message, 'error');
  13127. }
  13128. }
  13129. // ==================== DHCP SERVER (/ip dhcp-server) ====================
  13130. async function loadDHCPServer(populate = true) {
  13131. try {
  13132. const [sumRes, srvRes, netRes, leaseRes, optRes] = await Promise.all([
  13133. fetch(`${API_BASE}/dhcp-server/summary`),
  13134. fetch(`${API_BASE}/dhcp-server/servers`),
  13135. fetch(`${API_BASE}/dhcp-server/networks`),
  13136. fetch(`${API_BASE}/dhcp-server/leases`),
  13137. fetch(`${API_BASE}/dhcp-server/options`)
  13138. ]);
  13139. if (sumRes.ok) state.dhcpServerSummary = await sumRes.json();
  13140. if (srvRes.ok) state.dhcpServers = await srvRes.json();
  13141. if (netRes.ok) state.dhcpNetworks = await netRes.json();
  13142. if (leaseRes.ok) state.dhcpLeases = await leaseRes.json();
  13143. if (optRes.ok) state.dhcpOptions = await optRes.json();
  13144. const sum = state.dhcpServerSummary || {};
  13145. const srvs = state.dhcpServers || [];
  13146. const nets = state.dhcpNetworks || [];
  13147. const leases = state.dhcpLeases || [];
  13148. const opts = state.dhcpOptions || [];
  13149. // KPI Cards
  13150. const statActive = document.getElementById('dhcp-server-stat-active');
  13151. if (statActive) {
  13152. const activeCount = srvs.filter(s => s.running).length;
  13153. statActive.innerText = `${activeCount} / ${srvs.length}`;
  13154. }
  13155. const statLeases = document.getElementById('dhcp-server-stat-leases');
  13156. if (statLeases) {
  13157. statLeases.innerText = leases.length;
  13158. }
  13159. const statLeasesSub = document.getElementById('dhcp-server-stat-leases-sub');
  13160. if (statLeasesSub) {
  13161. const dyn = leases.filter(l => l.dynamic).length;
  13162. const st = leases.filter(l => !l.dynamic).length;
  13163. statLeasesSub.innerText = `${dyn} dynamic, ${st} static`;
  13164. }
  13165. const statNetworks = document.getElementById('dhcp-server-stat-networks');
  13166. if (statNetworks) {
  13167. statNetworks.innerText = nets.length;
  13168. }
  13169. // Subtab Badges
  13170. const bSrv = document.getElementById('dhcp-server-tab-badge-servers');
  13171. if (bSrv) bSrv.innerText = srvs.length;
  13172. const bNet = document.getElementById('dhcp-server-tab-badge-networks');
  13173. if (bNet) bNet.innerText = nets.length;
  13174. const bLease = document.getElementById('dhcp-server-tab-badge-leases');
  13175. if (bLease) bLease.innerText = leases.length;
  13176. const bOpt = document.getElementById('dhcp-server-tab-badge-options');
  13177. if (bOpt) bOpt.innerText = opts.length;
  13178. // Sidebar Badge
  13179. const sideBadge = document.getElementById('badge-dhcp-server-count');
  13180. if (sideBadge) sideBadge.innerText = leases.length || srvs.length;
  13181. renderCurrentDHCPServerTab();
  13182. } catch (err) {
  13183. console.error('Failed to load DHCP Server:', err);
  13184. }
  13185. }
  13186. function switchDHCPServerTab(tab) {
  13187. state.dhcpServerTab = tab;
  13188. const tabs = ['servers', 'networks', 'leases', 'options'];
  13189. tabs.forEach(t => {
  13190. const panel = document.getElementById(`dhcp-server-subtab-${t}`);
  13191. const btn = document.getElementById(`dhcp-server-tab-btn-${t}`);
  13192. if (panel) {
  13193. if (t === tab) panel.classList.remove('hidden');
  13194. else panel.classList.add('hidden');
  13195. }
  13196. if (btn) {
  13197. if (t === tab) {
  13198. 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';
  13199. } else {
  13200. 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';
  13201. }
  13202. }
  13203. });
  13204. const addBtn = document.getElementById('dhcp-server-primary-add-btn');
  13205. if (addBtn) {
  13206. if (tab === 'servers') addBtn.innerHTML = '<span>+ Add Server</span>';
  13207. else if (tab === 'networks') addBtn.innerHTML = '<span>+ Add Network</span>';
  13208. else if (tab === 'leases') addBtn.innerHTML = '<span>+ Add Static Lease</span>';
  13209. else if (tab === 'options') addBtn.innerHTML = '<span>+ Add Option</span>';
  13210. }
  13211. renderCurrentDHCPServerTab();
  13212. }
  13213. function handleDHCPServerPrimaryAdd() {
  13214. const tab = state.dhcpServerTab || 'servers';
  13215. if (tab === 'servers') openAddDHCPServerModal();
  13216. else if (tab === 'networks') openAddDHCPNetworkModal();
  13217. else if (tab === 'leases') openAddDHCPStaticLeaseModal();
  13218. else if (tab === 'options') openAddDHCPOptionModal();
  13219. }
  13220. function renderCurrentDHCPServerTab() {
  13221. const tab = state.dhcpServerTab || 'servers';
  13222. if (tab === 'servers') renderDHCPServers();
  13223. else if (tab === 'networks') renderDHCPNetworks();
  13224. else if (tab === 'leases') renderDHCPLeases();
  13225. else if (tab === 'options') renderDHCPOptions();
  13226. }
  13227. function renderDHCPServers() {
  13228. const tbody = document.getElementById('dhcp-server-tbody');
  13229. const empty = document.getElementById('dhcp-server-empty');
  13230. if (!tbody) return;
  13231. const servers = state.dhcpServers || [];
  13232. if (servers.length === 0) {
  13233. tbody.innerHTML = '';
  13234. empty?.classList.remove('hidden');
  13235. return;
  13236. }
  13237. empty?.classList.add('hidden');
  13238. const sig = servers.map(s => `${s.id}:${s.running}:${s.disabled}:${s.active_leases}:${s.interface}`).join(';');
  13239. if (tbody.dataset.sig === sig) return;
  13240. tbody.dataset.sig = sig;
  13241. tbody.innerHTML = '';
  13242. servers.forEach(s => {
  13243. const tr = document.createElement('tr');
  13244. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  13245. tr.innerHTML = `
  13246. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(s.running, s.disabled)}</td>
  13247. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(s.name)}</td>
  13248. <td class="py-2.5 px-3 font-mono text-cyan-400 font-semibold">${escapeHtml(s.interface)}</td>
  13249. <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>
  13250. <td class="py-2.5 px-3 font-mono text-emerald-400">${escapeHtml(s.address_pool)}</td>
  13251. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(s.lease_time || '12h')}</td>
  13252. <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>
  13253. <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>
  13254. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]" title="${escapeHtml(s.comment || '')}">${escapeHtml(s.comment || '-')}</td>
  13255. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  13256. <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>
  13257. <button onclick="openEditDHCPServerModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  13258. <button onclick="deleteDHCPServer('${s.id}', '${escapeHtml(s.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  13259. </td>
  13260. `;
  13261. tbody.appendChild(tr);
  13262. });
  13263. }
  13264. function renderDHCPNetworks() {
  13265. const tbody = document.getElementById('dhcp-networks-tbody');
  13266. const empty = document.getElementById('dhcp-networks-empty');
  13267. if (!tbody) return;
  13268. tbody.innerHTML = '';
  13269. const networks = state.dhcpNetworks || [];
  13270. if (networks.length === 0) {
  13271. empty?.classList.remove('hidden');
  13272. return;
  13273. }
  13274. empty?.classList.add('hidden');
  13275. networks.forEach(n => {
  13276. const tr = document.createElement('tr');
  13277. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  13278. const dnsStr = (n.dns_servers || []).join(', ') || '-';
  13279. const optionsChips = (n.dhcp_options || []).map(optId => {
  13280. const opt = (state.dhcpOptions || []).find(o => o.id === optId);
  13281. if (!opt) return '';
  13282. 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>`;
  13283. }).filter(Boolean).join('');
  13284. tr.innerHTML = `
  13285. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${escapeHtml(n.address)}</td>
  13286. <td class="py-2.5 px-3 font-mono text-cyan-300 font-semibold">${escapeHtml(n.gateway || '-')}</td>
  13287. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(n.netmask || '-')}</td>
  13288. <td class="py-2.5 px-3 font-mono text-slate-300 truncate max-w-[140px]" title="${escapeHtml(dnsStr)}">${escapeHtml(dnsStr)}</td>
  13289. <td class="py-2.5 px-3 font-mono text-slate-400">${escapeHtml(n.domain || '-')}</td>
  13290. <td class="py-2.5 px-3 font-mono">${optionsChips || '<span class="text-slate-600 font-sans">-</span>'}</td>
  13291. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(n.comment || '')}">${escapeHtml(n.comment || '-')}</td>
  13292. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  13293. <button onclick="openEditDHCPNetworkModal('${n.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  13294. <button onclick="deleteDHCPNetwork('${n.id}', '${escapeHtml(n.address)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  13295. </td>
  13296. `;
  13297. tbody.appendChild(tr);
  13298. });
  13299. }
  13300. function renderDHCPLeases() {
  13301. const tbody = document.getElementById('dhcp-leases-tbody');
  13302. const empty = document.getElementById('dhcp-leases-empty');
  13303. if (!tbody) return;
  13304. tbody.innerHTML = '';
  13305. const leases = state.dhcpLeases || [];
  13306. if (leases.length === 0) {
  13307. empty?.classList.remove('hidden');
  13308. return;
  13309. }
  13310. empty?.classList.add('hidden');
  13311. leases.forEach(l => {
  13312. const tr = document.createElement('tr');
  13313. tr.className = `hover:bg-slate-800/40 transition text-xs ${l.disabled ? 'opacity-50' : ''}`;
  13314. 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>';
  13315. const statusBadge = l.status === 'bound'
  13316. ? '<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>'
  13317. : l.status === 'static'
  13318. ? '<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>'
  13319. : '<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>';
  13320. const makeStaticBtn = l.dynamic
  13321. ? `<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>`
  13322. : `<button onclick="deleteDHCPStaticLease('${l.id}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Remove</button>`;
  13323. tr.innerHTML = `
  13324. <td class="py-2.5 px-3 text-center">${flag}</td>
  13325. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(l.address)}</td>
  13326. <td class="py-2.5 px-3 font-mono text-cyan-300">${escapeHtml(l.mac_address)}</td>
  13327. <td class="py-2.5 px-3 font-sans text-slate-200 font-medium">${escapeHtml(l.hostname || '*')}</td>
  13328. <td class="py-2.5 px-3 font-mono text-slate-400">${escapeHtml(l.server || 'all')}</td>
  13329. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(l.expires_in || 'never')}</td>
  13330. <td class="py-2.5 px-3">${statusBadge}</td>
  13331. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(l.comment || '')}">${escapeHtml(l.comment || '-')}</td>
  13332. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  13333. ${makeStaticBtn}
  13334. </td>
  13335. `;
  13336. tbody.appendChild(tr);
  13337. });
  13338. }
  13339. function renderDHCPOptions() {
  13340. const tbody = document.getElementById('dhcp-options-tbody');
  13341. const empty = document.getElementById('dhcp-options-empty');
  13342. if (!tbody) return;
  13343. tbody.innerHTML = '';
  13344. const options = state.dhcpOptions || [];
  13345. if (options.length === 0) {
  13346. empty?.classList.remove('hidden');
  13347. return;
  13348. }
  13349. empty?.classList.add('hidden');
  13350. options.forEach(o => {
  13351. const tr = document.createElement('tr');
  13352. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  13353. tr.innerHTML = `
  13354. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(o.name)}</td>
  13355. <td class="py-2.5 px-3 font-bold text-cyan-400 font-mono">${o.code}</td>
  13356. <td class="py-2.5 px-3 font-mono text-emerald-400 break-all max-w-xs">${escapeHtml(o.value)}</td>
  13357. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-xs" title="${escapeHtml(o.comment || '')}">${escapeHtml(o.comment || '-')}</td>
  13358. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  13359. <button onclick="openEditDHCPOptionModal('${o.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  13360. <button onclick="deleteDHCPOption('${o.id}', '${escapeHtml(o.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  13361. </td>
  13362. `;
  13363. tbody.appendChild(tr);
  13364. });
  13365. }
  13366. // ==================== MODALS & ACTIONS: SERVER ====================
  13367. function populateDHCPNetworkSelect(elemId, selectedVal) {
  13368. const sel = document.getElementById(elemId);
  13369. if (!sel) return;
  13370. sel.innerHTML = '<option value="">Select network subnet...</option>';
  13371. const networks = state.dhcpNetworks || [];
  13372. networks.forEach(n => {
  13373. const opt = document.createElement('option');
  13374. opt.value = n.address;
  13375. opt.innerText = `${n.address} (Gateway: ${n.gateway || 'None'}${n.comment ? ' - ' + n.comment : ''})`;
  13376. if (selectedVal && (selectedVal === n.address || selectedVal === n.id)) {
  13377. opt.selected = true;
  13378. }
  13379. sel.appendChild(opt);
  13380. });
  13381. }
  13382. function onDHCPServerNetworkChange() {
  13383. const netSel = document.getElementById('dhcp-server-modal-network');
  13384. if (!netSel) return;
  13385. const netVal = netSel.value;
  13386. if (!netVal) return;
  13387. const poolInput = document.getElementById('dhcp-server-modal-pool');
  13388. if (!poolInput) return;
  13389. // Auto-calculate suggested address pool based on subnet CIDR
  13390. const parts = netVal.split('/');
  13391. const ip = parts[0];
  13392. const cidr = parseInt(parts[1] || '24', 10);
  13393. if (cidr === 24) {
  13394. const octets = ip.split('.');
  13395. if (octets.length === 4) {
  13396. const base = `${octets[0]}.${octets[1]}.${octets[2]}`;
  13397. poolInput.value = `${base}.10-${base}.254`;
  13398. }
  13399. }
  13400. }
  13401. function openAddDHCPServerModal() {
  13402. document.getElementById('dhcp-server-modal-title').innerText = 'Add DHCP Server';
  13403. document.getElementById('dhcp-server-modal-id').value = '';
  13404. document.getElementById('dhcp-server-modal-name').value = `dhcp${(state.dhcpServers || []).length + 1}`;
  13405. document.getElementById('dhcp-server-modal-pool').value = '192.168.88.10-192.168.88.254';
  13406. document.getElementById('dhcp-server-modal-leasetime').value = '12h';
  13407. document.getElementById('dhcp-server-modal-comment').value = '';
  13408. document.getElementById('dhcp-server-modal-authoritative').checked = true;
  13409. document.getElementById('dhcp-server-modal-disabled').checked = false;
  13410. populateDHCPIfaceSelect('dhcp-server-modal-iface', '');
  13411. const networks = state.dhcpNetworks || [];
  13412. const defaultNet = networks.length > 0 ? networks[0].address : '';
  13413. populateDHCPNetworkSelect('dhcp-server-modal-network', defaultNet);
  13414. if (defaultNet) {
  13415. onDHCPServerNetworkChange();
  13416. }
  13417. document.getElementById('dhcp-server-instance-modal').classList.remove('hidden');
  13418. }
  13419. function openEditDHCPServerModal(id) {
  13420. const s = (state.dhcpServers || []).find(item => item.id === id);
  13421. if (!s) return;
  13422. document.getElementById('dhcp-server-modal-title').innerText = `Edit DHCP Server (${s.name})`;
  13423. document.getElementById('dhcp-server-modal-id').value = s.id;
  13424. document.getElementById('dhcp-server-modal-name').value = s.name;
  13425. document.getElementById('dhcp-server-modal-pool').value = s.address_pool;
  13426. document.getElementById('dhcp-server-modal-leasetime').value = s.lease_time || '12h';
  13427. document.getElementById('dhcp-server-modal-comment').value = s.comment || '';
  13428. document.getElementById('dhcp-server-modal-authoritative').checked = s.authoritative !== false;
  13429. document.getElementById('dhcp-server-modal-disabled').checked = !!s.disabled;
  13430. populateDHCPIfaceSelect('dhcp-server-modal-iface', s.interface);
  13431. populateDHCPNetworkSelect('dhcp-server-modal-network', s.network || '');
  13432. document.getElementById('dhcp-server-instance-modal').classList.remove('hidden');
  13433. }
  13434. function closeDHCPServerModal() {
  13435. document.getElementById('dhcp-server-instance-modal').classList.add('hidden');
  13436. }
  13437. async function submitSaveDHCPServer(e) {
  13438. e.preventDefault();
  13439. const id = document.getElementById('dhcp-server-modal-id').value;
  13440. const name = document.getElementById('dhcp-server-modal-name').value.trim();
  13441. const iface = document.getElementById('dhcp-server-modal-iface').value;
  13442. const network = document.getElementById('dhcp-server-modal-network').value.trim();
  13443. const pool = document.getElementById('dhcp-server-modal-pool').value.trim();
  13444. const leaseTime = document.getElementById('dhcp-server-modal-leasetime').value.trim() || '12h';
  13445. const comment = document.getElementById('dhcp-server-modal-comment').value.trim();
  13446. const authoritative = document.getElementById('dhcp-server-modal-authoritative').checked;
  13447. const disabled = document.getElementById('dhcp-server-modal-disabled').checked;
  13448. try {
  13449. const res = await fetch(`${API_BASE}/dhcp-server/servers`, {
  13450. method: 'POST',
  13451. headers: { 'Content-Type': 'application/json' },
  13452. body: JSON.stringify({
  13453. id,
  13454. name,
  13455. interface: iface,
  13456. network,
  13457. address_pool: pool,
  13458. lease_time: leaseTime,
  13459. authoritative,
  13460. disabled,
  13461. comment
  13462. })
  13463. });
  13464. if (res.ok) {
  13465. showToast('DHCP Server Saved', `Server ${name} configured successfully`, 'success');
  13466. closeDHCPServerModal();
  13467. loadDHCPServer(false);
  13468. fetchData(false);
  13469. } else {
  13470. const err = await res.text();
  13471. showToast('Error', err, 'error');
  13472. }
  13473. } catch (err) {
  13474. showToast('Error', err.message, 'error');
  13475. }
  13476. }
  13477. async function toggleDHCPServerState(id, disabled) {
  13478. try {
  13479. const res = await fetch(`${API_BASE}/dhcp-server/servers/${encodeURIComponent(id)}/state`, {
  13480. method: 'POST',
  13481. headers: { 'Content-Type': 'application/json' },
  13482. body: JSON.stringify({ disabled })
  13483. });
  13484. if (res.ok) {
  13485. showToast('State Updated', disabled ? 'Server disabled' : 'Server enabled', 'info');
  13486. loadDHCPServer(false);
  13487. fetchData(false);
  13488. }
  13489. } catch (err) {
  13490. showToast('Error', err.message, 'error');
  13491. }
  13492. }
  13493. async function deleteDHCPServer(id, name) {
  13494. if (!confirm(`Are you sure you want to delete DHCP Server "${name}"?`)) return;
  13495. try {
  13496. const res = await fetch(`${API_BASE}/dhcp-server/servers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  13497. if (res.ok) {
  13498. showToast('Deleted', `DHCP Server ${name} removed`, 'success');
  13499. loadDHCPServer(false);
  13500. fetchData(false);
  13501. }
  13502. } catch (err) {
  13503. showToast('Error', err.message, 'error');
  13504. }
  13505. }
  13506. // ==================== MODALS & ACTIONS: NETWORKS ====================
  13507. function openAddDHCPNetworkModal() {
  13508. document.getElementById('dhcp-network-modal-title').innerText = 'Add DHCP Network';
  13509. document.getElementById('dhcp-network-modal-id').value = '';
  13510. document.getElementById('dhcp-network-modal-address').value = '192.168.88.0/24';
  13511. document.getElementById('dhcp-network-modal-gateway').value = '192.168.88.1';
  13512. document.getElementById('dhcp-network-modal-dns').value = '192.168.88.1, 1.1.1.1, 8.8.8.8';
  13513. document.getElementById('dhcp-network-modal-domain').value = 'lan';
  13514. document.getElementById('dhcp-network-modal-netmask').value = '';
  13515. document.getElementById('dhcp-network-modal-comment').value = '';
  13516. renderDHCPNetworkOptionsCheckboxes([]);
  13517. document.getElementById('dhcp-network-modal').classList.remove('hidden');
  13518. }
  13519. function openEditDHCPNetworkModal(id) {
  13520. const n = (state.dhcpNetworks || []).find(item => item.id === id);
  13521. if (!n) return;
  13522. document.getElementById('dhcp-network-modal-title').innerText = `Edit DHCP Network (${n.address})`;
  13523. document.getElementById('dhcp-network-modal-id').value = n.id;
  13524. document.getElementById('dhcp-network-modal-address').value = n.address;
  13525. document.getElementById('dhcp-network-modal-gateway').value = n.gateway || '';
  13526. document.getElementById('dhcp-network-modal-dns').value = (n.dns_servers || []).join(', ');
  13527. document.getElementById('dhcp-network-modal-domain').value = n.domain || '';
  13528. document.getElementById('dhcp-network-modal-netmask').value = n.netmask || '';
  13529. document.getElementById('dhcp-network-modal-comment').value = n.comment || '';
  13530. renderDHCPNetworkOptionsCheckboxes(n.dhcp_options || []);
  13531. document.getElementById('dhcp-network-modal').classList.remove('hidden');
  13532. }
  13533. function renderDHCPNetworkOptionsCheckboxes(selectedIds) {
  13534. const container = document.getElementById('dhcp-network-modal-options-list');
  13535. if (!container) return;
  13536. container.innerHTML = '';
  13537. const opts = state.dhcpOptions || [];
  13538. if (opts.length === 0) {
  13539. container.innerHTML = '<span class="text-slate-500 text-[11px] col-span-2">No custom options configured. Add some in the "Options" tab.</span>';
  13540. return;
  13541. }
  13542. opts.forEach(o => {
  13543. const isChecked = selectedIds.includes(o.id);
  13544. const label = document.createElement('label');
  13545. label.className = 'flex items-center space-x-2 text-slate-300 hover:text-white cursor-pointer';
  13546. label.innerHTML = `
  13547. <input type="checkbox" name="dhcp-net-opt" value="${o.id}" ${isChecked ? 'checked' : ''} class="rounded bg-slate-800 border-slate-700 text-emerald-600">
  13548. <span class="truncate" title="${escapeHtml(o.name)} (Code ${o.code})">${escapeHtml(o.name)} <span class="text-cyan-400">#${o.code}</span></span>
  13549. `;
  13550. container.appendChild(label);
  13551. });
  13552. }
  13553. function closeDHCPNetworkModal() {
  13554. document.getElementById('dhcp-network-modal').classList.add('hidden');
  13555. }
  13556. async function submitSaveDHCPNetwork(e) {
  13557. e.preventDefault();
  13558. const id = document.getElementById('dhcp-network-modal-id').value;
  13559. const address = document.getElementById('dhcp-network-modal-address').value.trim();
  13560. const gateway = document.getElementById('dhcp-network-modal-gateway').value.trim();
  13561. const dnsStr = document.getElementById('dhcp-network-modal-dns').value.trim();
  13562. const domain = document.getElementById('dhcp-network-modal-domain').value.trim();
  13563. const netmask = document.getElementById('dhcp-network-modal-netmask').value.trim();
  13564. const comment = document.getElementById('dhcp-network-modal-comment').value.trim();
  13565. const selectedOpts = [];
  13566. document.querySelectorAll('input[name="dhcp-net-opt"]:checked').forEach(cb => selectedOpts.push(cb.value));
  13567. const dnsServers = dnsStr ? dnsStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  13568. try {
  13569. const res = await fetch(`${API_BASE}/dhcp-server/networks`, {
  13570. method: 'POST',
  13571. headers: { 'Content-Type': 'application/json' },
  13572. body: JSON.stringify({
  13573. id,
  13574. address,
  13575. gateway,
  13576. netmask,
  13577. dns_servers: dnsServers,
  13578. domain,
  13579. dhcp_options: selectedOpts,
  13580. comment
  13581. })
  13582. });
  13583. if (res.ok) {
  13584. showToast('Network Saved', `Subnet ${address} configured successfully`, 'success');
  13585. closeDHCPNetworkModal();
  13586. loadDHCPServer(false);
  13587. fetchData(false);
  13588. } else {
  13589. const err = await res.text();
  13590. showToast('Error', err, 'error');
  13591. }
  13592. } catch (err) {
  13593. showToast('Error', err.message, 'error');
  13594. }
  13595. }
  13596. async function deleteDHCPNetwork(id, addr) {
  13597. if (!confirm(`Are you sure you want to delete DHCP Network "${addr}"?`)) return;
  13598. try {
  13599. const res = await fetch(`${API_BASE}/dhcp-server/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  13600. if (res.ok) {
  13601. showToast('Deleted', `Network ${addr} removed`, 'success');
  13602. loadDHCPServer(false);
  13603. fetchData(false);
  13604. }
  13605. } catch (err) {
  13606. showToast('Error', err.message, 'error');
  13607. }
  13608. }
  13609. // ==================== MODALS & ACTIONS: LEASES ====================
  13610. function openAddDHCPStaticLeaseModal() {
  13611. document.getElementById('dhcp-static-lease-modal-title').innerText = 'Add Static Lease Reservation';
  13612. document.getElementById('dhcp-static-lease-modal-id').value = '';
  13613. document.getElementById('dhcp-static-lease-modal-mac').value = '';
  13614. document.getElementById('dhcp-static-lease-modal-ip').value = '';
  13615. document.getElementById('dhcp-static-lease-modal-hostname').value = '';
  13616. document.getElementById('dhcp-static-lease-modal-server').value = 'all';
  13617. document.getElementById('dhcp-static-lease-modal-comment').value = '';
  13618. document.getElementById('dhcp-static-lease-modal-disabled').checked = false;
  13619. document.getElementById('dhcp-static-lease-modal').classList.remove('hidden');
  13620. }
  13621. function closeDHCPStaticLeaseModal() {
  13622. document.getElementById('dhcp-static-lease-modal').classList.add('hidden');
  13623. }
  13624. async function submitSaveDHCPStaticLease(e) {
  13625. e.preventDefault();
  13626. const id = document.getElementById('dhcp-static-lease-modal-id').value;
  13627. const mac = document.getElementById('dhcp-static-lease-modal-mac').value.trim();
  13628. const ip = document.getElementById('dhcp-static-lease-modal-ip').value.trim();
  13629. const hostname = document.getElementById('dhcp-static-lease-modal-hostname').value.trim();
  13630. const server = document.getElementById('dhcp-static-lease-modal-server').value.trim() || 'all';
  13631. const comment = document.getElementById('dhcp-static-lease-modal-comment').value.trim();
  13632. const disabled = document.getElementById('dhcp-static-lease-modal-disabled').checked;
  13633. try {
  13634. const res = await fetch(`${API_BASE}/dhcp-server/leases/static`, {
  13635. method: 'POST',
  13636. headers: { 'Content-Type': 'application/json' },
  13637. body: JSON.stringify({
  13638. id,
  13639. mac_address: mac,
  13640. address: ip,
  13641. hostname,
  13642. server,
  13643. comment,
  13644. disabled
  13645. })
  13646. });
  13647. if (res.ok) {
  13648. showToast('Static Lease Saved', `IP ${ip} reserved for ${mac}`, 'success');
  13649. closeDHCPStaticLeaseModal();
  13650. loadDHCPServer(false);
  13651. fetchData(false);
  13652. } else {
  13653. const err = await res.text();
  13654. showToast('Error', err, 'error');
  13655. }
  13656. } catch (err) {
  13657. showToast('Error', err.message, 'error');
  13658. }
  13659. }
  13660. async function deleteDHCPStaticLease(id) {
  13661. if (!confirm('Are you sure you want to remove this static reservation?')) return;
  13662. try {
  13663. const res = await fetch(`${API_BASE}/dhcp-server/leases/${encodeURIComponent(id)}`, { method: 'DELETE' });
  13664. if (res.ok) {
  13665. showToast('Deleted', 'Static lease removed', 'success');
  13666. loadDHCPServer(false);
  13667. fetchData(false);
  13668. }
  13669. } catch (err) {
  13670. showToast('Error', err.message, 'error');
  13671. }
  13672. }
  13673. async function makeDHCPLeaseStatic(mac, ip, hostname, comment) {
  13674. try {
  13675. const res = await fetch(`${API_BASE}/dhcp-server/leases/make-static`, {
  13676. method: 'POST',
  13677. headers: { 'Content-Type': 'application/json' },
  13678. body: JSON.stringify({
  13679. mac_address: mac,
  13680. address: ip,
  13681. hostname,
  13682. comment: comment || 'Converted to static'
  13683. })
  13684. });
  13685. if (res.ok) {
  13686. showToast('Lease Made Static', `IP ${ip} permanently reserved for ${mac}`, 'success');
  13687. loadDHCPServer(false);
  13688. fetchData(false);
  13689. } else {
  13690. const err = await res.text();
  13691. showToast('Error', err, 'error');
  13692. }
  13693. } catch (err) {
  13694. showToast('Error', err.message, 'error');
  13695. }
  13696. }
  13697. // ==================== MODALS & ACTIONS: OPTIONS ====================
  13698. function openAddDHCPOptionModal() {
  13699. document.getElementById('dhcp-option-modal-title').innerText = 'Add DHCP Option';
  13700. document.getElementById('dhcp-option-modal-id').value = '';
  13701. document.getElementById('dhcp-option-modal-name').value = '';
  13702. document.getElementById('dhcp-option-modal-code').value = '';
  13703. document.getElementById('dhcp-option-modal-value').value = '';
  13704. document.getElementById('dhcp-option-modal-comment').value = '';
  13705. document.getElementById('dhcp-option-modal').classList.remove('hidden');
  13706. }
  13707. function openEditDHCPOptionModal(id) {
  13708. const o = (state.dhcpOptions || []).find(item => item.id === id);
  13709. if (!o) return;
  13710. document.getElementById('dhcp-option-modal-title').innerText = `Edit DHCP Option (${o.name})`;
  13711. document.getElementById('dhcp-option-modal-id').value = o.id;
  13712. document.getElementById('dhcp-option-modal-name').value = o.name;
  13713. document.getElementById('dhcp-option-modal-code').value = o.code;
  13714. document.getElementById('dhcp-option-modal-value').value = o.value;
  13715. document.getElementById('dhcp-option-modal-comment').value = o.comment || '';
  13716. document.getElementById('dhcp-option-modal').classList.remove('hidden');
  13717. }
  13718. function closeDHCPOptionModal() {
  13719. document.getElementById('dhcp-option-modal').classList.add('hidden');
  13720. }
  13721. async function submitSaveDHCPOption(e) {
  13722. e.preventDefault();
  13723. const id = document.getElementById('dhcp-option-modal-id').value;
  13724. const name = document.getElementById('dhcp-option-modal-name').value.trim();
  13725. const code = parseInt(document.getElementById('dhcp-option-modal-code').value);
  13726. const value = document.getElementById('dhcp-option-modal-value').value.trim();
  13727. const comment = document.getElementById('dhcp-option-modal-comment').value.trim();
  13728. try {
  13729. const res = await fetch(`${API_BASE}/dhcp-server/options`, {
  13730. method: 'POST',
  13731. headers: { 'Content-Type': 'application/json' },
  13732. body: JSON.stringify({ id, name, code, value, comment })
  13733. });
  13734. if (res.ok) {
  13735. showToast('Option Saved', `DHCP option ${name} (#${code}) configured`, 'success');
  13736. closeDHCPOptionModal();
  13737. loadDHCPServer(false);
  13738. fetchData(false);
  13739. } else {
  13740. const err = await res.text();
  13741. showToast('Error', err, 'error');
  13742. }
  13743. } catch (err) {
  13744. showToast('Error', err.message, 'error');
  13745. }
  13746. }
  13747. async function deleteDHCPOption(id, name) {
  13748. if (!confirm(`Are you sure you want to delete DHCP Option "${name}"?`)) return;
  13749. try {
  13750. const res = await fetch(`${API_BASE}/dhcp-server/options/${encodeURIComponent(id)}`, { method: 'DELETE' });
  13751. if (res.ok) {
  13752. showToast('Deleted', `Option ${name} removed`, 'success');
  13753. loadDHCPServer(false);
  13754. fetchData(false);
  13755. }
  13756. } catch (err) {
  13757. showToast('Error', err.message, 'error');
  13758. }
  13759. }
  13760. // ==================== WIZARD: DHCP SETUP (MikroTik style) ====================
  13761. function openDHCPServerSetupModal() {
  13762. populateDHCPIfaceSelect('dhcp-wizard-iface', '');
  13763. onDHCPWizardIfaceChange();
  13764. document.getElementById('dhcp-setup-wizard-modal').classList.remove('hidden');
  13765. }
  13766. function closeDHCPServerSetupModal() {
  13767. document.getElementById('dhcp-setup-wizard-modal').classList.add('hidden');
  13768. }
  13769. function onDHCPWizardIfaceChange() {
  13770. const ifaceName = document.getElementById('dhcp-wizard-iface').value;
  13771. const iface = (state.interfaces || []).find(i => i.name === ifaceName);
  13772. let ip = '192.168.88.1';
  13773. let prefix = '24';
  13774. if (iface && iface.ip_address) {
  13775. const parts = iface.ip_address.split('/');
  13776. ip = parts[0];
  13777. if (parts.length > 1) prefix = parts[1];
  13778. }
  13779. // Calculate subnet base (e.g. 192.168.88.0/24)
  13780. const ipParts = ip.split('.');
  13781. if (ipParts.length === 4) {
  13782. const baseSpace = `${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.0/${prefix}`;
  13783. const pool = `${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.10-${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.254`;
  13784. document.getElementById('dhcp-wizard-space').value = baseSpace;
  13785. document.getElementById('dhcp-wizard-gateway').value = ip;
  13786. document.getElementById('dhcp-wizard-pool').value = pool;
  13787. document.getElementById('dhcp-wizard-dns').value = `${ip}, 1.1.1.1, 8.8.8.8`;
  13788. document.getElementById('dhcp-wizard-ntp').value = `${ip}`;
  13789. }
  13790. }
  13791. async function submitDHCPServerSetupWizard(e) {
  13792. e.preventDefault();
  13793. const iface = document.getElementById('dhcp-wizard-iface').value;
  13794. const space = document.getElementById('dhcp-wizard-space').value.trim();
  13795. const gw = document.getElementById('dhcp-wizard-gateway').value.trim();
  13796. const pool = document.getElementById('dhcp-wizard-pool').value.trim();
  13797. const dnsStr = document.getElementById('dhcp-wizard-dns').value.trim();
  13798. const leaseTime = document.getElementById('dhcp-wizard-leasetime').value.trim() || '12h';
  13799. const ntpStr = document.getElementById('dhcp-wizard-ntp').value.trim();
  13800. const tftp = document.getElementById('dhcp-wizard-tftp').value.trim();
  13801. const dnsServers = dnsStr ? dnsStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  13802. const ntpServers = ntpStr ? ntpStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  13803. try {
  13804. const res = await fetch(`${API_BASE}/dhcp-server/setup`, {
  13805. method: 'POST',
  13806. headers: { 'Content-Type': 'application/json' },
  13807. body: JSON.stringify({
  13808. interface: iface,
  13809. address_space: space,
  13810. gateway: gw,
  13811. address_pool: pool,
  13812. dns_servers: dnsServers,
  13813. lease_time: leaseTime,
  13814. ntp_servers: ntpServers,
  13815. next_server: tftp
  13816. })
  13817. });
  13818. if (res.ok) {
  13819. showToast('DHCP Setup Complete', `DHCP Server setup finished on ${iface}`, 'success');
  13820. closeDHCPServerSetupModal();
  13821. loadDHCPServer(false);
  13822. fetchData(false);
  13823. } else {
  13824. const err = await res.text();
  13825. showToast('Error', err, 'error');
  13826. }
  13827. } catch (err) {
  13828. showToast('Error', err.message, 'error');
  13829. }
  13830. }
  13831. function populateDHCPIfaceSelect(elemId, selectedVal) {
  13832. const sel = document.getElementById(elemId);
  13833. if (!sel) return;
  13834. sel.innerHTML = '<option value="">Select interface...</option>';
  13835. const ifaces = state.interfaces || [];
  13836. ifaces.forEach(i => {
  13837. if (i.name === 'lo') return;
  13838. const opt = document.createElement('option');
  13839. opt.value = i.name;
  13840. const ipStr = i.ip_address ? ` (${i.ip_address})` : '';
  13841. opt.textContent = `${i.name}${ipStr} [${i.role || i.type || 'interface'}]`;
  13842. if (i.name === selectedVal) opt.selected = true;
  13843. sel.appendChild(opt);
  13844. });
  13845. }
  13846. // ==================== UNIVERSAL TABLE ORDERING / SORTING (WINBOX / WEBFIG STYLE) ====================
  13847. function initTableSorting() {
  13848. document.querySelectorAll('table').forEach(setupSortableTable);
  13849. }
  13850. function setupSortableTable(table) {
  13851. const thead = table.querySelector('thead');
  13852. const tbody = table.querySelector('tbody');
  13853. if (!thead || !tbody) return;
  13854. const headerRows = thead.querySelectorAll('tr');
  13855. if (headerRows.length === 0) return;
  13856. const ths = headerRows[headerRows.length - 1].querySelectorAll('th');
  13857. ths.forEach((th, colIdx) => {
  13858. if (th._sortBound) return;
  13859. th._sortBound = true;
  13860. const rawText = th.innerText.trim().toLowerCase();
  13861. const isActionsCol = rawText === 'actions' || (rawText === 'action' && th.classList.contains('text-right'));
  13862. const isCheckboxCol = !!th.querySelector('input[type="checkbox"]');
  13863. const isExpandCol = (th.classList.contains('w-8') || th.classList.contains('w-6')) && !rawText;
  13864. const isExplicitNoSort = th.classList.contains('no-sort') || th.getAttribute('data-sortable') === 'false';
  13865. if (isActionsCol || isCheckboxCol || isExpandCol || isExplicitNoSort) {
  13866. return;
  13867. }
  13868. th.classList.add('table-sortable', 'group');
  13869. if (!th.title) th.title = 'Click to sort (Ascending / Descending / Default)';
  13870. let icon = th.querySelector('.table-sort-icon');
  13871. if (!icon) {
  13872. icon = document.createElement('span');
  13873. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  13874. icon.innerHTML = '⇅';
  13875. th.appendChild(icon);
  13876. }
  13877. th.addEventListener('click', (e) => {
  13878. if (e.target.tagName === 'INPUT' || e.target.tagName === 'BUTTON' || e.target.closest('button, input')) return;
  13879. handleHeaderClick(table, th, colIdx);
  13880. });
  13881. });
  13882. if (!tbody._sortObserved) {
  13883. tbody._sortObserved = true;
  13884. let sortDebounceTimer = null;
  13885. const observer = new MutationObserver((mutations) => {
  13886. if (tbody._isSorting) return;
  13887. const hasChildChanges = mutations.some(m => m.type === 'childList' && m.addedNodes.length > 0);
  13888. if (!hasChildChanges) return;
  13889. clearTimeout(sortDebounceTimer);
  13890. sortDebounceTimer = setTimeout(() => {
  13891. if (tbody._isSorting) return;
  13892. if (table._activeSort && table._activeSort.dir !== 'none') {
  13893. applyTableSort(table, table._activeSort.colIdx, table._activeSort.dir, false);
  13894. } else {
  13895. tagOriginalRowOrder(tbody);
  13896. }
  13897. }, 50);
  13898. });
  13899. tbody._sortObserver = observer;
  13900. observer.observe(tbody, { childList: true });
  13901. }
  13902. tagOriginalRowOrder(tbody);
  13903. }
  13904. function tagOriginalRowOrder(tbody) {
  13905. let idx = 0;
  13906. Array.from(tbody.children).forEach(tr => {
  13907. if (!tr.querySelector('td[colspan]')) {
  13908. if (!tr.hasAttribute('data-orig-idx')) {
  13909. tr.setAttribute('data-orig-idx', idx++);
  13910. }
  13911. }
  13912. });
  13913. }
  13914. function handleHeaderClick(table, th, colIdx) {
  13915. const currentSort = table._activeSort || { colIdx: -1, dir: 'none' };
  13916. let newDir = 'asc';
  13917. if (currentSort.colIdx === colIdx) {
  13918. if (currentSort.dir === 'asc') newDir = 'desc';
  13919. else if (currentSort.dir === 'desc') newDir = 'none';
  13920. else newDir = 'asc';
  13921. } else {
  13922. newDir = 'asc';
  13923. }
  13924. table._activeSort = { colIdx, dir: newDir };
  13925. updateHeaderIcons(table, colIdx, newDir);
  13926. applyTableSort(table, colIdx, newDir, true);
  13927. }
  13928. function updateHeaderIcons(table, activeColIdx, dir) {
  13929. const thead = table.querySelector('thead');
  13930. if (!thead) return;
  13931. const ths = thead.querySelectorAll('th');
  13932. ths.forEach((th, idx) => {
  13933. const icon = th.querySelector('.table-sort-icon');
  13934. if (!icon) return;
  13935. if (idx === activeColIdx && dir !== 'none') {
  13936. icon.innerHTML = dir === 'asc' ? '▲' : '▼';
  13937. icon.className = 'table-sort-icon text-cyan-400 font-bold opacity-100';
  13938. th.classList.add('table-sorted-active');
  13939. } else {
  13940. icon.innerHTML = '⇅';
  13941. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  13942. th.classList.remove('table-sorted-active');
  13943. }
  13944. });
  13945. }
  13946. function applyTableSort(table, colIdx, dir, userInitiated) {
  13947. const tbody = table.querySelector('tbody');
  13948. if (!tbody || tbody.children.length <= 1) return;
  13949. tbody._isSorting = true;
  13950. tagOriginalRowOrder(tbody);
  13951. // Group parent rows and any attached drawer/sub-rows
  13952. const groups = [];
  13953. let currentGroup = null;
  13954. Array.from(tbody.children).forEach(tr => {
  13955. if (tr.querySelector('td[colspan]')) {
  13956. if (currentGroup) {
  13957. currentGroup.subRows.push(tr);
  13958. } else {
  13959. groups.push({ mainRow: tr, subRows: [] });
  13960. }
  13961. } else {
  13962. currentGroup = { mainRow: tr, subRows: [] };
  13963. groups.push(currentGroup);
  13964. }
  13965. });
  13966. if (dir === 'none') {
  13967. groups.sort((a, b) => {
  13968. const idxA = parseInt(a.mainRow.getAttribute('data-orig-idx') || '0', 10);
  13969. const idxB = parseInt(b.mainRow.getAttribute('data-orig-idx') || '0', 10);
  13970. return idxA - idxB;
  13971. });
  13972. } else {
  13973. groups.sort((a, b) => {
  13974. const cellA = a.mainRow.children[colIdx];
  13975. const cellB = b.mainRow.children[colIdx];
  13976. const res = compareTableCells(cellA, cellB);
  13977. return dir === 'asc' ? res : -res;
  13978. });
  13979. }
  13980. // Check if rows are already in correct order to avoid modifying DOM
  13981. let alreadyOrdered = true;
  13982. let childIdx = 0;
  13983. for (const g of groups) {
  13984. if (tbody.children[childIdx] !== g.mainRow) {
  13985. alreadyOrdered = false;
  13986. break;
  13987. }
  13988. childIdx++;
  13989. for (const sub of g.subRows) {
  13990. if (tbody.children[childIdx] !== sub) {
  13991. alreadyOrdered = false;
  13992. break;
  13993. }
  13994. childIdx++;
  13995. }
  13996. }
  13997. if (alreadyOrdered) {
  13998. tbody._isSorting = false;
  13999. return;
  14000. }
  14001. // Disconnect observer while re-ordering to prevent recursion and thrashing
  14002. if (tbody._sortObserver) {
  14003. tbody._sortObserver.disconnect();
  14004. }
  14005. // Re-append rows in sorted order
  14006. groups.forEach(g => {
  14007. tbody.appendChild(g.mainRow);
  14008. g.subRows.forEach(sub => tbody.appendChild(sub));
  14009. });
  14010. // Drain any queued mutations and re-connect observer
  14011. if (tbody._sortObserver) {
  14012. tbody._sortObserver.takeRecords();
  14013. tbody._sortObserver.observe(tbody, { childList: true });
  14014. }
  14015. tbody._isSorting = false;
  14016. }
  14017. function getCellRawText(cell) {
  14018. if (!cell) return '';
  14019. if (cell.hasAttribute('data-sort-value')) return cell.getAttribute('data-sort-value');
  14020. const input = cell.querySelector('input, select');
  14021. if (input) {
  14022. if (input.type === 'checkbox') return input.checked ? '1' : '0';
  14023. return input.value;
  14024. }
  14025. return cell.innerText.trim();
  14026. }
  14027. function parseTrafficToNumber(str) {
  14028. const m = str.match(/^([\d.,]+)\s*([KMGTkmgt]?[iI]?[Bb](?:ps|\/s)?)/);
  14029. if (!m) return null;
  14030. const num = parseFloat(m[1].replace(/,/g, ''));
  14031. if (isNaN(num)) return null;
  14032. const unit = m[2].toUpperCase();
  14033. let mult = 1;
  14034. if (unit.startsWith('K')) mult = 1024;
  14035. else if (unit.startsWith('M')) mult = 1024 * 1024;
  14036. else if (unit.startsWith('G')) mult = 1024 * 1024 * 1024;
  14037. else if (unit.startsWith('T')) mult = 1024 * 1024 * 1024 * 1024;
  14038. return num * mult;
  14039. }
  14040. function parseIpToNumber(str) {
  14041. const clean = str.replace(/^[!~]/, '').trim();
  14042. const m = clean.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(?:\/(\d{1,2}))?/);
  14043. if (!m) return null;
  14044. const o1 = parseInt(m[1], 10);
  14045. const o2 = parseInt(m[2], 10);
  14046. const o3 = parseInt(m[3], 10);
  14047. const o4 = parseInt(m[4], 10);
  14048. if (o1 > 255 || o2 > 255 || o3 > 255 || o4 > 255) return null;
  14049. return ((o1 * 256 + o2) * 256 + o3) * 256 + o4;
  14050. }
  14051. function parseCompoundPackets(str) {
  14052. const m = str.match(/^([\d,]+)p/);
  14053. if (!m) return null;
  14054. return parseInt(m[1].replace(/,/g, ''), 10);
  14055. }
  14056. function compareTableCells(cellA, cellB) {
  14057. const a = getCellRawText(cellA);
  14058. const b = getCellRawText(cellB);
  14059. if (a === '' && b !== '') return 1;
  14060. if (b === '' && a !== '') return -1;
  14061. if (a === b) return 0;
  14062. // 1. IP Addresses / CIDR
  14063. const ipA = parseIpToNumber(a);
  14064. const ipB = parseIpToNumber(b);
  14065. if (ipA !== null && ipB !== null) return ipA - ipB;
  14066. // 2. Packet counts (e.g. "1,250p / 45 KB")
  14067. const pktA = parseCompoundPackets(a);
  14068. const pktB = parseCompoundPackets(b);
  14069. if (pktA !== null && pktB !== null) return pktA - pktB;
  14070. // 3. Traffic / Throughput / Bytes (e.g. "1.2 MB", "500 KiB", "10 Gbps")
  14071. const trafA = parseTrafficToNumber(a);
  14072. const trafB = parseTrafficToNumber(b);
  14073. if (trafA !== null && trafB !== null) return trafA - trafB;
  14074. // 4. Numbers with '#' or formatted with commas (e.g. "#1", "24", "1,200")
  14075. const cleanNumA = a.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  14076. const cleanNumB = b.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  14077. const numA = Number(cleanNumA);
  14078. const numB = Number(cleanNumB);
  14079. if (!isNaN(numA) && !isNaN(numB) && cleanNumA !== '' && cleanNumB !== '') {
  14080. return numA - numB;
  14081. }
  14082. // 5. Natural case-insensitive string compare
  14083. return a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' });
  14084. }
  14085. // ==================== VRRP HIGH AVAILABILITY CONTROLLER ====================
  14086. async function loadVRRP(showToastNotification = false) {
  14087. try {
  14088. const [instRes, sumRes] = await Promise.all([
  14089. fetch(`${API_BASE}/vrrp/instances`),
  14090. fetch(`${API_BASE}/vrrp/summary`)
  14091. ]);
  14092. if (instRes.ok) {
  14093. state.vrrpInstances = await instRes.json();
  14094. renderVRRP();
  14095. }
  14096. if (sumRes.ok) {
  14097. state.vrrpSummary = await sumRes.json();
  14098. renderVRRPSummary();
  14099. }
  14100. if (showToastNotification) {
  14101. showToast('Refreshed', 'VRRP telemetry refreshed', 'info');
  14102. }
  14103. } catch (err) {
  14104. console.error('Failed to load VRRP:', err);
  14105. }
  14106. }
  14107. function renderVRRPSummary() {
  14108. const s = state.vrrpSummary || { total_instances: 0, master_instances: 0, backup_instances: 0 };
  14109. const elTotal = document.getElementById('vrrp-stat-total');
  14110. if (elTotal) elTotal.innerText = s.total_instances || 0;
  14111. const elMaster = document.getElementById('vrrp-stat-master');
  14112. if (elMaster) elMaster.innerText = s.master_instances || 0;
  14113. const elBackup = document.getElementById('vrrp-stat-backup');
  14114. if (elBackup) elBackup.innerText = s.backup_instances || 0;
  14115. const bCount = document.getElementById('badge-vrrp-count');
  14116. if (bCount) bCount.innerText = s.total_instances || 0;
  14117. const dot = document.getElementById('badge-vrrp-dot');
  14118. if (dot) {
  14119. if (s.master_instances > 0) {
  14120. dot.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  14121. } else if (s.backup_instances > 0) {
  14122. dot.className = 'w-2 h-2 rounded-full bg-sky-400';
  14123. } else {
  14124. dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  14125. }
  14126. }
  14127. }
  14128. function renderVRRP() {
  14129. const tbody = document.getElementById('vrrp-table-tbody');
  14130. const empty = document.getElementById('vrrp-table-empty');
  14131. if (!tbody) return;
  14132. tbody.innerHTML = '';
  14133. const instances = state.vrrpInstances || [];
  14134. if (instances.length === 0) {
  14135. empty?.classList.remove('hidden');
  14136. return;
  14137. }
  14138. empty?.classList.add('hidden');
  14139. instances.forEach(inst => {
  14140. const tr = document.createElement('tr');
  14141. tr.className = `hover:bg-slate-800/40 transition text-xs ${inst.disabled ? 'opacity-50' : ''}`;
  14142. // Render Flag: M (Master), B (Backup), F (Fault), X (Disabled)
  14143. 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>`;
  14144. if (inst.disabled) {
  14145. 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>`;
  14146. } else if (inst.state === 'MASTER') {
  14147. 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>`;
  14148. } else if (inst.state === 'BACKUP') {
  14149. 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>`;
  14150. } else if (inst.state === 'FAULT') {
  14151. 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>`;
  14152. }
  14153. // Render State Badge
  14154. let stateBadge = `<span class="px-2 py-0.5 rounded text-[10px] bg-slate-800 text-slate-400 border border-slate-700">DISABLED</span>`;
  14155. if (!inst.disabled) {
  14156. if (inst.state === 'MASTER') {
  14157. 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>`;
  14158. } else if (inst.state === 'BACKUP') {
  14159. 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>`;
  14160. } else if (inst.state === 'FAULT') {
  14161. 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>`;
  14162. }
  14163. }
  14164. const vipsStr = (inst.virtual_ips || []).join(', ') || '-';
  14165. tr.innerHTML = `
  14166. <td class="py-2.5 px-3 text-center">${flagHtml}</td>
  14167. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(inst.name)}</td>
  14168. <td class="py-2.5 px-3 font-mono text-cyan-400 font-semibold">${escapeHtml(inst.interface)}</td>
  14169. <td class="py-2.5 px-3 font-mono font-bold text-center text-white">${inst.vrid}</td>
  14170. <td class="py-2.5 px-3 font-mono text-center text-slate-300 font-semibold">${inst.priority}</td>
  14171. <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>
  14172. <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>
  14173. <td class="py-2.5 px-3 font-mono text-slate-400 text-[11px]">${escapeHtml(inst.virtual_mac || '-')}</td>
  14174. <td class="py-2.5 px-3 text-center">${stateBadge}</td>
  14175. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]" title="${escapeHtml(inst.comment || '')}">${escapeHtml(inst.comment || '-')}</td>
  14176. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  14177. <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>
  14178. <button onclick="openEditVRRPModal('${inst.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  14179. <button onclick="deleteVRRP('${inst.id}', '${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  14180. </td>
  14181. `;
  14182. tbody.appendChild(tr);
  14183. });
  14184. }
  14185. function populateVRRPIfaceSelect(elemId, selectedIface) {
  14186. const sel = document.getElementById(elemId);
  14187. if (!sel) return;
  14188. sel.innerHTML = '<option value="">Select interface...</option>';
  14189. const ifaces = state.interfaces || [];
  14190. ifaces.forEach(i => {
  14191. const opt = document.createElement('option');
  14192. opt.value = i.name;
  14193. opt.innerText = `${i.name} (${i.type || 'net'}${i.ip ? ' - ' + i.ip : ''})`;
  14194. if (selectedIface && selectedIface === i.name) opt.selected = true;
  14195. sel.appendChild(opt);
  14196. });
  14197. }
  14198. function openAddVRRPModal() {
  14199. document.getElementById('modal-vrrp-title').innerText = 'Add VRRP Instance';
  14200. document.getElementById('modal-vrrp-id').value = '';
  14201. document.getElementById('modal-vrrp-name').value = `vrrp${(state.vrrpInstances || []).length + 1}`;
  14202. document.getElementById('modal-vrrp-vrid').value = 10 + (state.vrrpInstances || []).length;
  14203. document.getElementById('modal-vrrp-priority').value = 100;
  14204. document.getElementById('modal-vrrp-vip').value = '192.168.88.254/24';
  14205. document.getElementById('modal-vrrp-version').value = '3';
  14206. document.getElementById('modal-vrrp-interval').value = 1;
  14207. document.getElementById('modal-vrrp-authtype').value = 'none';
  14208. document.getElementById('modal-vrrp-authpass').value = '';
  14209. document.getElementById('modal-vrrp-comment').value = '';
  14210. document.getElementById('modal-vrrp-preempt').checked = true;
  14211. document.getElementById('modal-vrrp-disabled').checked = false;
  14212. populateVRRPIfaceSelect('modal-vrrp-iface', '');
  14213. document.getElementById('modal-vrrp-instance').classList.remove('hidden');
  14214. }
  14215. function openEditVRRPModal(id) {
  14216. const inst = (state.vrrpInstances || []).find(item => item.id === id);
  14217. if (!inst) return;
  14218. document.getElementById('modal-vrrp-title').innerText = `Edit VRRP Instance (${inst.name})`;
  14219. document.getElementById('modal-vrrp-id').value = inst.id;
  14220. document.getElementById('modal-vrrp-name').value = inst.name;
  14221. document.getElementById('modal-vrrp-vrid').value = inst.vrid;
  14222. document.getElementById('modal-vrrp-priority').value = inst.priority;
  14223. document.getElementById('modal-vrrp-vip').value = (inst.virtual_ips || []).join(', ');
  14224. document.getElementById('modal-vrrp-version').value = String(inst.version || 3);
  14225. document.getElementById('modal-vrrp-interval').value = inst.interval || 1;
  14226. document.getElementById('modal-vrrp-authtype').value = inst.auth_type || 'none';
  14227. document.getElementById('modal-vrrp-authpass').value = inst.auth_password || '';
  14228. document.getElementById('modal-vrrp-comment').value = inst.comment || '';
  14229. document.getElementById('modal-vrrp-preempt').checked = inst.preempt !== false;
  14230. document.getElementById('modal-vrrp-disabled').checked = !!inst.disabled;
  14231. populateVRRPIfaceSelect('modal-vrrp-iface', inst.interface);
  14232. document.getElementById('modal-vrrp-instance').classList.remove('hidden');
  14233. }
  14234. function closeVRRPModal() {
  14235. document.getElementById('modal-vrrp-instance').classList.add('hidden');
  14236. }
  14237. async function submitSaveVRRP(e) {
  14238. e.preventDefault();
  14239. const id = document.getElementById('modal-vrrp-id').value;
  14240. const name = document.getElementById('modal-vrrp-name').value.trim();
  14241. const iface = document.getElementById('modal-vrrp-iface').value;
  14242. const vrid = parseInt(document.getElementById('modal-vrrp-vrid').value, 10) || 1;
  14243. const priority = parseInt(document.getElementById('modal-vrrp-priority').value, 10) || 100;
  14244. const vipRaw = document.getElementById('modal-vrrp-vip').value.trim();
  14245. const version = parseInt(document.getElementById('modal-vrrp-version').value, 10) || 3;
  14246. const interval = parseInt(document.getElementById('modal-vrrp-interval').value, 10) || 1;
  14247. const authType = document.getElementById('modal-vrrp-authtype').value;
  14248. const authPass = document.getElementById('modal-vrrp-authpass').value.trim();
  14249. const comment = document.getElementById('modal-vrrp-comment').value.trim();
  14250. const preempt = document.getElementById('modal-vrrp-preempt').checked;
  14251. const disabled = document.getElementById('modal-vrrp-disabled').checked;
  14252. const vips = vipRaw.split(',').map(s => s.trim()).filter(Boolean);
  14253. try {
  14254. const res = await fetch(`${API_BASE}/vrrp/instances`, {
  14255. method: 'POST',
  14256. headers: { 'Content-Type': 'application/json' },
  14257. body: JSON.stringify({
  14258. id,
  14259. name,
  14260. interface: iface,
  14261. vrid,
  14262. priority,
  14263. virtual_ips: vips,
  14264. version,
  14265. interval,
  14266. auth_type: authType,
  14267. auth_password: authPass,
  14268. comment,
  14269. preempt,
  14270. disabled
  14271. })
  14272. });
  14273. if (res.ok) {
  14274. showToast('VRRP Saved', `VRRP instance ${name} configured`, 'success');
  14275. closeVRRPModal();
  14276. loadVRRP(false);
  14277. fetchData(false);
  14278. } else {
  14279. const err = await res.text();
  14280. showToast('Error', err, 'error');
  14281. }
  14282. } catch (err) {
  14283. showToast('Error', err.message, 'error');
  14284. }
  14285. }
  14286. async function deleteVRRP(id, name) {
  14287. if (!confirm(`Delete VRRP instance "${name}"?`)) return;
  14288. try {
  14289. const res = await fetch(`${API_BASE}/vrrp/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  14290. if (res.ok) {
  14291. showToast('Deleted', `VRRP instance ${name} removed`, 'info');
  14292. loadVRRP(false);
  14293. fetchData(false);
  14294. } else {
  14295. const err = await res.text();
  14296. showToast('Error', err, 'error');
  14297. }
  14298. } catch (err) {
  14299. showToast('Error', err.message, 'error');
  14300. }
  14301. }
  14302. async function toggleVRRPState(id, disabled) {
  14303. try {
  14304. const res = await fetch(`${API_BASE}/vrrp/instances/${encodeURIComponent(id)}/state`, {
  14305. method: 'POST',
  14306. headers: { 'Content-Type': 'application/json' },
  14307. body: JSON.stringify({ disabled })
  14308. });
  14309. if (res.ok) {
  14310. showToast('State Updated', disabled ? 'VRRP disabled' : 'VRRP enabled', 'info');
  14311. loadVRRP(false);
  14312. fetchData(false);
  14313. } else {
  14314. const err = await res.text();
  14315. showToast('Error', err, 'error');
  14316. }
  14317. } catch (err) {
  14318. showToast('Error', err.message, 'error');
  14319. }
  14320. }
  14321. // Global observer for dynamically injected tables (e.g. inside modals or drawers)
  14322. if (typeof MutationObserver !== 'undefined' && typeof document !== 'undefined') {
  14323. let docSortDebounce = null;
  14324. const docTableObserver = new MutationObserver((mutations) => {
  14325. let needsInit = false;
  14326. for (const m of mutations) {
  14327. for (const node of m.addedNodes) {
  14328. if (node.nodeType === 1) {
  14329. if (node.tagName === 'TABLE' && !node.closest('tbody, thead')) {
  14330. needsInit = true;
  14331. break;
  14332. } else if (node.querySelector && !node.closest('table') && node.querySelector('table')) {
  14333. needsInit = true;
  14334. break;
  14335. }
  14336. }
  14337. }
  14338. if (needsInit) break;
  14339. }
  14340. if (needsInit) {
  14341. clearTimeout(docSortDebounce);
  14342. docSortDebounce = setTimeout(initTableSorting, 100);
  14343. }
  14344. });
  14345. docTableObserver.observe(document.body || document.documentElement, { childList: true, subtree: true });
  14346. }
  14347. // =========================================================================
  14348. // BANDWIDTH TEST (BwTest) BENCHMARK ENGINE
  14349. // =========================================================================
  14350. const bwtestState = {
  14351. running: false,
  14352. pollTimer: null,
  14353. eventSource: null,
  14354. chartPoints: [],
  14355. maxChartPoints: 60,
  14356. serverConfig: null,
  14357. peakTx: 0,
  14358. peakRx: 0,
  14359. targetDuration: 10,
  14360. lastSampleElapsed: -1,
  14361. sessionID: null
  14362. };
  14363. async function loadBwTestView() {
  14364. resizeBwTestCanvas();
  14365. await Promise.all([fetchBwTestServerStatus(), loadBwTestHistory(), checkActiveBwTest()]);
  14366. }
  14367. async function fetchBwTestServerStatus() {
  14368. try {
  14369. const res = await fetch(`${API_BASE}/tools/bwtest/server`);
  14370. if (!res.ok) return;
  14371. const s = await res.json();
  14372. bwtestState.serverConfig = s;
  14373. // Update indicator and badges
  14374. const indicator = document.getElementById('bwtest-server-indicator');
  14375. const badge = document.getElementById('bwtest-server-badge');
  14376. const sideBadge = document.getElementById('badge-bwtest-server');
  14377. if (s.enabled && s.running) {
  14378. if (indicator) indicator.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  14379. if (badge) {
  14380. badge.innerText = `Port ${s.port} (Active)`;
  14381. badge.className = 'text-emerald-400 font-bold';
  14382. }
  14383. if (sideBadge) {
  14384. sideBadge.innerText = s.port;
  14385. 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';
  14386. }
  14387. } else {
  14388. if (indicator) indicator.className = 'w-2 h-2 rounded-full bg-slate-600';
  14389. if (badge) {
  14390. badge.innerText = `Disabled`;
  14391. badge.className = 'text-slate-500 font-bold';
  14392. }
  14393. if (sideBadge) {
  14394. sideBadge.innerText = 'Off';
  14395. sideBadge.className = 'text-[10px] bg-slate-800 text-slate-500 border border-slate-700 px-1.5 py-0.2 rounded-full font-mono';
  14396. }
  14397. }
  14398. // Modal fields
  14399. const toggle = document.getElementById('bwtest-server-enable-toggle');
  14400. const serverModal = document.getElementById('modal-bwtest-server');
  14401. const editing = serverModal && !serverModal.classList.contains('hidden');
  14402. if (toggle && !editing) toggle.checked = !!s.enabled;
  14403. const portInp = document.getElementById('bwtest-server-port-input');
  14404. if (portInp && !editing) portInp.value = s.port || 2000;
  14405. const actSess = document.getElementById('bwtest-modal-active-sessions');
  14406. if (actSess) actSess.innerText = s.active_sessions || 0;
  14407. const totServ = document.getElementById('bwtest-modal-total-served');
  14408. if (totServ) totServ.innerText = s.total_sessions_served || 0;
  14409. const totBytes = document.getElementById('bwtest-modal-total-bytes');
  14410. if (totBytes) totBytes.innerText = formatBytes(s.total_bytes_processed || 0);
  14411. } catch (err) {
  14412. console.error('Failed to fetch BwTest server status:', err);
  14413. }
  14414. }
  14415. function openBwTestServerModal() {
  14416. const cfg = bwtestState.serverConfig;
  14417. if (cfg) {
  14418. document.getElementById('bwtest-server-enable-toggle').checked = !!cfg.enabled;
  14419. document.getElementById('bwtest-server-port-input').value = cfg.port || 2000;
  14420. }
  14421. fetchBwTestServerStatus();
  14422. document.getElementById('modal-bwtest-server')?.classList.remove('hidden');
  14423. }
  14424. function closeBwTestServerModal() {
  14425. document.getElementById('modal-bwtest-server')?.classList.add('hidden');
  14426. }
  14427. async function submitBwTestServerSettings(e) {
  14428. e.preventDefault();
  14429. const enabled = document.getElementById('bwtest-server-enable-toggle').checked;
  14430. const port = parseInt(document.getElementById('bwtest-server-port-input').value, 10) || 2000;
  14431. try {
  14432. const res = await fetch(`${API_BASE}/tools/bwtest/server`, {
  14433. method: 'POST',
  14434. headers: { 'Content-Type': 'application/json' },
  14435. body: JSON.stringify({ enabled, port, listen_addr: '0.0.0.0', allow_anonymous: true })
  14436. });
  14437. if (!res.ok) {
  14438. const err = await res.json();
  14439. throw new Error(err.error || 'Failed to update server configuration');
  14440. }
  14441. showToast('BwTest Server', `Bandwidth Test server updated (Port ${port})`, 'success');
  14442. closeBwTestServerModal();
  14443. fetchBwTestServerStatus();
  14444. } catch (err) {
  14445. showToast('Server Configuration Error', err.message, 'error');
  14446. }
  14447. }
  14448. function setBwTestTarget(target) {
  14449. const inp = document.getElementById('bwtest-input-target');
  14450. if (inp) inp.value = target;
  14451. }
  14452. function setBwTestProtocol(proto) {
  14453. const hiddenInp = document.getElementById('bwtest-input-protocol');
  14454. if (hiddenInp) hiddenInp.value = proto;
  14455. const btnUdp = document.getElementById('bwtest-proto-udp');
  14456. const btnTcp = document.getElementById('bwtest-proto-tcp');
  14457. const badge = document.getElementById('bwtest-proto-badge');
  14458. const pktField = document.getElementById('bwtest-field-pktsize');
  14459. 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';
  14460. 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';
  14461. 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';
  14462. if (proto === 'udp') {
  14463. if (btnUdp) {
  14464. btnUdp.className = activeUdpCls;
  14465. const dot = btnUdp.querySelector('span');
  14466. if (dot) dot.className = 'w-2 h-2 rounded-full bg-emerald-400';
  14467. }
  14468. if (btnTcp) {
  14469. btnTcp.className = inactiveCls;
  14470. const dot = btnTcp.querySelector('span');
  14471. if (dot) dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  14472. }
  14473. if (badge) {
  14474. badge.innerText = 'UDP Mode (RFC 3550 Jitter + Loss %)';
  14475. badge.className = 'text-[10px] font-mono text-emerald-400 bg-emerald-500/10 px-2 py-0.5 rounded border border-emerald-500/20';
  14476. }
  14477. if (pktField) pktField.classList.remove('opacity-40');
  14478. } else {
  14479. if (btnUdp) {
  14480. btnUdp.className = inactiveCls;
  14481. const dot = btnUdp.querySelector('span');
  14482. if (dot) dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  14483. }
  14484. if (btnTcp) {
  14485. btnTcp.className = activeTcpCls;
  14486. const dot = btnTcp.querySelector('span');
  14487. if (dot) dot.className = 'w-2 h-2 rounded-full bg-blue-400';
  14488. }
  14489. if (badge) {
  14490. badge.innerText = 'TCP Mode (Sliding Window Throughput)';
  14491. badge.className = 'text-[10px] font-mono text-blue-400 bg-blue-500/10 px-2 py-0.5 rounded border border-blue-500/20';
  14492. }
  14493. if (pktField) pktField.classList.add('opacity-40');
  14494. }
  14495. }
  14496. function setBwTestDirection(dir) {
  14497. const hiddenInp = document.getElementById('bwtest-input-direction');
  14498. if (hiddenInp) hiddenInp.value = dir;
  14499. const btnBoth = document.getElementById('bwtest-dir-both');
  14500. const btnTx = document.getElementById('bwtest-dir-tx');
  14501. const btnRx = document.getElementById('bwtest-dir-rx');
  14502. 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';
  14503. 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';
  14504. if (btnBoth) btnBoth.className = dir === 'both' ? activeCls : inactiveCls;
  14505. if (btnTx) btnTx.className = dir === 'tx' ? activeCls : inactiveCls;
  14506. if (btnRx) btnRx.className = dir === 'rx' ? activeCls : inactiveCls;
  14507. }
  14508. function setBwTestLimit(bps) {
  14509. const sel = document.getElementById('bwtest-input-limit');
  14510. if (sel) sel.value = String(bps);
  14511. }
  14512. async function checkActiveBwTest() {
  14513. try {
  14514. const res = await fetch(`${API_BASE}/tools/bwtest/status`);
  14515. if (!res.ok) return;
  14516. const st = await res.json();
  14517. if (st.running) {
  14518. setBwTestRunningUI(true);
  14519. processBwTestStatus(st);
  14520. startBwTestTelemetry();
  14521. }
  14522. } catch (err) {
  14523. console.error('Failed to check active BwTest:', err);
  14524. }
  14525. }
  14526. async function startBwTest(e) {
  14527. if (e && e.preventDefault) e.preventDefault();
  14528. const target = document.getElementById('bwtest-input-target').value.trim() || '127.0.0.1';
  14529. const port = parseInt(document.getElementById('bwtest-input-port').value, 10) || 2000;
  14530. const direction = document.getElementById('bwtest-input-direction').value || 'both';
  14531. const protocol = document.getElementById('bwtest-input-protocol').value || 'udp';
  14532. const bandwidth_limit = parseInt(document.getElementById('bwtest-input-limit').value, 10) || 0;
  14533. const packet_size = parseInt(document.getElementById('bwtest-input-pktsize').value, 10) || 1472;
  14534. const streams = parseInt(document.getElementById('bwtest-input-streams').value, 10) || 1;
  14535. const duration = parseInt(document.getElementById('bwtest-input-duration').value, 10);
  14536. bwtestState.targetDuration = duration;
  14537. bwtestState.chartPoints = [];
  14538. bwtestState.peakTx = 0;
  14539. bwtestState.peakRx = 0;
  14540. bwtestState.lastSampleElapsed = -1;
  14541. bwtestState.sessionID = null;
  14542. // Clear UI elements
  14543. document.getElementById('bwtest-stat-tx-mbps').innerText = '0.00';
  14544. document.getElementById('bwtest-stat-tx-peak').innerText = '0.00 Mbps';
  14545. document.getElementById('bwtest-stat-tx-pkts').innerText = '0';
  14546. document.getElementById('bwtest-stat-rx-mbps').innerText = '0.00';
  14547. document.getElementById('bwtest-stat-rx-peak').innerText = '0.00 Mbps';
  14548. document.getElementById('bwtest-stat-rx-pkts').innerText = '0';
  14549. document.getElementById('bwtest-stat-loss').innerText = '0.0%';
  14550. document.getElementById('bwtest-stat-jitter').innerText = '0.00 ms';
  14551. document.getElementById('bwtest-stat-time').innerText = '0.0s';
  14552. document.getElementById('bwtest-stat-data').innerText = '0.0 MB';
  14553. document.getElementById('bwtest-stat-target-dur').innerText = duration > 0 ? `/ ${duration}s` : '/ ∞';
  14554. const tbody = document.getElementById('bwtest-samples-tbody');
  14555. if (tbody) tbody.innerHTML = '';
  14556. document.getElementById('bwtest-sample-count').innerText = '0 samples';
  14557. setBwTestRunningUI(true);
  14558. try {
  14559. const res = await fetch(`${API_BASE}/tools/bwtest/start`, {
  14560. method: 'POST',
  14561. headers: { 'Content-Type': 'application/json' },
  14562. body: JSON.stringify({
  14563. target,
  14564. port,
  14565. direction,
  14566. protocol,
  14567. bandwidth_limit,
  14568. packet_size,
  14569. streams,
  14570. duration
  14571. })
  14572. });
  14573. if (!res.ok) {
  14574. const err = await res.json();
  14575. throw new Error(err.error || 'Failed to start bandwidth test');
  14576. }
  14577. showToast('Benchmark Started', `Target: ${target}:${port} (${direction.toUpperCase()}, ${protocol.toUpperCase()})`, 'info');
  14578. startBwTestTelemetry();
  14579. } catch (err) {
  14580. setBwTestRunningUI(false);
  14581. showToast('Start Failed', err.message, 'error');
  14582. }
  14583. }
  14584. function setBwTestRunningUI(running) {
  14585. bwtestState.running = running;
  14586. const startBtn = document.getElementById('bwtest-btn-start');
  14587. const stopBtn = document.getElementById('bwtest-btn-stop');
  14588. const badge = document.getElementById('bwtest-run-status-badge');
  14589. const ph = document.getElementById('bwtest-chart-placeholder');
  14590. if (running) {
  14591. if (startBtn) {
  14592. startBtn.disabled = true;
  14593. startBtn.classList.add('opacity-50', 'cursor-not-allowed');
  14594. }
  14595. if (stopBtn) {
  14596. stopBtn.disabled = false;
  14597. stopBtn.classList.remove('opacity-40');
  14598. }
  14599. if (badge) {
  14600. badge.innerText = 'TESTING...';
  14601. 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';
  14602. }
  14603. if (ph) ph.style.display = 'none';
  14604. } else {
  14605. if (startBtn) {
  14606. startBtn.disabled = false;
  14607. startBtn.classList.remove('opacity-50', 'cursor-not-allowed');
  14608. }
  14609. if (stopBtn) {
  14610. stopBtn.disabled = true;
  14611. stopBtn.classList.add('opacity-40');
  14612. }
  14613. if (badge) {
  14614. badge.innerText = 'IDLE';
  14615. badge.className = 'px-2 py-0.5 rounded text-[10px] font-mono bg-slate-800 text-slate-400 border border-slate-700 font-semibold';
  14616. }
  14617. }
  14618. }
  14619. async function stopBwTest() {
  14620. try {
  14621. const res = await fetch(`${API_BASE}/tools/bwtest/stop`, { method: 'POST' });
  14622. if (!res.ok) throw new Error(await responseError(res));
  14623. showToast('Stop Requested', 'Waiting for the bandwidth test to finish', 'info');
  14624. if (!bwtestState.pollTimer) startBwTestTelemetry();
  14625. } catch (err) {
  14626. showToast('Stop Failed', err.message, 'error');
  14627. }
  14628. }
  14629. async function responseError(res) {
  14630. const text = await res.text();
  14631. try { const data = JSON.parse(text); return data.message || (typeof data.error === 'string' ? data.error : null) || `HTTP ${res.status}`; }
  14632. catch { return text || `HTTP ${res.status}`; }
  14633. }
  14634. function processBwTestStatus(st) {
  14635. if (st.session_id && bwtestState.sessionID !== st.session_id) {
  14636. bwtestState.sessionID = st.session_id;
  14637. bwtestState.lastSampleElapsed = -1;
  14638. }
  14639. for (const sample of st.recent_samples || []) {
  14640. if (sample.elapsed_sec > (bwtestState.lastSampleElapsed ?? -1)) {
  14641. handleBwTestSample(sample);
  14642. bwtestState.lastSampleElapsed = sample.elapsed_sec;
  14643. }
  14644. }
  14645. if (!st.running) {
  14646. if (bwtestState.pollTimer) clearInterval(bwtestState.pollTimer);
  14647. bwtestState.pollTimer = null;
  14648. setBwTestRunningUI(false);
  14649. handleBwTestFinish(st.summary, st.error);
  14650. }
  14651. }
  14652. function startBwTestTelemetry() {
  14653. if (!state.currentUser) return;
  14654. if (bwtestState.pollTimer) clearInterval(bwtestState.pollTimer);
  14655. let busy = false;
  14656. const poll = async () => {
  14657. if (busy || !state.currentUser || document.hidden) return;
  14658. busy = true;
  14659. try {
  14660. const res = await fetch(`${API_BASE}/tools/bwtest/status`);
  14661. if (!res.ok) throw new Error(await responseError(res));
  14662. processBwTestStatus(await res.json());
  14663. } catch (err) {
  14664. console.error('BwTest polling error:', err);
  14665. } finally { busy = false; }
  14666. };
  14667. bwtestState.pollTimer = setInterval(poll, 400);
  14668. poll();
  14669. }
  14670. function handleBwTestSample(s) {
  14671. if (!s) return;
  14672. const payloadHint = document.getElementById('bwtest-effective-payload');
  14673. if (payloadHint && s.packet_size) payloadHint.innerText = `Effective datagram: ${s.packet_size} bytes`;
  14674. const txMbps = s.tx_mbps || 0;
  14675. const rxMbps = s.rx_mbps || 0;
  14676. if (txMbps > bwtestState.peakTx) bwtestState.peakTx = txMbps;
  14677. if (rxMbps > bwtestState.peakRx) bwtestState.peakRx = rxMbps;
  14678. // KPI updates
  14679. const elTx = document.getElementById('bwtest-stat-tx-mbps');
  14680. if (elTx) {
  14681. elTx.innerText = txMbps.toFixed(2);
  14682. elTx.title = `Confirmed by peer; locally offered: ${(s.offered_tx_mbps || 0).toFixed(2)} Mbps`;
  14683. }
  14684. const elTxPeak = document.getElementById('bwtest-stat-tx-peak');
  14685. if (elTxPeak) elTxPeak.innerText = `${bwtestState.peakTx.toFixed(2)} Mbps`;
  14686. const elTxPkts = document.getElementById('bwtest-stat-tx-pkts');
  14687. if (elTxPkts) elTxPkts.innerText = s.tx_packets || 0;
  14688. const elRx = document.getElementById('bwtest-stat-rx-mbps');
  14689. if (elRx) elRx.innerText = rxMbps.toFixed(2);
  14690. const elRxPeak = document.getElementById('bwtest-stat-rx-peak');
  14691. if (elRxPeak) elRxPeak.innerText = `${bwtestState.peakRx.toFixed(2)} Mbps`;
  14692. const elRxPkts = document.getElementById('bwtest-stat-rx-pkts');
  14693. if (elRxPkts) elRxPkts.innerText = s.rx_packets || 0;
  14694. const elLoss = document.getElementById('bwtest-stat-loss');
  14695. if (elLoss) {
  14696. elLoss.innerText = `${(s.loss_pct || 0).toFixed(1)}%`;
  14697. elLoss.className = (s.loss_pct > 1.0) ? 'text-2xl font-bold text-rose-400' : 'text-2xl font-bold text-emerald-400';
  14698. }
  14699. const elLostPkts = document.getElementById('bwtest-stat-lost-pkts');
  14700. if (elLostPkts) elLostPkts.innerText = s.lost_packets || 0;
  14701. const elJitter = document.getElementById('bwtest-stat-jitter');
  14702. if (elJitter) elJitter.innerText = `${(s.jitter_ms || 0).toFixed(2)} ms`;
  14703. const elTime = document.getElementById('bwtest-stat-time');
  14704. if (elTime) elTime.innerText = `${(s.elapsed_sec || 0).toFixed(1)}s`;
  14705. const elData = document.getElementById('bwtest-stat-data');
  14706. if (elData) elData.innerText = formatBytes((s.tx_bytes || 0) + (s.rx_bytes || 0));
  14707. const elGraphRate = document.getElementById('bwtest-graph-rate');
  14708. if (elGraphRate) elGraphRate.innerText = `TX: ${txMbps.toFixed(1)} Mbps • RX: ${rxMbps.toFixed(1)} Mbps`;
  14709. // Append point to chart buffer
  14710. bwtestState.chartPoints.push({
  14711. elapsed: s.elapsed_sec || 0,
  14712. tx: txMbps,
  14713. rx: rxMbps
  14714. });
  14715. if (bwtestState.chartPoints.length > bwtestState.maxChartPoints) {
  14716. bwtestState.chartPoints.shift();
  14717. }
  14718. drawBwTestChart();
  14719. // Add row to breakdown table
  14720. const tbody = document.getElementById('bwtest-samples-tbody');
  14721. if (tbody) {
  14722. const tr = document.createElement('tr');
  14723. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  14724. tr.innerHTML = `
  14725. <td class="py-1.5 px-3 font-semibold text-white">${(s.elapsed_sec || 0).toFixed(1)}s</td>
  14726. <td class="py-1.5 px-3 font-bold text-cyan-400">${txMbps.toFixed(2)} Mbps</td>
  14727. <td class="py-1.5 px-3 font-bold text-purple-400">${rxMbps.toFixed(2)} Mbps</td>
  14728. <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>
  14729. <td class="py-1.5 px-3 text-slate-300">${(s.jitter_ms || 0).toFixed(2)} ms</td>
  14730. <td class="py-1.5 px-3 text-slate-400">${formatBytes((s.tx_bytes || 0) + (s.rx_bytes || 0))}</td>
  14731. `;
  14732. tbody.insertBefore(tr, tbody.firstChild);
  14733. const countEl = document.getElementById('bwtest-sample-count');
  14734. if (countEl) countEl.innerText = `${tbody.children.length} samples`;
  14735. }
  14736. }
  14737. function handleBwTestFinish(summary, error) {
  14738. const badge = document.getElementById('bwtest-run-status-badge');
  14739. if (error) {
  14740. showToast('Benchmark Error', error, 'error');
  14741. if (badge) {
  14742. badge.innerText = 'ERROR';
  14743. 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';
  14744. }
  14745. } else if (summary) {
  14746. const avgTx = summary.avg_tx_mbps.toFixed(1);
  14747. const avgRx = summary.avg_rx_mbps.toFixed(1);
  14748. showToast('Benchmark Complete', `Average TX: ${avgTx} Mbps | RX: ${avgRx} Mbps (Loss: ${summary.avg_loss_pct.toFixed(1)}%)`, 'success');
  14749. if (badge) {
  14750. badge.innerText = 'COMPLETED';
  14751. 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';
  14752. }
  14753. }
  14754. loadBwTestHistory();
  14755. fetchBwTestServerStatus();
  14756. }
  14757. function resizeBwTestCanvas() {
  14758. const canvas = document.getElementById('bwtest-chart');
  14759. if (!canvas || !canvas.parentElement) return;
  14760. const rect = canvas.parentElement.getBoundingClientRect();
  14761. const dpr = window.devicePixelRatio || 1;
  14762. canvas.width = rect.width * dpr;
  14763. canvas.height = rect.height * dpr;
  14764. const ctx = canvas.getContext('2d');
  14765. ctx.scale(dpr, dpr);
  14766. drawBwTestChart();
  14767. }
  14768. window.addEventListener('resize', () => {
  14769. if (state.activeTab === 'bwtest') resizeBwTestCanvas();
  14770. });
  14771. function drawBwTestChart() {
  14772. const canvas = document.getElementById('bwtest-chart');
  14773. if (!canvas) return;
  14774. const ctx = canvas.getContext('2d');
  14775. const dpr = window.devicePixelRatio || 1;
  14776. const width = canvas.width / dpr;
  14777. const height = canvas.height / dpr;
  14778. ctx.clearRect(0, 0, width, height);
  14779. const points = bwtestState.chartPoints;
  14780. if (!points || points.length === 0) return;
  14781. // Determine scale ceiling
  14782. let maxRate = 10;
  14783. for (const p of points) {
  14784. if (p.tx > maxRate) maxRate = p.tx;
  14785. if (p.rx > maxRate) maxRate = p.rx;
  14786. }
  14787. maxRate = Math.ceil(maxRate * 1.25); // 25% headroom
  14788. const paddingLeft = 55;
  14789. const paddingBottom = 24;
  14790. const paddingTop = 12;
  14791. const paddingRight = 16;
  14792. const chartW = width - paddingLeft - paddingRight;
  14793. const chartH = height - paddingTop - paddingBottom;
  14794. // Grid Lines and Y-Axis labels
  14795. ctx.strokeStyle = 'rgba(51, 65, 85, 0.4)';
  14796. ctx.lineWidth = 1;
  14797. ctx.fillStyle = '#94a3b8';
  14798. ctx.font = '10px monospace';
  14799. ctx.textAlign = 'right';
  14800. const gridSteps = 4;
  14801. for (let i = 0; i <= gridSteps; i++) {
  14802. const val = (maxRate / gridSteps) * i;
  14803. const y = paddingTop + chartH - (i / gridSteps) * chartH;
  14804. ctx.beginPath();
  14805. ctx.moveTo(paddingLeft, y);
  14806. ctx.lineTo(width - paddingRight, y);
  14807. ctx.stroke();
  14808. ctx.fillText(`${Math.round(val)}M`, paddingLeft - 8, y + 3);
  14809. }
  14810. // Draw TX Line (Cyan #22d3ee)
  14811. drawSeries(ctx, points, p => p.tx, maxRate, paddingLeft, paddingTop, chartW, chartH, '#22d3ee', 'rgba(34, 211, 238, 0.15)');
  14812. // Draw RX Line (Purple #a855f7)
  14813. drawSeries(ctx, points, p => p.rx, maxRate, paddingLeft, paddingTop, chartW, chartH, '#a855f7', 'rgba(168, 85, 247, 0.15)');
  14814. }
  14815. function drawSeries(ctx, points, valFn, maxVal, left, top, w, h, strokeColor, fillColor) {
  14816. if (points.length < 2) return;
  14817. const stepX = w / Math.max(points.length - 1, 1);
  14818. // Gradient area fill
  14819. const grad = ctx.createLinearGradient(0, top, 0, top + h);
  14820. grad.addColorStop(0, fillColor);
  14821. grad.addColorStop(1, 'rgba(0, 0, 0, 0)');
  14822. ctx.beginPath();
  14823. points.forEach((p, idx) => {
  14824. const x = left + idx * stepX;
  14825. const val = valFn(p);
  14826. const y = top + h - (val / maxVal) * h;
  14827. if (idx === 0) {
  14828. ctx.moveTo(x, y);
  14829. } else {
  14830. ctx.lineTo(x, y);
  14831. }
  14832. });
  14833. // Complete path for fill
  14834. ctx.lineTo(left + (points.length - 1) * stepX, top + h);
  14835. ctx.lineTo(left, top + h);
  14836. ctx.closePath();
  14837. ctx.fillStyle = grad;
  14838. ctx.fill();
  14839. // Draw line stroke
  14840. ctx.beginPath();
  14841. ctx.lineWidth = 2.5;
  14842. ctx.strokeStyle = strokeColor;
  14843. points.forEach((p, idx) => {
  14844. const x = left + idx * stepX;
  14845. const val = valFn(p);
  14846. const y = top + h - (val / maxVal) * h;
  14847. if (idx === 0) {
  14848. ctx.moveTo(x, y);
  14849. } else {
  14850. ctx.lineTo(x, y);
  14851. }
  14852. });
  14853. ctx.stroke();
  14854. // Draw end point halo
  14855. const lastP = points[points.length - 1];
  14856. const lastX = left + (points.length - 1) * stepX;
  14857. const lastY = top + h - (valFn(lastP) / maxVal) * h;
  14858. ctx.fillStyle = strokeColor;
  14859. ctx.beginPath();
  14860. ctx.arc(lastX, lastY, 4, 0, 2 * Math.PI);
  14861. ctx.fill();
  14862. }
  14863. async function loadBwTestHistory() {
  14864. try {
  14865. const res = await fetch(`${API_BASE}/tools/bwtest/history`);
  14866. if (!res.ok) return;
  14867. const list = await res.json();
  14868. renderBwTestHistory(Array.isArray(list) ? list : []);
  14869. } catch (err) {
  14870. console.error('Failed to load BwTest history:', err);
  14871. }
  14872. }
  14873. function renderBwTestHistory(list) {
  14874. const tbody = document.getElementById('bwtest-history-tbody');
  14875. if (!tbody) return;
  14876. if (list.length === 0) {
  14877. 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>`;
  14878. return;
  14879. }
  14880. tbody.innerHTML = '';
  14881. list.forEach(item => {
  14882. const s = item.summary || {};
  14883. const tr = document.createElement('tr');
  14884. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  14885. const dirBadge = item.direction === 'both'
  14886. ? `<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>`
  14887. : item.direction === 'tx'
  14888. ? `<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>`
  14889. : `<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>`;
  14890. const protoBadge = item.protocol === 'tcp'
  14891. ? `<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>`
  14892. : `<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>`;
  14893. const dateStr = item.timestamp ? new Date(item.timestamp).toLocaleString() : '-';
  14894. tr.innerHTML = `
  14895. <td class="py-2.5 px-4 font-bold text-white font-mono text-[11px]">${escapeHtml(item.id || '-')}</td>
  14896. <td class="py-2.5 px-4 text-emerald-400 font-mono font-medium">${escapeHtml(item.target || '-')}</td>
  14897. <td class="py-2.5 px-4">${protoBadge}</td>
  14898. <td class="py-2.5 px-4">${dirBadge}</td>
  14899. <td class="py-2.5 px-4 text-slate-300">${(s.duration_sec || 0).toFixed(1)}s</td>
  14900. <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>
  14901. <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>
  14902. <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>
  14903. <td class="py-2.5 px-4 text-slate-300 font-mono">${(s.avg_jitter_ms || 0).toFixed(2)} ms</td>
  14904. <td class="py-2.5 px-4 text-slate-400 text-[11px] font-sans">${escapeHtml(dateStr)}</td>
  14905. `;
  14906. tbody.appendChild(tr);
  14907. });
  14908. }
  14909. // ======================== SETTINGS & ROUTER DNS ========================
  14910. state.settingsSubTab = 'dns';
  14911. state.dnsSettings = null;
  14912. state.dnsStaticRecords = [];
  14913. state.dnsStatus = null;
  14914. function switchSettingsSubTab(sub) {
  14915. state.settingsSubTab = sub;
  14916. const btnDns = document.getElementById('btn-settings-subtab-dns');
  14917. const btnSys = document.getElementById('btn-settings-subtab-system');
  14918. const btnBak = document.getElementById('btn-settings-subtab-backup');
  14919. const tabDns = document.getElementById('settings-subtab-dns');
  14920. const tabSys = document.getElementById('settings-subtab-system');
  14921. const tabBak = document.getElementById('settings-subtab-backup');
  14922. 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';
  14923. 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';
  14924. if (btnDns) btnDns.className = inactiveClass;
  14925. if (btnSys) btnSys.className = inactiveClass;
  14926. if (btnBak) btnBak.className = inactiveClass;
  14927. tabDns?.classList.add('hidden');
  14928. tabSys?.classList.add('hidden');
  14929. tabBak?.classList.add('hidden');
  14930. if (sub === 'dns') {
  14931. if (btnDns) btnDns.className = activeClass;
  14932. tabDns?.classList.remove('hidden');
  14933. loadDNSSettings();
  14934. } else if (sub === 'system') {
  14935. if (btnSys) btnSys.className = activeClass;
  14936. tabSys?.classList.remove('hidden');
  14937. loadSystemSettings();
  14938. } else if (sub === 'backup') {
  14939. if (btnBak) btnBak.className = activeClass;
  14940. tabBak?.classList.remove('hidden');
  14941. loadBackupList();
  14942. }
  14943. }
  14944. async function loadSettingsData(showLoading = false) {
  14945. if (state.settingsSubTab === 'system') {
  14946. await loadSystemSettings();
  14947. } else if (state.settingsSubTab === 'backup') {
  14948. await loadBackupList();
  14949. } else {
  14950. await loadDNSSettings();
  14951. }
  14952. }
  14953. async function loadDNSSettings() {
  14954. try {
  14955. const [settingsRes, staticRes, statusRes] = await Promise.all([
  14956. fetch(`${API_BASE}/dns/settings`),
  14957. fetch(`${API_BASE}/dns/static`),
  14958. fetch(`${API_BASE}/dns/status`)
  14959. ]);
  14960. if (settingsRes.ok) {
  14961. state.dnsSettings = await settingsRes.json();
  14962. populateDNSSettingsForm(state.dnsSettings);
  14963. }
  14964. if (staticRes.ok) {
  14965. state.dnsStaticRecords = await staticRes.json();
  14966. renderStaticDNSList();
  14967. }
  14968. if (statusRes.ok) {
  14969. state.dnsStatus = await statusRes.json();
  14970. updateDNSStatusView(state.dnsStatus);
  14971. }
  14972. } catch (err) {
  14973. console.error('Failed to load DNS settings:', err);
  14974. }
  14975. }
  14976. function populateDNSSettingsForm(s) {
  14977. if (!s) return;
  14978. const dnsForm = document.getElementById('form-dns-settings');
  14979. const isEditing = dnsForm && (dnsForm.contains(document.activeElement) || dnsForm.dataset.dirty === 'true');
  14980. const dynamicEl = document.getElementById('dns-dynamic-servers-list');
  14981. if (dynamicEl) {
  14982. if (Array.isArray(s.dynamic_servers) && s.dynamic_servers.length > 0) {
  14983. 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(' ');
  14984. } else {
  14985. dynamicEl.innerText = 'None';
  14986. }
  14987. }
  14988. // If user is actively typing or editing in the form, do not overwrite their inputs!
  14989. if (isEditing) return;
  14990. const serversInput = document.getElementById('dns-servers-input');
  14991. if (serversInput) serversInput.value = (s.servers || []).join(', ');
  14992. const cacheSizeInput = document.getElementById('dns-cache-size-input');
  14993. if (cacheSizeInput) cacheSizeInput.value = s.cache_size || 2048;
  14994. const domainInput = document.getElementById('dns-domain-input');
  14995. if (domainInput) domainInput.value = s.domain || '';
  14996. const allowRemoteInput = document.getElementById('dns-allow-remote-input');
  14997. if (allowRemoteInput) allowRemoteInput.checked = s.allow_remote_requests !== false;
  14998. }
  14999. function updateDNSStatusView(st) {
  15000. if (!st) return;
  15001. const preview = document.getElementById('dns-resolv-preview');
  15002. if (preview) preview.innerText = st.resolv_conf_content || '(empty)';
  15003. const pillText = document.getElementById('dns-live-status-text');
  15004. const pill = document.getElementById('dns-live-status-pill');
  15005. if (pill && pillText) {
  15006. if (st.service_running) {
  15007. 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';
  15008. pillText.innerText = 'DNS Service Active';
  15009. } else {
  15010. 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';
  15011. pillText.innerText = 'DNS Service Inactive';
  15012. }
  15013. }
  15014. }
  15015. function appendDNSPreset(preset) {
  15016. const input = document.getElementById('dns-servers-input');
  15017. if (!input) return;
  15018. const dnsForm = document.getElementById('form-dns-settings');
  15019. if (dnsForm) dnsForm.dataset.dirty = 'true';
  15020. const current = input.value.trim();
  15021. if (!current) {
  15022. input.value = preset;
  15023. } else {
  15024. const existing = current.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  15025. const toAdd = preset.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  15026. toAdd.forEach(ip => {
  15027. if (!existing.includes(ip)) existing.push(ip);
  15028. });
  15029. input.value = existing.join(', ');
  15030. }
  15031. }
  15032. async function saveDNSSettings(e) {
  15033. e.preventDefault();
  15034. const rawServers = document.getElementById('dns-servers-input')?.value || '';
  15035. const servers = rawServers.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  15036. if (servers.length === 0) {
  15037. showToast('Validation Error', 'Please enter at least one upstream DNS server IP', 'error');
  15038. return;
  15039. }
  15040. const cacheSize = parseInt(document.getElementById('dns-cache-size-input')?.value || '2048', 10);
  15041. const domain = (document.getElementById('dns-domain-input')?.value || '').trim();
  15042. const allowRemote = document.getElementById('dns-allow-remote-input')?.checked ?? true;
  15043. try {
  15044. const res = await fetch(`${API_BASE}/dns/settings`, {
  15045. method: 'POST',
  15046. headers: { 'Content-Type': 'application/json' },
  15047. body: JSON.stringify({
  15048. servers: servers,
  15049. cache_size: cacheSize,
  15050. domain: domain,
  15051. allow_remote_requests: allowRemote
  15052. })
  15053. });
  15054. const data = await res.json();
  15055. if (res.ok) {
  15056. const dnsForm = document.getElementById('form-dns-settings');
  15057. if (dnsForm) dnsForm.dataset.dirty = 'false';
  15058. showToast('DNS Applied', 'Router DNS forwarders and resolver settings updated successfully', 'success');
  15059. loadDNSSettings();
  15060. } else {
  15061. showToast('Error', data.error || data.message || 'Failed to save DNS settings', 'error');
  15062. }
  15063. } catch (err) {
  15064. showToast('Error', err.message, 'error');
  15065. }
  15066. }
  15067. async function flushDNSCache() {
  15068. try {
  15069. const res = await fetch(`${API_BASE}/dns/flush`, { method: 'POST' });
  15070. if (res.ok) {
  15071. showToast('Cache Flushed', 'Router DNS cache cleared and static hosts reloaded', 'success');
  15072. loadDNSSettings();
  15073. } else {
  15074. const err = await res.json();
  15075. showToast('Error', err.error || 'Failed to flush cache', 'error');
  15076. }
  15077. } catch (err) {
  15078. showToast('Error', err.message, 'error');
  15079. }
  15080. }
  15081. function renderStaticDNSList() {
  15082. const tbody = document.getElementById('dns-static-tbody');
  15083. const empty = document.getElementById('dns-static-empty');
  15084. const badge = document.getElementById('dns-static-count-badge');
  15085. if (!tbody) return;
  15086. tbody.innerHTML = '';
  15087. const records = state.dnsStaticRecords || [];
  15088. if (badge) badge.innerText = `${records.length} Records`;
  15089. if (records.length === 0) {
  15090. empty?.classList.remove('hidden');
  15091. return;
  15092. }
  15093. empty?.classList.add('hidden');
  15094. records.forEach(rec => {
  15095. const tr = document.createElement('tr');
  15096. tr.className = `hover:bg-slate-800/40 transition text-xs ${rec.disabled ? 'opacity-50' : ''}`;
  15097. tr.innerHTML = `
  15098. <td class="py-2.5 px-4 font-bold text-white">${escapeHtml(rec.name)}</td>
  15099. <td class="py-2.5 px-4">
  15100. <span class="px-2 py-0.5 rounded text-[10px] font-bold ${
  15101. rec.type === 'CNAME' ? 'bg-purple-950 text-purple-300 border border-purple-800' :
  15102. (rec.type === 'AAAA' ? 'bg-blue-950 text-blue-300 border border-blue-800' : 'bg-cyan-950 text-cyan-300 border border-cyan-800')
  15103. }">
  15104. ${rec.type || 'A'}
  15105. </span>
  15106. </td>
  15107. <td class="py-2.5 px-4 text-emerald-400 font-mono">${escapeHtml(rec.address)}</td>
  15108. <td class="py-2.5 px-4 text-slate-400 font-mono">${rec.ttl || 3600}s</td>
  15109. <td class="py-2.5 px-4 text-slate-400 italic truncate max-w-[140px]">${escapeHtml(rec.comment || '-')}</td>
  15110. <td class="py-2.5 px-4">
  15111. <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'}">
  15112. ${rec.disabled ? 'Disabled' : 'Active'}
  15113. </span>
  15114. </td>
  15115. <td class="py-2.5 px-4 text-right space-x-2 font-sans whitespace-nowrap">
  15116. <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>
  15117. <button onclick="openStaticDNSModal('${rec.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold">Edit</button>
  15118. <button onclick="deleteStaticDNS('${rec.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  15119. </td>
  15120. `;
  15121. tbody.appendChild(tr);
  15122. });
  15123. }
  15124. function openStaticDNSModal(id = null) {
  15125. const modal = document.getElementById('modal-static-dns');
  15126. const title = document.getElementById('modal-static-dns-title');
  15127. const form = document.getElementById('form-static-dns');
  15128. if (!modal || !form) return;
  15129. form.reset();
  15130. document.getElementById('modal-static-dns-id').value = '';
  15131. if (id) {
  15132. const rec = (state.dnsStaticRecords || []).find(r => r.id === id);
  15133. if (rec) {
  15134. if (title) title.innerText = 'Edit Static DNS Record';
  15135. document.getElementById('modal-static-dns-id').value = rec.id;
  15136. document.getElementById('modal-static-dns-name').value = rec.name;
  15137. document.getElementById('modal-static-dns-type').value = rec.type || 'A';
  15138. document.getElementById('modal-static-dns-addr').value = rec.address;
  15139. document.getElementById('modal-static-dns-ttl').value = rec.ttl || 3600;
  15140. document.getElementById('modal-static-dns-comment').value = rec.comment || '';
  15141. document.getElementById('modal-static-dns-disabled').checked = !!rec.disabled;
  15142. }
  15143. } else {
  15144. if (title) title.innerText = 'Add Static DNS Record';
  15145. }
  15146. modal.classList.remove('hidden');
  15147. }
  15148. function closeStaticDNSModal() {
  15149. document.getElementById('modal-static-dns')?.classList.add('hidden');
  15150. }
  15151. async function submitSaveStaticDNS(e) {
  15152. e.preventDefault();
  15153. const id = document.getElementById('modal-static-dns-id')?.value || '';
  15154. const name = (document.getElementById('modal-static-dns-name')?.value || '').trim();
  15155. const type = document.getElementById('modal-static-dns-type')?.value || 'A';
  15156. const address = (document.getElementById('modal-static-dns-addr')?.value || '').trim();
  15157. const ttl = parseInt(document.getElementById('modal-static-dns-ttl')?.value || '3600', 10);
  15158. const comment = (document.getElementById('modal-static-dns-comment')?.value || '').trim();
  15159. const disabled = document.getElementById('modal-static-dns-disabled')?.checked ?? false;
  15160. if (!name || !address) {
  15161. showToast('Validation Error', 'Name and Target Address are required', 'error');
  15162. return;
  15163. }
  15164. try {
  15165. const res = await fetch(`${API_BASE}/dns/static`, {
  15166. method: 'POST',
  15167. headers: { 'Content-Type': 'application/json' },
  15168. body: JSON.stringify({ id, name, type, address, ttl, comment, disabled })
  15169. });
  15170. const data = await res.json();
  15171. if (res.ok) {
  15172. showToast('Static DNS Saved', `Saved record ${name} -> ${address}`, 'success');
  15173. closeStaticDNSModal();
  15174. loadDNSSettings();
  15175. } else {
  15176. showToast('Error', data.error || data.message || 'Failed to save record', 'error');
  15177. }
  15178. } catch (err) {
  15179. showToast('Error', err.message, 'error');
  15180. }
  15181. }
  15182. async function deleteStaticDNS(id) {
  15183. if (!confirm('Are you sure you want to delete this static DNS entry?')) return;
  15184. try {
  15185. const res = await fetch(`${API_BASE}/dns/static/${encodeURIComponent(id)}`, { method: 'DELETE' });
  15186. if (res.ok) {
  15187. showToast('Deleted', 'Static DNS record deleted', 'success');
  15188. loadDNSSettings();
  15189. }
  15190. } catch (err) {
  15191. showToast('Error', err.message, 'error');
  15192. }
  15193. }
  15194. async function toggleStaticDNS(id, disabled) {
  15195. try {
  15196. const res = await fetch(`${API_BASE}/dns/static/${encodeURIComponent(id)}/state`, {
  15197. method: 'POST',
  15198. headers: { 'Content-Type': 'application/json' },
  15199. body: JSON.stringify({ disabled })
  15200. });
  15201. if (res.ok) {
  15202. showToast('Updated', `Record ${disabled ? 'disabled' : 'enabled'}`, 'success');
  15203. loadDNSSettings();
  15204. }
  15205. } catch (err) {
  15206. showToast('Error', err.message, 'error');
  15207. }
  15208. }
  15209. async function loadSystemSettings() {
  15210. try {
  15211. const sysForm = document.getElementById('form-system-settings');
  15212. const isEditing = sysForm && (sysForm.contains(document.activeElement) || sysForm.dataset.dirty === 'true');
  15213. const res = await fetch(`${API_BASE}/system/settings`);
  15214. if (res.ok) {
  15215. const data = await res.json();
  15216. if (!isEditing) {
  15217. const hostInput = document.getElementById('system-hostname-input');
  15218. if (hostInput) hostInput.value = data.hostname || '';
  15219. const tzInput = document.getElementById('system-timezone-input');
  15220. if (tzInput && data.timezone) tzInput.value = data.timezone;
  15221. }
  15222. }
  15223. } catch (err) {
  15224. console.error('Failed to load system settings:', err);
  15225. }
  15226. }
  15227. async function saveSystemSettings(e) {
  15228. e.preventDefault();
  15229. const hostname = (document.getElementById('system-hostname-input')?.value || '').trim();
  15230. const timezone = document.getElementById('system-timezone-input')?.value || 'UTC';
  15231. try {
  15232. const res = await fetch(`${API_BASE}/system/settings`, {
  15233. method: 'POST',
  15234. headers: { 'Content-Type': 'application/json' },
  15235. body: JSON.stringify({ hostname, timezone })
  15236. });
  15237. const data = await res.json();
  15238. if (res.ok) {
  15239. const sysForm = document.getElementById('form-system-settings');
  15240. if (sysForm) sysForm.dataset.dirty = 'false';
  15241. showToast('System Updated', 'Hostname and timezone saved successfully', 'success');
  15242. const sideH = document.getElementById('side-hostname');
  15243. if (sideH) sideH.innerText = data.hostname;
  15244. } else {
  15245. showToast('Error', data.error || 'Failed to save system settings', 'error');
  15246. }
  15247. } catch (err) {
  15248. showToast('Error', err.message, 'error');
  15249. }
  15250. }
  15251. // =============================================================================
  15252. // BACKUP & RESTORE MANAGER
  15253. // =============================================================================
  15254. state.selectedBackupFile = null;
  15255. state.inspectedBackupManifest = null;
  15256. state.pendingRestoreTarget = null;
  15257. state.backupsList = [];
  15258. async function exportBackupDownload() {
  15259. const btn = document.getElementById('btn-export-backup');
  15260. const commentInput = document.getElementById('backup-export-comment');
  15261. const comment = (commentInput?.value || '').trim();
  15262. const originalHtml = btn ? btn.innerHTML : '';
  15263. if (btn) {
  15264. btn.disabled = true;
  15265. 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...`;
  15266. }
  15267. try {
  15268. const res = await fetch(`${API_BASE}/system/backup/export?comment=${encodeURIComponent(comment)}`);
  15269. if (!res.ok) {
  15270. const err = await res.json().catch(() => ({}));
  15271. showToast('Export Failed', err.message || 'Failed to generate backup archive', 'error');
  15272. return;
  15273. }
  15274. const blob = await res.blob();
  15275. const disposition = res.headers.get('Content-Disposition') || '';
  15276. let filename = 'debtik-backup.zip';
  15277. const match = disposition.match(/filename="?([^";]+)"?/);
  15278. if (match && match[1]) {
  15279. filename = match[1];
  15280. }
  15281. const blobUrl = window.URL.createObjectURL(blob);
  15282. const a = document.createElement('a');
  15283. a.href = blobUrl;
  15284. a.download = filename;
  15285. document.body.appendChild(a);
  15286. a.click();
  15287. setTimeout(() => {
  15288. window.URL.revokeObjectURL(blobUrl);
  15289. a.remove();
  15290. }, 1000);
  15291. showToast('Backup Created', `Full configuration archive saved as ${filename}`, 'success');
  15292. } catch (err) {
  15293. showToast('Export Error', err.message || 'Network error during download', 'error');
  15294. } finally {
  15295. if (btn) {
  15296. btn.disabled = false;
  15297. btn.innerHTML = originalHtml;
  15298. }
  15299. }
  15300. }
  15301. async function onBackupFileSelected(e) {
  15302. const file = e.target.files?.[0];
  15303. if (!file) return;
  15304. const label = document.getElementById('backup-file-label');
  15305. if (label) {
  15306. label.innerText = `Selected: ${file.name} (${formatBytes(file.size)})`;
  15307. }
  15308. await inspectBackupFile(file);
  15309. }
  15310. async function inspectBackupFile(file) {
  15311. const preview = document.getElementById('backup-inspect-preview');
  15312. const restoreBtn = document.getElementById('btn-restore-backup');
  15313. const formData = new FormData();
  15314. formData.append('backup', file);
  15315. try {
  15316. const res = await fetch(`${API_BASE}/system/backup/inspect`, {
  15317. method: 'POST',
  15318. body: formData
  15319. });
  15320. const data = await res.json();
  15321. if (!res.ok || !data.success || !data.manifest) {
  15322. if (preview) preview.classList.add('hidden');
  15323. if (restoreBtn) restoreBtn.disabled = true;
  15324. showToast('Validation Error', data.message || 'Invalid or corrupted DebTik backup archive', 'error');
  15325. return;
  15326. }
  15327. const mf = data.manifest;
  15328. state.selectedBackupFile = file;
  15329. state.inspectedBackupManifest = mf;
  15330. const vEl = document.getElementById('backup-inspect-version');
  15331. const hEl = document.getElementById('backup-inspect-hostname');
  15332. const fEl = document.getElementById('backup-inspect-files');
  15333. const dEl = document.getElementById('backup-inspect-date');
  15334. const cEl = document.getElementById('backup-inspect-comment');
  15335. if (vEl) vEl.innerText = `DebTik v${escapeHtml(mf.debtik_version || '1.0')}`;
  15336. if (hEl) hEl.innerText = escapeHtml(mf.hostname || 'DebTik');
  15337. if (fEl) fEl.innerText = `${mf.files?.length || 0} items`;
  15338. if (dEl) dEl.innerText = mf.created_at ? new Date(mf.created_at).toLocaleString() : 'N/A';
  15339. if (cEl) cEl.innerText = mf.comment ? `"${escapeHtml(mf.comment)}"` : '';
  15340. if (preview) preview.classList.remove('hidden');
  15341. if (restoreBtn) restoreBtn.disabled = false;
  15342. } catch (err) {
  15343. if (preview) preview.classList.add('hidden');
  15344. if (restoreBtn) restoreBtn.disabled = true;
  15345. showToast('Inspection Failed', err.message || 'Failed to inspect backup file', 'error');
  15346. }
  15347. }
  15348. function confirmRestoreBackup(localFilename = null) {
  15349. const modal = document.getElementById('modal-restore-confirm');
  15350. const details = document.getElementById('modal-restore-details');
  15351. const progress = document.getElementById('modal-restore-progress');
  15352. const cancelBtn = document.getElementById('btn-cancel-restore');
  15353. const execBtn = document.getElementById('btn-execute-restore');
  15354. if (progress) progress.classList.add('hidden');
  15355. if (cancelBtn) cancelBtn.disabled = false;
  15356. if (execBtn) {
  15357. execBtn.disabled = false;
  15358. execBtn.innerText = 'Yes, Restore & Reload';
  15359. }
  15360. if (localFilename) {
  15361. state.pendingRestoreTarget = { type: 'local', filename: localFilename };
  15362. if (details) {
  15363. details.innerHTML = `<div>Source: <span class="text-white font-bold">Local Safety Backup</span></div>
  15364. <div>File: <span class="text-cyan-400 font-bold">${escapeHtml(localFilename)}</span></div>`;
  15365. }
  15366. } else {
  15367. if (!state.selectedBackupFile || !state.inspectedBackupManifest) {
  15368. showToast('Error', 'Please select a valid backup archive first', 'error');
  15369. return;
  15370. }
  15371. state.pendingRestoreTarget = { type: 'file', file: state.selectedBackupFile };
  15372. const mf = state.inspectedBackupManifest;
  15373. if (details) {
  15374. details.innerHTML = `<div>Archive: <span class="text-white font-bold">${escapeHtml(state.selectedBackupFile.name)}</span> (${formatBytes(state.selectedBackupFile.size)})</div>
  15375. <div>Origin Hostname: <span class="text-cyan-400 font-bold">${escapeHtml(mf.hostname)}</span></div>
  15376. <div>Created: <span class="text-slate-300">${mf.created_at ? new Date(mf.created_at).toLocaleString() : 'N/A'}</span></div>
  15377. <div>Files: <span class="text-emerald-400">${mf.files?.length || 0} configuration files</span></div>`;
  15378. }
  15379. }
  15380. if (modal) modal.classList.remove('hidden');
  15381. }
  15382. function closeRestoreModal() {
  15383. const modal = document.getElementById('modal-restore-confirm');
  15384. if (modal) modal.classList.add('hidden');
  15385. }
  15386. async function executeRestoreBackup() {
  15387. const target = state.pendingRestoreTarget;
  15388. if (!target) return;
  15389. const progress = document.getElementById('modal-restore-progress');
  15390. const progressText = document.getElementById('modal-restore-progress-text');
  15391. const cancelBtn = document.getElementById('btn-cancel-restore');
  15392. const execBtn = document.getElementById('btn-execute-restore');
  15393. if (cancelBtn) cancelBtn.disabled = true;
  15394. if (execBtn) execBtn.disabled = true;
  15395. if (progress) progress.classList.remove('hidden');
  15396. if (progressText) progressText.innerText = 'Restoring configuration files into appliance...';
  15397. try {
  15398. let res;
  15399. if (target.type === 'file') {
  15400. const formData = new FormData();
  15401. formData.append('backup', target.file);
  15402. res = await fetch(`${API_BASE}/system/backup/restore`, {
  15403. method: 'POST',
  15404. body: formData
  15405. });
  15406. } else {
  15407. res = await fetch(`${API_BASE}/system/backups/${encodeURIComponent(target.filename)}/restore`, {
  15408. method: 'POST'
  15409. });
  15410. }
  15411. const data = await res.json();
  15412. if (!res.ok || !data.success) {
  15413. showToast('Restore Failed', data.message || 'Error occurred while restoring configuration', 'error');
  15414. if (cancelBtn) cancelBtn.disabled = false;
  15415. if (execBtn) execBtn.disabled = false;
  15416. if (progress) progress.classList.add('hidden');
  15417. return;
  15418. }
  15419. if (progressText) {
  15420. progressText.innerText = 'Configuration applied! DebTik appliance is reloading services, reconnecting...';
  15421. }
  15422. pollAfterRestoreReconnect();
  15423. } catch (err) {
  15424. showToast('Restore Error', err.message || 'Network error during restore', 'error');
  15425. if (cancelBtn) cancelBtn.disabled = false;
  15426. if (execBtn) execBtn.disabled = false;
  15427. if (progress) progress.classList.add('hidden');
  15428. }
  15429. }
  15430. function pollAfterRestoreReconnect() {
  15431. let attempts = 0;
  15432. const maxAttempts = 25;
  15433. const timer = setInterval(async () => {
  15434. attempts++;
  15435. try {
  15436. const res = await fetch(`${API_BASE}/system/status`, { cache: 'no-store' });
  15437. if (res.ok) {
  15438. clearInterval(timer);
  15439. closeRestoreModal();
  15440. showToast('Restoration Complete', 'DebTik configuration restored and appliance is back online!', 'success');
  15441. setTimeout(() => {
  15442. window.location.reload();
  15443. }, 1200);
  15444. }
  15445. } catch (_) {
  15446. // Still restarting, retry
  15447. }
  15448. if (attempts >= maxAttempts) {
  15449. clearInterval(timer);
  15450. closeRestoreModal();
  15451. showToast('Reload Notice', 'Restore applied. Please refresh your browser to re-authenticate.', 'info');
  15452. }
  15453. }, 1500);
  15454. }
  15455. async function loadBackupList() {
  15456. const tbody = document.getElementById('backups-table-tbody');
  15457. const empty = document.getElementById('backups-empty-state');
  15458. if (!tbody) return;
  15459. try {
  15460. const res = await fetch(`${API_BASE}/system/backups`);
  15461. if (!res.ok) return;
  15462. const list = await res.json();
  15463. state.backupsList = list || [];
  15464. renderBackupsTable(state.backupsList);
  15465. } catch (err) {
  15466. console.error('Failed to load backup list:', err);
  15467. }
  15468. }
  15469. function renderBackupsTable(backups) {
  15470. const tbody = document.getElementById('backups-table-tbody');
  15471. const empty = document.getElementById('backups-empty-state');
  15472. if (!tbody) return;
  15473. if (!backups || backups.length === 0) {
  15474. tbody.innerHTML = '';
  15475. if (empty) empty.classList.remove('hidden');
  15476. return;
  15477. }
  15478. if (empty) empty.classList.add('hidden');
  15479. tbody.innerHTML = backups.map(bk => {
  15480. const isAuto = bk.filename && bk.filename.startsWith('pre-restore-');
  15481. const badge = isAuto
  15482. ? `<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>`
  15483. : `<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>`;
  15484. const dateStr = bk.mod_time ? new Date(bk.mod_time).toLocaleString() : 'N/A';
  15485. return `<tr class="hover:bg-slate-800/40 transition">
  15486. <td class="py-3 px-4 font-bold text-white flex items-center gap-2">
  15487. ${badge}
  15488. <span>${escapeHtml(bk.filename)}</span>
  15489. </td>
  15490. <td class="py-3 px-4 text-slate-300">${escapeHtml(bk.debtik_version || '1.0')}</td>
  15491. <td class="py-3 px-4 text-cyan-400 font-bold">${escapeHtml(bk.hostname || 'DebTik')}</td>
  15492. <td class="py-3 px-4 text-slate-400">${dateStr}</td>
  15493. <td class="py-3 px-4 text-slate-300">${formatBytes(bk.size)}</td>
  15494. <td class="py-3 px-4 text-slate-400 italic">${escapeHtml(bk.comment || '—')}</td>
  15495. <td class="py-3 px-4 text-right space-x-2">
  15496. <button type="button" onclick="downloadLocalBackup('${escapeHtml(bk.filename)}')"
  15497. 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">
  15498. Download
  15499. </button>
  15500. <button type="button" onclick="confirmRestoreBackup('${escapeHtml(bk.filename)}')"
  15501. 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">
  15502. Restore
  15503. </button>
  15504. </td>
  15505. </tr>`;
  15506. }).join('');
  15507. }
  15508. async function downloadLocalBackup(filename) {
  15509. try {
  15510. const res = await fetch(`${API_BASE}/system/backups/${encodeURIComponent(filename)}`);
  15511. if (!res.ok) {
  15512. showToast('Download Error', 'Failed to retrieve backup file', 'error');
  15513. return;
  15514. }
  15515. const blob = await res.blob();
  15516. const blobUrl = window.URL.createObjectURL(blob);
  15517. const a = document.createElement('a');
  15518. a.href = blobUrl;
  15519. a.download = filename;
  15520. document.body.appendChild(a);
  15521. a.click();
  15522. setTimeout(() => {
  15523. window.URL.revokeObjectURL(blobUrl);
  15524. a.remove();
  15525. }, 1000);
  15526. } catch (err) {
  15527. showToast('Download Error', err.message, 'error');
  15528. }
  15529. }
  15530. // =============================================================================
  15531. // AUTHENTICATION & USER MANAGER
  15532. // =============================================================================
  15533. async function checkAuthStatus() {
  15534. try {
  15535. const res = await originalFetch(`${API_BASE}/auth/me`, {
  15536. headers: {
  15537. 'Authorization': `Bearer ${localStorage.getItem('debtik_token') || ''}`
  15538. }
  15539. });
  15540. if (res.ok) {
  15541. const user = await res.json();
  15542. state.currentUser = user;
  15543. updateUserProfileHeader(user);
  15544. hideLoginScreen();
  15545. state.isPolling = true;
  15546. fetchData();
  15547. initLiveTrafficStream();
  15548. return true;
  15549. } else {
  15550. showLoginScreen(false);
  15551. return false;
  15552. }
  15553. } catch (err) {
  15554. showLoginScreen(false);
  15555. return false;
  15556. }
  15557. }
  15558. function showLoginScreen(isExpired = false) {
  15559. const el = document.getElementById('login-screen');
  15560. if (el) el.classList.remove('hidden');
  15561. const errEl = document.getElementById('login-error');
  15562. const errTxt = document.getElementById('login-error-text');
  15563. if (isExpired && errEl && errTxt) {
  15564. errTxt.innerText = 'Session expired. Please sign in again.';
  15565. errEl.classList.remove('hidden');
  15566. } else if (errEl) {
  15567. errEl.classList.add('hidden');
  15568. }
  15569. const pwInput = document.getElementById('login-password');
  15570. if (pwInput) pwInput.value = '';
  15571. const userInput = document.getElementById('login-username');
  15572. if (userInput && !userInput.value) userInput.focus();
  15573. else if (pwInput) pwInput.focus();
  15574. }
  15575. function hideLoginScreen() {
  15576. const el = document.getElementById('login-screen');
  15577. if (el) el.classList.add('hidden');
  15578. const errEl = document.getElementById('login-error');
  15579. if (errEl) errEl.classList.add('hidden');
  15580. }
  15581. async function handleLoginSubmit(event) {
  15582. event.preventDefault();
  15583. const username = (document.getElementById('login-username')?.value || '').trim();
  15584. const password = document.getElementById('login-password')?.value || '';
  15585. const errEl = document.getElementById('login-error');
  15586. const errTxt = document.getElementById('login-error-text');
  15587. const btn = document.getElementById('login-submit-btn');
  15588. const btnText = document.getElementById('login-btn-text');
  15589. const spinner = document.getElementById('login-btn-spinner');
  15590. if (!username || !password) {
  15591. if (errTxt) errTxt.innerText = 'Username and password are required.';
  15592. if (errEl) errEl.classList.remove('hidden');
  15593. return;
  15594. }
  15595. if (errEl) errEl.classList.add('hidden');
  15596. if (btn) btn.disabled = true;
  15597. if (btnText) btnText.innerText = 'Authenticating...';
  15598. if (spinner) spinner.classList.remove('hidden');
  15599. try {
  15600. const res = await originalFetch(`${API_BASE}/auth/login`, {
  15601. method: 'POST',
  15602. headers: { 'Content-Type': 'application/json' },
  15603. body: JSON.stringify({ username, password })
  15604. });
  15605. const data = await res.json();
  15606. if (res.ok && data.success) {
  15607. localStorage.setItem('debtik_token', data.token);
  15608. state.currentUser = data.user;
  15609. updateUserProfileHeader(data.user);
  15610. hideLoginScreen();
  15611. state.isPolling = true;
  15612. showToast('Authenticated', `Signed in as ${data.user.username}`, 'success');
  15613. const hash = window.location.hash.replace('#', '') || 'dashboard';
  15614. navigate(hash);
  15615. fetchData();
  15616. initLiveTrafficStream();
  15617. // Ensure background telemetry polling is active
  15618. if (!window._telemetryInterval) {
  15619. window._telemetryInterval = setInterval(() => {
  15620. if (state.isPolling && state.currentUser && !document.hidden) {
  15621. fetchData(false);
  15622. }
  15623. }, 5000);
  15624. }
  15625. } else {
  15626. if (errTxt) errTxt.innerText = data.message || 'Invalid username or password';
  15627. if (errEl) errEl.classList.remove('hidden');
  15628. }
  15629. } catch (err) {
  15630. if (errTxt) errTxt.innerText = err.message || 'Failed to connect to router';
  15631. if (errEl) errEl.classList.remove('hidden');
  15632. } finally {
  15633. if (btn) btn.disabled = false;
  15634. if (btnText) btnText.innerText = 'Sign In to Controller';
  15635. if (spinner) spinner.classList.add('hidden');
  15636. }
  15637. }
  15638. async function handleLogoutClick() {
  15639. try {
  15640. await originalFetch(`${API_BASE}/auth/logout`, {
  15641. method: 'POST',
  15642. headers: {
  15643. 'Authorization': `Bearer ${localStorage.getItem('debtik_token') || ''}`
  15644. }
  15645. });
  15646. } catch (e) {}
  15647. stopSessionPolling();
  15648. localStorage.removeItem('debtik_token');
  15649. state.currentUser = null;
  15650. state.isPolling = false;
  15651. if (window._telemetryInterval) {
  15652. clearInterval(window._telemetryInterval);
  15653. window._telemetryInterval = null;
  15654. }
  15655. if (trafficEventSource) {
  15656. trafficEventSource.close();
  15657. trafficEventSource = null;
  15658. }
  15659. if (trafficPollFallback) {
  15660. clearInterval(trafficPollFallback);
  15661. trafficPollFallback = null;
  15662. }
  15663. showLoginScreen(false);
  15664. showToast('Signed Out', 'You have been signed out successfully', 'info');
  15665. }
  15666. function togglePasswordVisibility(id) {
  15667. const input = document.getElementById(id);
  15668. if (!input) return;
  15669. input.type = input.type === 'password' ? 'text' : 'password';
  15670. }
  15671. function toggleUserMenu() {
  15672. const menu = document.getElementById('user-menu-dropdown');
  15673. if (menu) menu.classList.toggle('hidden');
  15674. }
  15675. function closeUserMenu() {
  15676. const menu = document.getElementById('user-menu-dropdown');
  15677. if (menu) menu.classList.add('hidden');
  15678. }
  15679. // Close user menu on outside click
  15680. document.addEventListener('click', (e) => {
  15681. const menu = document.getElementById('user-menu-dropdown');
  15682. if (!menu || menu.classList.contains('hidden')) return;
  15683. if (!e.target.closest('#user-menu-dropdown') && !e.target.closest('button[onclick*="toggleUserMenu"]')) {
  15684. menu.classList.add('hidden');
  15685. }
  15686. });
  15687. function updateUserProfileHeader(user) {
  15688. if (!user) return;
  15689. const navName = document.getElementById('nav-user-name');
  15690. if (navName) navName.innerText = user.username;
  15691. const dropName = document.getElementById('dropdown-user-name');
  15692. if (dropName) dropName.innerText = user.username;
  15693. const navRole = document.getElementById('nav-user-role');
  15694. if (navRole) navRole.innerText = (user.role || 'read').toUpperCase();
  15695. const navAvatar = document.getElementById('nav-user-avatar');
  15696. if (navAvatar) {
  15697. const initials = (user.username || 'AD').slice(0, 2).toUpperCase();
  15698. navAvatar.innerText = initials;
  15699. }
  15700. const statCurUser = document.getElementById('stat-current-user');
  15701. if (statCurUser) statCurUser.innerText = user.username;
  15702. const statCurRole = document.getElementById('stat-current-role');
  15703. if (statCurRole) statCurRole.innerText = (user.role || 'read').toUpperCase();
  15704. // Role permissions UI visibility: hide user management for non-admins
  15705. const isFullAdmin = user.role === 'full';
  15706. const navUsers = document.getElementById('nav-users');
  15707. if (navUsers) {
  15708. if (isFullAdmin) navUsers.classList.remove('hidden');
  15709. else navUsers.classList.add('hidden');
  15710. }
  15711. const dropdownUsers = document.getElementById('dropdown-item-users');
  15712. if (dropdownUsers) {
  15713. if (isFullAdmin) dropdownUsers.classList.remove('hidden');
  15714. else dropdownUsers.classList.add('hidden');
  15715. }
  15716. }
  15717. // ================= User Management CRUD =================
  15718. async function loadUsers(isManual = false) {
  15719. try {
  15720. const res = await fetch(`${API_BASE}/users`);
  15721. if (res.status === 403) {
  15722. const tbody = document.getElementById('users-table-tbody');
  15723. if (tbody) {
  15724. tbody.innerHTML = `
  15725. <tr>
  15726. <td colspan="6" class="p-6 text-center text-amber-400 font-sans">
  15727. <div class="inline-flex items-center gap-2">
  15728. <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>
  15729. <span>Viewing and managing users requires Super Administrator (full) permissions.</span>
  15730. </div>
  15731. </td>
  15732. </tr>
  15733. `;
  15734. }
  15735. return;
  15736. }
  15737. if (res.ok) {
  15738. state.users = await res.json();
  15739. renderUsersTable();
  15740. const totalUsers = document.getElementById('stat-total-users');
  15741. if (totalUsers) totalUsers.innerText = state.users.length;
  15742. const adminCount = state.users.filter(u => u.role === 'full' && !u.disabled).length;
  15743. const adminUsers = document.getElementById('stat-admin-users');
  15744. if (adminUsers) adminUsers.innerText = adminCount;
  15745. const badgeCount = document.getElementById('badge-users-count');
  15746. if (badgeCount) badgeCount.innerText = state.users.length;
  15747. if (isManual) showToast('Refreshed', 'User list updated', 'info');
  15748. }
  15749. } catch (err) {
  15750. console.error('Failed to load users:', err);
  15751. }
  15752. }
  15753. function renderUsersTable() {
  15754. const tbody = document.getElementById('users-table-tbody');
  15755. const emptyState = document.getElementById('users-empty-state');
  15756. if (!tbody) return;
  15757. tbody.innerHTML = '';
  15758. const query = (document.getElementById('users-search-input')?.value || '').trim().toLowerCase();
  15759. const filtered = (state.users || []).filter(u => {
  15760. if (!query) return true;
  15761. return u.username.toLowerCase().includes(query) ||
  15762. (u.role || '').toLowerCase().includes(query) ||
  15763. (u.comment || '').toLowerCase().includes(query);
  15764. });
  15765. if (filtered.length === 0) {
  15766. if (emptyState) emptyState.classList.remove('hidden');
  15767. return;
  15768. }
  15769. if (emptyState) emptyState.classList.add('hidden');
  15770. const currentAuthUser = state.currentUser?.username || '';
  15771. filtered.forEach(u => {
  15772. const isSelf = u.username === currentAuthUser;
  15773. const isFull = u.role === 'full';
  15774. const isWrite = u.role === 'write';
  15775. 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>`;
  15776. if (isFull) {
  15777. 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>`;
  15778. } else if (isWrite) {
  15779. 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>`;
  15780. }
  15781. const statusBadge = u.disabled
  15782. ? `<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>`
  15783. : `<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>`;
  15784. let lastLoginText = 'Never';
  15785. if (u.last_login_at && !u.last_login_at.startsWith('0001-01-01')) {
  15786. const dt = new Date(u.last_login_at);
  15787. lastLoginText = dt.toLocaleString();
  15788. }
  15789. const initials = u.username.slice(0, 2).toUpperCase();
  15790. const tr = document.createElement('tr');
  15791. tr.className = 'hover:bg-slate-800/40 transition group';
  15792. tr.innerHTML = `
  15793. <td class="py-3 px-4">
  15794. <div class="flex items-center gap-3">
  15795. <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">
  15796. ${initials}
  15797. </div>
  15798. <div>
  15799. <div class="font-bold text-white text-xs flex items-center gap-2">
  15800. <span>${escapeHtml(u.username)}</span>
  15801. ${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>' : ''}
  15802. </div>
  15803. <div class="text-[10px] text-slate-500 font-sans">Created: ${u.created_at ? new Date(u.created_at).toLocaleDateString() : '-'}</div>
  15804. </div>
  15805. </div>
  15806. </td>
  15807. <td class="py-3 px-4 font-sans">
  15808. ${roleBadge}
  15809. </td>
  15810. <td class="py-3 px-4 font-sans">
  15811. ${statusBadge}
  15812. </td>
  15813. <td class="py-3 px-4 text-slate-300 font-sans text-xs">
  15814. ${escapeHtml(u.comment) || '<span class="text-slate-600">-</span>'}
  15815. </td>
  15816. <td class="py-3 px-4 text-slate-400 text-xs">
  15817. ${lastLoginText}
  15818. </td>
  15819. <td class="py-3 px-4 text-right space-x-1.5 font-sans">
  15820. <button onclick="openAdminResetPasswordModal('${escapeHtml(u.username)}')"
  15821. class="p-1.5 rounded-lg text-slate-400 hover:text-amber-400 hover:bg-slate-800 transition" title="Reset User Password">
  15822. <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>
  15823. </button>
  15824. <button onclick="openEditUserModal('${escapeHtml(u.username)}')"
  15825. class="p-1.5 rounded-lg text-slate-400 hover:text-cyan-400 hover:bg-slate-800 transition" title="Edit User">
  15826. <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>
  15827. </button>
  15828. ${!isSelf ? `
  15829. <button onclick="deleteUser('${escapeHtml(u.username)}')"
  15830. class="p-1.5 rounded-lg text-slate-400 hover:text-rose-400 hover:bg-slate-800 transition" title="Delete User">
  15831. <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>
  15832. </button>
  15833. ` : ''}
  15834. </td>
  15835. `;
  15836. tbody.appendChild(tr);
  15837. });
  15838. }
  15839. function openAddUserModal() {
  15840. document.getElementById('user-add-username').value = '';
  15841. document.getElementById('user-add-password').value = '';
  15842. document.getElementById('user-add-confirm').value = '';
  15843. document.getElementById('user-add-role').value = 'full';
  15844. document.getElementById('user-add-comment').value = '';
  15845. document.getElementById('modal-add-user')?.classList.remove('hidden');
  15846. document.getElementById('user-add-username')?.focus();
  15847. }
  15848. function closeAddUserModal() {
  15849. document.getElementById('modal-add-user')?.classList.add('hidden');
  15850. }
  15851. async function submitAddUser(event) {
  15852. event.preventDefault();
  15853. const username = (document.getElementById('user-add-username')?.value || '').trim();
  15854. const password = document.getElementById('user-add-password')?.value || '';
  15855. const confirm = document.getElementById('user-add-confirm')?.value || '';
  15856. const role = document.getElementById('user-add-role')?.value || 'full';
  15857. const comment = (document.getElementById('user-add-comment')?.value || '').trim();
  15858. if (password !== confirm) {
  15859. showToast('Validation Error', 'Passwords do not match', 'warning');
  15860. return;
  15861. }
  15862. if (password.length < 4) {
  15863. showToast('Validation Error', 'Password must be at least 4 characters', 'warning');
  15864. return;
  15865. }
  15866. try {
  15867. const res = await fetch(`${API_BASE}/users`, {
  15868. method: 'POST',
  15869. headers: { 'Content-Type': 'application/json' },
  15870. body: JSON.stringify({ username, password, role, comment })
  15871. });
  15872. const data = await res.json();
  15873. if (res.ok) {
  15874. showToast('User Created', `Created user ${username} with ${role.toUpperCase()} permissions`, 'success');
  15875. closeAddUserModal();
  15876. loadUsers(false);
  15877. } else {
  15878. showToast('Error', data.message || 'Failed to create user', 'error');
  15879. }
  15880. } catch (err) {
  15881. showToast('Error', err.message, 'error');
  15882. }
  15883. }
  15884. function openEditUserModal(username) {
  15885. const user = (state.users || []).find(u => u.username === username);
  15886. if (!user) return;
  15887. document.getElementById('user-edit-username').value = user.username;
  15888. document.getElementById('user-edit-username-title').innerText = `@${user.username}`;
  15889. document.getElementById('user-edit-role').value = user.role || 'read';
  15890. document.getElementById('user-edit-comment').value = user.comment || '';
  15891. document.getElementById('user-edit-disabled').checked = !!user.disabled;
  15892. document.getElementById('modal-edit-user')?.classList.remove('hidden');
  15893. }
  15894. function closeEditUserModal() {
  15895. document.getElementById('modal-edit-user')?.classList.add('hidden');
  15896. }
  15897. async function submitEditUser(event) {
  15898. event.preventDefault();
  15899. const username = document.getElementById('user-edit-username')?.value;
  15900. const role = document.getElementById('user-edit-role')?.value || 'read';
  15901. const comment = (document.getElementById('user-edit-comment')?.value || '').trim();
  15902. const disabled = document.getElementById('user-edit-disabled')?.checked || false;
  15903. try {
  15904. const res = await fetch(`${API_BASE}/users/${encodeURIComponent(username)}`, {
  15905. method: 'PUT',
  15906. headers: { 'Content-Type': 'application/json' },
  15907. body: JSON.stringify({ role, comment, disabled })
  15908. });
  15909. const data = await res.json();
  15910. if (res.ok) {
  15911. showToast('User Updated', `Updated settings for ${username}`, 'success');
  15912. closeEditUserModal();
  15913. loadUsers(false);
  15914. // If updated own role/disabled status, refresh self profile
  15915. if (username === state.currentUser?.username) {
  15916. checkAuthStatus();
  15917. }
  15918. } else {
  15919. showToast('Error', data.message || 'Failed to update user', 'error');
  15920. }
  15921. } catch (err) {
  15922. showToast('Error', err.message, 'error');
  15923. }
  15924. }
  15925. function openAdminResetPasswordModal(username) {
  15926. document.getElementById('admin-reset-username').value = username;
  15927. document.getElementById('admin-reset-username-title').innerText = `@${username}`;
  15928. document.getElementById('admin-reset-new-pw').value = '';
  15929. document.getElementById('admin-reset-confirm-pw').value = '';
  15930. document.getElementById('modal-admin-reset-pw')?.classList.remove('hidden');
  15931. document.getElementById('admin-reset-new-pw')?.focus();
  15932. }
  15933. function closeAdminResetPasswordModal() {
  15934. document.getElementById('modal-admin-reset-pw')?.classList.add('hidden');
  15935. }
  15936. async function submitAdminResetPassword(event) {
  15937. event.preventDefault();
  15938. const username = document.getElementById('admin-reset-username')?.value;
  15939. const newPassword = document.getElementById('admin-reset-new-pw')?.value || '';
  15940. const confirm = document.getElementById('admin-reset-confirm-pw')?.value || '';
  15941. if (newPassword !== confirm) {
  15942. showToast('Validation Error', 'Passwords do not match', 'warning');
  15943. return;
  15944. }
  15945. if (newPassword.length < 4) {
  15946. showToast('Validation Error', 'Password must be at least 4 characters', 'warning');
  15947. return;
  15948. }
  15949. try {
  15950. const res = await fetch(`${API_BASE}/users/${encodeURIComponent(username)}/password`, {
  15951. method: 'POST',
  15952. headers: { 'Content-Type': 'application/json' },
  15953. body: JSON.stringify({ new_password: newPassword })
  15954. });
  15955. const data = await res.json();
  15956. if (res.ok) {
  15957. showToast('Password Reset', `Password for user ${username} updated successfully`, 'success');
  15958. closeAdminResetPasswordModal();
  15959. } else {
  15960. showToast('Error', data.message || 'Failed to reset password', 'error');
  15961. }
  15962. } catch (err) {
  15963. showToast('Error', err.message, 'error');
  15964. }
  15965. }
  15966. async function deleteUser(username) {
  15967. if (username === state.currentUser?.username) {
  15968. showToast('Action Forbidden', 'You cannot delete your own account', 'warning');
  15969. return;
  15970. }
  15971. if (!confirm(`Are you sure you want to completely remove user "${username}"?`)) {
  15972. return;
  15973. }
  15974. try {
  15975. const res = await fetch(`${API_BASE}/users/${encodeURIComponent(username)}`, {
  15976. method: 'DELETE'
  15977. });
  15978. const data = await res.json();
  15979. if (res.ok) {
  15980. showToast('User Deleted', `User ${username} has been removed`, 'success');
  15981. loadUsers(false);
  15982. } else {
  15983. showToast('Error', data.message || 'Failed to delete user', 'error');
  15984. }
  15985. } catch (err) {
  15986. showToast('Error', err.message, 'error');
  15987. }
  15988. }
  15989. function openSelfPasswordModal() {
  15990. document.getElementById('self-current-password').value = '';
  15991. document.getElementById('self-new-password').value = '';
  15992. document.getElementById('self-confirm-password').value = '';
  15993. document.getElementById('modal-self-password')?.classList.remove('hidden');
  15994. document.getElementById('self-current-password')?.focus();
  15995. }
  15996. function closeSelfPasswordModal() {
  15997. document.getElementById('modal-self-password')?.classList.add('hidden');
  15998. }
  15999. async function submitSelfPassword(event) {
  16000. event.preventDefault();
  16001. const oldPassword = document.getElementById('self-current-password')?.value || '';
  16002. const newPassword = document.getElementById('self-new-password')?.value || '';
  16003. const confirm = document.getElementById('self-confirm-password')?.value || '';
  16004. if (newPassword !== confirm) {
  16005. showToast('Validation Error', 'New passwords do not match', 'warning');
  16006. return;
  16007. }
  16008. if (newPassword.length < 4) {
  16009. showToast('Validation Error', 'Password must be at least 4 characters', 'warning');
  16010. return;
  16011. }
  16012. try {
  16013. const res = await fetch(`${API_BASE}/auth/change-password`, {
  16014. method: 'POST',
  16015. headers: { 'Content-Type': 'application/json' },
  16016. body: JSON.stringify({ old_password: oldPassword, new_password: newPassword })
  16017. });
  16018. const data = await res.json();
  16019. if (res.ok) {
  16020. showToast('Password Changed', 'Your password has been changed successfully', 'success');
  16021. closeSelfPasswordModal();
  16022. } else {
  16023. showToast('Error', data.message || 'Failed to change password', 'error');
  16024. }
  16025. } catch (err) {
  16026. showToast('Error', err.message, 'error');
  16027. }
  16028. }
  16029. // ==================== MANAGEMENT SERVICES (/ip service) ====================
  16030. state.services = [];
  16031. async function loadServices(manual = false) {
  16032. try {
  16033. const res = await fetch(`${API_BASE}/system/services`);
  16034. if (!res.ok) throw new Error('Failed to load services');
  16035. const data = await res.json();
  16036. state.services = data || [];
  16037. renderServicesTable();
  16038. updateCertificatesBadges();
  16039. if (manual) showToast('Services Updated', 'Service status synchronized', 'success');
  16040. } catch (err) {
  16041. if (manual) showToast('Error', err.message, 'error');
  16042. }
  16043. }
  16044. function renderServicesTable() {
  16045. const tbody = document.getElementById('services-table-body');
  16046. if (!tbody) return;
  16047. if (!state.services || state.services.length === 0) {
  16048. tbody.innerHTML = '<tr><td colspan="5" class="py-6 text-center text-slate-500 text-xs">No services configured.</td></tr>';
  16049. return;
  16050. }
  16051. tbody.innerHTML = state.services.map(s => {
  16052. const isOff = s.disabled;
  16053. const statusBadge = isOff
  16054. ? '<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>'
  16055. : '<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>';
  16056. const toggleBtn = isOff
  16057. ? `<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>`
  16058. : `<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>`;
  16059. let certBadge = '';
  16060. if (s.name === 'www-ssl') {
  16061. if (s.certificate) {
  16062. 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>`;
  16063. } else {
  16064. 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>`;
  16065. }
  16066. }
  16067. const certArg = s.certificate ? `'${escapeHtml(s.certificate)}'` : "''";
  16068. return `
  16069. <tr class="hover:bg-slate-800/40 transition">
  16070. <td class="py-3 px-4 font-bold text-white uppercase">${s.name} ${certBadge}</td>
  16071. <td class="py-3 px-4">
  16072. <div class="flex items-center gap-2">
  16073. <span class="text-cyan-400 font-mono font-bold">${s.port}</span>
  16074. <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">
  16075. <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>
  16076. </button>
  16077. </div>
  16078. </td>
  16079. <td class="py-3 px-4">${statusBadge}</td>
  16080. <td class="py-3 px-4 text-slate-400 text-xs font-sans">${s.comment || '-'}</td>
  16081. <td class="py-3 px-4 text-right">
  16082. <div class="flex items-center justify-end gap-2">
  16083. <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">
  16084. <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>
  16085. <span>Edit</span>
  16086. </button>
  16087. ${toggleBtn}
  16088. </div>
  16089. </td>
  16090. </tr>
  16091. `;
  16092. }).join('');
  16093. }
  16094. function openEditServiceModal(serviceName, currentPort, isDisabled, currentCert = '') {
  16095. document.getElementById('modal-service-name').value = serviceName;
  16096. document.getElementById('modal-service-disabled').value = String(isDisabled);
  16097. document.getElementById('modal-service-display-name').textContent = serviceName.toUpperCase();
  16098. document.getElementById('modal-service-port').value = currentPort;
  16099. const hintEl = document.getElementById('modal-service-port-hint');
  16100. const warnEl = document.getElementById('modal-service-warning');
  16101. const certGroup = document.getElementById('modal-service-cert-group');
  16102. const certSelect = document.getElementById('modal-service-cert-select');
  16103. if (serviceName === 'www') {
  16104. hintEl.textContent = 'Default HTTP web port: 80';
  16105. warnEl.classList.remove('hidden');
  16106. certGroup.classList.add('hidden');
  16107. } else if (serviceName === 'www-ssl') {
  16108. hintEl.textContent = 'Default HTTPS web port: 443';
  16109. warnEl.classList.remove('hidden');
  16110. certGroup.classList.remove('hidden');
  16111. const populateCertOptions = (certs) => {
  16112. certSelect.innerHTML = '<option value="">-- No Certificate Selected --</option>';
  16113. (certs || []).forEach(c => {
  16114. const opt = document.createElement('option');
  16115. opt.value = c.name;
  16116. opt.textContent = `${c.name} (${c.common_name})${c.is_ca ? ' [CA]' : ''}`;
  16117. if (c.name === currentCert) opt.selected = true;
  16118. certSelect.appendChild(opt);
  16119. });
  16120. };
  16121. if (state.certificates && state.certificates.length > 0) {
  16122. populateCertOptions(state.certificates);
  16123. } else {
  16124. loadCertificates(false).then(() => {
  16125. populateCertOptions(state.certificates);
  16126. });
  16127. }
  16128. } else if (serviceName === 'telnet') {
  16129. hintEl.textContent = 'Default Telnet console port: 8282';
  16130. warnEl.classList.add('hidden');
  16131. certGroup.classList.add('hidden');
  16132. } else if (serviceName === 'ssh') {
  16133. hintEl.textContent = 'Default SSH port: 2222';
  16134. warnEl.classList.add('hidden');
  16135. certGroup.classList.add('hidden');
  16136. } else {
  16137. hintEl.textContent = '';
  16138. warnEl.classList.add('hidden');
  16139. certGroup.classList.add('hidden');
  16140. }
  16141. const modal = document.getElementById('modal-service-edit');
  16142. modal.classList.remove('hidden');
  16143. setTimeout(() => document.getElementById('modal-service-port').focus(), 50);
  16144. }
  16145. function closeEditServiceModal() {
  16146. const modal = document.getElementById('modal-service-edit');
  16147. if (modal) modal.classList.add('hidden');
  16148. }
  16149. async function submitSaveServicePort(event) {
  16150. event.preventDefault();
  16151. const name = document.getElementById('modal-service-name').value;
  16152. const disabled = document.getElementById('modal-service-disabled').value === 'true';
  16153. const port = parseInt(document.getElementById('modal-service-port').value, 10);
  16154. if (isNaN(port) || port < 1 || port > 65535) {
  16155. showToast('Invalid Port', 'Port must be a valid number between 1 and 65535', 'error');
  16156. return;
  16157. }
  16158. const certSelect = document.getElementById('modal-service-cert-select');
  16159. const certVal = (name === 'www-ssl' && certSelect) ? certSelect.value : '';
  16160. try {
  16161. const res = await fetch(`${API_BASE}/system/services/${name}`, {
  16162. method: 'POST',
  16163. headers: { 'Content-Type': 'application/json' },
  16164. body: JSON.stringify({ port: port, disabled: disabled, certificate: certVal })
  16165. });
  16166. if (!res.ok) {
  16167. const errData = await res.json();
  16168. throw new Error(errData.message || 'Failed to update service settings');
  16169. }
  16170. closeEditServiceModal();
  16171. showToast('Service Updated', `Service ${name.toUpperCase()} settings saved`, 'success');
  16172. await loadServices();
  16173. } catch (err) {
  16174. showToast('Error', err.message, 'error');
  16175. }
  16176. }
  16177. async function toggleServiceState(serviceName, newDisabled) {
  16178. if (serviceName === 'www' && newDisabled) {
  16179. 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?")) {
  16180. return;
  16181. }
  16182. }
  16183. if (serviceName === 'www-ssl' && !newDisabled) {
  16184. const sslSvc = (state.services || []).find(s => s.name === 'www-ssl');
  16185. if (!sslSvc || !sslSvc.certificate) {
  16186. showToast('Certificate Required', 'Please assign an SSL/TLS certificate to www-ssl before enabling HTTPS.', 'warning');
  16187. openEditServiceModal('www-ssl', sslSvc ? sslSvc.port : 443, false, '');
  16188. return;
  16189. }
  16190. }
  16191. try {
  16192. const res = await fetch(`${API_BASE}/system/services/${serviceName}/state`, {
  16193. method: 'POST',
  16194. headers: { 'Content-Type': 'application/json' },
  16195. body: JSON.stringify({ disabled: newDisabled })
  16196. });
  16197. if (!res.ok) {
  16198. const errData = await res.json();
  16199. throw new Error(errData.message || 'Failed to update service');
  16200. }
  16201. showToast('Service Updated', `Service ${serviceName} is now ${newDisabled ? 'disabled' : 'enabled'}`, 'success');
  16202. await loadServices();
  16203. } catch (err) {
  16204. showToast('Error', err.message, 'error');
  16205. }
  16206. }
  16207. // ==================== SYSTEM LOGS (/log) ====================
  16208. state.logs = [];
  16209. let logsTimer = null;
  16210. async function loadLogs(manual = false) {
  16211. const limitEl = document.getElementById('logs-limit-select');
  16212. const limit = limitEl ? limitEl.value : '100';
  16213. try {
  16214. const res = await fetch(`${API_BASE}/system/logs?limit=${limit}`);
  16215. if (!res.ok) throw new Error('Failed to load logs');
  16216. const data = await res.json();
  16217. state.logs = data.logs || [];
  16218. renderLogsTable();
  16219. if (manual) showToast('Logs Refreshed', `Fetched ${state.logs.length} log records`, 'success');
  16220. } catch (err) {
  16221. if (manual) showToast('Error', err.message, 'error');
  16222. }
  16223. // Setup auto-refresh if enabled and on logs tab
  16224. if (!logsTimer && state.currentUser) {
  16225. logsTimer = setInterval(() => {
  16226. if (state.currentUser && !document.hidden && state.activeTab === 'logs') {
  16227. const auto = document.getElementById('logs-auto-refresh');
  16228. if (auto && auto.checked) {
  16229. loadLogs(false);
  16230. }
  16231. }
  16232. }, 3000);
  16233. }
  16234. }
  16235. function renderLogsTable() {
  16236. const tbody = document.getElementById('logs-table-body');
  16237. if (!tbody) return;
  16238. const search = (document.getElementById('logs-search-input')?.value || '').toLowerCase();
  16239. const topicFilter = (document.getElementById('logs-topic-filter')?.value || '').toLowerCase();
  16240. const filtered = state.logs.filter(entry => {
  16241. if (topicFilter && !entry.topics.toLowerCase().includes(topicFilter)) {
  16242. return false;
  16243. }
  16244. if (search && !entry.message.toLowerCase().includes(search) && !entry.topics.toLowerCase().includes(search)) {
  16245. return false;
  16246. }
  16247. return true;
  16248. });
  16249. if (filtered.length === 0) {
  16250. tbody.innerHTML = '<tr><td colspan="4" class="py-8 text-center text-slate-500 text-xs">No matching log entries found.</td></tr>';
  16251. return;
  16252. }
  16253. tbody.innerHTML = filtered.map(l => {
  16254. let topicColor = 'bg-slate-800 text-slate-300 border-slate-700';
  16255. const topLower = l.topics.toLowerCase();
  16256. if (topLower.includes('auth')) {
  16257. topicColor = 'bg-amber-500/20 text-amber-300 border-amber-500/30';
  16258. } else if (topLower.includes('dhcp')) {
  16259. topicColor = 'bg-cyan-500/20 text-cyan-300 border-cyan-500/30';
  16260. } else if (topLower.includes('route')) {
  16261. topicColor = 'bg-blue-500/20 text-blue-300 border-blue-500/30';
  16262. } else if (topLower.includes('firewall')) {
  16263. topicColor = 'bg-rose-500/20 text-rose-300 border-rose-500/30';
  16264. } else if (topLower.includes('error')) {
  16265. topicColor = 'bg-red-500/20 text-red-300 border-red-500/30';
  16266. } else if (topLower.includes('system')) {
  16267. topicColor = 'bg-emerald-500/20 text-emerald-300 border-emerald-500/30';
  16268. }
  16269. const d = new Date(l.time);
  16270. const timeStr = d.toLocaleDateString('en-US', { month: 'short', day: '2-digit' }) + ' ' + d.toLocaleTimeString('en-US', { hour12: false });
  16271. return `
  16272. <tr class="hover:bg-slate-800/40 transition">
  16273. <td class="py-2 px-3 text-slate-500 font-mono">${l.id}</td>
  16274. <td class="py-2 px-3 text-slate-400 font-mono whitespace-nowrap">${timeStr}</td>
  16275. <td class="py-2 px-3 whitespace-nowrap">
  16276. <span class="px-2 py-0.5 rounded text-[10px] font-bold border ${topicColor}">${l.topics}</span>
  16277. </td>
  16278. <td class="py-2 px-3 text-slate-200 font-mono break-all">${escapeHtml(l.message)}</td>
  16279. </tr>
  16280. `;
  16281. }).join('');
  16282. }
  16283. // ==================== CERTIFICATES & SSL/TLS (/certificate) ====================
  16284. state.certificates = [];
  16285. async function loadCertificates(manual = false) {
  16286. try {
  16287. const res = await fetch(`${API_BASE}/certificates`);
  16288. if (!res.ok) throw new Error('Failed to load certificates');
  16289. state.certificates = await res.json() || [];
  16290. updateCertificatesBadges();
  16291. renderCertificatesTable();
  16292. if (manual) showToast('Certificates Updated', `Loaded ${state.certificates.length} certificates`, 'success');
  16293. } catch (err) {
  16294. if (manual) showToast('Error', err.message, 'error');
  16295. }
  16296. }
  16297. function updateCertificatesBadges() {
  16298. const total = (state.certificates || []).length;
  16299. const caCount = (state.certificates || []).filter(c => c.is_ca).length;
  16300. const bCount = document.getElementById('badge-certs-count');
  16301. if (bCount) bCount.innerText = total;
  16302. const kpiTotal = document.getElementById('kpi-certs-total');
  16303. if (kpiTotal) kpiTotal.innerText = total;
  16304. const kpiCA = document.getElementById('kpi-certs-ca');
  16305. if (kpiCA) kpiCA.innerText = caCount;
  16306. const kpiHttps = document.getElementById('kpi-https-status');
  16307. if (kpiHttps) {
  16308. const sslSvc = (state.services || []).find(s => s.name === 'www-ssl');
  16309. if (sslSvc) {
  16310. if (!sslSvc.disabled) {
  16311. 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>`;
  16312. } else {
  16313. 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>`;
  16314. }
  16315. }
  16316. }
  16317. }
  16318. function renderCertificatesTable() {
  16319. const tbody = document.getElementById('certs-table-body');
  16320. if (!tbody) return;
  16321. if (!state.certificates || state.certificates.length === 0) {
  16322. 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>';
  16323. return;
  16324. }
  16325. tbody.innerHTML = state.certificates.map(c => {
  16326. let typeBadge = '';
  16327. if (c.is_ca) {
  16328. 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>';
  16329. } else if (c.type === 'acme') {
  16330. 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>';
  16331. } else if (c.issuer && c.issuer !== c.common_name) {
  16332. 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>';
  16333. } else {
  16334. 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>';
  16335. }
  16336. const sansHtml = (c.sans && c.sans.length > 0)
  16337. ? 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('')
  16338. : '<span class="text-slate-500">-</span>';
  16339. const validTo = c.valid_to ? new Date(c.valid_to) : null;
  16340. let validStr = '-';
  16341. let validBadge = '';
  16342. if (validTo && !isNaN(validTo.getTime())) {
  16343. const now = new Date();
  16344. const daysLeft = Math.round((validTo - now) / (1000 * 60 * 60 * 24));
  16345. validStr = validTo.toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' });
  16346. if (daysLeft < 0) {
  16347. validBadge = '<span class="ml-1 text-[10px] text-rose-400 font-bold">(Expired)</span>';
  16348. } else if (daysLeft < 30) {
  16349. validBadge = `<span class="ml-1 text-[10px] text-amber-400 font-bold">(${daysLeft}d left)</span>`;
  16350. } else {
  16351. validBadge = `<span class="ml-1 text-[10px] text-slate-400">(${daysLeft}d left)</span>`;
  16352. }
  16353. }
  16354. return `
  16355. <tr class="hover:bg-slate-800/40 transition">
  16356. <td class="py-3 px-4">${typeBadge}</td>
  16357. <td class="py-3 px-4">
  16358. <div class="font-bold text-white">${escapeHtml(c.name)}</div>
  16359. <div class="text-[10px] text-slate-400 font-sans truncate max-w-xs" title="${escapeHtml(c.common_name)}">${escapeHtml(c.common_name)}</div>
  16360. </td>
  16361. <td class="py-3 px-4 text-slate-300 text-xs truncate max-w-xs" title="${escapeHtml(c.issuer || '-')}">${escapeHtml(c.issuer || '-')}</td>
  16362. <td class="py-3 px-4 max-w-xs">${sansHtml}</td>
  16363. <td class="py-3 px-4 whitespace-nowrap text-xs text-slate-300">
  16364. <span>${validStr}</span> ${validBadge}
  16365. ${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>` : ''}
  16366. <div class="text-[10px] text-slate-500">${c.key_type || ''}</div>
  16367. </td>
  16368. <td class="py-3 px-4 text-right whitespace-nowrap">
  16369. <div class="flex items-center justify-end gap-1.5">
  16370. <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">
  16371. <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>
  16372. <span>View</span>
  16373. </button>
  16374. <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">
  16375. <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>
  16376. </button>
  16377. </div>
  16378. </td>
  16379. </tr>
  16380. `;
  16381. }).join('');
  16382. }
  16383. // Create CA
  16384. function openCreateCAModal() {
  16385. document.getElementById('form-create-ca').reset();
  16386. document.getElementById('ca-days').value = '3650';
  16387. document.getElementById('ca-org').value = 'DebTik Network Appliance';
  16388. document.getElementById('ca-country').value = 'GR';
  16389. document.getElementById('ca-key-type').value = 'RSA-2048';
  16390. document.getElementById('modal-create-ca').classList.remove('hidden');
  16391. setTimeout(() => document.getElementById('ca-name').focus(), 50);
  16392. }
  16393. function closeCreateCAModal() {
  16394. document.getElementById('modal-create-ca').classList.add('hidden');
  16395. }
  16396. async function submitCreateCA(event) {
  16397. event.preventDefault();
  16398. const payload = {
  16399. name: document.getElementById('ca-name').value.trim(),
  16400. common_name: document.getElementById('ca-cn').value.trim(),
  16401. organization: document.getElementById('ca-org').value.trim(),
  16402. country: document.getElementById('ca-country').value.trim(),
  16403. days: parseInt(document.getElementById('ca-days').value, 10) || 3650,
  16404. key_type: document.getElementById('ca-key-type').value
  16405. };
  16406. try {
  16407. const res = await fetch(`${API_BASE}/certificates/ca`, {
  16408. method: 'POST',
  16409. headers: { 'Content-Type': 'application/json' },
  16410. body: JSON.stringify(payload)
  16411. });
  16412. if (!res.ok) {
  16413. const errData = await res.json();
  16414. throw new Error(errData.message || 'Failed to create CA');
  16415. }
  16416. closeCreateCAModal();
  16417. showToast('CA Created', `Root CA ${payload.name} generated successfully`, 'success');
  16418. await loadCertificates();
  16419. } catch (err) {
  16420. showToast('Error', err.message, 'error');
  16421. }
  16422. }
  16423. // Create Cert
  16424. function openCreateCertModal() {
  16425. document.getElementById('form-create-cert').reset();
  16426. document.getElementById('cert-days').value = '730';
  16427. document.getElementById('cert-key-type').value = 'RSA-2048';
  16428. const caSelect = document.getElementById('cert-ca-select');
  16429. caSelect.innerHTML = '<option value="">[ Self-Signed Certificate ]</option>';
  16430. (state.certificates || []).filter(c => c.is_ca).forEach(ca => {
  16431. const opt = document.createElement('option');
  16432. opt.value = ca.name;
  16433. opt.textContent = `${ca.name} (${ca.common_name})`;
  16434. caSelect.appendChild(opt);
  16435. });
  16436. document.getElementById('modal-create-cert').classList.remove('hidden');
  16437. setTimeout(() => document.getElementById('cert-name').focus(), 50);
  16438. }
  16439. function closeCreateCertModal() {
  16440. document.getElementById('modal-create-cert').classList.add('hidden');
  16441. }
  16442. async function submitCreateCert(event) {
  16443. event.preventDefault();
  16444. const rawSans = document.getElementById('cert-sans').value;
  16445. const sansList = rawSans ? rawSans.split(',').map(s => s.trim()).filter(Boolean) : [];
  16446. const caName = document.getElementById('cert-ca-select').value;
  16447. const payload = {
  16448. name: document.getElementById('cert-name').value.trim(),
  16449. common_name: document.getElementById('cert-cn').value.trim(),
  16450. ca_name: caName,
  16451. sans: sansList,
  16452. days: parseInt(document.getElementById('cert-days').value, 10) || 730,
  16453. key_type: document.getElementById('cert-key-type').value,
  16454. is_server: true
  16455. };
  16456. try {
  16457. const res = await fetch(`${API_BASE}/certificates/generate`, {
  16458. method: 'POST',
  16459. headers: { 'Content-Type': 'application/json' },
  16460. body: JSON.stringify(payload)
  16461. });
  16462. if (!res.ok) {
  16463. const errData = await res.json();
  16464. throw new Error(errData.message || 'Failed to issue certificate');
  16465. }
  16466. closeCreateCertModal();
  16467. showToast('Certificate Issued', `Certificate ${payload.name} generated successfully`, 'success');
  16468. await loadCertificates();
  16469. } catch (err) {
  16470. showToast('Error', err.message, 'error');
  16471. }
  16472. }
  16473. // Let's Encrypt
  16474. function openLetsEncryptModal() {
  16475. document.getElementById('form-letsencrypt').reset();
  16476. document.getElementById('modal-letsencrypt').classList.remove('hidden');
  16477. setTimeout(() => document.getElementById('le-domain').focus(), 50);
  16478. }
  16479. function closeLetsEncryptModal() {
  16480. document.getElementById('modal-letsencrypt').classList.add('hidden');
  16481. }
  16482. async function submitLetsEncrypt(event) {
  16483. event.preventDefault();
  16484. const domain = document.getElementById('le-domain').value.trim();
  16485. const email = document.getElementById('le-email').value.trim();
  16486. let name = document.getElementById('le-name').value.trim();
  16487. if (!name) name = domain.replace(/[^a-zA-Z0-9_-]/g, '-');
  16488. const staging = document.getElementById('le-staging').checked;
  16489. const btn = document.getElementById('btn-submit-letsencrypt');
  16490. const origBtnHtml = btn.innerHTML;
  16491. btn.disabled = true;
  16492. 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>`;
  16493. try {
  16494. const res = await fetch(`${API_BASE}/certificates/letsencrypt`, {
  16495. method: 'POST',
  16496. headers: { 'Content-Type': 'application/json' },
  16497. body: JSON.stringify({
  16498. name: name,
  16499. domain: domain,
  16500. email: email,
  16501. staging: staging
  16502. })
  16503. });
  16504. if (!res.ok) {
  16505. const errData = await res.json();
  16506. throw new Error(errData.message || 'Let\'s Encrypt challenge failed');
  16507. }
  16508. closeLetsEncryptModal();
  16509. showToast('Let\'s Encrypt Issued', `Successfully issued trusted certificate for ${domain}`, 'success');
  16510. await loadCertificates();
  16511. } catch (err) {
  16512. showToast('Let\'s Encrypt Error', err.message, 'error');
  16513. } finally {
  16514. btn.disabled = false;
  16515. btn.innerHTML = origBtnHtml;
  16516. }
  16517. }
  16518. // Import Cert
  16519. function openImportCertModal() {
  16520. document.getElementById('form-import-cert').reset();
  16521. document.getElementById('modal-import-cert').classList.remove('hidden');
  16522. setTimeout(() => document.getElementById('import-cert-name').focus(), 50);
  16523. }
  16524. function closeImportCertModal() {
  16525. document.getElementById('modal-import-cert').classList.add('hidden');
  16526. }
  16527. async function submitImportCert(event) {
  16528. event.preventDefault();
  16529. const payload = {
  16530. name: document.getElementById('import-cert-name').value.trim(),
  16531. cert_pem: document.getElementById('import-cert-pem').value.trim(),
  16532. key_pem: document.getElementById('import-key-pem').value.trim()
  16533. };
  16534. try {
  16535. const res = await fetch(`${API_BASE}/certificates/import`, {
  16536. method: 'POST',
  16537. headers: { 'Content-Type': 'application/json' },
  16538. body: JSON.stringify(payload)
  16539. });
  16540. if (!res.ok) {
  16541. const errData = await res.json();
  16542. throw new Error(errData.message || 'Failed to import certificate');
  16543. }
  16544. closeImportCertModal();
  16545. showToast('Certificate Imported', `Imported ${payload.name} successfully`, 'success');
  16546. await loadCertificates();
  16547. } catch (err) {
  16548. showToast('Error', err.message, 'error');
  16549. }
  16550. }
  16551. // View / Export Modal
  16552. async function openViewCertModal(name) {
  16553. const c = (state.certificates || []).find(x => x.name === name);
  16554. if (!c) return;
  16555. document.getElementById('view-cert-modal-title').textContent = `Certificate: ${c.name}`;
  16556. document.getElementById('view-cert-cn').textContent = c.common_name || '-';
  16557. document.getElementById('view-cert-issuer').textContent = c.issuer || '-';
  16558. document.getElementById('view-cert-type').textContent = `${c.is_ca ? 'CA' : 'Server/Client'} (${c.key_type || 'Unknown'})`;
  16559. document.getElementById('view-cert-validto').textContent = c.valid_to ? new Date(c.valid_to).toLocaleString() : '-';
  16560. document.getElementById('view-cert-sans').textContent = (c.sans && c.sans.length > 0) ? c.sans.join(', ') : 'None';
  16561. document.getElementById('view-cert-fp').textContent = c.fingerprint || '-';
  16562. document.getElementById('view-cert-pem-text').value = 'Loading PEM...';
  16563. document.getElementById('view-key-pem-text').value = 'Loading Key...';
  16564. document.getElementById('modal-view-cert').classList.remove('hidden');
  16565. try {
  16566. const res = await fetch(`${API_BASE}/certificates/${encodeURIComponent(name)}/export`);
  16567. if (!res.ok) throw new Error('Failed to export certificate PEM');
  16568. const data = await res.json();
  16569. document.getElementById('view-cert-pem-text').value = data.cert_pem || '';
  16570. document.getElementById('view-key-pem-text').value = data.key_pem || '(Private key not available)';
  16571. } catch (err) {
  16572. document.getElementById('view-cert-pem-text').value = 'Error loading certificate PEM: ' + err.message;
  16573. document.getElementById('view-key-pem-text').value = '';
  16574. }
  16575. }
  16576. function closeViewCertModal() {
  16577. document.getElementById('modal-view-cert').classList.add('hidden');
  16578. }
  16579. function copyCertPEM() {
  16580. const text = document.getElementById('view-cert-pem-text').value;
  16581. if (!text) return;
  16582. navigator.clipboard.writeText(text).then(() => {
  16583. showToast('Copied', 'Certificate PEM copied to clipboard', 'info');
  16584. }).catch(() => {
  16585. showToast('Error', 'Failed to copy to clipboard', 'error');
  16586. });
  16587. }
  16588. function copyKeyPEM() {
  16589. const text = document.getElementById('view-key-pem-text').value;
  16590. if (!text) return;
  16591. navigator.clipboard.writeText(text).then(() => {
  16592. showToast('Copied', 'Private Key PEM copied to clipboard', 'info');
  16593. }).catch(() => {
  16594. showToast('Error', 'Failed to copy to clipboard', 'error');
  16595. });
  16596. }
  16597. async function deleteCertificate(name) {
  16598. if (!confirm(`Are you sure you want to delete certificate "${name}"? This action cannot be undone.`)) {
  16599. return;
  16600. }
  16601. try {
  16602. const res = await fetch(`${API_BASE}/certificates/${encodeURIComponent(name)}`, {
  16603. method: 'DELETE'
  16604. });
  16605. if (!res.ok) {
  16606. const errData = await res.json();
  16607. throw new Error(errData.message || 'Failed to delete certificate');
  16608. }
  16609. showToast('Certificate Deleted', `Certificate "${name}" removed`, 'success');
  16610. await loadCertificates();
  16611. } catch (err) {
  16612. showToast('Error', err.message, 'error');
  16613. }
  16614. }
  16615. // Refresh immediately when returning to a backgrounded controller tab.
  16616. document.addEventListener('visibilitychange', () => {
  16617. if (!state.currentUser) return;
  16618. if (document.hidden) {
  16619. if (trafficEventSource) trafficEventSource.close();
  16620. trafficEventSource = null;
  16621. if (trafficPollFallback) clearInterval(trafficPollFallback);
  16622. trafficPollFallback = null;
  16623. } else {
  16624. fetchData(false);
  16625. initLiveTrafficStream();
  16626. if (state.activeTab === 'bwtest') loadBwTestView();
  16627. }
  16628. });
  16629. async function loadUpdateStatus(populate = true) {
  16630. try {
  16631. const res = await fetch(`${API_BASE}/update/status`);
  16632. if (!res.ok) throw new Error(await responseError(res));
  16633. const data = await res.json();
  16634. if (populate && document.activeElement?.id !== 'update-repository') document.getElementById('update-repository').value = data.repository || '';
  16635. if (populate && document.activeElement?.id !== 'update-tls-pin') document.getElementById('update-tls-pin').value = data.tls_key_pin || '';
  16636. document.getElementById('update-installed').textContent = data.installed_version || 'unknown';
  16637. document.getElementById('update-state').textContent = data.state || 'idle';
  16638. document.getElementById('update-log').textContent = data.log || '';
  16639. } catch (err) { showToast('Update Status', err.message, 'error'); }
  16640. }
  16641. async function saveUpdateConfig() {
  16642. try {
  16643. const repository = document.getElementById('update-repository').value.trim();
  16644. const branch = 'master';
  16645. const tls_key_pin = document.getElementById('update-tls-pin').value.trim();
  16646. const res = await fetch(`${API_BASE}/update/config`, {method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({repository,branch,tls_key_pin})});
  16647. if (!res.ok) throw new Error(await responseError(res));
  16648. document.getElementById('update-install-button').disabled = true;
  16649. document.getElementById('update-available').textContent = '—';
  16650. showToast('Update Source Saved', 'Repository and branch saved', 'success');
  16651. await loadUpdateStatus(false);
  16652. } catch (err) { showToast('Update Source', err.message, 'error'); }
  16653. }
  16654. async function checkUpdate() {
  16655. try {
  16656. const res = await fetch(`${API_BASE}/update/check`, {method:'POST'});
  16657. if (!res.ok) throw new Error(await responseError(res));
  16658. const data = await res.json();
  16659. document.getElementById('update-available').textContent = data.available_version;
  16660. document.getElementById('update-install-button').disabled = !data.update_available;
  16661. showToast('Git Check', data.update_available ? 'An update is available' : 'No newer version available', 'info');
  16662. } catch (err) { showToast('Git Check Failed', err.message, 'error'); }
  16663. }
  16664. async function startUpdate(action) {
  16665. if (!confirm(action === 'rollback' ? 'Restore the previous version and restart DebTik?' : 'Install the newer release version and restart DebTik?')) return;
  16666. try {
  16667. const res = await fetch(`${API_BASE}/update/${action}`, {method:'POST'});
  16668. if (!res.ok) throw new Error(await responseError(res));
  16669. showToast('Update Started', 'The service will restart; reconnect after a few seconds', 'info');
  16670. await loadUpdateStatus(false);
  16671. } catch (err) { showToast('Update Failed', err.message, 'error'); }
  16672. }
  16673. async function resetCurrentRuleCounters() { return resetFirewallRuleCounter('filter', resetRuleCounterDisplay); }
  16674. async function resetCurrentNATRuleCounters() { return resetFirewallRuleCounter('nat', resetNATCounterDisplay); }
  16675. async function resetCurrentMangleRuleCounters() { return resetFirewallRuleCounter('mangle', resetMangleCounterDisplay); }
  16676. function safeFirewallRow(row) {
  16677. const result = {...row};
  16678. for (const [key,value] of Object.entries(result)) if (typeof value === 'string') result[key] = escapeHtml(value);
  16679. result.id = encodeURIComponent(String(row.id || '')).replace(/'/g, '%27').replace(/\(/g, '%28').replace(/\)/g, '%29');
  16680. return result;
  16681. }
  16682. function setFirewallDays(prefix, days) {
  16683. const selected = days ? days.toLowerCase().split(',') : ['sun','mon','tue','wed','thu','fri','sat'];
  16684. 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); }
  16685. }
  16686. function getFirewallDays(prefix) {
  16687. if (document.getElementById(prefix+'-field-days')?.classList.contains('hidden')) return '';
  16688. const selected = ['sun','mon','tue','wed','thu','fri','sat'].filter(d => document.getElementById(prefix+'-day-'+d)?.checked);
  16689. if (!selected.length) throw new Error('Select at least one weekday, or remove the Days condition.');
  16690. return selected.join(',');
  16691. }
  16692. async function resetFirewallRuleCounter(kind, resetDisplay) {
  16693. const id = document.getElementById(kind+'-modal-id')?.value;
  16694. if (!id) { resetDisplay(); return; }
  16695. try {
  16696. const response = await fetch(`${API_BASE}/firewall/${kind}/${encodeURIComponent(id)}/reset-counters`, {method:'POST'});
  16697. if (!response.ok) { const error = await response.json(); throw new Error(error.message || 'Counter reset failed'); }
  16698. resetDisplay(); await loadFirewall(false);
  16699. } catch(error) { showToast('Error', error.message, 'error'); }
  16700. }
  16701. function reviewLegacyFirewallSettings(kind, id) {
  16702. if (!id) return true;
  16703. const rows = kind === 'filter' ? state.filterRules : kind === 'nat' ? state.natRules : state.mangleRules;
  16704. const rule = (rows || []).find(r => r.id === id);
  16705. if (!rule) return true;
  16706. 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'];
  16707. const present = unsupported.filter(key => rule[key]);
  16708. if (!present.length) return true;
  16709. return confirm('This saved rule contains unsupported settings: '+present.join(', ')+'. Saving removes them. Review the remaining match conditions before continuing.');
  16710. }
  16711. function refreshFirewallRejectTypes() {
  16712. const select=document.getElementById('filter-modal-rejectwith'); if(!select) return;
  16713. const old=select.value;
  16714. const ipv6=document.getElementById('filter-modal-family')?.value==='6';
  16715. 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'];
  16716. select.replaceChildren(...types.map(value=>{const option=document.createElement('option');option.value=value;option.textContent=value;return option}));
  16717. if(types.includes(old))select.value=old;
  16718. }
  16719. function setFirewallActionSelection(kind, value) {
  16720. const select=document.getElementById(kind+'-modal-action'); if(!select)return;
  16721. if(!Array.from(select.options).some(option=>option.value===value)) {
  16722. const option=document.createElement('option');option.value=value;option.textContent='Unsupported saved action: '+value;option.disabled=true;select.appendChild(option);
  16723. }
  16724. select.value=value;
  16725. }
  16726. // ==========================================
  16727. // REVERSE PROXY & APPLICATION GATEWAY
  16728. // ==========================================
  16729. state.proxyRules = [];
  16730. state.proxyConfig = null;
  16731. async function loadReverseProxy(manual = false) {
  16732. try {
  16733. const [cfgRes, rulesRes, certsRes] = await Promise.all([
  16734. fetch(`${API_BASE}/proxy/config`),
  16735. fetch(`${API_BASE}/proxy/rules`),
  16736. fetch(`${API_BASE}/certificates`).catch(() => null)
  16737. ]);
  16738. if (!cfgRes.ok) throw new Error('Failed to load proxy config');
  16739. if (!rulesRes.ok) throw new Error('Failed to load proxy rules');
  16740. state.proxyConfig = await cfgRes.json();
  16741. state.proxyRules = await rulesRes.json() || [];
  16742. if (certsRes && certsRes.ok) {
  16743. state.certificates = await certsRes.json() || [];
  16744. }
  16745. renderProxyRules(state.proxyRules);
  16746. updateProxyMetrics();
  16747. if (manual) showToast('Reverse Proxy', 'Proxy configuration and rules reloaded', 'success');
  16748. } catch (err) {
  16749. console.error('loadReverseProxy error:', err);
  16750. if (manual) showToast('Error', err.message, 'error');
  16751. }
  16752. }
  16753. function updateProxyMetrics() {
  16754. const badge = document.getElementById('badge-proxy-count');
  16755. if (badge) badge.textContent = (state.proxyRules || []).length;
  16756. const metricRules = document.getElementById('proxy-metric-rules');
  16757. if (metricRules) metricRules.textContent = (state.proxyRules || []).length;
  16758. const cfg = state.proxyConfig;
  16759. const statusEl = document.getElementById('proxy-metric-status');
  16760. const portsEl = document.getElementById('proxy-metric-ports');
  16761. if (cfg) {
  16762. if (statusEl) {
  16763. if (cfg.enabled) {
  16764. statusEl.innerHTML = '<span class="w-2.5 h-2.5 rounded-full bg-emerald-500 animate-pulse"></span><span class="text-white">Active</span>';
  16765. } else {
  16766. statusEl.innerHTML = '<span class="w-2.5 h-2.5 rounded-full bg-rose-500"></span><span class="text-rose-400">Disabled</span>';
  16767. }
  16768. }
  16769. if (portsEl) {
  16770. portsEl.textContent = `HTTP: ${cfg.http_port || 80} | HTTPS: ${cfg.https_port || 443}`;
  16771. }
  16772. }
  16773. let totalRequests = 0;
  16774. const certSet = new Set();
  16775. (state.proxyRules || []).forEach(r => {
  16776. totalRequests += (r.stats && r.stats.requests) || 0;
  16777. if (r.enabled && r.certificate) certSet.add(r.certificate.toLowerCase());
  16778. });
  16779. const metricRequests = document.getElementById('proxy-metric-requests');
  16780. if (metricRequests) metricRequests.textContent = totalRequests.toLocaleString();
  16781. const metricCerts = document.getElementById('proxy-metric-certs');
  16782. if (metricCerts) metricCerts.textContent = certSet.size;
  16783. }
  16784. function renderProxyRules(rules) {
  16785. const tbody = document.getElementById('proxy-rules-table-body');
  16786. if (!tbody) return;
  16787. if (!rules || rules.length === 0) {
  16788. 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>';
  16789. return;
  16790. }
  16791. tbody.innerHTML = rules.map(r => {
  16792. const isEnabled = r.enabled !== false;
  16793. 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>';
  16794. 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>`;
  16795. let protoBadge = '<span class="px-1.5 py-0.5 rounded bg-slate-800 text-slate-300 text-[10px] font-mono">HTTP/S</span>';
  16796. 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>';
  16797. 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>';
  16798. 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>` : '';
  16799. const stripBadge = r.strip_path ? '<span class="text-amber-400 text-[11px]">Yes</span>' : '<span class="text-slate-500 text-[11px]">No</span>';
  16800. const requests = (r.stats && r.stats.requests) ? r.stats.requests.toLocaleString() : '0';
  16801. return `
  16802. <tr class="hover:bg-slate-800/40 transition">
  16803. <td class="py-3 px-4">
  16804. <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'}">
  16805. <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>
  16806. </button>
  16807. </td>
  16808. <td class="py-3 px-4">
  16809. <div class="font-bold text-white text-xs">${escapeHtml(r.name || 'Unnamed Rule')}</div>
  16810. ${r.comment ? `<div class="text-[10px] text-slate-400 font-sans truncate max-w-[200px]">${escapeHtml(r.comment)}</div>` : ''}
  16811. </td>
  16812. <td class="py-3 px-4 flex flex-wrap gap-1 items-center max-w-xs">
  16813. ${domainsStr}
  16814. </td>
  16815. <td class="py-3 px-4">
  16816. ${pathBadge}
  16817. </td>
  16818. <td class="py-3 px-4 font-mono text-slate-300 max-w-xs truncate" title="${escapeHtml(r.target_url || '')}">
  16819. <span class="text-emerald-400">→</span> ${escapeHtml(r.target_url || '')}
  16820. </td>
  16821. <td class="py-3 px-4 whitespace-nowrap">
  16822. ${protoBadge}${certBadge}
  16823. </td>
  16824. <td class="py-3 px-4 font-mono">
  16825. ${stripBadge}
  16826. </td>
  16827. <td class="py-3 px-4 font-mono text-slate-300">
  16828. ${requests}
  16829. </td>
  16830. <td class="py-3 px-4 text-right whitespace-nowrap">
  16831. <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>
  16832. <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>
  16833. </td>
  16834. </tr>
  16835. `;
  16836. }).join('');
  16837. }
  16838. function populateProxyCertDropdown(selectedVal = '') {
  16839. const select = document.getElementById('proxy-rule-cert');
  16840. if (!select) return;
  16841. const certs = state.certificates || [];
  16842. select.innerHTML = '<option value="">(None / Use Default Cert)</option>';
  16843. certs.filter(c => !c.is_ca).forEach(c => {
  16844. const opt = document.createElement('option');
  16845. opt.value = c.name;
  16846. const cn = c.common_name ? ` (${c.common_name})` : '';
  16847. opt.textContent = `${c.name}${cn}`;
  16848. if (selectedVal && selectedVal.toLowerCase() === c.name.toLowerCase()) {
  16849. opt.selected = true;
  16850. }
  16851. select.appendChild(opt);
  16852. });
  16853. }
  16854. function populateDefaultProxyCertDropdown(selectedVal = '') {
  16855. const select = document.getElementById('proxy-cfg-default-cert');
  16856. if (!select) return;
  16857. const certs = state.certificates || [];
  16858. select.innerHTML = '<option value="">(None / First Available Cert)</option>';
  16859. certs.filter(c => !c.is_ca).forEach(c => {
  16860. const opt = document.createElement('option');
  16861. opt.value = c.name;
  16862. const cn = c.common_name ? ` (${c.common_name})` : '';
  16863. opt.textContent = `${c.name}${cn}`;
  16864. if (selectedVal && selectedVal.toLowerCase() === c.name.toLowerCase()) {
  16865. opt.selected = true;
  16866. }
  16867. select.appendChild(opt);
  16868. });
  16869. }
  16870. function onProxyProtoChange() {
  16871. const proto = document.getElementById('proxy-rule-proto')?.value;
  16872. const certSelect = document.getElementById('proxy-rule-cert');
  16873. const redirectCheck = document.getElementById('proxy-rule-http-to-https');
  16874. if (proto === 'http') {
  16875. if (certSelect) certSelect.disabled = true;
  16876. if (redirectCheck) redirectCheck.disabled = true;
  16877. } else {
  16878. if (certSelect) certSelect.disabled = false;
  16879. if (redirectCheck) redirectCheck.disabled = false;
  16880. }
  16881. }
  16882. function openAddProxyRuleModal() {
  16883. const modal = document.getElementById('modal-proxy-rule');
  16884. if (!modal) return;
  16885. document.getElementById('proxy-rule-modal-title').innerHTML = `
  16886. <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>
  16887. <span>Add Reverse Proxy Rule</span>
  16888. `;
  16889. document.getElementById('proxy-rule-id').value = '';
  16890. document.getElementById('proxy-rule-name').value = '';
  16891. document.getElementById('proxy-rule-domains').value = '';
  16892. document.getElementById('proxy-rule-path').value = '/';
  16893. document.getElementById('proxy-rule-target').value = '';
  16894. document.getElementById('proxy-rule-proto').value = 'both';
  16895. document.getElementById('proxy-rule-strip-path').checked = false;
  16896. document.getElementById('proxy-rule-http-to-https').checked = false;
  16897. document.getElementById('proxy-rule-preserve-host').checked = false;
  16898. document.getElementById('proxy-rule-insecure-tls').checked = false;
  16899. document.getElementById('proxy-rule-enabled').checked = true;
  16900. document.getElementById('proxy-rule-comment').value = '';
  16901. populateProxyCertDropdown('');
  16902. onProxyProtoChange();
  16903. modal.classList.remove('hidden');
  16904. }
  16905. function openEditProxyRuleModal(id) {
  16906. const modal = document.getElementById('modal-proxy-rule');
  16907. if (!modal) return;
  16908. const rule = (state.proxyRules || []).find(r => r.id === id);
  16909. if (!rule) {
  16910. showToast('Error', 'Rule not found', 'error');
  16911. return;
  16912. }
  16913. document.getElementById('proxy-rule-modal-title').innerHTML = `
  16914. <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>
  16915. <span>Edit Reverse Proxy Rule</span>
  16916. `;
  16917. document.getElementById('proxy-rule-id').value = rule.id || '';
  16918. document.getElementById('proxy-rule-name').value = rule.name || '';
  16919. document.getElementById('proxy-rule-domains').value = (rule.domains || []).join(', ');
  16920. document.getElementById('proxy-rule-path').value = rule.path || '/';
  16921. document.getElementById('proxy-rule-target').value = rule.target_url || '';
  16922. document.getElementById('proxy-rule-proto').value = rule.protocol || 'both';
  16923. document.getElementById('proxy-rule-strip-path').checked = !!rule.strip_path;
  16924. document.getElementById('proxy-rule-http-to-https').checked = !!rule.http_to_https;
  16925. document.getElementById('proxy-rule-preserve-host').checked = !!rule.preserve_host;
  16926. document.getElementById('proxy-rule-insecure-tls').checked = !!rule.insecure_tls;
  16927. document.getElementById('proxy-rule-enabled').checked = rule.enabled !== false;
  16928. document.getElementById('proxy-rule-comment').value = rule.comment || '';
  16929. populateProxyCertDropdown(rule.certificate || '');
  16930. onProxyProtoChange();
  16931. modal.classList.remove('hidden');
  16932. }
  16933. function closeProxyRuleModal() {
  16934. const modal = document.getElementById('modal-proxy-rule');
  16935. if (modal) modal.classList.add('hidden');
  16936. }
  16937. async function saveProxyRule(event) {
  16938. event.preventDefault();
  16939. const id = document.getElementById('proxy-rule-id').value;
  16940. const name = document.getElementById('proxy-rule-name').value.trim();
  16941. const rawDomains = document.getElementById('proxy-rule-domains').value.trim();
  16942. const pathVal = document.getElementById('proxy-rule-path').value.trim() || '/';
  16943. const target = document.getElementById('proxy-rule-target').value.trim();
  16944. const proto = document.getElementById('proxy-rule-proto').value;
  16945. const cert = document.getElementById('proxy-rule-cert').value;
  16946. const stripPath = document.getElementById('proxy-rule-strip-path').checked;
  16947. const httpToHttps = document.getElementById('proxy-rule-http-to-https').checked;
  16948. const preserveHost = document.getElementById('proxy-rule-preserve-host').checked;
  16949. const insecureTLS = document.getElementById('proxy-rule-insecure-tls').checked;
  16950. const enabled = document.getElementById('proxy-rule-enabled').checked;
  16951. const comment = document.getElementById('proxy-rule-comment').value.trim();
  16952. let domains = [];
  16953. if (rawDomains && rawDomains !== '*') {
  16954. domains = rawDomains.split(',').map(d => d.trim()).filter(d => d.length > 0);
  16955. }
  16956. const payload = {
  16957. id: id || undefined,
  16958. name,
  16959. domains,
  16960. path: pathVal,
  16961. target_url: target,
  16962. protocol: proto,
  16963. certificate: cert,
  16964. strip_path: stripPath,
  16965. http_to_https: httpToHttps,
  16966. preserve_host: preserveHost,
  16967. insecure_tls: insecureTLS,
  16968. enabled,
  16969. comment
  16970. };
  16971. try {
  16972. const url = id ? `${API_BASE}/proxy/rules/${encodeURIComponent(id)}` : `${API_BASE}/proxy/rules`;
  16973. const method = id ? 'PUT' : 'POST';
  16974. const res = await fetch(url, {
  16975. method,
  16976. headers: { 'Content-Type': 'application/json' },
  16977. body: JSON.stringify(payload)
  16978. });
  16979. if (!res.ok) {
  16980. const errData = await res.json().catch(() => ({}));
  16981. throw new Error(errData.message || 'Failed to save proxy rule');
  16982. }
  16983. closeProxyRuleModal();
  16984. showToast('Success', `Proxy rule "${name}" saved successfully`, 'success');
  16985. await loadReverseProxy(false);
  16986. } catch (err) {
  16987. showToast('Error', err.message, 'error');
  16988. }
  16989. }
  16990. async function deleteProxyRule(id) {
  16991. const rule = (state.proxyRules || []).find(r => r.id === id);
  16992. const name = rule ? rule.name : id;
  16993. if (!confirm(`Are you sure you want to delete proxy rule "${name}"?`)) {
  16994. return;
  16995. }
  16996. try {
  16997. const res = await fetch(`${API_BASE}/proxy/rules/${encodeURIComponent(id)}`, {
  16998. method: 'DELETE'
  16999. });
  17000. if (!res.ok) {
  17001. const errData = await res.json().catch(() => ({}));
  17002. throw new Error(errData.message || 'Failed to delete rule');
  17003. }
  17004. showToast('Rule Deleted', `Proxy rule "${name}" removed`, 'success');
  17005. await loadReverseProxy(false);
  17006. } catch (err) {
  17007. showToast('Error', err.message, 'error');
  17008. }
  17009. }
  17010. async function toggleProxyRuleState(id, currentState) {
  17011. try {
  17012. const res = await fetch(`${API_BASE}/proxy/rules/${encodeURIComponent(id)}/state`, {
  17013. method: 'POST',
  17014. headers: { 'Content-Type': 'application/json' },
  17015. body: JSON.stringify({ enabled: !currentState })
  17016. });
  17017. if (!res.ok) {
  17018. const errData = await res.json().catch(() => ({}));
  17019. throw new Error(errData.message || 'Failed to toggle rule state');
  17020. }
  17021. await loadReverseProxy(false);
  17022. } catch (err) {
  17023. showToast('Error', err.message, 'error');
  17024. }
  17025. }
  17026. function openProxyConfigModal() {
  17027. const modal = document.getElementById('modal-proxy-config');
  17028. if (!modal) return;
  17029. const cfg = state.proxyConfig || { enabled: true, http_port: 80, https_port: 443, default_cert: '' };
  17030. document.getElementById('proxy-cfg-enabled').checked = cfg.enabled !== false;
  17031. document.getElementById('proxy-cfg-http-port').value = cfg.http_port || 80;
  17032. document.getElementById('proxy-cfg-https-port').value = cfg.https_port || 443;
  17033. populateDefaultProxyCertDropdown(cfg.default_cert || '');
  17034. modal.classList.remove('hidden');
  17035. }
  17036. function closeProxyConfigModal() {
  17037. const modal = document.getElementById('modal-proxy-config');
  17038. if (modal) modal.classList.add('hidden');
  17039. }
  17040. async function saveProxyConfig(event) {
  17041. event.preventDefault();
  17042. const enabled = document.getElementById('proxy-cfg-enabled').checked;
  17043. const httpPort = parseInt(document.getElementById('proxy-cfg-http-port').value, 10) || 80;
  17044. const httpsPort = parseInt(document.getElementById('proxy-cfg-https-port').value, 10) || 443;
  17045. const defaultCert = document.getElementById('proxy-cfg-default-cert').value;
  17046. const payload = {
  17047. enabled,
  17048. http_port: httpPort,
  17049. https_port: httpsPort,
  17050. default_cert: defaultCert
  17051. };
  17052. try {
  17053. const res = await fetch(`${API_BASE}/proxy/config`, {
  17054. method: 'POST',
  17055. headers: { 'Content-Type': 'application/json' },
  17056. body: JSON.stringify(payload)
  17057. });
  17058. if (!res.ok) {
  17059. const errData = await res.json().catch(() => ({}));
  17060. throw new Error(errData.message || 'Failed to update proxy settings');
  17061. }
  17062. closeProxyConfigModal();
  17063. showToast('Success', 'Reverse proxy settings updated', 'success');
  17064. await loadReverseProxy(false);
  17065. } catch (err) {
  17066. showToast('Error', err.message, 'error');
  17067. }
  17068. }
  17069. // ==================== SD-WAN Controller ====================
  17070. async function loadSDWAN(manual = false) {
  17071. try {
  17072. const [groupsRes, telemetryRes] = await Promise.all([
  17073. fetch(`${API_BASE}/sdwan/groups`),
  17074. fetch(`${API_BASE}/sdwan/telemetry`)
  17075. ]);
  17076. if (!groupsRes.ok) throw new Error('Failed to load SD-WAN groups');
  17077. state.sdwanGroups = await groupsRes.json() || [];
  17078. if (telemetryRes.ok) {
  17079. state.sdwanTelemetry = await telemetryRes.json() || {};
  17080. }
  17081. renderSDWANGroups(state.sdwanGroups);
  17082. renderSDWANMembers(state.sdwanGroups);
  17083. updateSDWANMetrics(state.sdwanTelemetry);
  17084. if (manual) showToast('SD-WAN', 'SD-WAN groups and live telemetry reloaded', 'success');
  17085. } catch (err) {
  17086. console.error('loadSDWAN error:', err);
  17087. if (manual) showToast('Error', err.message, 'error');
  17088. }
  17089. }
  17090. function updateSDWANMetrics(telemetry) {
  17091. const groups = state.sdwanGroups || [];
  17092. const t = telemetry || {};
  17093. const badge = document.getElementById('badge-sdwan-count');
  17094. if (badge) badge.textContent = groups.length;
  17095. const metricGroups = document.getElementById('sdwan-metric-groups');
  17096. if (metricGroups) metricGroups.textContent = `${t.active_groups || 0} / ${t.total_groups || groups.length}`;
  17097. const metricHealthy = document.getElementById('sdwan-metric-healthy');
  17098. if (metricHealthy) metricHealthy.textContent = t.healthy_members || 0;
  17099. const metricDegraded = document.getElementById('sdwan-metric-degraded');
  17100. if (metricDegraded) metricDegraded.textContent = t.degraded_members || 0;
  17101. const metricDown = document.getElementById('sdwan-metric-down');
  17102. if (metricDown) metricDown.textContent = t.down_members || 0;
  17103. }
  17104. function renderSDWANGroups(groups) {
  17105. const tbody = document.getElementById('sdwan-groups-table-body');
  17106. if (!tbody) return;
  17107. if (!groups || groups.length === 0) {
  17108. 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>';
  17109. return;
  17110. }
  17111. tbody.innerHTML = groups.map(g => {
  17112. const isEnabled = g.disabled !== true;
  17113. const members = g.members || [];
  17114. const totalWeight = members.filter(m => !m.disabled).reduce((sum, m) => sum + (m.weight || 50), 0) || 1;
  17115. // Build distribution progress bar
  17116. let distHtml = '';
  17117. if (members.length === 0) {
  17118. distHtml = '<span class="text-slate-500 text-[11px] font-sans">No links attached</span>';
  17119. } else if (g.mode === 'weighted' || g.mode === 'pcc') {
  17120. const colors = ['bg-amber-500', 'bg-cyan-500', 'bg-emerald-500', 'bg-purple-500', 'bg-rose-500'];
  17121. const segments = members.map((m, idx) => {
  17122. const pct = m.disabled ? 0 : Math.round(((m.weight || 50) / totalWeight) * 100);
  17123. const col = colors[idx % colors.length];
  17124. return `<div class="${col} h-2 transition-all relative group" style="width: ${pct}%" title="${escapeHtml(m.interface)}: ${pct}%"></div>`;
  17125. }).join('');
  17126. const labels = members.map((m, idx) => {
  17127. const pct = m.disabled ? '0%' : `${Math.round(((m.weight || 50) / totalWeight) * 100)}%`;
  17128. const textCol = ['text-amber-400', 'text-cyan-400', 'text-emerald-400', 'text-purple-400', 'text-rose-400'][idx % 5];
  17129. return `<span class="${textCol} text-[10px] font-mono mr-2">${escapeHtml(m.interface)}: ${pct}</span>`;
  17130. }).join('');
  17131. distHtml = `
  17132. <div class="w-48 bg-slate-800 rounded-full h-2 overflow-hidden flex mb-1 border border-slate-700/50">${segments}</div>
  17133. <div class="flex flex-wrap">${labels}</div>
  17134. `;
  17135. } else if (g.mode === 'lowest-latency') {
  17136. distHtml = '<span class="text-emerald-400 text-[11px] font-sans">⚡ Auto: lowest RTT probe</span>';
  17137. } else if (g.mode === 'lowest-loss') {
  17138. distHtml = '<span class="text-cyan-400 text-[11px] font-sans">🛡 Auto: minimum packet loss</span>';
  17139. } else if (g.mode === 'failover') {
  17140. distHtml = '<span class="text-amber-400 text-[11px] font-sans">🔄 Priority Failover (Active-Backup)</span>';
  17141. }
  17142. let modeBadge = '';
  17143. switch (g.mode) {
  17144. case 'weighted':
  17145. 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>';
  17146. break;
  17147. case 'pcc':
  17148. 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>';
  17149. break;
  17150. case 'lowest-latency':
  17151. 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>';
  17152. break;
  17153. case 'lowest-loss':
  17154. 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>';
  17155. break;
  17156. case 'failover':
  17157. 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>';
  17158. break;
  17159. default:
  17160. modeBadge = `<span class="px-2 py-0.5 rounded bg-slate-800 text-slate-300 text-[10px] font-bold">${escapeHtml(g.mode)}</span>`;
  17161. }
  17162. const autoNatBadge = g.auto_nat
  17163. ? '<span class="text-emerald-400 text-[11px]">Enabled</span>'
  17164. : '<span class="text-slate-500 text-[11px]">Disabled</span>';
  17165. return `
  17166. <tr class="hover:bg-slate-800/40 transition">
  17167. <td class="py-3 px-4">
  17168. <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'}">
  17169. <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>
  17170. </button>
  17171. </td>
  17172. <td class="py-3 px-4">
  17173. <div class="font-bold text-white text-xs flex items-center gap-1.5">
  17174. <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>
  17175. ${g.comment ? `<span class="text-slate-400 text-[10px] font-sans truncate max-w-[150px]" title="${escapeHtml(g.comment)}">(${escapeHtml(g.comment)})</span>` : ''}
  17176. </div>
  17177. </td>
  17178. <td class="py-3 px-4">${modeBadge}</td>
  17179. <td class="py-3 px-4">${distHtml}</td>
  17180. <td class="py-3 px-4">
  17181. <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>
  17182. </td>
  17183. <td class="py-3 px-4 text-slate-300 font-mono text-xs">${g.probe_interval || 3}s</td>
  17184. <td class="py-3 px-4">${autoNatBadge}</td>
  17185. <td class="py-3 px-4 text-right">
  17186. <div class="flex items-center justify-end gap-1.5">
  17187. <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">
  17188. <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>
  17189. </button>
  17190. <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">
  17191. <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>
  17192. </button>
  17193. <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">
  17194. <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>
  17195. </button>
  17196. </div>
  17197. </td>
  17198. </tr>
  17199. `;
  17200. }).join('');
  17201. }
  17202. function renderSDWANMembers(groups) {
  17203. const tbody = document.getElementById('sdwan-members-table-body');
  17204. if (!tbody) return;
  17205. const allMembers = [];
  17206. (groups || []).forEach(g => {
  17207. (g.members || []).forEach(m => {
  17208. allMembers.push({ ...m, group_id: g.id, group_name: g.name });
  17209. });
  17210. });
  17211. if (allMembers.length === 0) {
  17212. 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>';
  17213. return;
  17214. }
  17215. tbody.innerHTML = allMembers.map(m => {
  17216. const isEnabled = m.disabled !== true;
  17217. 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>';
  17218. if (!isEnabled) {
  17219. statusBadge = '<span class="px-2 py-0.5 rounded bg-slate-800 text-slate-400 border border-slate-700 text-[10px]">DISABLED</span>';
  17220. } else if (m.status === 'DEGRADED') {
  17221. 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>';
  17222. } else if (m.status === 'DOWN') {
  17223. 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>';
  17224. }
  17225. const latColor = m.live_latency > (m.max_latency || 250) ? 'text-amber-400' : 'text-emerald-400';
  17226. const lossColor = m.packet_loss > (m.max_loss || 20) ? 'text-rose-400' : 'text-slate-300';
  17227. return `
  17228. <tr class="hover:bg-slate-800/40 transition">
  17229. <td class="py-3 px-4">
  17230. <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'}">
  17231. <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>
  17232. </button>
  17233. </td>
  17234. <td class="py-3 px-4">
  17235. <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>
  17236. </td>
  17237. <td class="py-3 px-4">
  17238. <div class="font-bold text-white text-xs font-mono">${escapeHtml(m.interface)}</div>
  17239. ${m.comment ? `<div class="text-[10px] text-slate-500 font-sans">${escapeHtml(m.comment)}</div>` : ''}
  17240. </td>
  17241. <td class="py-3 px-4 text-slate-300 font-mono text-xs">${escapeHtml(m.gateway || '(auto)')}</td>
  17242. <td class="py-3 px-4">
  17243. <div class="text-xs font-mono text-white">W: ${m.weight || 50}</div>
  17244. <div class="text-[10px] text-slate-500">Prio: ${m.priority || 1}</div>
  17245. </td>
  17246. <td class="py-3 px-4">${statusBadge}</td>
  17247. <td class="py-3 px-4 text-cyan-400 font-mono text-xs">${escapeHtml(m.target_probe || '1.1.1.1')}</td>
  17248. <td class="py-3 px-4 font-mono text-xs ${latColor}">
  17249. ${m.live_latency ? `${m.live_latency.toFixed(1)} ms` : '<span class="text-slate-500">--</span>'}
  17250. </td>
  17251. <td class="py-3 px-4 font-mono text-xs ${lossColor}">
  17252. ${m.packet_loss !== undefined ? `${m.packet_loss.toFixed(1)}%` : '<span class="text-slate-500">--</span>'}
  17253. </td>
  17254. <td class="py-3 px-4 font-mono text-xs text-slate-400">
  17255. ${m.jitter ? `${m.jitter.toFixed(1)} ms` : '<span class="text-slate-500">--</span>'}
  17256. </td>
  17257. <td class="py-3 px-4 text-right">
  17258. <div class="flex items-center justify-end gap-1.5">
  17259. <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">
  17260. <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>
  17261. </button>
  17262. <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">
  17263. <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>
  17264. </button>
  17265. </div>
  17266. </td>
  17267. </tr>
  17268. `;
  17269. }).join('');
  17270. }
  17271. // Modal handling for SD-WAN Groups
  17272. function openAddSDWANGroupModal() {
  17273. const modal = document.getElementById('modal-sdwan-group');
  17274. if (!modal) return;
  17275. document.getElementById('sdwan-group-modal-title').querySelector('span').textContent = 'Create SD-WAN Group';
  17276. document.getElementById('sdwan-group-id').value = '';
  17277. document.getElementById('sdwan-group-name').value = `sdwan${(state.sdwanGroups || []).length}`;
  17278. document.getElementById('sdwan-group-name').disabled = false;
  17279. document.getElementById('sdwan-group-mode').value = 'weighted';
  17280. document.getElementById('sdwan-group-pcc-container').classList.add('hidden');
  17281. document.getElementById('sdwan-group-hash-fields').value = 'both-addresses-and-ports';
  17282. document.getElementById('sdwan-group-probe-interval').value = 3;
  17283. document.getElementById('sdwan-group-auto-nat').checked = true;
  17284. document.getElementById('sdwan-group-comment').value = '';
  17285. modal.classList.remove('hidden');
  17286. }
  17287. function openEditSDWANGroupModal(id) {
  17288. const group = (state.sdwanGroups || []).find(g => g.id === id);
  17289. if (!group) return;
  17290. const modal = document.getElementById('modal-sdwan-group');
  17291. if (!modal) return;
  17292. document.getElementById('sdwan-group-modal-title').querySelector('span').textContent = `Edit SD-WAN Group (${group.name})`;
  17293. document.getElementById('sdwan-group-id').value = group.id;
  17294. document.getElementById('sdwan-group-name').value = group.name;
  17295. document.getElementById('sdwan-group-name').disabled = true;
  17296. document.getElementById('sdwan-group-mode').value = group.mode || 'weighted';
  17297. if (group.mode === 'pcc') {
  17298. document.getElementById('sdwan-group-pcc-container').classList.remove('hidden');
  17299. } else {
  17300. document.getElementById('sdwan-group-pcc-container').classList.add('hidden');
  17301. }
  17302. document.getElementById('sdwan-group-hash-fields').value = group.hash_fields || 'both-addresses-and-ports';
  17303. document.getElementById('sdwan-group-probe-interval').value = group.probe_interval || 3;
  17304. document.getElementById('sdwan-group-auto-nat').checked = group.auto_nat !== false;
  17305. document.getElementById('sdwan-group-comment').value = group.comment || '';
  17306. modal.classList.remove('hidden');
  17307. }
  17308. function closeSDWANGroupModal() {
  17309. const modal = document.getElementById('modal-sdwan-group');
  17310. if (modal) modal.classList.add('hidden');
  17311. }
  17312. function onSDWANModeChange() {
  17313. const mode = document.getElementById('sdwan-group-mode').value;
  17314. const pccContainer = document.getElementById('sdwan-group-pcc-container');
  17315. if (pccContainer) {
  17316. if (mode === 'pcc') pccContainer.classList.remove('hidden');
  17317. else pccContainer.classList.add('hidden');
  17318. }
  17319. }
  17320. async function saveSDWANGroup(event) {
  17321. event.preventDefault();
  17322. const id = document.getElementById('sdwan-group-id').value;
  17323. const name = document.getElementById('sdwan-group-name').value.trim();
  17324. const mode = document.getElementById('sdwan-group-mode').value;
  17325. const hashFields = document.getElementById('sdwan-group-hash-fields').value;
  17326. const probeInterval = parseInt(document.getElementById('sdwan-group-probe-interval').value, 10) || 3;
  17327. const autoNAT = document.getElementById('sdwan-group-auto-nat').checked;
  17328. const comment = document.getElementById('sdwan-group-comment').value.trim();
  17329. const existing = (state.sdwanGroups || []).find(g => g.id === id);
  17330. const payload = {
  17331. id: id || undefined,
  17332. name,
  17333. mode,
  17334. hash_fields: mode === 'pcc' ? hashFields : undefined,
  17335. probe_interval: probeInterval,
  17336. auto_nat: autoNAT,
  17337. comment,
  17338. members: existing ? existing.members : undefined
  17339. };
  17340. try {
  17341. const res = await fetch(`${API_BASE}/sdwan/groups`, {
  17342. method: 'POST',
  17343. headers: { 'Content-Type': 'application/json' },
  17344. body: JSON.stringify(payload)
  17345. });
  17346. if (!res.ok) {
  17347. const err = await res.json().catch(() => ({}));
  17348. throw new Error(err.message || 'Failed to save SD-WAN group');
  17349. }
  17350. closeSDWANGroupModal();
  17351. showToast('Success', `SD-WAN group ${name} saved successfully`, 'success');
  17352. await loadSDWAN(false);
  17353. } catch (err) {
  17354. showToast('Error', err.message, 'error');
  17355. }
  17356. }
  17357. async function toggleSDWANGroupState(id, currentState) {
  17358. try {
  17359. const res = await fetch(`${API_BASE}/sdwan/groups/${id}/state`, {
  17360. method: 'POST',
  17361. headers: { 'Content-Type': 'application/json' },
  17362. body: JSON.stringify({ disabled: currentState })
  17363. });
  17364. if (!res.ok) throw new Error('Failed to update group state');
  17365. await loadSDWAN(false);
  17366. } catch (err) {
  17367. showToast('Error', err.message, 'error');
  17368. }
  17369. }
  17370. async function deleteSDWANGroup(id) {
  17371. const group = (state.sdwanGroups || []).find(g => g.id === id);
  17372. const name = group ? group.name : id;
  17373. if (!confirm(`Are you sure you want to delete SD-WAN group "${name}"? Member routing tables will be cleared.`)) return;
  17374. try {
  17375. const res = await fetch(`${API_BASE}/sdwan/groups/${id}`, {
  17376. method: 'DELETE'
  17377. });
  17378. if (!res.ok) {
  17379. const err = await res.json().catch(() => ({}));
  17380. throw new Error(err.message || 'Failed to delete SD-WAN group');
  17381. }
  17382. showToast('Deleted', `SD-WAN group ${name} removed`, 'success');
  17383. await loadSDWAN(false);
  17384. } catch (err) {
  17385. showToast('Error', err.message, 'error');
  17386. }
  17387. }
  17388. // Modal handling for SD-WAN Members
  17389. function populateSDWANGroupsSelect(selectedId = '') {
  17390. const sel = document.getElementById('sdwan-member-group-id');
  17391. if (!sel) return;
  17392. sel.innerHTML = '';
  17393. (state.sdwanGroups || []).forEach(g => {
  17394. const opt = document.createElement('option');
  17395. opt.value = g.id;
  17396. opt.textContent = `${g.name} (${g.mode})`;
  17397. if (g.id === selectedId) opt.selected = true;
  17398. sel.appendChild(opt);
  17399. });
  17400. }
  17401. function populateSDWANMemberInterfaceSelect(selectedVal = '') {
  17402. const sel = document.getElementById('sdwan-member-interface');
  17403. if (!sel) return;
  17404. sel.innerHTML = '';
  17405. (state.interfaces || []).forEach(i => {
  17406. const opt = document.createElement('option');
  17407. opt.value = i.name;
  17408. opt.textContent = `${i.name} (${i.role || i.type})`;
  17409. if (i.name === selectedVal) opt.selected = true;
  17410. sel.appendChild(opt);
  17411. });
  17412. }
  17413. function openAddSDWANMemberModal(defaultGroupId = null) {
  17414. const modal = document.getElementById('modal-sdwan-member');
  17415. if (!modal) return;
  17416. if (!state.sdwanGroups || state.sdwanGroups.length === 0) {
  17417. showToast('Notice', 'Please create an SD-WAN group first before adding member links', 'warning');
  17418. return;
  17419. }
  17420. document.getElementById('sdwan-member-modal-title').querySelector('span').textContent = 'Add Member Link';
  17421. document.getElementById('sdwan-member-id').value = '';
  17422. populateSDWANGroupsSelect(defaultGroupId || (state.sdwanGroups[0] && state.sdwanGroups[0].id));
  17423. populateSDWANMemberInterfaceSelect();
  17424. document.getElementById('sdwan-member-gateway').value = '';
  17425. document.getElementById('sdwan-member-weight').value = 50;
  17426. document.getElementById('sdwan-member-priority').value = 1;
  17427. document.getElementById('sdwan-member-probe').value = '1.1.1.1';
  17428. document.getElementById('sdwan-member-max-lat').value = 250;
  17429. document.getElementById('sdwan-member-max-loss').value = 20;
  17430. document.getElementById('sdwan-member-comment').value = '';
  17431. modal.classList.remove('hidden');
  17432. }
  17433. function openEditSDWANMemberModal(groupId, memberId) {
  17434. const group = (state.sdwanGroups || []).find(g => g.id === groupId);
  17435. if (!group) return;
  17436. const member = (group.members || []).find(m => m.id === memberId);
  17437. if (!member) return;
  17438. const modal = document.getElementById('modal-sdwan-member');
  17439. if (!modal) return;
  17440. document.getElementById('sdwan-member-modal-title').querySelector('span').textContent = `Edit Member Link (${member.interface})`;
  17441. document.getElementById('sdwan-member-id').value = member.id;
  17442. populateSDWANGroupsSelect(group.id);
  17443. document.getElementById('sdwan-member-group-id').disabled = true;
  17444. populateSDWANMemberInterfaceSelect(member.interface);
  17445. document.getElementById('sdwan-member-interface').disabled = true;
  17446. document.getElementById('sdwan-member-gateway').value = member.gateway || '';
  17447. document.getElementById('sdwan-member-weight').value = member.weight || 50;
  17448. document.getElementById('sdwan-member-priority').value = member.priority || 1;
  17449. document.getElementById('sdwan-member-probe').value = member.target_probe || '1.1.1.1';
  17450. document.getElementById('sdwan-member-max-lat').value = member.max_latency || 250;
  17451. document.getElementById('sdwan-member-max-loss').value = member.max_loss || 20;
  17452. document.getElementById('sdwan-member-comment').value = member.comment || '';
  17453. modal.classList.remove('hidden');
  17454. }
  17455. function closeSDWANMemberModal() {
  17456. const modal = document.getElementById('modal-sdwan-member');
  17457. if (modal) {
  17458. document.getElementById('sdwan-member-group-id').disabled = false;
  17459. document.getElementById('sdwan-member-interface').disabled = false;
  17460. modal.classList.add('hidden');
  17461. }
  17462. }
  17463. async function saveSDWANMember(event) {
  17464. event.preventDefault();
  17465. const id = document.getElementById('sdwan-member-id').value;
  17466. let groupId = document.getElementById('sdwan-member-group-id').value;
  17467. let iface = document.getElementById('sdwan-member-interface').value;
  17468. // In edit mode with disabled selects, fallback to existing member data if needed
  17469. if (id) {
  17470. const existingGroup = (state.sdwanGroups || []).find(g => (g.members || []).some(m => m.id === id));
  17471. if (existingGroup) {
  17472. if (!groupId) groupId = existingGroup.id;
  17473. const mem = (existingGroup.members || []).find(m => m.id === id);
  17474. if (mem && !iface) iface = mem.interface;
  17475. }
  17476. }
  17477. const gateway = document.getElementById('sdwan-member-gateway').value.trim();
  17478. const weight = parseInt(document.getElementById('sdwan-member-weight').value, 10) || 50;
  17479. const priority = parseInt(document.getElementById('sdwan-member-priority').value, 10) || 1;
  17480. const targetProbe = document.getElementById('sdwan-member-probe').value.trim() || '1.1.1.1';
  17481. const maxLatency = parseInt(document.getElementById('sdwan-member-max-lat').value, 10) || 250;
  17482. const maxLoss = parseInt(document.getElementById('sdwan-member-max-loss').value, 10) || 20;
  17483. const comment = document.getElementById('sdwan-member-comment').value.trim();
  17484. const payload = {
  17485. id: id || undefined,
  17486. interface: iface,
  17487. gateway,
  17488. weight,
  17489. priority,
  17490. target_probe: targetProbe,
  17491. max_latency: maxLatency,
  17492. max_loss: maxLoss,
  17493. comment
  17494. };
  17495. try {
  17496. const method = id ? 'PUT' : 'POST';
  17497. const res = await fetch(`${API_BASE}/sdwan/groups/${groupId}/members`, {
  17498. method,
  17499. headers: { 'Content-Type': 'application/json' },
  17500. body: JSON.stringify(payload)
  17501. });
  17502. if (!res.ok) {
  17503. const err = await res.json().catch(() => ({}));
  17504. throw new Error(err.message || 'Failed to save member link');
  17505. }
  17506. closeSDWANMemberModal();
  17507. showToast('Success', `Link ${iface} saved to SD-WAN group`, 'success');
  17508. await loadSDWAN(false);
  17509. } catch (err) {
  17510. showToast('Error', err.message, 'error');
  17511. }
  17512. }
  17513. async function toggleSDWANMemberState(groupId, memberId, currentState) {
  17514. const group = (state.sdwanGroups || []).find(g => g.id === groupId);
  17515. if (!group) return;
  17516. const member = (group.members || []).find(m => m.id === memberId);
  17517. if (!member) return;
  17518. const payload = {
  17519. ...member,
  17520. disabled: currentState
  17521. };
  17522. try {
  17523. const res = await fetch(`${API_BASE}/sdwan/groups/${groupId}/members`, {
  17524. method: 'PUT',
  17525. headers: { 'Content-Type': 'application/json' },
  17526. body: JSON.stringify(payload)
  17527. });
  17528. if (!res.ok) throw new Error('Failed to update member state');
  17529. await loadSDWAN(false);
  17530. } catch (err) {
  17531. showToast('Error', err.message, 'error');
  17532. }
  17533. }
  17534. async function deleteSDWANMember(groupId, iface) {
  17535. if (!confirm(`Are you sure you want to remove link "${iface}" from this SD-WAN group?`)) return;
  17536. try {
  17537. const res = await fetch(`${API_BASE}/sdwan/groups/${groupId}/members/${iface}`, {
  17538. method: 'DELETE'
  17539. });
  17540. if (!res.ok) {
  17541. const err = await res.json().catch(() => ({}));
  17542. throw new Error(err.message || 'Failed to remove member link');
  17543. }
  17544. showToast('Removed', `Link ${iface} removed from SD-WAN group`, 'success');
  17545. await loadSDWAN(false);
  17546. } catch (err) {
  17547. showToast('Error', err.message, 'error');
  17548. }
  17549. }
  17550. // ==============================================================================
  17551. // DYNAMIC ROUTING: RIP MODULE
  17552. // ==============================================================================
  17553. state.ripInstances = [];
  17554. state.ripInterfaces = [];
  17555. state.ripNeighborsLive = [];
  17556. state.ripRoutes = [];
  17557. state.selectedRipRow = {};
  17558. state.activeRipTab = 'instances';
  17559. function switchRipTab(tab) {
  17560. state.activeRipTab = tab;
  17561. ['instances', 'interfaces', 'neighbors', 'routes'].forEach(t => {
  17562. const pane = document.getElementById(`rip-pane-${t}`);
  17563. const btn = document.getElementById(`rip-tab-btn-${t}`);
  17564. if (pane) {
  17565. if (t === tab) pane.classList.remove('hidden');
  17566. else pane.classList.add('hidden');
  17567. }
  17568. if (btn) {
  17569. if (t === tab) {
  17570. 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';
  17571. } else {
  17572. 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';
  17573. }
  17574. }
  17575. });
  17576. }
  17577. function selectRipRow(tab, id) {
  17578. if (!state.selectedRipRow) state.selectedRipRow = {};
  17579. state.selectedRipRow[tab] = id;
  17580. if (tab === 'instances') {
  17581. renderRipInstances();
  17582. const btnEn = document.getElementById('btn-rip-inst-enable');
  17583. const btnDis = document.getElementById('btn-rip-inst-disable');
  17584. const btnRem = document.getElementById('btn-rip-inst-remove');
  17585. if (btnEn) btnEn.disabled = false;
  17586. if (btnDis) btnDis.disabled = false;
  17587. if (btnRem) btnRem.disabled = false;
  17588. } else if (tab === 'interfaces') {
  17589. renderRipInterfaces();
  17590. const btnEn = document.getElementById('btn-rip-iface-enable');
  17591. const btnDis = document.getElementById('btn-rip-iface-disable');
  17592. const btnRem = document.getElementById('btn-rip-iface-remove');
  17593. if (btnEn) btnEn.disabled = false;
  17594. if (btnDis) btnDis.disabled = false;
  17595. if (btnRem) btnRem.disabled = false;
  17596. }
  17597. }
  17598. function renderRipInstances() {
  17599. const tbody = document.getElementById('rip-instances-table-body');
  17600. if (!tbody) return;
  17601. const countEl = document.getElementById('rip-instances-footer-count');
  17602. const filter = (document.getElementById('filter-rip-instances')?.value || '').toLowerCase();
  17603. let list = state.ripInstances || [];
  17604. if (filter) {
  17605. list = list.filter(i => (i.name || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  17606. }
  17607. if (countEl) countEl.innerText = list.length;
  17608. const selId = state.selectedRipRow?.instances;
  17609. tbody.innerHTML = list.map((inst, idx) => {
  17610. const isSel = inst.id === selId;
  17611. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-rose-400' : 'hover:bg-[#1a2636] text-slate-300';
  17612. const flagD = inst.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '<span class="text-emerald-400">R</span>';
  17613. const redist = [];
  17614. if (inst.redistribute_connected) redist.push('conn');
  17615. if (inst.redistribute_static) redist.push('static');
  17616. if (inst.redistribute_bgp) redist.push('bgp');
  17617. if (inst.redistribute_ospf) redist.push('ospf');
  17618. if (inst.redistribute_default) redist.push('default');
  17619. return `
  17620. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectRipRow('instances', '${inst.id}')" ondblclick="openEditRipInstanceModal('${inst.id}')">
  17621. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  17622. <td class="py-1.5 px-3 w-12 text-center">${flagD}</td>
  17623. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(inst.comment || '')}</td>
  17624. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  17625. <span class="text-rose-400">↳</span> <span>${escapeHtml(inst.name || 'default')}</span>
  17626. </td>
  17627. <td class="py-1.5 px-3 uppercase text-rose-300 font-bold">${escapeHtml(inst.version || 'rip2')}</td>
  17628. <td class="py-1.5 px-3 text-slate-400">${inst.update_time || 30}s</td>
  17629. <td class="py-1.5 px-3 text-slate-400">${inst.timeout_time || 180}s</td>
  17630. <td class="py-1.5 px-3 font-mono text-cyan-300">${redist.join(', ') || 'none'}</td>
  17631. <td class="py-1.5 px-3 font-mono text-slate-300">${inst.default_metric || 1}</td>
  17632. </tr>
  17633. `;
  17634. }).join('');
  17635. }
  17636. function renderRipInterfaces() {
  17637. const tbody = document.getElementById('rip-interfaces-table-body');
  17638. if (!tbody) return;
  17639. const countEl = document.getElementById('rip-interfaces-footer-count');
  17640. const filter = (document.getElementById('filter-rip-interfaces')?.value || '').toLowerCase();
  17641. let list = state.ripInterfaces || [];
  17642. if (filter) {
  17643. list = list.filter(i => (i.interface || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  17644. }
  17645. if (countEl) countEl.innerText = list.length;
  17646. const selId = state.selectedRipRow?.interfaces;
  17647. tbody.innerHTML = list.map((iface, idx) => {
  17648. const isSel = iface.id === selId;
  17649. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-rose-400' : 'hover:bg-[#1a2636] text-slate-300';
  17650. const flagD = iface.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '<span class="text-emerald-400">R</span>';
  17651. return `
  17652. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectRipRow('interfaces', '${iface.id}')" ondblclick="openEditRipInterfaceModal('${iface.id}')">
  17653. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  17654. <td class="py-1.5 px-3 w-12 text-center">${flagD}</td>
  17655. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(iface.comment || '')}</td>
  17656. <td class="py-1.5 px-3 font-mono font-semibold text-white">${escapeHtml(iface.interface || '*')}</td>
  17657. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(iface.mode || 'multicast')}</td>
  17658. <td class="py-1.5 px-3 font-mono text-slate-300">${iface.metric || 1}</td>
  17659. <td class="py-1.5 px-3 text-slate-400">${iface.passive ? 'yes' : 'no'}</td>
  17660. <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>
  17661. </tr>
  17662. `;
  17663. }).join('');
  17664. }
  17665. function renderRipNeighbors() {
  17666. const tbody = document.getElementById('rip-neighbors-table-body');
  17667. if (!tbody) return;
  17668. const countEl = document.getElementById('rip-neighbors-footer-count');
  17669. const list = state.ripNeighborsLive || [];
  17670. if (countEl) countEl.innerText = list.length;
  17671. tbody.innerHTML = list.map((nbr, idx) => `
  17672. <tr class="hover:bg-[#1a2636] text-slate-300">
  17673. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  17674. <td class="py-1.5 px-3 font-mono font-semibold text-rose-300">${escapeHtml(nbr.address || '')}</td>
  17675. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(nbr.interface || '')}</td>
  17676. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(nbr.last_seen || '')}</td>
  17677. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(nbr.uptime || '')}</td>
  17678. </tr>
  17679. `).join('');
  17680. }
  17681. function renderRipRoutes() {
  17682. const tbody = document.getElementById('rip-routes-table-body');
  17683. if (!tbody) return;
  17684. const countEl = document.getElementById('rip-routes-footer-count');
  17685. const list = state.ripRoutes || [];
  17686. if (countEl) countEl.innerText = list.length;
  17687. tbody.innerHTML = list.map((r, idx) => `
  17688. <tr class="hover:bg-[#1a2636] text-slate-300">
  17689. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  17690. <td class="py-1.5 px-3 font-mono font-semibold text-white">${escapeHtml(r.prefix || '')}</td>
  17691. <td class="py-1.5 px-3 font-mono text-cyan-300">${escapeHtml(r.next_hop || '')}</td>
  17692. <td class="py-1.5 px-3 font-mono text-slate-300">${r.metric || 1}</td>
  17693. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(r.interface || '')}</td>
  17694. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(r.uptime || '')}</td>
  17695. </tr>
  17696. `).join('');
  17697. }
  17698. function openRipInstanceModal() {
  17699. document.getElementById('rip-instance-modal-title').innerText = 'New RIP Instance';
  17700. document.getElementById('modal-rip-instance-id').value = '';
  17701. document.getElementById('modal-rip-instance-name').value = 'rip1';
  17702. document.getElementById('modal-rip-instance-version').value = 'rip2';
  17703. document.getElementById('modal-rip-instance-update').value = '30';
  17704. document.getElementById('modal-rip-instance-timeout').value = '180';
  17705. document.getElementById('modal-rip-instance-garbage').value = '120';
  17706. document.getElementById('modal-rip-instance-metric').value = '1';
  17707. document.getElementById('modal-rip-instance-comment').value = '';
  17708. document.getElementById('modal-rip-instance-enabled').checked = true;
  17709. document.getElementById('modal-rip-instance-redist-conn').checked = false;
  17710. document.getElementById('modal-rip-instance-redist-static').checked = false;
  17711. document.getElementById('modal-rip-instance-redist-bgp').checked = false;
  17712. document.getElementById('modal-rip-instance-redist-ospf').checked = false;
  17713. document.getElementById('modal-rip-instance-redist-default').checked = false;
  17714. document.getElementById('rip-instance-modal')?.classList.remove('hidden');
  17715. }
  17716. function openEditRipInstanceModal(id) {
  17717. const inst = (state.ripInstances || []).find(i => i.id === id);
  17718. if (!inst) return;
  17719. document.getElementById('rip-instance-modal-title').innerText = `Edit RIP Instance: ${inst.name}`;
  17720. document.getElementById('modal-rip-instance-id').value = inst.id;
  17721. document.getElementById('modal-rip-instance-name').value = inst.name || '';
  17722. document.getElementById('modal-rip-instance-version').value = inst.version || 'rip2';
  17723. document.getElementById('modal-rip-instance-update').value = inst.update_time || 30;
  17724. document.getElementById('modal-rip-instance-timeout').value = inst.timeout_time || 180;
  17725. document.getElementById('modal-rip-instance-garbage').value = inst.garbage_time || 120;
  17726. document.getElementById('modal-rip-instance-metric').value = inst.default_metric || 1;
  17727. document.getElementById('modal-rip-instance-comment').value = inst.comment || '';
  17728. document.getElementById('modal-rip-instance-enabled').checked = !inst.disabled;
  17729. document.getElementById('modal-rip-instance-redist-conn').checked = !!inst.redistribute_connected;
  17730. document.getElementById('modal-rip-instance-redist-static').checked = !!inst.redistribute_static;
  17731. document.getElementById('modal-rip-instance-redist-bgp').checked = !!inst.redistribute_bgp;
  17732. document.getElementById('modal-rip-instance-redist-ospf').checked = !!inst.redistribute_ospf;
  17733. document.getElementById('modal-rip-instance-redist-default').checked = !!inst.redistribute_default;
  17734. document.getElementById('rip-instance-modal')?.classList.remove('hidden');
  17735. }
  17736. function closeRipInstanceModal() {
  17737. document.getElementById('rip-instance-modal')?.classList.add('hidden');
  17738. }
  17739. async function submitRipInstance(e) {
  17740. e.preventDefault();
  17741. const id = document.getElementById('modal-rip-instance-id').value;
  17742. const payload = {
  17743. id: id || undefined,
  17744. name: document.getElementById('modal-rip-instance-name').value.trim(),
  17745. version: document.getElementById('modal-rip-instance-version').value,
  17746. update_time: parseInt(document.getElementById('modal-rip-instance-update').value, 10) || 30,
  17747. timeout_time: parseInt(document.getElementById('modal-rip-instance-timeout').value, 10) || 180,
  17748. garbage_time: parseInt(document.getElementById('modal-rip-instance-garbage').value, 10) || 120,
  17749. default_metric: parseInt(document.getElementById('modal-rip-instance-metric').value, 10) || 1,
  17750. comment: document.getElementById('modal-rip-instance-comment').value.trim(),
  17751. disabled: !document.getElementById('modal-rip-instance-enabled').checked,
  17752. redistribute_connected: document.getElementById('modal-rip-instance-redist-conn').checked,
  17753. redistribute_static: document.getElementById('modal-rip-instance-redist-static').checked,
  17754. redistribute_bgp: document.getElementById('modal-rip-instance-redist-bgp').checked,
  17755. redistribute_ospf: document.getElementById('modal-rip-instance-redist-ospf').checked,
  17756. redistribute_default: document.getElementById('modal-rip-instance-redist-default').checked
  17757. };
  17758. try {
  17759. const res = await fetch(`${API_BASE}/routing/rip/instances`, {
  17760. method: 'POST',
  17761. headers: { 'Content-Type': 'application/json' },
  17762. body: JSON.stringify(payload)
  17763. });
  17764. if (!res.ok) throw new Error(await res.text());
  17765. closeRipInstanceModal();
  17766. showToast('Saved', `RIP instance ${payload.name} saved`, 'success');
  17767. await loadDynamicRouting(false);
  17768. } catch (err) {
  17769. showToast('Error', err.message, 'error');
  17770. }
  17771. }
  17772. async function enableSelectedRipInstance() {
  17773. const id = state.selectedRipRow?.instances;
  17774. if (!id) return;
  17775. await fetch(`${API_BASE}/routing/rip/instances/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: false }) });
  17776. await loadDynamicRouting(false);
  17777. }
  17778. async function disableSelectedRipInstance() {
  17779. const id = state.selectedRipRow?.instances;
  17780. if (!id) return;
  17781. await fetch(`${API_BASE}/routing/rip/instances/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: true }) });
  17782. await loadDynamicRouting(false);
  17783. }
  17784. async function removeSelectedRipInstance() {
  17785. const id = state.selectedRipRow?.instances;
  17786. if (!id || !confirm('Are you sure you want to delete this RIP instance?')) return;
  17787. await fetch(`${API_BASE}/routing/rip/instances/${id}`, { method: 'DELETE' });
  17788. state.selectedRipRow.instances = null;
  17789. await loadDynamicRouting(false);
  17790. }
  17791. function openRipInterfaceModal() {
  17792. document.getElementById('rip-interface-modal-title').innerText = 'New RIP Interface';
  17793. document.getElementById('modal-rip-iface-id').value = '';
  17794. document.getElementById('modal-rip-iface-pattern').value = '';
  17795. document.getElementById('modal-rip-iface-instance').value = 'rip1';
  17796. document.getElementById('modal-rip-iface-mode').value = 'multicast';
  17797. document.getElementById('modal-rip-iface-metric').value = '1';
  17798. document.getElementById('modal-rip-iface-comment').value = '';
  17799. document.getElementById('modal-rip-iface-enabled').checked = true;
  17800. document.getElementById('modal-rip-iface-passive').checked = false;
  17801. document.getElementById('modal-rip-iface-bfd').checked = false;
  17802. document.getElementById('rip-interface-modal')?.classList.remove('hidden');
  17803. }
  17804. function openEditRipInterfaceModal(id) {
  17805. const iface = (state.ripInterfaces || []).find(i => i.id === id);
  17806. if (!iface) return;
  17807. document.getElementById('rip-interface-modal-title').innerText = `Edit RIP Interface: ${iface.interface}`;
  17808. document.getElementById('modal-rip-iface-id').value = iface.id;
  17809. document.getElementById('modal-rip-iface-pattern').value = iface.interface || '';
  17810. document.getElementById('modal-rip-iface-instance').value = iface.instance || '';
  17811. document.getElementById('modal-rip-iface-mode').value = iface.mode || 'multicast';
  17812. document.getElementById('modal-rip-iface-metric').value = iface.metric || 1;
  17813. document.getElementById('modal-rip-iface-comment').value = iface.comment || '';
  17814. document.getElementById('modal-rip-iface-enabled').checked = !iface.disabled;
  17815. document.getElementById('modal-rip-iface-passive').checked = !!iface.passive;
  17816. document.getElementById('modal-rip-iface-bfd').checked = !!iface.use_bfd;
  17817. document.getElementById('rip-interface-modal')?.classList.remove('hidden');
  17818. }
  17819. function closeRipInterfaceModal() {
  17820. document.getElementById('rip-interface-modal')?.classList.add('hidden');
  17821. }
  17822. async function submitRipInterface(e) {
  17823. e.preventDefault();
  17824. const id = document.getElementById('modal-rip-iface-id').value;
  17825. const payload = {
  17826. id: id || undefined,
  17827. interface: document.getElementById('modal-rip-iface-pattern').value.trim(),
  17828. instance: document.getElementById('modal-rip-iface-instance').value.trim(),
  17829. mode: document.getElementById('modal-rip-iface-mode').value,
  17830. metric: parseInt(document.getElementById('modal-rip-iface-metric').value, 10) || 1,
  17831. comment: document.getElementById('modal-rip-iface-comment').value.trim(),
  17832. disabled: !document.getElementById('modal-rip-iface-enabled').checked,
  17833. passive: document.getElementById('modal-rip-iface-passive').checked,
  17834. use_bfd: document.getElementById('modal-rip-iface-bfd').checked
  17835. };
  17836. try {
  17837. const res = await fetch(`${API_BASE}/routing/rip/interfaces`, {
  17838. method: 'POST',
  17839. headers: { 'Content-Type': 'application/json' },
  17840. body: JSON.stringify(payload)
  17841. });
  17842. if (!res.ok) throw new Error(await res.text());
  17843. closeRipInterfaceModal();
  17844. showToast('Saved', `RIP interface template saved`, 'success');
  17845. await loadDynamicRouting(false);
  17846. } catch (err) {
  17847. showToast('Error', err.message, 'error');
  17848. }
  17849. }
  17850. async function enableSelectedRipInterface() {
  17851. const id = state.selectedRipRow?.interfaces;
  17852. if (!id) return;
  17853. await fetch(`${API_BASE}/routing/rip/interfaces/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: false }) });
  17854. await loadDynamicRouting(false);
  17855. }
  17856. async function disableSelectedRipInterface() {
  17857. const id = state.selectedRipRow?.interfaces;
  17858. if (!id) return;
  17859. await fetch(`${API_BASE}/routing/rip/interfaces/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: true }) });
  17860. await loadDynamicRouting(false);
  17861. }
  17862. async function removeSelectedRipInterface() {
  17863. const id = state.selectedRipRow?.interfaces;
  17864. if (!id || !confirm('Are you sure you want to delete this RIP interface template?')) return;
  17865. await fetch(`${API_BASE}/routing/rip/interfaces/${id}`, { method: 'DELETE' });
  17866. state.selectedRipRow.interfaces = null;
  17867. await loadDynamicRouting(false);
  17868. }
  17869. // ==============================================================================
  17870. // DYNAMIC ROUTING: BFD MODULE
  17871. // ==============================================================================
  17872. state.bfdInstance = null;
  17873. state.bfdInterfaces = [];
  17874. state.bfdNeighbors = [];
  17875. state.bfdSessions = [];
  17876. state.selectedBfdRow = {};
  17877. state.activeBfdTab = 'config';
  17878. function switchBfdTab(tab) {
  17879. state.activeBfdTab = tab;
  17880. ['config', 'interfaces', 'peers', 'sessions'].forEach(t => {
  17881. const pane = document.getElementById(`bfd-pane-${t}`);
  17882. const btn = document.getElementById(`bfd-tab-btn-${t}`);
  17883. if (pane) {
  17884. if (t === tab) pane.classList.remove('hidden');
  17885. else pane.classList.add('hidden');
  17886. }
  17887. if (btn) {
  17888. if (t === tab) {
  17889. 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';
  17890. } else {
  17891. 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';
  17892. }
  17893. }
  17894. });
  17895. }
  17896. function selectBfdRow(tab, id) {
  17897. if (!state.selectedBfdRow) state.selectedBfdRow = {};
  17898. state.selectedBfdRow[tab] = id;
  17899. if (tab === 'interfaces') {
  17900. renderBfdInterfaces();
  17901. const btnEn = document.getElementById('btn-bfd-iface-enable');
  17902. const btnDis = document.getElementById('btn-bfd-iface-disable');
  17903. const btnRem = document.getElementById('btn-bfd-iface-remove');
  17904. if (btnEn) btnEn.disabled = false;
  17905. if (btnDis) btnDis.disabled = false;
  17906. if (btnRem) btnRem.disabled = false;
  17907. } else if (tab === 'peers') {
  17908. renderBfdPeers();
  17909. const btnEn = document.getElementById('btn-bfd-peer-enable');
  17910. const btnDis = document.getElementById('btn-bfd-peer-disable');
  17911. const btnRem = document.getElementById('btn-bfd-peer-remove');
  17912. if (btnEn) btnEn.disabled = false;
  17913. if (btnDis) btnDis.disabled = false;
  17914. if (btnRem) btnRem.disabled = false;
  17915. }
  17916. }
  17917. function renderBfdConfig() {
  17918. const inst = state.bfdInstance;
  17919. const pill = document.getElementById('bfd-live-status-pill');
  17920. const toggleBtn = document.getElementById('bfd-global-toggle-btn');
  17921. const ifaceStat = document.getElementById('bfd-stat-interfaces');
  17922. const peerStat = document.getElementById('bfd-stat-peers');
  17923. const sessStat = document.getElementById('bfd-stat-sessions');
  17924. if (ifaceStat) ifaceStat.innerText = (state.bfdInterfaces || []).length;
  17925. if (peerStat) peerStat.innerText = (state.bfdNeighbors || []).length;
  17926. if (sessStat) sessStat.innerText = (state.bfdSessions || []).length;
  17927. if (!inst || inst.disabled) {
  17928. if (pill) {
  17929. pill.className = 'text-[10px] px-2 py-0.5 rounded font-mono bg-slate-800 text-slate-400 border border-slate-700';
  17930. pill.innerText = 'DISABLED';
  17931. }
  17932. if (toggleBtn) {
  17933. toggleBtn.innerText = 'Enable BFD';
  17934. 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';
  17935. }
  17936. } else {
  17937. if (pill) {
  17938. 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';
  17939. pill.innerText = inst.running ? 'RUNNING (ACTIVE)' : 'CONFIGURED';
  17940. }
  17941. if (toggleBtn) {
  17942. toggleBtn.innerText = 'Disable BFD';
  17943. toggleBtn.className = 'px-4 py-2 rounded-lg text-xs font-semibold bg-rose-600/80 hover:bg-rose-600 text-white transition';
  17944. }
  17945. }
  17946. }
  17947. async function toggleBfdGlobalState() {
  17948. const current = state.bfdInstance;
  17949. const newDisabled = current ? !current.disabled : false;
  17950. try {
  17951. const res = await fetch(`${API_BASE}/routing/bfd/instance`, {
  17952. method: 'POST',
  17953. headers: { 'Content-Type': 'application/json' },
  17954. body: JSON.stringify({ enabled: !newDisabled, disabled: newDisabled })
  17955. });
  17956. if (!res.ok) throw new Error(await res.text());
  17957. showToast('Success', `BFD protocol ${newDisabled ? 'disabled' : 'enabled'}`, 'success');
  17958. await loadDynamicRouting(false);
  17959. } catch (err) {
  17960. showToast('Error', err.message, 'error');
  17961. }
  17962. }
  17963. function renderBfdInterfaces() {
  17964. const tbody = document.getElementById('bfd-interfaces-table-body');
  17965. if (!tbody) return;
  17966. const countEl = document.getElementById('bfd-interfaces-footer-count');
  17967. const filter = (document.getElementById('filter-bfd-interfaces')?.value || '').toLowerCase();
  17968. let list = state.bfdInterfaces || [];
  17969. if (filter) {
  17970. list = list.filter(i => (i.interface || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  17971. }
  17972. if (countEl) countEl.innerText = list.length;
  17973. const selId = state.selectedBfdRow?.interfaces;
  17974. tbody.innerHTML = list.map((iface, idx) => {
  17975. const isSel = iface.id === selId;
  17976. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-amber-400' : 'hover:bg-[#1a2636] text-slate-300';
  17977. const flagD = iface.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '<span class="text-emerald-400">B</span>';
  17978. return `
  17979. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectBfdRow('interfaces', '${iface.id}')" ondblclick="openEditBfdInterfaceModal('${iface.id}')">
  17980. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  17981. <td class="py-1.5 px-3 w-12 text-center">${flagD}</td>
  17982. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(iface.comment || '')}</td>
  17983. <td class="py-1.5 px-3 font-mono font-semibold text-white">${escapeHtml(iface.interface || '*')}</td>
  17984. <td class="py-1.5 px-3 font-mono text-slate-300">${iface.min_rx_interval || 100} ms</td>
  17985. <td class="py-1.5 px-3 font-mono text-slate-300">${iface.min_tx_interval || 100} ms</td>
  17986. <td class="py-1.5 px-3 font-mono text-slate-400">${iface.idle_tx_interval || 1000} ms</td>
  17987. <td class="py-1.5 px-3 font-mono text-slate-300">${iface.multiplier || 3}</td>
  17988. <td class="py-1.5 px-3 text-slate-400">${iface.passive ? 'yes' : 'no'}</td>
  17989. </tr>
  17990. `;
  17991. }).join('');
  17992. }
  17993. function renderBfdPeers() {
  17994. const tbody = document.getElementById('bfd-peers-table-body');
  17995. if (!tbody) return;
  17996. const countEl = document.getElementById('bfd-peers-footer-count');
  17997. const filter = (document.getElementById('filter-bfd-peers')?.value || '').toLowerCase();
  17998. let list = state.bfdNeighbors || [];
  17999. if (filter) {
  18000. list = list.filter(p => (p.address || '').toLowerCase().includes(filter) || (p.comment || '').toLowerCase().includes(filter));
  18001. }
  18002. if (countEl) countEl.innerText = list.length;
  18003. const selId = state.selectedBfdRow?.peers;
  18004. tbody.innerHTML = list.map((p, idx) => {
  18005. const isSel = p.id === selId;
  18006. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-amber-400' : 'hover:bg-[#1a2636] text-slate-300';
  18007. const flagD = p.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '<span class="text-emerald-400">B</span>';
  18008. return `
  18009. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectBfdRow('peers', '${p.id}')" ondblclick="openEditBfdPeerModal('${p.id}')">
  18010. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  18011. <td class="py-1.5 px-3 w-12 text-center">${flagD}</td>
  18012. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(p.comment || '')}</td>
  18013. <td class="py-1.5 px-3 font-mono font-semibold text-amber-300">${escapeHtml(p.address || '')}</td>
  18014. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(p.interface || 'auto')}</td>
  18015. <td class="py-1.5 px-3 text-slate-400">${p.multihop ? 'yes' : 'no'}</td>
  18016. </tr>
  18017. `;
  18018. }).join('');
  18019. }
  18020. function renderBfdSessions() {
  18021. const tbody = document.getElementById('bfd-sessions-table-body');
  18022. if (!tbody) return;
  18023. const countEl = document.getElementById('bfd-sessions-footer-count');
  18024. const list = state.bfdSessions || [];
  18025. if (countEl) countEl.innerText = list.length;
  18026. tbody.innerHTML = list.map((s, idx) => {
  18027. const isUp = (s.state || '').toLowerCase() === 'up';
  18028. const stateBadge = isUp
  18029. ? '<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>'
  18030. : `<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>`;
  18031. return `
  18032. <tr class="hover:bg-[#1a2636] text-slate-300">
  18033. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  18034. <td class="py-1.5 px-3 font-mono font-semibold text-white">${escapeHtml(s.ip || '')}</td>
  18035. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(s.interface || '')}</td>
  18036. <td class="py-1.5 px-3">${stateBadge}</td>
  18037. <td class="py-1.5 px-3 font-mono text-slate-400">${escapeHtml(s.interval || '')}</td>
  18038. <td class="py-1.5 px-3 font-mono text-slate-400">${escapeHtml(s.timeout || '')}</td>
  18039. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(s.since || '')}</td>
  18040. </tr>
  18041. `;
  18042. }).join('');
  18043. }
  18044. function openBfdInterfaceModal() {
  18045. document.getElementById('bfd-interface-modal-title').innerText = 'New BFD Interface Profile';
  18046. document.getElementById('modal-bfd-iface-id').value = '';
  18047. document.getElementById('modal-bfd-iface-pattern').value = '*';
  18048. document.getElementById('modal-bfd-iface-min-rx').value = '100';
  18049. document.getElementById('modal-bfd-iface-min-tx').value = '100';
  18050. document.getElementById('modal-bfd-iface-idle-tx').value = '1000';
  18051. document.getElementById('modal-bfd-iface-multiplier').value = '3';
  18052. document.getElementById('modal-bfd-iface-comment').value = '';
  18053. document.getElementById('modal-bfd-iface-enabled').checked = true;
  18054. document.getElementById('modal-bfd-iface-passive').checked = false;
  18055. document.getElementById('bfd-interface-modal')?.classList.remove('hidden');
  18056. }
  18057. function openEditBfdInterfaceModal(id) {
  18058. const iface = (state.bfdInterfaces || []).find(i => i.id === id);
  18059. if (!iface) return;
  18060. document.getElementById('bfd-interface-modal-title').innerText = `Edit BFD Interface: ${iface.interface}`;
  18061. document.getElementById('modal-bfd-iface-id').value = iface.id;
  18062. document.getElementById('modal-bfd-iface-pattern').value = iface.interface || '*';
  18063. document.getElementById('modal-bfd-iface-min-rx').value = iface.min_rx_interval || 100;
  18064. document.getElementById('modal-bfd-iface-min-tx').value = iface.min_tx_interval || 100;
  18065. document.getElementById('modal-bfd-iface-idle-tx').value = iface.idle_tx_interval || 1000;
  18066. document.getElementById('modal-bfd-iface-multiplier').value = iface.multiplier || 3;
  18067. document.getElementById('modal-bfd-iface-comment').value = iface.comment || '';
  18068. document.getElementById('modal-bfd-iface-enabled').checked = !iface.disabled;
  18069. document.getElementById('modal-bfd-iface-passive').checked = !!iface.passive;
  18070. document.getElementById('bfd-interface-modal')?.classList.remove('hidden');
  18071. }
  18072. function closeBfdInterfaceModal() {
  18073. document.getElementById('bfd-interface-modal')?.classList.add('hidden');
  18074. }
  18075. async function submitBfdInterface(e) {
  18076. e.preventDefault();
  18077. const id = document.getElementById('modal-bfd-iface-id').value;
  18078. const payload = {
  18079. id: id || undefined,
  18080. interface: document.getElementById('modal-bfd-iface-pattern').value.trim(),
  18081. min_rx_interval: parseInt(document.getElementById('modal-bfd-iface-min-rx').value, 10) || 100,
  18082. min_tx_interval: parseInt(document.getElementById('modal-bfd-iface-min-tx').value, 10) || 100,
  18083. idle_tx_interval: parseInt(document.getElementById('modal-bfd-iface-idle-tx').value, 10) || 1000,
  18084. multiplier: parseInt(document.getElementById('modal-bfd-iface-multiplier').value, 10) || 3,
  18085. comment: document.getElementById('modal-bfd-iface-comment').value.trim(),
  18086. disabled: !document.getElementById('modal-bfd-iface-enabled').checked,
  18087. passive: document.getElementById('modal-bfd-iface-passive').checked
  18088. };
  18089. try {
  18090. const res = await fetch(`${API_BASE}/routing/bfd/interfaces`, {
  18091. method: 'POST',
  18092. headers: { 'Content-Type': 'application/json' },
  18093. body: JSON.stringify(payload)
  18094. });
  18095. if (!res.ok) throw new Error(await res.text());
  18096. closeBfdInterfaceModal();
  18097. showToast('Saved', `BFD profile saved`, 'success');
  18098. await loadDynamicRouting(false);
  18099. } catch (err) {
  18100. showToast('Error', err.message, 'error');
  18101. }
  18102. }
  18103. async function enableSelectedBfdInterface() {
  18104. const id = state.selectedBfdRow?.interfaces;
  18105. if (!id) return;
  18106. await fetch(`${API_BASE}/routing/bfd/interfaces/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: false }) });
  18107. await loadDynamicRouting(false);
  18108. }
  18109. async function disableSelectedBfdInterface() {
  18110. const id = state.selectedBfdRow?.interfaces;
  18111. if (!id) return;
  18112. await fetch(`${API_BASE}/routing/bfd/interfaces/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: true }) });
  18113. await loadDynamicRouting(false);
  18114. }
  18115. async function removeSelectedBfdInterface() {
  18116. const id = state.selectedBfdRow?.interfaces;
  18117. if (!id || !confirm('Are you sure you want to remove this BFD interface template?')) return;
  18118. await fetch(`${API_BASE}/routing/bfd/interfaces/${id}`, { method: 'DELETE' });
  18119. state.selectedBfdRow.interfaces = null;
  18120. await loadDynamicRouting(false);
  18121. }
  18122. function openBfdPeerModal() {
  18123. document.getElementById('bfd-peer-modal-title').innerText = 'New Static BFD Peer';
  18124. document.getElementById('modal-bfd-peer-id').value = '';
  18125. document.getElementById('modal-bfd-peer-address').value = '';
  18126. document.getElementById('modal-bfd-peer-interface').value = '';
  18127. document.getElementById('modal-bfd-peer-comment').value = '';
  18128. document.getElementById('modal-bfd-peer-enabled').checked = true;
  18129. document.getElementById('modal-bfd-peer-multihop').checked = false;
  18130. document.getElementById('bfd-peer-modal')?.classList.remove('hidden');
  18131. }
  18132. function openEditBfdPeerModal(id) {
  18133. const p = (state.bfdNeighbors || []).find(n => n.id === id);
  18134. if (!p) return;
  18135. document.getElementById('bfd-peer-modal-title').innerText = `Edit BFD Peer: ${p.address}`;
  18136. document.getElementById('modal-bfd-peer-id').value = p.id;
  18137. document.getElementById('modal-bfd-peer-address').value = p.address || '';
  18138. document.getElementById('modal-bfd-peer-interface').value = p.interface || '';
  18139. document.getElementById('modal-bfd-peer-comment').value = p.comment || '';
  18140. document.getElementById('modal-bfd-peer-enabled').checked = !p.disabled;
  18141. document.getElementById('modal-bfd-peer-multihop').checked = !!p.multihop;
  18142. document.getElementById('bfd-peer-modal')?.classList.remove('hidden');
  18143. }
  18144. function closeBfdPeerModal() {
  18145. document.getElementById('bfd-peer-modal')?.classList.add('hidden');
  18146. }
  18147. async function submitBfdPeer(e) {
  18148. e.preventDefault();
  18149. const id = document.getElementById('modal-bfd-peer-id').value;
  18150. const payload = {
  18151. id: id || undefined,
  18152. address: document.getElementById('modal-bfd-peer-address').value.trim(),
  18153. interface: document.getElementById('modal-bfd-peer-interface').value.trim(),
  18154. comment: document.getElementById('modal-bfd-peer-comment').value.trim(),
  18155. disabled: !document.getElementById('modal-bfd-peer-enabled').checked,
  18156. multihop: document.getElementById('modal-bfd-peer-multihop').checked
  18157. };
  18158. try {
  18159. const res = await fetch(`${API_BASE}/routing/bfd/peers`, {
  18160. method: 'POST',
  18161. headers: { 'Content-Type': 'application/json' },
  18162. body: JSON.stringify(payload)
  18163. });
  18164. if (!res.ok) throw new Error(await res.text());
  18165. closeBfdPeerModal();
  18166. showToast('Saved', `BFD peer saved`, 'success');
  18167. await loadDynamicRouting(false);
  18168. } catch (err) {
  18169. showToast('Error', err.message, 'error');
  18170. }
  18171. }
  18172. async function enableSelectedBfdPeer() {
  18173. const id = state.selectedBfdRow?.peers;
  18174. if (!id) return;
  18175. const p = (state.bfdNeighbors || []).find(n => n.id === id);
  18176. if (!p) return;
  18177. await fetch(`${API_BASE}/routing/bfd/peers`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ ...p, disabled: false }) });
  18178. await loadDynamicRouting(false);
  18179. }
  18180. async function disableSelectedBfdPeer() {
  18181. const id = state.selectedBfdRow?.peers;
  18182. if (!id) return;
  18183. const p = (state.bfdNeighbors || []).find(n => n.id === id);
  18184. if (!p) return;
  18185. await fetch(`${API_BASE}/routing/bfd/peers`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ ...p, disabled: true }) });
  18186. await loadDynamicRouting(false);
  18187. }
  18188. async function removeSelectedBfdPeer() {
  18189. const id = state.selectedBfdRow?.peers;
  18190. if (!id || !confirm('Are you sure you want to remove this BFD peer?')) return;
  18191. await fetch(`${API_BASE}/routing/bfd/peers/${id}`, { method: 'DELETE' });
  18192. state.selectedBfdRow.peers = null;
  18193. await loadDynamicRouting(false);
  18194. }
  18195. // ==============================================================================
  18196. // DYNAMIC ROUTING: BABEL MODULE
  18197. // ==============================================================================
  18198. state.babelInstances = [];
  18199. state.babelInterfaces = [];
  18200. state.babelInterfacesLive = [];
  18201. state.babelNeighbors = [];
  18202. state.babelRoutes = [];
  18203. state.selectedBabelRow = {};
  18204. state.activeBabelTab = 'instances';
  18205. function switchBabelTab(tab) {
  18206. state.activeBabelTab = tab;
  18207. ['instances', 'interfaces', 'interfaces-live', 'neighbors', 'routes'].forEach(t => {
  18208. const pane = document.getElementById(`babel-pane-${t}`);
  18209. const btn = document.getElementById(`babel-tab-btn-${t}`);
  18210. if (pane) {
  18211. if (t === tab) pane.classList.remove('hidden');
  18212. else pane.classList.add('hidden');
  18213. }
  18214. if (btn) {
  18215. if (t === tab) {
  18216. 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';
  18217. } else {
  18218. 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';
  18219. }
  18220. }
  18221. });
  18222. }
  18223. function selectBabelRow(tab, id) {
  18224. if (!state.selectedBabelRow) state.selectedBabelRow = {};
  18225. state.selectedBabelRow[tab] = id;
  18226. if (tab === 'instances') {
  18227. renderBabelInstances();
  18228. const btnEn = document.getElementById('btn-babel-inst-enable');
  18229. const btnDis = document.getElementById('btn-babel-inst-disable');
  18230. const btnRem = document.getElementById('btn-babel-inst-remove');
  18231. if (btnEn) btnEn.disabled = false;
  18232. if (btnDis) btnDis.disabled = false;
  18233. if (btnRem) btnRem.disabled = false;
  18234. } else if (tab === 'interfaces') {
  18235. renderBabelInterfaces();
  18236. const btnEn = document.getElementById('btn-babel-iface-enable');
  18237. const btnDis = document.getElementById('btn-babel-iface-disable');
  18238. const btnRem = document.getElementById('btn-babel-iface-remove');
  18239. if (btnEn) btnEn.disabled = false;
  18240. if (btnDis) btnDis.disabled = false;
  18241. if (btnRem) btnRem.disabled = false;
  18242. }
  18243. }
  18244. function renderBabelInstances() {
  18245. const tbody = document.getElementById('babel-instances-table-body');
  18246. if (!tbody) return;
  18247. const countEl = document.getElementById('babel-instances-footer-count');
  18248. const filter = (document.getElementById('filter-babel-instances')?.value || '').toLowerCase();
  18249. let list = state.babelInstances || [];
  18250. if (filter) {
  18251. list = list.filter(i => (i.name || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  18252. }
  18253. if (countEl) countEl.innerText = list.length;
  18254. const selId = state.selectedBabelRow?.instances;
  18255. tbody.innerHTML = list.map((inst, idx) => {
  18256. const isSel = inst.id === selId;
  18257. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-teal-400' : 'hover:bg-[#1a2636] text-slate-300';
  18258. const flagD = inst.disabled
  18259. ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>'
  18260. : (inst.running
  18261. ? '<span class="text-emerald-400 font-bold" title="Running">R</span>'
  18262. : '<span class="text-amber-400 font-bold" title="Inactive">I</span>');
  18263. const redist = [];
  18264. if (inst.redistribute_connected) redist.push('conn');
  18265. if (inst.redistribute_static) redist.push('static');
  18266. if (inst.redistribute_bgp) redist.push('bgp');
  18267. if (inst.redistribute_ospf) redist.push('ospf');
  18268. if (inst.redistribute_default) redist.push('default');
  18269. return `
  18270. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectBabelRow('instances', '${inst.id}')" ondblclick="openEditBabelInstanceModal('${inst.id}')">
  18271. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  18272. <td class="py-1.5 px-3 w-12 text-center">${flagD}</td>
  18273. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(inst.comment || '')}</td>
  18274. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  18275. <span class="text-teal-400">↳</span> <span>${escapeHtml(inst.name || 'default')}</span>
  18276. </td>
  18277. <td class="py-1.5 px-3 font-mono text-cyan-300">${escapeHtml(inst.router_id || 'auto')}</td>
  18278. <td class="py-1.5 px-3 text-emerald-400 font-bold">IPv4 + IPv6</td>
  18279. <td class="py-1.5 px-3 font-mono text-cyan-300">${redist.join(', ') || 'none'}</td>
  18280. <td class="py-1.5 px-3 font-mono text-slate-300">${inst.default_metric || 10}</td>
  18281. </tr>
  18282. `;
  18283. }).join('');
  18284. }
  18285. function renderBabelInterfaces() {
  18286. const tbody = document.getElementById('babel-interfaces-table-body');
  18287. if (!tbody) return;
  18288. const countEl = document.getElementById('babel-interfaces-footer-count');
  18289. const filter = (document.getElementById('filter-babel-interfaces')?.value || '').toLowerCase();
  18290. let list = state.babelInterfaces || [];
  18291. if (filter) {
  18292. list = list.filter(i => (i.interface || '').toLowerCase().includes(filter) || (i.instance || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  18293. }
  18294. if (countEl) countEl.innerText = list.length;
  18295. const selId = state.selectedBabelRow?.interfaces;
  18296. tbody.innerHTML = list.map((iface, idx) => {
  18297. const isSel = iface.id === selId;
  18298. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-teal-400' : 'hover:bg-[#1a2636] text-slate-300';
  18299. const flagD = iface.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '<span class="text-emerald-400">B</span>';
  18300. return `
  18301. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectBabelRow('interfaces', '${iface.id}')" ondblclick="openEditBabelInterfaceModal('${iface.id}')">
  18302. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  18303. <td class="py-1.5 px-3 w-12 text-center">${flagD}</td>
  18304. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(iface.comment || '')}</td>
  18305. <td class="py-1.5 px-3 font-semibold text-teal-300 font-mono">${escapeHtml(iface.instance || 'all')}</td>
  18306. <td class="py-1.5 px-3 font-mono font-semibold text-white">${escapeHtml(iface.interface || '*')}</td>
  18307. <td class="py-1.5 px-3 uppercase text-teal-300 font-bold">${escapeHtml(iface.type || 'wired')}</td>
  18308. <td class="py-1.5 px-3 font-mono text-slate-300">${iface.rxcost || 10}</td>
  18309. <td class="py-1.5 px-3 text-slate-400">${iface.hello_interval || 4}s</td>
  18310. <td class="py-1.5 px-3 text-slate-400">${iface.update_interval || 16}s</td>
  18311. </tr>
  18312. `;
  18313. }).join('');
  18314. }
  18315. function renderBabelLiveInterfaces() {
  18316. const tbody = document.getElementById('babel-interfaces-live-table-body');
  18317. if (!tbody) return;
  18318. const countEl = document.getElementById('babel-interfaces-live-footer-count');
  18319. const filter = (document.getElementById('filter-babel-interfaces-live')?.value || '').toLowerCase();
  18320. let list = state.babelInterfacesLive || [];
  18321. if (filter) {
  18322. list = list.filter(i => (i.interface || '').toLowerCase().includes(filter) || (i.instance || '').toLowerCase().includes(filter));
  18323. }
  18324. if (countEl) countEl.innerText = list.length;
  18325. tbody.innerHTML = list.map((iface, idx) => {
  18326. const isUp = (iface.state || '').toLowerCase() === 'up';
  18327. const stateBadge = isUp
  18328. ? '<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>'
  18329. : '<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>';
  18330. return `
  18331. <tr class="hover:bg-[#1a2636] text-slate-300 font-mono">
  18332. <td class="py-1.5 px-3 w-8 text-center text-slate-500 font-sans">${idx}</td>
  18333. <td class="py-1.5 px-3 w-12 text-center text-cyan-400 font-bold">D</td>
  18334. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(iface.interface || '')}</td>
  18335. <td class="py-1.5 px-3 font-semibold text-teal-300">${escapeHtml(iface.instance || 'default')}</td>
  18336. <td class="py-1.5 px-3">${stateBadge}</td>
  18337. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(iface.auth || 'No')}</td>
  18338. <td class="py-1.5 px-3 text-slate-300">${iface.rxcost || 96}</td>
  18339. <td class="py-1.5 px-3 text-slate-300">${iface.neighbors || 0}</td>
  18340. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(iface.timer || '')}</td>
  18341. <td class="py-1.5 px-3 text-cyan-300">${escapeHtml(iface.next_hop_v4 || '-')}</td>
  18342. <td class="py-1.5 px-3 text-slate-400 text-[11px]">${escapeHtml(iface.next_hop_v6 || '-')}</td>
  18343. </tr>
  18344. `;
  18345. }).join('');
  18346. }
  18347. function renderBabelNeighbors() {
  18348. const tbody = document.getElementById('babel-neighbors-table-body');
  18349. if (!tbody) return;
  18350. const countEl = document.getElementById('babel-neighbors-footer-count');
  18351. const list = state.babelNeighbors || [];
  18352. if (countEl) countEl.innerText = list.length;
  18353. tbody.innerHTML = list.map((nbr, idx) => `
  18354. <tr class="hover:bg-[#1a2636] text-slate-300">
  18355. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  18356. <td class="py-1.5 px-3 font-mono font-semibold text-teal-300">${escapeHtml(nbr.ip || '')}</td>
  18357. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(nbr.interface || '')}</td>
  18358. <td class="py-1.5 px-3 font-mono text-slate-400">${nbr.metric || 0}</td>
  18359. <td class="py-1.5 px-3 font-mono text-slate-400">${nbr.cost || nbr.routes || 0}</td>
  18360. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(nbr.uptime || nbr.expires || '')}</td>
  18361. </tr>
  18362. `).join('');
  18363. }
  18364. function renderBabelRoutes() {
  18365. const tbody = document.getElementById('babel-routes-table-body');
  18366. if (!tbody) return;
  18367. const countEl = document.getElementById('babel-routes-footer-count');
  18368. const list = state.babelRoutes || [];
  18369. if (countEl) countEl.innerText = list.length;
  18370. tbody.innerHTML = list.map((r, idx) => `
  18371. <tr class="hover:bg-[#1a2636] text-slate-300">
  18372. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  18373. <td class="py-1.5 px-3 font-mono font-semibold text-white">${escapeHtml(r.prefix || '')}</td>
  18374. <td class="py-1.5 px-3 font-mono text-cyan-300">${escapeHtml(r.next_hop || '')}</td>
  18375. <td class="py-1.5 px-3 font-mono text-slate-300">${r.metric || 10}</td>
  18376. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(r.interface || '')}</td>
  18377. </tr>
  18378. `).join('');
  18379. }
  18380. function openBabelInstanceModal() {
  18381. document.getElementById('babel-instance-modal-title').innerText = 'New Babel Instance';
  18382. document.getElementById('modal-babel-instance-id').value = '';
  18383. document.getElementById('modal-babel-instance-name').value = 'babel1';
  18384. document.getElementById('modal-babel-instance-routerid').value = '';
  18385. document.getElementById('modal-babel-instance-metric').value = '10';
  18386. document.getElementById('modal-babel-instance-comment').value = '';
  18387. document.getElementById('modal-babel-instance-enabled').checked = true;
  18388. document.getElementById('modal-babel-instance-redist-conn').checked = false;
  18389. document.getElementById('modal-babel-instance-redist-static').checked = false;
  18390. document.getElementById('modal-babel-instance-redist-bgp').checked = false;
  18391. document.getElementById('modal-babel-instance-redist-ospf').checked = false;
  18392. document.getElementById('modal-babel-instance-redist-default').checked = false;
  18393. document.getElementById('babel-instance-modal')?.classList.remove('hidden');
  18394. }
  18395. function openEditBabelInstanceModal(id) {
  18396. const inst = (state.babelInstances || []).find(i => i.id === id);
  18397. if (!inst) return;
  18398. document.getElementById('babel-instance-modal-title').innerText = `Edit Babel Instance: ${inst.name}`;
  18399. document.getElementById('modal-babel-instance-id').value = inst.id;
  18400. document.getElementById('modal-babel-instance-name').value = inst.name || '';
  18401. document.getElementById('modal-babel-instance-routerid').value = inst.router_id || '';
  18402. document.getElementById('modal-babel-instance-metric').value = inst.default_metric || 10;
  18403. document.getElementById('modal-babel-instance-comment').value = inst.comment || '';
  18404. document.getElementById('modal-babel-instance-enabled').checked = !inst.disabled;
  18405. document.getElementById('modal-babel-instance-redist-conn').checked = !!inst.redistribute_connected;
  18406. document.getElementById('modal-babel-instance-redist-static').checked = !!inst.redistribute_static;
  18407. document.getElementById('modal-babel-instance-redist-bgp').checked = !!inst.redistribute_bgp;
  18408. document.getElementById('modal-babel-instance-redist-ospf').checked = !!inst.redistribute_ospf;
  18409. document.getElementById('modal-babel-instance-redist-default').checked = !!inst.redistribute_default;
  18410. document.getElementById('babel-instance-modal')?.classList.remove('hidden');
  18411. }
  18412. function closeBabelInstanceModal() {
  18413. document.getElementById('babel-instance-modal')?.classList.add('hidden');
  18414. }
  18415. async function submitBabelInstance(e) {
  18416. e.preventDefault();
  18417. const id = document.getElementById('modal-babel-instance-id').value;
  18418. const isEnabled = document.getElementById('modal-babel-instance-enabled').checked;
  18419. const payload = {
  18420. id: id || undefined,
  18421. name: document.getElementById('modal-babel-instance-name').value.trim(),
  18422. router_id: document.getElementById('modal-babel-instance-routerid').value.trim(),
  18423. default_metric: parseInt(document.getElementById('modal-babel-instance-metric').value, 10) || 10,
  18424. comment: document.getElementById('modal-babel-instance-comment').value.trim(),
  18425. enabled: isEnabled,
  18426. disabled: !isEnabled,
  18427. redistribute_connected: document.getElementById('modal-babel-instance-redist-conn').checked,
  18428. redistribute_static: document.getElementById('modal-babel-instance-redist-static').checked,
  18429. redistribute_bgp: document.getElementById('modal-babel-instance-redist-bgp').checked,
  18430. redistribute_ospf: document.getElementById('modal-babel-instance-redist-ospf').checked,
  18431. redistribute_default: document.getElementById('modal-babel-instance-redist-default').checked
  18432. };
  18433. try {
  18434. const res = await fetch(`${API_BASE}/routing/babel/instances`, {
  18435. method: 'POST',
  18436. headers: { 'Content-Type': 'application/json' },
  18437. body: JSON.stringify(payload)
  18438. });
  18439. if (!res.ok) throw new Error(await res.text());
  18440. closeBabelInstanceModal();
  18441. showToast('Saved', `Babel instance saved`, 'success');
  18442. await loadDynamicRouting(false);
  18443. } catch (err) {
  18444. showToast('Error', err.message, 'error');
  18445. }
  18446. }
  18447. async function enableSelectedBabelInstance() {
  18448. const id = state.selectedBabelRow?.instances;
  18449. if (!id) return;
  18450. await fetch(`${API_BASE}/routing/babel/instances/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: false }) });
  18451. await loadDynamicRouting(false);
  18452. }
  18453. async function disableSelectedBabelInstance() {
  18454. const id = state.selectedBabelRow?.instances;
  18455. if (!id) return;
  18456. await fetch(`${API_BASE}/routing/babel/instances/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: true }) });
  18457. await loadDynamicRouting(false);
  18458. }
  18459. async function removeSelectedBabelInstance() {
  18460. const id = state.selectedBabelRow?.instances;
  18461. if (!id || !confirm('Are you sure you want to remove this Babel instance?')) return;
  18462. await fetch(`${API_BASE}/routing/babel/instances/${id}`, { method: 'DELETE' });
  18463. state.selectedBabelRow.instances = null;
  18464. await loadDynamicRouting(false);
  18465. }
  18466. function toggleBabelAuthKey() {
  18467. const authVal = document.getElementById('modal-babel-iface-auth')?.value;
  18468. const wrap = document.getElementById('modal-babel-iface-auth-key-wrap');
  18469. if (wrap) {
  18470. if (authVal === 'mac') wrap.classList.remove('hidden');
  18471. else wrap.classList.add('hidden');
  18472. }
  18473. }
  18474. function openBabelInterfaceModal() {
  18475. document.getElementById('babel-interface-modal-title').innerText = 'New Babel Interface Template';
  18476. document.getElementById('modal-babel-iface-id').value = '';
  18477. const instSel = document.getElementById('modal-babel-iface-instance');
  18478. if (instSel) {
  18479. instSel.innerHTML = '<option value="all">all (Any instance)</option>' +
  18480. (state.babelInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)}</option>`).join('');
  18481. if (state.babelInstances && state.babelInstances.length > 0) {
  18482. instSel.value = state.babelInstances[0].name;
  18483. }
  18484. }
  18485. const dl = document.getElementById('babel-iface-datalist');
  18486. if (dl) {
  18487. dl.innerHTML = '<option value="*">' + (state.interfaces || []).map(i => `<option value="${escapeHtml(i.name)}">`).join('');
  18488. }
  18489. document.getElementById('modal-babel-iface-pattern').value = '*';
  18490. document.getElementById('modal-babel-iface-type').value = 'wired';
  18491. document.getElementById('modal-babel-iface-auth').value = 'none';
  18492. document.getElementById('modal-babel-iface-auth-key').value = '';
  18493. toggleBabelAuthKey();
  18494. document.getElementById('modal-babel-iface-rxcost').value = '10';
  18495. document.getElementById('modal-babel-iface-hello').value = '4';
  18496. document.getElementById('modal-babel-iface-update').value = '16';
  18497. document.getElementById('modal-babel-iface-comment').value = '';
  18498. document.getElementById('modal-babel-iface-enabled').checked = true;
  18499. document.getElementById('babel-interface-modal')?.classList.remove('hidden');
  18500. }
  18501. function openEditBabelInterfaceModal(id) {
  18502. const iface = (state.babelInterfaces || []).find(i => i.id === id);
  18503. if (!iface) return;
  18504. document.getElementById('babel-interface-modal-title').innerText = `Edit Babel Interface: ${iface.interface}`;
  18505. document.getElementById('modal-babel-iface-id').value = iface.id;
  18506. const instSel = document.getElementById('modal-babel-iface-instance');
  18507. if (instSel) {
  18508. instSel.innerHTML = '<option value="all">all (Any instance)</option>' +
  18509. (state.babelInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)}</option>`).join('');
  18510. instSel.value = iface.instance || 'all';
  18511. }
  18512. const dl = document.getElementById('babel-iface-datalist');
  18513. if (dl) {
  18514. dl.innerHTML = '<option value="*">' + (state.interfaces || []).map(i => `<option value="${escapeHtml(i.name)}">`).join('');
  18515. }
  18516. document.getElementById('modal-babel-iface-pattern').value = iface.interface || '';
  18517. document.getElementById('modal-babel-iface-type').value = iface.type || 'wired';
  18518. document.getElementById('modal-babel-iface-auth').value = iface.auth || 'none';
  18519. document.getElementById('modal-babel-iface-auth-key').value = iface.auth_key || '';
  18520. toggleBabelAuthKey();
  18521. document.getElementById('modal-babel-iface-rxcost').value = iface.rxcost || 10;
  18522. document.getElementById('modal-babel-iface-hello').value = iface.hello_interval || 4;
  18523. document.getElementById('modal-babel-iface-update').value = iface.update_interval || 16;
  18524. document.getElementById('modal-babel-iface-comment').value = iface.comment || '';
  18525. document.getElementById('modal-babel-iface-enabled').checked = !iface.disabled;
  18526. document.getElementById('babel-interface-modal')?.classList.remove('hidden');
  18527. }
  18528. function closeBabelInterfaceModal() {
  18529. document.getElementById('babel-interface-modal')?.classList.add('hidden');
  18530. }
  18531. async function submitBabelInterface(e) {
  18532. e.preventDefault();
  18533. const id = document.getElementById('modal-babel-iface-id').value;
  18534. const isEnabled = document.getElementById('modal-babel-iface-enabled').checked;
  18535. const payload = {
  18536. id: id || undefined,
  18537. instance: document.getElementById('modal-babel-iface-instance').value.trim(),
  18538. interface: document.getElementById('modal-babel-iface-pattern').value.trim(),
  18539. type: document.getElementById('modal-babel-iface-type').value,
  18540. auth: document.getElementById('modal-babel-iface-auth').value,
  18541. auth_key: document.getElementById('modal-babel-iface-auth-key').value.trim(),
  18542. rxcost: parseInt(document.getElementById('modal-babel-iface-rxcost').value, 10) || 10,
  18543. hello_interval: parseInt(document.getElementById('modal-babel-iface-hello').value, 10) || 4,
  18544. update_interval: parseInt(document.getElementById('modal-babel-iface-update').value, 10) || 16,
  18545. comment: document.getElementById('modal-babel-iface-comment').value.trim(),
  18546. disabled: !isEnabled
  18547. };
  18548. try {
  18549. const res = await fetch(`${API_BASE}/routing/babel/interfaces`, {
  18550. method: 'POST',
  18551. headers: { 'Content-Type': 'application/json' },
  18552. body: JSON.stringify(payload)
  18553. });
  18554. if (!res.ok) throw new Error(await res.text());
  18555. closeBabelInterfaceModal();
  18556. showToast('Saved', `Babel interface template saved`, 'success');
  18557. await loadDynamicRouting(false);
  18558. } catch (err) {
  18559. showToast('Error', err.message, 'error');
  18560. }
  18561. }
  18562. async function enableSelectedBabelInterface() {
  18563. const id = state.selectedBabelRow?.interfaces;
  18564. if (!id) return;
  18565. await fetch(`${API_BASE}/routing/babel/interfaces/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: false }) });
  18566. await loadDynamicRouting(false);
  18567. }
  18568. async function disableSelectedBabelInterface() {
  18569. const id = state.selectedBabelRow?.interfaces;
  18570. if (!id) return;
  18571. await fetch(`${API_BASE}/routing/babel/interfaces/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: true }) });
  18572. await loadDynamicRouting(false);
  18573. }
  18574. async function removeSelectedBabelInterface() {
  18575. const id = state.selectedBabelRow?.interfaces;
  18576. if (!id || !confirm('Are you sure you want to remove this Babel interface template?')) return;
  18577. await fetch(`${API_BASE}/routing/babel/interfaces/${id}`, { method: 'DELETE' });
  18578. state.selectedBabelRow.interfaces = null;
  18579. await loadDynamicRouting(false);
  18580. }
  18581. // ==============================================================================
  18582. // DYNAMIC ROUTING: RADV MODULE (IPv6 Router Advertisements)
  18583. // ==============================================================================
  18584. state.radvInstances = [];
  18585. state.radvInterfaces = [];
  18586. state.selectedRadvRow = {};
  18587. state.activeRadvTab = 'instances';
  18588. function switchRadvTab(tab) {
  18589. state.activeRadvTab = tab;
  18590. ['instances', 'interfaces'].forEach(t => {
  18591. const pane = document.getElementById(`radv-pane-${t}`);
  18592. const btn = document.getElementById(`radv-tab-btn-${t}`);
  18593. if (pane) {
  18594. if (t === tab) pane.classList.remove('hidden');
  18595. else pane.classList.add('hidden');
  18596. }
  18597. if (btn) {
  18598. if (t === tab) {
  18599. 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';
  18600. } else {
  18601. 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';
  18602. }
  18603. }
  18604. });
  18605. }
  18606. function selectRadvRow(tab, id) {
  18607. if (!state.selectedRadvRow) state.selectedRadvRow = {};
  18608. state.selectedRadvRow[tab] = id;
  18609. if (tab === 'instances') {
  18610. renderRAdvInstances();
  18611. const btnEn = document.getElementById('btn-radv-inst-enable');
  18612. const btnDis = document.getElementById('btn-radv-inst-disable');
  18613. const btnRem = document.getElementById('btn-radv-inst-remove');
  18614. if (btnEn) btnEn.disabled = false;
  18615. if (btnDis) btnDis.disabled = false;
  18616. if (btnRem) btnRem.disabled = false;
  18617. } else if (tab === 'interfaces') {
  18618. renderRAdvInterfaces();
  18619. const btnEn = document.getElementById('btn-radv-iface-enable');
  18620. const btnDis = document.getElementById('btn-radv-iface-disable');
  18621. const btnRem = document.getElementById('btn-radv-iface-remove');
  18622. if (btnEn) btnEn.disabled = false;
  18623. if (btnDis) btnDis.disabled = false;
  18624. if (btnRem) btnRem.disabled = false;
  18625. }
  18626. }
  18627. function renderRAdvInstances() {
  18628. const tbody = document.getElementById('radv-instances-table-body');
  18629. if (!tbody) return;
  18630. const countEl = document.getElementById('radv-instances-footer-count');
  18631. const filter = (document.getElementById('filter-radv-instances')?.value || '').toLowerCase();
  18632. let list = state.radvInstances || [];
  18633. if (filter) {
  18634. list = list.filter(i => (i.name || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  18635. }
  18636. if (countEl) countEl.innerText = list.length;
  18637. const selId = state.selectedRadvRow?.instances;
  18638. tbody.innerHTML = list.map((inst, idx) => {
  18639. const isSel = inst.id === selId;
  18640. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-blue-400' : 'hover:bg-[#1a2636] text-slate-300';
  18641. const flagD = inst.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '<span class="text-emerald-400">R</span>';
  18642. return `
  18643. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectRadvRow('instances', '${inst.id}')" ondblclick="openEditRAdvInstanceModal('${inst.id}')">
  18644. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  18645. <td class="py-1.5 px-3 w-12 text-center">${flagD}</td>
  18646. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(inst.comment || '')}</td>
  18647. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  18648. <span class="text-blue-400">↳</span> <span>${escapeHtml(inst.name || 'default')}</span>
  18649. </td>
  18650. <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>
  18651. </tr>
  18652. `;
  18653. }).join('');
  18654. }
  18655. function renderRAdvInterfaces() {
  18656. const tbody = document.getElementById('radv-interfaces-table-body');
  18657. if (!tbody) return;
  18658. const countEl = document.getElementById('radv-interfaces-footer-count');
  18659. const filter = (document.getElementById('filter-radv-interfaces')?.value || '').toLowerCase();
  18660. let list = state.radvInterfaces || [];
  18661. if (filter) {
  18662. list = list.filter(i => (i.interface || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  18663. }
  18664. if (countEl) countEl.innerText = list.length;
  18665. const selId = state.selectedRadvRow?.interfaces;
  18666. tbody.innerHTML = list.map((iface, idx) => {
  18667. const isSel = iface.id === selId;
  18668. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-blue-400' : 'hover:bg-[#1a2636] text-slate-300';
  18669. const flagD = iface.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '<span class="text-emerald-400">R</span>';
  18670. const prefixes = (iface.prefixes || []).join(', ') || 'default';
  18671. const rdnss = (iface.rdnss || []).join(', ') || 'none';
  18672. return `
  18673. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectRadvRow('interfaces', '${iface.id}')" ondblclick="openEditRAdvInterfaceModal('${iface.id}')">
  18674. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  18675. <td class="py-1.5 px-3 w-12 text-center">${flagD}</td>
  18676. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(iface.comment || '')}</td>
  18677. <td class="py-1.5 px-3 font-mono font-semibold text-white">${escapeHtml(iface.interface || '')}</td>
  18678. <td class="py-1.5 px-3 text-slate-300">${iface.min_ra_interval || 200}s / ${iface.max_ra_interval || 600}s</td>
  18679. <td class="py-1.5 px-3 text-slate-400">${iface.default_lifetime || 1800}s</td>
  18680. <td class="py-1.5 px-3 font-mono text-cyan-300">${escapeHtml(prefixes)}</td>
  18681. <td class="py-1.5 px-3 font-mono text-purple-300">${escapeHtml(rdnss)}</td>
  18682. </tr>
  18683. `;
  18684. }).join('');
  18685. }
  18686. function openRAdvInstanceModal() {
  18687. document.getElementById('radv-instance-modal-title').innerText = 'New RAdv Instance';
  18688. document.getElementById('modal-radv-instance-id').value = '';
  18689. document.getElementById('modal-radv-instance-name').value = 'radv1';
  18690. document.getElementById('modal-radv-instance-comment').value = '';
  18691. document.getElementById('modal-radv-instance-enabled').checked = true;
  18692. document.getElementById('radv-instance-modal')?.classList.remove('hidden');
  18693. }
  18694. function openEditRAdvInstanceModal(id) {
  18695. const inst = (state.radvInstances || []).find(i => i.id === id);
  18696. if (!inst) return;
  18697. document.getElementById('radv-instance-modal-title').innerText = `Edit RAdv Instance: ${inst.name}`;
  18698. document.getElementById('modal-radv-instance-id').value = inst.id;
  18699. document.getElementById('modal-radv-instance-name').value = inst.name || '';
  18700. document.getElementById('modal-radv-instance-comment').value = inst.comment || '';
  18701. document.getElementById('modal-radv-instance-enabled').checked = !inst.disabled;
  18702. document.getElementById('radv-instance-modal')?.classList.remove('hidden');
  18703. }
  18704. function closeRAdvInstanceModal() {
  18705. document.getElementById('radv-instance-modal')?.classList.add('hidden');
  18706. }
  18707. async function submitRAdvInstance(e) {
  18708. e.preventDefault();
  18709. const id = document.getElementById('modal-radv-instance-id').value;
  18710. const payload = {
  18711. id: id || undefined,
  18712. name: document.getElementById('modal-radv-instance-name').value.trim(),
  18713. comment: document.getElementById('modal-radv-instance-comment').value.trim(),
  18714. disabled: !document.getElementById('modal-radv-instance-enabled').checked
  18715. };
  18716. try {
  18717. const res = await fetch(`${API_BASE}/routing/radv/instances`, {
  18718. method: 'POST',
  18719. headers: { 'Content-Type': 'application/json' },
  18720. body: JSON.stringify(payload)
  18721. });
  18722. if (!res.ok) throw new Error(await res.text());
  18723. closeRAdvInstanceModal();
  18724. showToast('Saved', `RAdv instance saved`, 'success');
  18725. await loadDynamicRouting(false);
  18726. } catch (err) {
  18727. showToast('Error', err.message, 'error');
  18728. }
  18729. }
  18730. async function enableSelectedRadvInstance() {
  18731. const id = state.selectedRadvRow?.instances;
  18732. if (!id) return;
  18733. await fetch(`${API_BASE}/routing/radv/instances/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: false }) });
  18734. await loadDynamicRouting(false);
  18735. }
  18736. async function disableSelectedRadvInstance() {
  18737. const id = state.selectedRadvRow?.instances;
  18738. if (!id) return;
  18739. await fetch(`${API_BASE}/routing/radv/instances/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: true }) });
  18740. await loadDynamicRouting(false);
  18741. }
  18742. async function removeSelectedRadvInstance() {
  18743. const id = state.selectedRadvRow?.instances;
  18744. if (!id || !confirm('Are you sure you want to remove this RAdv instance?')) return;
  18745. await fetch(`${API_BASE}/routing/radv/instances/${id}`, { method: 'DELETE' });
  18746. state.selectedRadvRow.instances = null;
  18747. await loadDynamicRouting(false);
  18748. }
  18749. function openRAdvInterfaceModal() {
  18750. document.getElementById('radv-interface-modal-title').innerText = 'New RAdv Interface';
  18751. document.getElementById('modal-radv-iface-id').value = '';
  18752. document.getElementById('modal-radv-iface-interface').value = '';
  18753. document.getElementById('modal-radv-iface-instance').value = 'radv1';
  18754. document.getElementById('modal-radv-iface-min-ra').value = '200';
  18755. document.getElementById('modal-radv-iface-max-ra').value = '600';
  18756. document.getElementById('modal-radv-iface-lifetime').value = '1800';
  18757. document.getElementById('modal-radv-iface-hoplimit').value = '64';
  18758. document.getElementById('modal-radv-iface-prefixes').value = '';
  18759. document.getElementById('modal-radv-iface-rdnss').value = '';
  18760. document.getElementById('modal-radv-iface-comment').value = '';
  18761. document.getElementById('modal-radv-iface-enabled').checked = true;
  18762. document.getElementById('radv-interface-modal')?.classList.remove('hidden');
  18763. }
  18764. function openEditRAdvInterfaceModal(id) {
  18765. const iface = (state.radvInterfaces || []).find(i => i.id === id);
  18766. if (!iface) return;
  18767. document.getElementById('radv-interface-modal-title').innerText = `Edit RAdv Interface: ${iface.interface}`;
  18768. document.getElementById('modal-radv-iface-id').value = iface.id;
  18769. document.getElementById('modal-radv-iface-interface').value = iface.interface || '';
  18770. document.getElementById('modal-radv-iface-instance').value = iface.instance || '';
  18771. document.getElementById('modal-radv-iface-min-ra').value = iface.min_ra_interval || 200;
  18772. document.getElementById('modal-radv-iface-max-ra').value = iface.max_ra_interval || 600;
  18773. document.getElementById('modal-radv-iface-lifetime').value = iface.default_lifetime || 1800;
  18774. document.getElementById('modal-radv-iface-hoplimit').value = iface.hop_limit || 64;
  18775. document.getElementById('modal-radv-iface-prefixes').value = (iface.prefixes || []).join(', ');
  18776. document.getElementById('modal-radv-iface-rdnss').value = (iface.rdnss || []).join(', ');
  18777. document.getElementById('modal-radv-iface-comment').value = iface.comment || '';
  18778. document.getElementById('modal-radv-iface-enabled').checked = !iface.disabled;
  18779. document.getElementById('radv-interface-modal')?.classList.remove('hidden');
  18780. }
  18781. function closeRAdvInterfaceModal() {
  18782. document.getElementById('radv-interface-modal')?.classList.add('hidden');
  18783. }
  18784. async function submitRAdvInterface(e) {
  18785. e.preventDefault();
  18786. const id = document.getElementById('modal-radv-iface-id').value;
  18787. const pRaw = document.getElementById('modal-radv-iface-prefixes').value;
  18788. const rRaw = document.getElementById('modal-radv-iface-rdnss').value;
  18789. const prefixes = pRaw ? pRaw.split(',').map(s => s.trim()).filter(Boolean) : [];
  18790. const rdnss = rRaw ? rRaw.split(',').map(s => s.trim()).filter(Boolean) : [];
  18791. const payload = {
  18792. id: id || undefined,
  18793. interface: document.getElementById('modal-radv-iface-interface').value.trim(),
  18794. instance: document.getElementById('modal-radv-iface-instance').value.trim(),
  18795. min_ra_interval: parseInt(document.getElementById('modal-radv-iface-min-ra').value, 10) || 200,
  18796. max_ra_interval: parseInt(document.getElementById('modal-radv-iface-max-ra').value, 10) || 600,
  18797. default_lifetime: parseInt(document.getElementById('modal-radv-iface-lifetime').value, 10) || 1800,
  18798. hop_limit: parseInt(document.getElementById('modal-radv-iface-hoplimit').value, 10) || 64,
  18799. prefixes: prefixes,
  18800. rdnss: rdnss,
  18801. comment: document.getElementById('modal-radv-iface-comment').value.trim(),
  18802. disabled: !document.getElementById('modal-radv-iface-enabled').checked
  18803. };
  18804. try {
  18805. const res = await fetch(`${API_BASE}/routing/radv/interfaces`, {
  18806. method: 'POST',
  18807. headers: { 'Content-Type': 'application/json' },
  18808. body: JSON.stringify(payload)
  18809. });
  18810. if (!res.ok) throw new Error(await res.text());
  18811. closeRAdvInterfaceModal();
  18812. showToast('Saved', `RAdv interface saved`, 'success');
  18813. await loadDynamicRouting(false);
  18814. } catch (err) {
  18815. showToast('Error', err.message, 'error');
  18816. }
  18817. }
  18818. async function enableSelectedRadvInterface() {
  18819. const id = state.selectedRadvRow?.interfaces;
  18820. if (!id) return;
  18821. await fetch(`${API_BASE}/routing/radv/interfaces/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: false }) });
  18822. await loadDynamicRouting(false);
  18823. }
  18824. async function disableSelectedRadvInterface() {
  18825. const id = state.selectedRadvRow?.interfaces;
  18826. if (!id) return;
  18827. await fetch(`${API_BASE}/routing/radv/interfaces/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: true }) });
  18828. await loadDynamicRouting(false);
  18829. }
  18830. async function removeSelectedRadvInterface() {
  18831. const id = state.selectedRadvRow?.interfaces;
  18832. if (!id || !confirm('Are you sure you want to remove this RAdv interface?')) return;
  18833. await fetch(`${API_BASE}/routing/radv/interfaces/${id}`, { method: 'DELETE' });
  18834. state.selectedRadvRow.interfaces = null;
  18835. await loadDynamicRouting(false);
  18836. }